Programs & Examples On #Implicit style

How do I disable text selection with CSS or JavaScript?

You can use JavaScript to do what you want:


if (document.addEventListener !== undefined) {
  // Not IE
  document.addEventListener('click', checkSelection, false);
} else {
  // IE
  document.attachEvent('onclick', checkSelection);
}

function checkSelection() {
    var sel = {};
    if (window.getSelection) {
        // Mozilla
        sel = window.getSelection();
    } else if (document.selection) {
        // IE
        sel = document.selection.createRange();
    }

    // Mozilla
    if (sel.rangeCount) {
        sel.removeAllRanges();
        return;
    }

    // IE
    if (sel.text > '') {
        document.selection.empty();
        return;
    }
}

Soap box: You really shouldn't be screwing with the client's user agent in this manner. If the client wants to select things on the document, then they should be able to select things on the document. It doesn't matter if you don't like the highlight color, because you aren't the one viewing the document.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

I my case I'd manually moved a .war file to /var/lib/tomcat9/webapps and unzipped it, then did "chown -R tomcat:tomcat *" in that directory and it resolved it.

Python, add items from txt file into a list

names=[line.strip() for line in open('names.txt')]

Easiest way to open a download window without navigating away from the page

I always add a target="_blank" to the download link. This will open a new window, but as soon as the user clicks save, the new window is closed.

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

I use this script on sql server 2008 R2.

USE [db_name]

ALTER DATABASE [db_name] SET RECOVERY SIMPLE WITH NO_WAIT

DBCC SHRINKFILE([log_file_name]/log_file_number, wanted_size)

ALTER DATABASE [db_name] SET RECOVERY FULL WITH NO_WAIT

alternative to "!is.null()" in R

To handle undefined variables as well as nulls, you can use substitute with deparse:

nullSafe <- function(x) {
  if (!exists(deparse(substitute(x))) || is.null(x)) {
    return(NA)
  } else {
    return(x)
  }
}

nullSafe(my.nonexistent.var)

JavaScript function in href vs. onclick

Having javascript: in any attribute that isn't specifically for scripting is an outdated method of HTML. While technically it works, you're still assigning javascript properties to a non-script attribute, which isn't good practice. It can even fail on old browsers, or even some modern ones (a googled forum post seemd to indicate that Opera does not like 'javascript:' urls).

A better practice would be the second way, to put your javascript into the onclick attribute, which is ignored if no scripting functionality is available. Place a valid URL in the href field (commonly '#') for fallback for those who do not have javascript.

How do I generate random numbers in Dart?

Here's a snippet for generating a list of random numbers

import 'dart:math';

main() {
  var rng = new Random();
  var l = new List.generate(12, (_) => rng.nextInt(100));
}

This will generate a list of 12 integers from 0 to 99 (inclusive).

How to resolve symbolic links in a shell script

Another way:

# Gets the real path of a link, following all links
myreadlink() { [ ! -h "$1" ] && echo "$1" || (local link="$(expr "$(command ls -ld -- "$1")" : '.*-> \(.*\)$')"; cd $(dirname $1); myreadlink "$link" | sed "s|^\([^/].*\)\$|$(dirname $1)/\1|"); }

# Returns the absolute path to a command, maybe in $PATH (which) or not. If not found, returns the same
whereis() { echo $1 | sed "s|^\([^/].*/.*\)|$(pwd)/\1|;s|^\([^/]*\)$|$(which -- $1)|;s|^$|$1|"; } 

# Returns the realpath of a called command.
whereis_realpath() { local SCRIPT_PATH=$(whereis $1); myreadlink ${SCRIPT_PATH} | sed "s|^\([^/].*\)\$|$(dirname ${SCRIPT_PATH})/\1|"; } 

Negate if condition in bash script

Better

if ! wget -q --spider --tries=10 --timeout=20 google.com
then
  echo 'Sorry you are Offline'
  exit 1
fi

How to send HTTP request in java?

You can use java.net.HttpUrlConnection.

Example (from here), with improvements. Included in case of link rot:

public static String executePost(String targetURL, String urlParameters) {
  HttpURLConnection connection = null;

  try {
    //Create connection
    URL url = new URL(targetURL);
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", 
        "application/x-www-form-urlencoded");

    connection.setRequestProperty("Content-Length", 
        Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");  

    connection.setUseCaches(false);
    connection.setDoOutput(true);

    //Send request
    DataOutputStream wr = new DataOutputStream (
        connection.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.close();

    //Get Response  
    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
    String line;
    while ((line = rd.readLine()) != null) {
      response.append(line);
      response.append('\r');
    }
    rd.close();
    return response.toString();
  } catch (Exception e) {
    e.printStackTrace();
    return null;
  } finally {
    if (connection != null) {
      connection.disconnect();
    }
  }
}

Django MEDIA_URL and MEDIA_ROOT

Do I need to setup specific URLconf patters for uploaded media?

Yes. For development, it's as easy as adding this to your URLconf:

if settings.DEBUG:
    urlpatterns += patterns('django.views.static',
        (r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
    )

However, for production, you'll want to serve the media using Apache, lighttpd, nginx, or your preferred web server.

regex for zip-code

For the listed three conditions only, these expressions might work also:

^\d{5}[-\s]?(?:\d{4})?$
^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
^\[0-9]{5}[-\s]?(?:\d{4})?$
^\d{5}[-\s]?(?:[0-9]{4})?$

Please see this demo for additional explanation.

If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:

123451234
12345 1234
12345  1234

this expression for instance would be a secondary option with less constraints:

^\d{5}([-]|\s*)?(\d{4})?$

Please see this demo for additional explanation.

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Test

_x000D_
_x000D_
const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;_x000D_
const str = `12345_x000D_
12345-6789_x000D_
12345 1234_x000D_
123451234_x000D_
12345 1234_x000D_
12345  1234_x000D_
1234512341_x000D_
123451`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
    // This is necessary to avoid infinite loops with zero-width matches_x000D_
    if (m.index === regex.lastIndex) {_x000D_
        regex.lastIndex++;_x000D_
    }_x000D_
    _x000D_
    // The result can be accessed through the `m`-variable._x000D_
    m.forEach((match, groupIndex) => {_x000D_
        console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
    });_x000D_
}
_x000D_
_x000D_
_x000D_

Finding modified date of a file/folder

You can try dirTimesJS.bat and fileTimesJS.bat

example:

C:\>dirTimesJS.bat %windir%

directory timestamps for C:\Windows :

Modified : 2020-11-22 22:12:55
Modified - milliseconds passed : 1604607175000
Modified day of the week : 4

Created : 2019-12-11 11:03:44
Created - milliseconds passed : 1575709424000
Created day of the week : 6

Accessed : 2020-11-16 16:39:22
Accessed - milliseconds passed : 1605019162000
Accessed day of the week : 2

C:\>fileTimesJS.bat %windir%\notepad.exe

file timestamps for C:\Windows\notepad.exe :

Modified : 2020-09-08 08:33:31
Modified - milliseconds passed : 1599629611000
Modified day of the week : 3

Created : 2020-09-08 08:33:31
Created - milliseconds passed : 1599629611000
Created day of the week : 3

Accessed : 2020-11-23 23:59:22
Accessed - milliseconds passed : 1604613562000
Accessed day of the week : 4

Concatenate multiple result rows of one column into one, group by another column

You can use array_agg function for that:

SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";

Result:

MOVIE ACTOR
A 1,2,3
B 4

See this SQLFiddle

For more See 9.18. Aggregate Functions

Delete all duplicate rows Excel vba

There's a RemoveDuplicates method that you could use:

Sub DeleteRows()

    With ActiveSheet
        Set Rng = Range("A1", Range("B1").End(xlDown))
        Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
    End With

End Sub

How can I subset rows in a data frame in R based on a vector of values?

Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:

# Set seed for reproducibility.
set.seed(1)

# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))

# compare data frames by specific columns and keep only 
# the rows with equal values 
data_A[data_A$id %in% data_B$id,]   # will keep data in data_A
data_B[data_B$id %in% data_A$id,]   # will keep data in data_b

Results:

> data_A[data_A$id %in% data_B$id,]
  id value
1  1     1
2  2     2
3  3     3

> data_B[data_B$id %in% data_A$id,]
  id value
1  1     5
2  2     6
3  3     7

VBScript - How to make program wait until process has finished?

You need to tell the run to wait until the process is finished. Something like:

const DontWaitUntilFinished = false, ShowWindow = 1, DontShowWindow = 0, WaitUntilFinished = true
set oShell = WScript.CreateObject("WScript.Shell")
command = "cmd /c C:\windows\system32\wscript.exe <path>\myScript.vbs " & args
oShell.Run command, DontShowWindow, WaitUntilFinished

In the script itself, start Excel like so. While debugging start visible:

File = "c:\test\myfile.xls"
oShell.run """C:\Program Files\Microsoft Office\Office14\EXCEL.EXE"" " & File, 1, true

Remove credentials from Git

Retype:

$ git config credential.helper store

And then you will be prompted to enter your credentials again.

WARNING

Using this helper will store your passwords unencrypted on disk

Source: https://git-scm.com/docs/git-credential-store

How to use a servlet filter in Java to change an incoming servlet request url?

  1. Implement javax.servlet.Filter.
  2. In doFilter() method, cast the incoming ServletRequest to HttpServletRequest.
  3. Use HttpServletRequest#getRequestURI() to grab the path.
  4. Use straightforward java.lang.String methods like substring(), split(), concat() and so on to extract the part of interest and compose the new path.
  5. Use either ServletRequest#getRequestDispatcher() and then RequestDispatcher#forward() to forward the request/response to the new URL (server-side redirect, not reflected in browser address bar), or cast the incoming ServletResponse to HttpServletResponse and then HttpServletResponse#sendRedirect() to redirect the response to the new URL (client side redirect, reflected in browser address bar).
  6. Register the filter in web.xml on an url-pattern of /* or /Check_License/*, depending on the context path, or if you're on Servlet 3.0 already, use the @WebFilter annotation for that instead.

Don't forget to add a check in the code if the URL needs to be changed and if not, then just call FilterChain#doFilter(), else it will call itself in an infinite loop.

Alternatively you can also just use an existing 3rd party API to do all the work for you, such as Tuckey's UrlRewriteFilter which can be configured the way as you would do with Apache's mod_rewrite.

PowerShell: Create Local User Account

As of PowerShell 5.1 there cmdlet New-LocalUser which could create local user account.

Example of usage:

Create a user account

New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword

or Create a user account that has a password

$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."

or Create a user account that is connected to a Microsoft account

New-LocalUser -Name "MicrosoftAccount\usr [email protected]" -Description "Description of this account." 

Groovy String to Date

JChronic is your best choice. Here's an example that adds a .fromString() method to the Date class that parses just about anything you can throw at it:

Date.metaClass.'static'.fromString = { str ->
    com.mdimension.jchronic.Chronic.parse(str).beginCalendar.time
}

You can call it like this:

println Date.fromString("Tue Aug 10 16:02:43 PST 2010")
println Date.fromString("july 1, 2012")
println Date.fromString("next tuesday")

can't load package: package .: no buildable Go source files

I had this exact error code and after checking my repository discovered that there were no go files but actually just more directories. So it was more of a red herring than an error for me.

I would recommend doing

go env

and making sure that everything is as it should be, check your environment variables in your OS and check to make sure your shell (bash or w/e ) isn't compromising it via something like a .bash_profile or .bashrc file. good luck.

What size do you use for varchar(MAX) in your parameter declaration?

For those of us who did not see -1 by Michal Chaniewski, the complete line of code:

cmd.Parameters.Add("@blah",SqlDbType.VarChar,-1).Value = "some large text";

What does "hard coded" mean?

Scenario

In a college there are many students doing different courses, and after an examination we have to prepare a marks card showing grade. I can calculate grade two ways

1. I can write some code like this

    if(totalMark <= 100 && totalMark > 90) { grade = "A+"; }
    else if(totalMark <= 90 && totalMark > 80) { grade = "A"; }
    else if(totalMark <= 80 && totalMark > 70) { grade = "B"; }
    else if(totalMark <= 70 && totalMark > 60) { grade = "C"; }

2. You can ask user to enter grade definition some where and save that data

Something like storing into a database table enter image description here

In the first case the grade is common for all the courses and if the rule changes the code needs to be changed. But for second case we are giving user the provision to enter grade based on their requirement. So the code will be not be changed when the grade rules changes.

That's the important thing when you give more provision for users to define business logic. The first case is nothing but Hard Coding.

So in your question if you ask the user to enter the path of the file at the start, then you can remove the hard coded path in your code.

Oracle DB: How can I write query ignoring case?

You could also use Regular Expressions:

SELECT * FROM TABLE WHERE REGEXP_LIKE (TABLE.NAME,'IgNoReCaSe','i');

How to play or open *.mp3 or *.wav sound file in c++ program?

First of all, write the following code:

#include <Mmsystem.h>
#include <mciapi.h>
//these two headers are already included in the <Windows.h> header
#pragma comment(lib, "Winmm.lib")

To open *.mp3:

mciSendString("open \"*.mp3\" type mpegvideo alias mp3", NULL, 0, NULL);

To play *.mp3:

mciSendString("play mp3", NULL, 0, NULL);

To play and wait until the *.mp3 has finished playing:

mciSendString("play mp3 wait", NULL, 0, NULL);

To replay (play again from start) the *.mp3:

mciSendString("play mp3 from 0", NULL, 0, NULL);

To replay and wait until the *.mp3 has finished playing:

mciSendString("play mp3 from 0 wait", NULL, 0, NULL);

To play the *.mp3 and replay it every time it ends like a loop:

mciSendString("play mp3 repeat", NULL, 0, NULL);

If you want to do something when the *.mp3 has finished playing, then you need to RegisterClassEx by the WNDCLASSEX structure, CreateWindowEx and process it's messages with the GetMessage, TranslateMessage and DispatchMessage functions in a while loop and call:

mciSendString("play mp3 notify", NULL, 0, hwnd); //hwnd is an handle to the window returned from CreateWindowEx. If this doesn't work, then replace the hwnd with MAKELONG(hwnd, 0).

In the window procedure, add the case MM_MCINOTIFY: The code in there will be executed when the mp3 has finished playing.

But if you program a Console Application and you don't deal with windows, then you can CreateThread in suspend state by specifying the CREATE_SUSPENDED flag in the dwCreationFlags parameter and keep the return value in a static variable and call it whatever you want. For instance, I call it mp3. The type of this static variable is HANDLE of course.

Here is the ThreadProc for the lpStartAddress of this thread:

DWORD WINAPI MP3Proc(_In_ LPVOID lpParameter) //lpParameter can be a pointer to a structure that store data that you cannot access outside of this function. You can prepare this structure before `CreateThread` and give it's address in the `lpParameter`
{
    Data *data = (Data*)lpParameter; //If you call this structure Data, but you can call it whatever you want.
    while (true)
    {
        mciSendString("play mp3 from 0 wait", NULL, 0, NULL);
        //Do here what you want to do when the mp3 playback is over
        SuspendThread(GetCurrentThread()); //or the handle of this thread that you keep in a static variable instead
    }
}

All what you have to do now is to ResumeThread(mp3); every time you want to replay your mp3 and something will happen every time it finishes.

You can #define play_my_mp3 ResumeThread(mp3); to make your code more readable.

Of course you can remove the while (true), SuspendThread and the from 0 codes, if you want to play your mp3 file only once and do whatever you want when it is over.

If you only remove the SuspendThread call, then the sound will play over and over again and do something whenever it is over. This is equivalent to:

mciSendString("play mp3 repeat notify", NULL, 0, hwnd); //or MAKELONG(hwnd, 0) instead

in windows.

To pause the *.mp3 in middle:

mciSendString("pause mp3", NULL, 0, NULL);

and to resume it:

mciSendString("resume mp3", NULL, 0, NULL);

To stop it in middle:

mciSendString("stop mp3", NULL, 0, NULL);

Note that you cannot resume a sound that has been stopped, but only paused, but you can replay it by carrying out the play command. When you're done playing this *.mp3, don't forget to:

mciSendString("close mp3", NULL, 0, NULL);

All these actions also apply to (work with) wave files too, but with wave files, you can use "waveaudio" instead of "mpegvideo". Also you can just play them directly without opening them:

PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME);

If you don't want to specify an handle to a module:

sndPlaySound("*.wav", SND_FILENAME);

If you don't want to wait until the playback is over:

PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC);
//or
sndPlaySound("*.wav", SND_FILENAME | SND_ASYNC);

To play the wave file over and over again:

PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC | SND_LOOP);
//or
sndPlaySound("*.wav", SND_FILENAME | SND_ASYNC | SND_LOOP);

Note that you must specify both the SND_ASYNC and SND_LOOP flags, because you never going to wait until a sound, that repeats itself countless times, is over!

Also you can fopen the wave file and copy all it's bytes to a buffer (an enormous/huge (very big) array of bytes) with the fread function and then:

PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY);
//or
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY | SND_ASYNC);
//or
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY | SND_ASYNC | SND_LOOP);
//or
sndPlaySound(buffer, SND_MEMORY);
//or
sndPlaySound(buffer, SND_MEMORY | SND_ASYNC);
//or
sndPlaySound(buffer, SND_MEMORY | SND_ASYNC | SND_LOOP);

Either OpenFile or CreateFile or CreateFile2 and either ReadFile or ReadFileEx functions can be used instead of fopen and fread functions.

Hope this fully answers perfectly your question.

Inserting a string into a list without getting split into characters

best put brackets around foo, and use +=

list+=['foo']

PHP - regex to allow letters and numbers only

try this way .eregi("[^A-Za-z0-9.]", $value)

How to get second-highest salary employees in a table

Can we also use

select e2.max(sal), e2.name
from emp e2
where (e2.sal <(Select max (Salary) from empo el))
group by e2.name

Please let me know what is wrong with this approach

How to get `DOM Element` in Angular 2?

Update (using renderer):

Note that the original Renderer service has now been deprecated in favor of Renderer2

as on Renderer2 official doc.

Furthermore, as pointed out by @GünterZöchbauer:

Actually using ElementRef is just fine. Also using ElementRef.nativeElement with Renderer2 is fine. What is discouraged is accessing properties of ElementRef.nativeElement.xxx directly.


You can achieve this by using elementRef as well as by ViewChild. however it's not recommendable to use elementRef due to:

  • security issue
  • tight coupling

as pointed out by official ng2 documentation.

1. Using elementRef (Direct Access):

export class MyComponent {    
constructor (private _elementRef : ElementRef) {
 this._elementRef.nativeElement.querySelector('textarea').focus();
 }
}

2. Using ViewChild (better approach):

<textarea  #tasknote name="tasknote" [(ngModel)]="taskNote" placeholder="{{ notePlaceholder }}" 
style="background-color: pink" (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} </textarea> // <-- changes id to local var


export class MyComponent implements AfterViewInit {
  @ViewChild('tasknote') input: ElementRef;

   ngAfterViewInit() {
    this.input.nativeElement.focus();

  }
}

3. Using renderer:

export class MyComponent implements AfterViewInit {
      @ViewChild('tasknote') input: ElementRef;
         constructor(private renderer: Renderer2){           
          }

       ngAfterViewInit() {
       //using selectRootElement instead of depreaced invokeElementMethod
       this.renderer.selectRootElement(this.input["nativeElement"]).focus();
      }

    }

Passing variable number of arguments around

Variadic Functions can be dangerous. Here's a safer trick:

   void func(type* values) {
        while(*values) {
            x = *values++;
            /* do whatever with x */
        }
    }

func((type[]){val1,val2,val3,val4,0});

How to add facebook share button on my website?

This Facebook page has a simple tool to create various share buttons.

For example, this is some output I got:

<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v8.0" nonce="dilSYGI6"></script>
<div class="fb-share-button" data-href="https://www.mocacleveland.org/exhibitions/lee-mingwei-you-are-not-stranger" data-layout="button" data-size="small">
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.mocacleveland.org%2Fexhibitions%2Flee-mingwei-you-are-not-stranger&amp;src=sdkpreparse" class="fb-xfbml-parse-ignore">Share</a>
</div>

How do I clear a C++ array?

Should you want to clear the array with something other than a value, std::file wont cut it; instead I found std::generate useful. e.g. I had a vector of lists I wanted to initialize

std::generate(v.begin(), v.end(), [] () { return std::list<X>(); });

You can do ints too e.g.

std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });

or just

std::generate(v.begin(), v.end(), [] (){ return 0; });

but I imagine std::fill is faster for the simplest case

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

How long will my session last?

You're searching for gc_maxlifetime, see http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime for a description.

Your session will last 1440 seconds which is 24 minutes (default).

Count character occurrences in a string in C++

Count character occurrences in a string is easy:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s="Sakib Hossain";
    int cou=count(s.begin(),s.end(),'a');
    cout<<cou;
}

How to add a browser tab icon (favicon) for a website?

I've successfully done this for my website.

Only exception is, the SeaMonkey browser requires HTML code inserted in your <head>; whereas, the other browsers will still display the favicon.ico without any HTML insertion. Also, any browser other than IE may use other types of images, not just the .ico format. I hope this helps.

Ruby, remove last N characters from a string?

You can always use something like

 "string".sub!(/.{X}$/,'')

Where X is the number of characters to remove.

Or with assigning/using the result:

myvar = "string"[0..-X]

where X is the number of characters plus one to remove.

Getting a list of values from a list of dicts

Please try out this one.

d =[{'value': 'apple', 'blah': 2},  {'value': 'banana', 'blah': 3} , {'value': 
'cars', 'blah': 4}] 
b=d[0]['value']
c=d[1]['value']
d=d[2]['value']
new_list=[b,c,d]
print(new_list)

Output:

['apple', 'banana', 'cars']

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

how to get the current working directory's absolute path from irb

If you want to get the full path of the directory of the current rb file:

File.expand_path('../', __FILE__)

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

What is the easiest way to get the current day of the week in Android?

Calendar.getInstance().get(Calendar.DAY_OF_WEEK)

or

new GregorianCalendar().get(Calendar.DAY_OF_WEEK);

Just the same as in Java, nothing particular to Android.

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

Download text/csv content as files from server in Angular

This is what worked for me for IE 11+, Firefox and Chrome. In safari it downloads a file but as unknown and the filename is not set.

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvDataString]);  //csv data string as an array.
    // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
    window.navigator.msSaveBlob(blob, fileName);
} else {
    var anchor = angular.element('<a/>');
    anchor.css({display: 'none'}); // Make sure it's not visible
    angular.element(document.body).append(anchor); // Attach to document for FireFox

    anchor.attr({
        href: 'data:attachment/csv;charset=utf-8,' + encodeURI(csvDataString),
        target: '_blank',
        download: fileName
})[0].click();
anchor.remove();
}

Create a Maven project in Eclipse complains "Could not resolve archetype"

I fixed this problem by following the solution to this other StackOverflow question

I had the same problem. I fixed it by adding the maven archetype catalog to eclipse. Steps are provided below: (Please note the https protocol)

  1. Open Window > Preferences
  2. Open Maven > Archetypes
  3. Click 'Add Remote Catalog' and add the following:

Serializing and submitting a form with jQuery and PHP

You can add extra data with form data

use serializeArray and add the additional data:

var data = $('#myForm').serializeArray();
    data.push({name: 'tienn2t', value: 'love'});
    $.ajax({
      type: "POST",
      url: "your url.php",
      data: data,
      dataType: "json",
      success: function(data) {
          //var obj = jQuery.parseJSON(data); if the dataType is not     specified as json uncomment this
        // do what ever you want with the server response
     },
    error: function() {
        alert('error handing here');
    }
});

Convert HTML Character Back to Text Using Java Standard Library

As @jem suggested, it is possible to use jsoup.

With jSoup 1.8.3 it il possible to use the method Parser.unescapeEntities that retain the original html.

import org.jsoup.parser.Parser;
...
String html = Parser.unescapeEntities(original_html, false);

It seems that in some previous release this method is not present.

How to delete all files from a specific folder?

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);

Or in a single line:

Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);

Enable CORS in Web API 2

I didn't need to install any package. Just a simple change in your WebAPI project's web.config is working great:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

Credit goes to: Using CORS in ASP.NET WebAPI Without Being a Rocket Scientist

How to debug a stored procedure in Toad?

Open a PL/SQL object in the Editor.

Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

Compile the object on the database.

Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

Batch command date and time in file name

Another solution:

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I

It will give you (independent of locale settings!):

  20130802203023.304000+120
( YYYYMMDDhhmmss.<milliseconds><always 000>+/-<minutes difference to UTC>  )

From here, it is easy:

set datetime=%datetime:~0,8%-%datetime:~8,6%
20130802-203023

For Logan's request for the same outputformat for the "date-time modified" of a file:

for %%F in (test.txt) do set file=%%~fF
for /f "tokens=2 delims==" %%I in ('wmic datafile where name^="%file:\=\\%" get lastmodified /format:list') do set datetime=%%I
echo %datetime%

It is a bit more complicated, because it works only with full paths, wmic expects the backslashes to be doubled and the = has to be escaped (the first one. The second one is protected by surrounding quotes).

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

Add dependencies. for example:- import 'package:audioplayers/audio_cache.dart'; in the above package if we only use this package then it shows error but if we add dependencies in pubspec.yaml such as

dependencies:
    flutter:
      sdk: flutter
    cupertino_icons: ^0.1.2
    audioplayers: ^0.14.1

enter image description here

then click on packages get.

as you see this, I can also insert dependencies so if you insert dependencies along with your package then you are good to go.

Custom style to jquery ui dialogs

The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.

HTML

<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
  Nothing here
</div>

You can use CSS to style the main section of the dialog but not the title

.custom-ui-widget-header-warning {
  background: #EBCCCC;
  font-size: 1em;
}

You need some JS to style the title

$(function() {
                   $("#nonmodal1").dialog({
                     minWidth: 400,
                     minHeight: 'auto',
                     autoOpen: false,
                     dialogClass: 'custom-ui-widget-header-warning',
                     position: {
                       my: 'center',
                       at: 'left'
                     }
                   });

                   $("#dialog1").click(function() {
                     if ($("#nonmodal1").dialog("isOpen") === true) {
                       $("#nonmodal1").dialog("close");
                     } else {
                       $("#nonmodal1").dialog("open").prev().css('background','#D9534F');

                     }
                   });
    });

The example only shows simple styling (background) but you can make it as complex as you wish.

You can see it in action here:

http://codepen.io/chris-hore/pen/OVMPay

selected value get from db into dropdown select box option using php mysql error

Answer is simple. when u pass value from dropdown.

Just use as if else.

for eg:

foreach($result as $row) {                      
   $GLOBALS['output'] .='<option value="'.$row["dropdownid"].'"'. 
   ($GLOBALS['passselectedvalueid']==$row["dropwdownid"] ? ' Selected' : '').' 
   >'.$row['valueetc'].'</option>';
}

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Consider a scenario where Test1, Test2 and Test3 are three classes. The Test3 class inherits Test2 and Test1 classes. If Test1 and Test2 classes have same method and you call it from child class object, there will be ambiguity to call method of Test1 or Test2 class but there is no such ambiguity for interface as in interface no implementation is there.

How do I match any character across multiple lines in a regular expression?

generally . doesn't match newlines, so try ((.|\n)*)<foobar>

How to do associative array/hashing in JavaScript

var associativeArray = {};
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";

If you are coming from an object-oriented language you should check this article.

Read pdf files with php

Not exactly php, but you could exec a program from php to convert the pdf to a temporary html file and then parse the resulting file with php. I've done something similar for a project of mine and this is the program I used:

PdfToHtml

The resulting HTML wraps text elements in < div > tags with absolute position coordinates. It seems like this is exactly what you are trying to do.

Convert a Python int into a big-endian string of bytes

Using the bitstring module:

>>> bitstring.BitArray(uint=1245427, length=24).bytes
'\x13\x00\xf3'

Note though that for this method you need to specify the length in bits of the bitstring you are creating.

Internally this is pretty much the same as Alex's answer, but the module has a lot of extra functionality available if you want to do more with your data.

Default username password for Tomcat Application Manager

To reset your keyring.

  1. Go into your home folder.

  2. Press ctrl & h to show your hidden folders.

  3. Now look in your .gnome2/keyrings directory.

  4. Find the default.keyring file.

  5. Move that file to a different folder.

  6. Once done, reboot your computer.

How can I tell jackson to ignore a property for which I don't have control over the source code?

You can use Jackson Mixins. For example:

class YourClass {
  public int ignoreThis() { return 0; }    
}

With this Mixin

abstract class MixIn {
  @JsonIgnore abstract int ignoreThis(); // we don't need it!  
}

With this:

objectMapper.getSerializationConfig().addMixInAnnotations(YourClass.class, MixIn.class);

Edit:

Thanks to the comments, with Jackson 2.5+, the API has changed and should be called with objectMapper.addMixIn(Class<?> target, Class<?> mixinSource)

How to check db2 version

Both worked for me.

SELECT * FROM TABLE(SYSPROC.ENV_GET_INST_INFO());

or

SELECT * FROM SYSIBMADM.ENV_INST_INFO;

Get button click inside UITableViewCell

The reason i like below technique because it also help me to identify the section of table.

Add Button in cell cellForRowAtIndexPath:

 UIButton *selectTaskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [selectTaskBtn setFrame:CGRectMake(15, 5, 30, 30.0)];
        [selectTaskBtn setTag:indexPath.section]; //Not required but may find useful if you need only section or row (indexpath.row) as suggested by MR.Tarun 
    [selectTaskBtn addTarget:self action:@selector(addTask:)   forControlEvents:UIControlEventTouchDown];
[cell addsubview: selectTaskBtn];

Event addTask:

-(void)addTask:(UIButton*)btn
{
    CGPoint buttonPosition = [btn convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)
    {
     int currentIndex = indexPath.row;
     int tableSection = indexPath.section;
    }
}

Hopes this help.

Generic htaccess redirect www to non-www

For those that need to able to access the entire site WITHOUT the 'www' prefix.

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

Mare sure you add this to the following file

/site/location/.htaccess 

database attached is read only

ALTER DATABASE [DatabaseName] SET READ_WRITE

Get querystring from URL using jQuery

From: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

This is what you need :)

The following code will return a JavaScript Object containing the URL parameters:

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

For example, if you have the URL:

http://www.example.com/?me=myValue&name2=SomeOtherValue

This code will return:

{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}

and you can do:

var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];

Warning: X may be used uninitialized in this function

When you use Vector *one you are merely creating a pointer to the structure but there is no memory allocated to it.

Simply use one = (Vector *)malloc(sizeof(Vector)); to declare memory and instantiate it.

how to parse json using groovy

        def jsonFile = new File('File Path');
        JsonSlurper jsonSlurper = new JsonSlurper();
        def parseJson = jsonSlurper.parse(jsonFile)
        String json = JsonOutput.toJson(parseJson)
        def prettyJson = JsonOutput.prettyPrint(json)
        println(prettyJson)

Metadata file '.dll' could not be found

I have found out that if you remove Microsoft.CSharp assembly as a reference in the project, you will get this error.

Call a python function from jinja2

Note: This is Flask specific!

I know this post is quite old, but there are better methods of doing this in the newer versions of Flask using context processors.

Variables can easily be created:

@app.context_processor
def example():
    return dict(myexample='This is an example')

The above can be used in a Jinja2 template with Flask like so:

{{ myexample }}

(Which outputs This is an example)

As well as full fledged functions:

@app.context_processor
def utility_processor():
    def format_price(amount, currency=u'€'):
        return u'{0:.2f}{1}'.format(amount, currency)
    return dict(format_price=format_price)

The above when used like so:

{{ format_price(0.33) }}

(Which outputs the input price with the currency symbol)

Alternatively, you can use jinja filters, baked into Flask. E.g. using decorators:

@app.template_filter('reverse')
def reverse_filter(s):
    return s[::-1]

Or, without decorators, and manually registering the function:

def reverse_filter(s):
    return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter

Filters applied with the above two methods can be used like this:

{% for x in mylist | reverse %}
{% endfor %}

How does Google calculate my location on a desktop?

It's a lot more simple that you think. You've signed into both your mobile and Chrome on your desktop using the same Google account. Google simply expect you will have your mobile with you most of the time. They take the location data from your phone and assume the location of your current desktop session is the same.

I proved this by RDPing into my Windows machine at home from work and checking Google maps remotely. It show my location as the same as Chrome on Linux at work.

If you don't have a mobile that is signed into Google then all they can do is lookup GeoIP data for the IP address assigned by your ISP. It will typically be wildly inaccurate.

How does the SQL injection from the "Bobby Tables" XKCD comic work?

In this case, ' is not a comment character. It's used to delimit string literals. The comic artist is banking on the idea that the school in question has dynamic sql somewhere that looks something like this:

$sql = "INSERT INTO `Students` (FirstName, LastName) VALUES ('" . $fname . "', '" . $lname . "')";

So now the ' character ends the string literal before the programmer was expecting it. Combined with the ; character to end the statement, an attacker can now add whatever sql they want. The -- comment at the end is to make sure any remaining sql in the original statement does not prevent the query from compiling on the server.

FWIW, I also think the comic in question has an important detail wrong: if you're thinking about sanitizing your database inputs, as the comic suggests, you're still doing it wrong. Instead, you should think in terms of quarantining your database inputs, and the correct way to do this is via parameterized queries.

TypeError: 'str' does not support the buffer interface

This problem commonly occurs when switching from py2 to py3. In py2 plaintext is both a string and a byte array type. In py3 plaintext is only a string, and the method outfile.write() actually takes a byte array when outfile is opened in binary mode, so an exception is raised. Change the input to plaintext.encode('utf-8') to fix the problem. Read on if this bothers you.

In py2, the declaration for file.write made it seem like you passed in a string: file.write(str). Actually you were passing in a byte array, you should have been reading the declaration like this: file.write(bytes). If you read it like this the problem is simple, file.write(bytes) needs a bytes type and in py3 to get bytes out of a str you convert it:

py3>> outfile.write(plaintext.encode('utf-8'))

Why did the py2 docs declare file.write took a string? Well in py2 the declaration distinction didn't matter because:

py2>> str==bytes         #str and bytes aliased a single hybrid class in py2
True

The str-bytes class of py2 has methods/constructors that make it behave like a string class in some ways and a byte array class in others. Convenient for file.write isn't it?:

py2>> plaintext='my string literal'
py2>> type(plaintext)
str                              #is it a string or is it a byte array? it's both!

py2>> outfile.write(plaintext)   #can use plaintext as a byte array

Why did py3 break this nice system? Well because in py2 basic string functions didn't work for the rest of the world. Measure the length of a word with a non-ASCII character?

py2>> len('¡no')        #length of string=3, length of UTF-8 byte array=4, since with variable len encoding the non-ASCII chars = 2-6 bytes
4                       #always gives bytes.len not str.len

All this time you thought you were asking for the len of a string in py2, you were getting the length of the byte array from the encoding. That ambiguity is the fundamental problem with double-duty classes. Which version of any method call do you implement?

The good news then is that py3 fixes this problem. It disentangles the str and bytes classes. The str class has string-like methods, the separate bytes class has byte array methods:

py3>> len('¡ok')       #string
3
py3>> len('¡ok'.encode('utf-8'))     #bytes
4

Hopefully knowing this helps de-mystify the issue, and makes the migration pain a little easier to bear.

How to access /storage/emulated/0/

https://productforums.google.com/forum/#!msg/nexus/WIcHUNQfRLU/ALpViG86AwAJ

Mr Expensive Toys said: Am amazed that this problem is still showing up as it started happening as far back as Honeycomb.

So, the /storage/emulated/0/DCIM/Camera is the same folder as your normal DCIM/Camera folder. Its just a symlink. So the files are actually in the right location you just have an app that put bad data into the MediaStore Database.

When accessing files from your PC your are actually enumerating the MediaStorage database for files. Its not pulling a traditional directory lists. So what you see is based on what is in that database and the path entries in the database. Files in the database pointing to emulated directories aren't shown as they are assumed to be duplicates as its the same physical directory as your normal DCIM/Camera. What is going on is that some poorly written third party apps are inserting entries into the database with the /storage/emulated/0/DCIM/Camera path instead of the proper root path to DCIM/Camera. Which means that the MTP service can't see them when you are hooked up to your PC.

Usually the easiest way to fix the problem is to just clear the MediaStore databases to get the bad entries out of the MediaStore Database and let the system reindex the files and put into the database with the proper paths.

Settings->apps Hit 3 dot menu in top right and select Show System Find Media Storage, Select it, Select Storage, then Clear Data Find External Storage, Select it , Select Storage, then Clear Data Turn phone off, turn phone back on, wait for indexer service to rebuild the data.

When you are done the files should show up with proper directory tree and be visible from the PC. Depending on amount of files on the phone it can take as 10-20 minutes to rebuild the media database as the service walks the phone directories, getting meta data, creating thumbnails, etc.

Do copyright dates need to be updated?

Copyright should be up to the date of publish.

So, if it's a static content (such as the Times article you linked to), it should probably be statically copyrighted.

If it's dynamically generated content, it should be copyrighted to the current year

Convert Base64 string to an image file?

An easy way I'm using:

file_put_contents($output_file, file_get_contents($base64_string));

This works well because file_get_contents can read data from a URI, including a data:// URI.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

A nice option is to use tar -tvvf <filePath> which adds a line that reports the kind of file.

Example in a valid .tar file:

> tar -tvvf filename.tar 
drwxr-xr-x  0 diegoreymendez staff       0 Jul 31 12:46 ./testfolder2/
-rw-r--r--  0 diegoreymendez staff      82 Jul 31 12:46 ./testfolder2/._.DS_Store
-rw-r--r--  0 diegoreymendez staff    6148 Jul 31 12:46 ./testfolder2/.DS_Store
drwxr-xr-x  0 diegoreymendez staff       0 Jul 31 12:42 ./testfolder2/testfolder/
-rw-r--r--  0 diegoreymendez staff      82 Jul 31 12:42 ./testfolder2/testfolder/._.DS_Store
-rw-r--r--  0 diegoreymendez staff    6148 Jul 31 12:42 ./testfolder2/testfolder/.DS_Store
-rw-r--r--  0 diegoreymendez staff  325377 Jul  5 09:50 ./testfolder2/testfolder/Scala.pages
Archive Format: POSIX ustar format,  Compression: none

Corrupted .tar file:

> tar -tvvf corrupted.tar 
tar: Unrecognized archive format
Archive Format: (null),  Compression: none
tar: Error exit delayed from previous errors.

Alter and Assign Object Without Side Effects

If you're using jQuery, you can use extend

myElement.id =0;
myElement.value=1;
myArray[0] = $.extend({}, myElement);

myElement.id = 2;
myElement.value = 3;
myArray[1] = $.extend({}, myElement);

FIX CSS <!--[if lt IE 8]> in IE

    <!--[if IE]>
    <style type='text/css'>
    #header ul#h-menu li a{font-weight:normal!important}
    </style>
    <![endif]-->

will apply that style in all versions of IE.

How can I remove non-ASCII characters but leave periods and spaces using Python?

You may use the following code to remove non-English letters:

import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)

This will return

123456790 ABC#%? .()

How to hide TabPage from TabControl

private System.Windows.Forms.TabControl _tabControl;
private System.Windows.Forms.TabPage _tabPage1;
private System.Windows.Forms.TabPage _tabPage2;

...
// Initialise the controls
...

// "hides" tab page 2
_tabControl.TabPages.Remove(_tabPage2);

// "shows" tab page 2
// if the tab control does not contain tabpage2
if (! _tabControl.TabPages.Contains(_tabPage2))
{
    _tabControl.TabPages.Add(_tabPage2);
}

Java: Static Class?

There's no point in declaring the class as static. Just declare its methods static and call them from the class name as normal, like Java's Math class.

Also, even though it isn't strictly necessary to make the constructor private, it is a good idea to do so. Marking the constructor private prevents other people from creating instances of your class, then calling static methods from those instances. (These calls work exactly the same in Java, they're just misleading and hurt the readability of your code.)

Convert NSArray to NSString in Objective-C

The way I know is easy.

var NSArray_variable = NSArray_Object[n]
var stringVarible = NSArray_variable as String

n is the inner position in the array This in SWIFT Language. It might work in Objective C

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

Try

java -cp .:mail-1.4.1.jar JavaxMailHTML 

no need to have manifest file.

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Check Following : 1) Package names 2) Import Statements (import every required packages) 3) Proper set of braces ,i.e { } 4) Check Syntax too.. i.e semicolons,commas,etc.

How to change the remote repository for a git submodule?

These commands will do the work on command prompt without altering any files on local repository

git config --file=.gitmodules submodule.Submod.url https://github.com/username/ABC.git
git config --file=.gitmodules submodule.Submod.branch Development
git submodule sync
git submodule update --init --recursive --remote

Please look at the blog for screenshots: Changing GIT submodules URL/Branch to other URL/branch of same repository

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Select Into functionality only works for PL/SQL Block, when you use Execute immediate , oracle interprets v_query_str as a SQL Query string so you can not use into .will get keyword missing Exception. in example 2 ,we are using begin end; so it became pl/sql block and its legal.

Converting a sentence string to a string array of words in Java

You can use simple following code

String str= "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.print(words[i]+" ");

What jar should I include to use javax.persistence package in a hibernate based application?

For JPA 2.1 the javax.persistence package can be found in here:

<dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.1-api</artifactId>
   <version>1.0.0.Final</version>
</dependency>

See: hibernate-jpa-2.1-api on Maven Central The pattern seems to be to change the artefact name as the JPA version changes. If this continues new versions can be expected to arrive in Maven Central here: Hibernate JPA versions

The above JPA 2.1 APi can be used in conjunction with Hibernate 4.3.7, specifically:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>4.3.7.Final</version>
</dependency>

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

I solved problem by this : NoSSLv3SocketFactory.java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class NoSSLv3SocketFactory extends SSLSocketFactory {
    private final SSLSocketFactory delegate;

    public NoSSLv3SocketFactory() {
        this.delegate = HttpsURLConnection.getDefaultSSLSocketFactory();
    }

    public NoSSLv3SocketFactory(SSLSocketFactory delegate) {
        this.delegate = delegate;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    private Socket makeSocketSafe(Socket socket) {
        if (socket instanceof SSLSocket) {
            socket = new NoSSLv3SSLSocket((SSLSocket) socket);
        }
        return socket;
    }

    @Override
    public Socket createSocket(Socket s, String host, int port,
            boolean autoClose) throws IOException {
        return makeSocketSafe(delegate.createSocket(s, host, port, autoClose));
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException {
        return makeSocketSafe(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost,
            int localPort) throws IOException {
        return makeSocketSafe(delegate.createSocket(host, port, localHost,
                localPort));
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return makeSocketSafe(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port,
            InetAddress localAddress, int localPort) throws IOException {
        return makeSocketSafe(delegate.createSocket(address, port,
                localAddress, localPort));
    }

    private class NoSSLv3SSLSocket extends DelegateSSLSocket {

        private NoSSLv3SSLSocket(SSLSocket delegate) {
            super(delegate);

        }

        @Override
        public void setEnabledProtocols(String[] protocols) {
            if (protocols != null && protocols.length == 1
                    && "SSLv3".equals(protocols[0])) {

                List<String> enabledProtocols = new ArrayList<String>(
                        Arrays.asList(delegate.getEnabledProtocols()));
                if (enabledProtocols.size() > 1) {
                    enabledProtocols.remove("SSLv3");
                    System.out.println("Removed SSLv3 from enabled protocols");
                } else {
                    System.out.println("SSL stuck with protocol available for "
                            + String.valueOf(enabledProtocols));
                }
                protocols = enabledProtocols
                        .toArray(new String[enabledProtocols.size()]);
            }

//          super.setEnabledProtocols(protocols);
            super.setEnabledProtocols(new String[]{"TLSv1.2"});
        }
    }

    public class DelegateSSLSocket extends SSLSocket {

        protected final SSLSocket delegate;

        DelegateSSLSocket(SSLSocket delegate) {
            this.delegate = delegate;
        }

        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }

        @Override
        public String[] getEnabledCipherSuites() {
            return delegate.getEnabledCipherSuites();
        }

        @Override
        public void setEnabledCipherSuites(String[] suites) {
            delegate.setEnabledCipherSuites(suites);
        }

        @Override
        public String[] getSupportedProtocols() {
            return delegate.getSupportedProtocols();
        }

        @Override
        public String[] getEnabledProtocols() {
            return delegate.getEnabledProtocols();
        }

        @Override
        public void setEnabledProtocols(String[] protocols) {
            delegate.setEnabledProtocols(protocols);
        }

        @Override
        public SSLSession getSession() {
            return delegate.getSession();
        }

        @Override
        public void addHandshakeCompletedListener(
                HandshakeCompletedListener listener) {
            delegate.addHandshakeCompletedListener(listener);
        }

        @Override
        public void removeHandshakeCompletedListener(
                HandshakeCompletedListener listener) {
            delegate.removeHandshakeCompletedListener(listener);
        }

        @Override
        public void startHandshake() throws IOException {
            delegate.startHandshake();
        }

        @Override
        public void setUseClientMode(boolean mode) {
            delegate.setUseClientMode(mode);
        }

        @Override
        public boolean getUseClientMode() {
            return delegate.getUseClientMode();
        }

        @Override
        public void setNeedClientAuth(boolean need) {
            delegate.setNeedClientAuth(need);
        }

        @Override
        public void setWantClientAuth(boolean want) {
            delegate.setWantClientAuth(want);
        }

        @Override
        public boolean getNeedClientAuth() {
            return delegate.getNeedClientAuth();
        }

        @Override
        public boolean getWantClientAuth() {
            return delegate.getWantClientAuth();
        }

        @Override
        public void setEnableSessionCreation(boolean flag) {
            delegate.setEnableSessionCreation(flag);
        }

        @Override
        public boolean getEnableSessionCreation() {
            return delegate.getEnableSessionCreation();
        }

        @Override
        public void bind(SocketAddress localAddr) throws IOException {
            delegate.bind(localAddr);
        }

        @Override
        public synchronized void close() throws IOException {
            delegate.close();
        }

        @Override
        public void connect(SocketAddress remoteAddr) throws IOException {
            delegate.connect(remoteAddr);
        }

        @Override
        public void connect(SocketAddress remoteAddr, int timeout)
                throws IOException {
            delegate.connect(remoteAddr, timeout);
        }

        @Override
        public SocketChannel getChannel() {
            return delegate.getChannel();
        }

        @Override
        public InetAddress getInetAddress() {
            return delegate.getInetAddress();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return delegate.getInputStream();
        }

        @Override
        public boolean getKeepAlive() throws SocketException {
            return delegate.getKeepAlive();
        }

        @Override
        public InetAddress getLocalAddress() {
            return delegate.getLocalAddress();
        }

        @Override
        public int getLocalPort() {
            return delegate.getLocalPort();
        }

        @Override
        public SocketAddress getLocalSocketAddress() {
            return delegate.getLocalSocketAddress();
        }

        @Override
        public boolean getOOBInline() throws SocketException {
            return delegate.getOOBInline();
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            return delegate.getOutputStream();
        }

        @Override
        public int getPort() {
            return delegate.getPort();
        }

        @Override
        public synchronized int getReceiveBufferSize() throws SocketException {
            return delegate.getReceiveBufferSize();
        }

        @Override
        public SocketAddress getRemoteSocketAddress() {
            return delegate.getRemoteSocketAddress();
        }

        @Override
        public boolean getReuseAddress() throws SocketException {
            return delegate.getReuseAddress();
        }

        @Override
        public synchronized int getSendBufferSize() throws SocketException {
            return delegate.getSendBufferSize();
        }

        @Override
        public int getSoLinger() throws SocketException {
            return delegate.getSoLinger();
        }

        @Override
        public synchronized int getSoTimeout() throws SocketException {
            return delegate.getSoTimeout();
        }

        @Override
        public boolean getTcpNoDelay() throws SocketException {
            return delegate.getTcpNoDelay();
        }

        @Override
        public int getTrafficClass() throws SocketException {
            return delegate.getTrafficClass();
        }

        @Override
        public boolean isBound() {
            return delegate.isBound();
        }

        @Override
        public boolean isClosed() {
            return delegate.isClosed();
        }

        @Override
        public boolean isConnected() {
            return delegate.isConnected();
        }

        @Override
        public boolean isInputShutdown() {
            return delegate.isInputShutdown();
        }

        @Override
        public boolean isOutputShutdown() {
            return delegate.isOutputShutdown();
        }

        @Override
        public void sendUrgentData(int value) throws IOException {
            delegate.sendUrgentData(value);
        }

        @Override
        public void setKeepAlive(boolean keepAlive) throws SocketException {
            delegate.setKeepAlive(keepAlive);
        }

        @Override
        public void setOOBInline(boolean oobinline) throws SocketException {
            delegate.setOOBInline(oobinline);
        }

        @Override
        public void setPerformancePreferences(int connectionTime, int latency,
                int bandwidth) {
            delegate.setPerformancePreferences(connectionTime, latency,
                    bandwidth);
        }

        @Override
        public synchronized void setReceiveBufferSize(int size)
                throws SocketException {
            delegate.setReceiveBufferSize(size);
        }

        @Override
        public void setReuseAddress(boolean reuse) throws SocketException {
            delegate.setReuseAddress(reuse);
        }

        @Override
        public synchronized void setSendBufferSize(int size)
                throws SocketException {
            delegate.setSendBufferSize(size);
        }

        @Override
        public void setSoLinger(boolean on, int timeout) throws SocketException {
            delegate.setSoLinger(on, timeout);
        }

        @Override
        public synchronized void setSoTimeout(int timeout)
                throws SocketException {
            delegate.setSoTimeout(timeout);
        }

        @Override
        public void setTcpNoDelay(boolean on) throws SocketException {
            delegate.setTcpNoDelay(on);
        }

        @Override
        public void setTrafficClass(int value) throws SocketException {
            delegate.setTrafficClass(value);
        }

        @Override
        public void shutdownInput() throws IOException {
            delegate.shutdownInput();
        }

        @Override
        public void shutdownOutput() throws IOException {
            delegate.shutdownOutput();
        }

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

        @Override
        public boolean equals(Object o) {
            return delegate.equals(o);
        }
    }
}

Main class :

URL url = new URL("https://www.example.com/test.png");
URLConnection l_connection = null;
SSLContext sslcontext = SSLContext.getInstance("TLSv1.2");
sslcontext.init(null, null, null);
SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());

package R does not exist

R.java is an autogenerated file, it usually does not get compiled if you have errors in xml file.

No You cannot write your own R.java file, it has to be generated by the resource compiler.

Check for errors in all your xml files.

Start redis-server with config file

Okay, redis is pretty user friendly but there are some gotchas.

Here are just some easy commands for working with redis on Ubuntu:

install:

sudo apt-get install redis-server

start with conf:

sudo redis-server <path to conf>
sudo redis-server config/redis.conf

stop with conf:

redis-ctl shutdown

(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)

log:

tail -f /var/log/redis/redis-server.log

Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:

/etc/redis/redis.conf

Then paste it at <path to conf>, tweak as needed and you're good to go.

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

In my case I was using the MailMessage constructor that takes two strings (to, from) and getting the same error. When I used the default constructor and then added a MailAddress object to the To property of the MailMessage it worked fine.

Hide Button After Click (With Existing Form on Page)

Here is another solution using Jquery I find it a little easier and neater than inline JS sometimes.

    <html>
    <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script>

        /* if you prefer to functionize and use onclick= rather then the .on bind
        function hide_show(){
            $(this).hide();
            $("#hidden-div").show();
        }
        */

        $(function(){
            $("#chkbtn").on('click',function() {
                $(this).hide();
                $("#hidden-div").show();
            }); 
        });
    </script>
    <style>
    .hidden-div {
        display:none
    }
    </style>
    </head>
    <body>
    <div class="reform">
        <form id="reform" action="action.php" method="post" enctype="multipart/form-data">
        <input type="hidden" name="type" value="" />
            <fieldset>
                content here...
            </fieldset>

                <div class="hidden-div" id="hidden-div">

            <fieldset>
                more content here that is hidden until the button below is clicked...
            </fieldset>
        </form>
                </div>
                <span style="display:block; padding-left:640px; margin-top:10px;"><button id="chkbtn">Check Availability</button></span>
    </div>
    </body>
    </html>

How to check String in response body with mockMvc

One possible approach is to simply include gson dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

and parse the value to make your verifications:

@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private HelloService helloService;

    @Before
    public void before() {
        Mockito.when(helloService.message()).thenReturn("hello world!");
    }

    @Test
    public void testMessage() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/"))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON_VALUE))
                .andReturn();

        String responseBody = mvcResult.getResponse().getContentAsString();
        ResponseDto responseDto
                = new Gson().fromJson(responseBody, ResponseDto.class);
        Assertions.assertThat(responseDto.message).isEqualTo("hello world!");
    }
}

Provisioning Profiles menu item missing from Xcode 5

Stupid as it may sound but all "Provisioning Profiles" re-appear under "Organizer - Devices" once you connect a real device.

What is the most efficient/elegant way to parse a flat table into a tree?

This was written quickly, and is neither pretty nor efficient (plus it autoboxes alot, converting between int and Integer is annoying!), but it works.

It probably breaks the rules since I'm creating my own objects but hey I'm doing this as a diversion from real work :)

This also assumes that the resultSet/table is completely read into some sort of structure before you start building Nodes, which wouldn't be the best solution if you have hundreds of thousands of rows.

public class Node {

    private Node parent = null;

    private List<Node> children;

    private String name;

    private int id = -1;

    public Node(Node parent, int id, String name) {
        this.parent = parent;
        this.children = new ArrayList<Node>();
        this.name = name;
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public void addChild(Node child) {
        children.add(child);
    }

    public List<Node> getChildren() {
        return children;
    }

    public boolean isRoot() {
        return (this.parent == null);
    }

    @Override
    public String toString() {
        return "id=" + id + ", name=" + name + ", parent=" + parent;
    }
}

public class NodeBuilder {

    public static Node build(List<Map<String, String>> input) {

        // maps id of a node to it's Node object
        Map<Integer, Node> nodeMap = new HashMap<Integer, Node>();

        // maps id of a node to the id of it's parent
        Map<Integer, Integer> childParentMap = new HashMap<Integer, Integer>();

        // create special 'root' Node with id=0
        Node root = new Node(null, 0, "root");
        nodeMap.put(root.getId(), root);

        // iterate thru the input
        for (Map<String, String> map : input) {

            // expect each Map to have keys for "id", "name", "parent" ... a
            // real implementation would read from a SQL object or resultset
            int id = Integer.parseInt(map.get("id"));
            String name = map.get("name");
            int parent = Integer.parseInt(map.get("parent"));

            Node node = new Node(null, id, name);
            nodeMap.put(id, node);

            childParentMap.put(id, parent);
        }

        // now that each Node is created, setup the child-parent relationships
        for (Map.Entry<Integer, Integer> entry : childParentMap.entrySet()) {
            int nodeId = entry.getKey();
            int parentId = entry.getValue();

            Node child = nodeMap.get(nodeId);
            Node parent = nodeMap.get(parentId);
            parent.addChild(child);
        }

        return root;
    }
}

public class NodePrinter {

    static void printRootNode(Node root) {
        printNodes(root, 0);
    }

    static void printNodes(Node node, int indentLevel) {

        printNode(node, indentLevel);
        // recurse
        for (Node child : node.getChildren()) {
            printNodes(child, indentLevel + 1);
        }
    }

    static void printNode(Node node, int indentLevel) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < indentLevel; i++) {
            sb.append("\t");
        }
        sb.append(node);

        System.out.println(sb.toString());
    }

    public static void main(String[] args) {

        // setup dummy data
        List<Map<String, String>> resultSet = new ArrayList<Map<String, String>>();
        resultSet.add(newMap("1", "Node 1", "0"));
        resultSet.add(newMap("2", "Node 1.1", "1"));
        resultSet.add(newMap("3", "Node 2", "0"));
        resultSet.add(newMap("4", "Node 1.1.1", "2"));
        resultSet.add(newMap("5", "Node 2.1", "3"));
        resultSet.add(newMap("6", "Node 1.2", "1"));

        Node root = NodeBuilder.build(resultSet);
        printRootNode(root);

    }

    //convenience method for creating our dummy data
    private static Map<String, String> newMap(String id, String name, String parentId) {
        Map<String, String> row = new HashMap<String, String>();
        row.put("id", id);
        row.put("name", name);
        row.put("parent", parentId);
        return row;
    }
}

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

Importing json file in TypeScript

Often in Node.js applications a .json is needed. With TypeScript 2.9, --resolveJsonModule allows for importing, extracting types from and generating .json files.

Example #

_x000D_
_x000D_
// tsconfig.json_x000D_
_x000D_
{_x000D_
    "compilerOptions": {_x000D_
        "module": "commonjs",_x000D_
        "resolveJsonModule": true,_x000D_
        "esModuleInterop": true_x000D_
    }_x000D_
}_x000D_
_x000D_
// .ts_x000D_
_x000D_
import settings from "./settings.json";_x000D_
_x000D_
settings.debug === true;  // OK_x000D_
settings.dry === 2;  // Error: Operator '===' cannot be applied boolean and number_x000D_
_x000D_
_x000D_
// settings.json_x000D_
_x000D_
{_x000D_
    "repo": "TypeScript",_x000D_
    "dry": false,_x000D_
    "debug": false_x000D_
}
_x000D_
_x000D_
_x000D_ by: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

How to use paginator from material angular?

The tricky part here is to handle is the page event. We can follow angular material documentation up to defining page event function.

Visit https://material.angular.io/components/paginator/examples for the reference.

I will add my work with hours of hard work in this regard. in the relevant HTML file should look like as follows,

<pre>
<mat-paginator
    [pageSizeOptions]="pageSizeOptions"
    [pageSize]="Size"
    (page)="pageEvent = pageNavigations($event)"
    [length]="recordCount">
</mat-paginator>
</pre>

Then go to the relevant typescript file and following code,

declarations,

@Input('data') customers: Observable<Customer[]>;
pageEvent: PageEvent;
Page: number=0;
Size: number=2;
recordCount: number;
pageSizeOptions: number[] = [2,3,4,5];

The key part of page navigation as follows,

pageNavigations(event? : PageEvent){
    console.log(event);
    this.Page = event.pageIndex;
    this.Size = event.pageSize;
    this.reloadData();
  }

We require the following function to call data from the backend.

reloadData() {

    this.customers = this.customerService.setPageSize(this.Page ,this.Size);
    this.customerService.getSize().subscribe(res => {
      this.recordCount = Number(res);
     
      console.log(this.recordCount);
    });
  }

Before the aforementioned implementation, our services file should contain the following service call

setPageSize(page: number, size: number): Observable<any> {
    return this.http.get(`${this.baseUrl}?pageSize=${size}&pageNo=${page}`);
  }

Then all set to go and enable pagination in our app. Feel free to ask related questions thank you.

Good PHP ORM Library?

Doctrine is probably your best bet. Prior to Doctrine, DB_DataObject was essentially the only other utility that was open sourced.

MySQL remove all whitespaces from the entire column

Using below query you can remove leading and trailing whitespace in a MySQL.

UPDATE `table_name`
SET `col_name` = TRIM(`col_name`);

Checkout subdirectories in Git?

You can't checkout a single directory of a repository because the entire repository is handled by the single .git folder in the root of the project instead of subversion's myriad of .svn directories.

The problem with working on plugins in a single repository is that making a commit to, e.g., mytheme will increment the revision number for myplugin, so even in subversion it is better to use separate repositories.

The subversion paradigm for sub-projects is svn:externals which translates somewhat to submodules in git (but not exactly in case you've used svn:externals before.)

Why would anybody use C over C++?

Because they're writing a plugin and C++ has no standard ABI.

CSS z-index not working (position absolute)

How about this?

http://jsfiddle.net/P7c9q/4/

<div class="relative">
  <div class="yellow-div"></div>
  <div class="yellow-div"></div>
  <div class="absolute"></div>
</div>

.relative{
position:relative;
}

.absolute {
position:absolute;
width: 40px;
height: 100px;
background: #000;
z-index: 1;
top:30px;
left:0px;
}
.yellow-div {
position:relative;
width: 200px;
height: 50px;
background: yellow;
margin-bottom:4px;
z-index:0;
}

use the relative div as wrapper and let the yellow div's have normal positioning.

Only the black block need to have an absolute position then.

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

How to create a new instance from a class object in Python

This is how you can dynamically create a class named Child in your code, assuming Parent already exists... even if you don't have an explicit Parent class, you could use object...

The code below defines __init__() and then associates it with the class.

>>> child_name = "Child"
>>> child_parents = (Parent,)
>>> child body = """
def __init__(self, arg1):
    # Initialization for the Child class
    self.foo = do_something(arg1)
"""
>>> child_dict = {}
>>> exec(child_body, globals(), child_dict)
>>> childobj = type(child_name, child_parents, child_dict)
>>> childobj.__name__
'Child'
>>> childobj.__bases__
(<type 'object'>,)
>>> # Instantiating the new Child object...
>>> childinst = childobj()
>>> childinst
<__main__.Child object at 0x1c91710>
>>>

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

1) You can use an Align widget, with FractionalOffset.bottomCenter.

2) You can also set left: 0.0 and right: 0.0 in the Positioned.

Fast check for NaN in NumPy

I think np.isnan(np.min(X)) should do what you want.

How do I insert datetime value into a SQLite database?

The format you need is:

'2007-01-01 10:00:00'

i.e. yyyy-MM-dd HH:mm:ss

If possible, however, use a parameterised query as this frees you from worrying about the formatting details.

C Linking Error: undefined reference to 'main'

You should provide output file name after -o option. In your case runexp.o is treated as output file name, not input object file and thus your main function is undefined.

How to use BigInteger?

java.math.BigInteger is an immutable class so we can not assign new object in the location of already assigned object. But you can create new object to assign new value like:

sum = sum.add(BigInteger.valueOf(i));

Print: Entry, ":CFBundleIdentifier", Does Not Exist

the 0.44 is ok to run,but 0.45 can not,maybe is the version problem i solved this by the following command: rninit init TaxiApp --source [email protected];

SQL Combine Two Columns in Select Statement

If your address1 = '123 Center St' and address2 = 'Apt 3B' then even if you combine and do a LIKE, you cannot search on searchstring as 'Center St 3B'. However, if your searchstring was 'Center St Apt', then you can do it using -

WHERE (address1 + ' ' + address2) LIKE '%searchstring%'

Alternative to file_get_contents?

If you have it available, using curl is your best option.

You can see if it is enabled by doing phpinfo() and searching the page for curl.

If it is enabled, try this:

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, SITE_PATH . 'cms/data.php');
$xml_file = curl_exec($curl_handle);
curl_close($curl_handle);

How can I sharpen an image in OpenCV?

One general procedure is laid out in the Wikipedia article on unsharp masking:

You use a Gaussian smoothing filter and subtract the smoothed version from the original image (in a weighted way so the values of a constant area remain constant).

To get a sharpened version of frame into image: (both cv::Mat)

cv::GaussianBlur(frame, image, cv::Size(0, 0), 3);
cv::addWeighted(frame, 1.5, image, -0.5, 0, image);

The parameters there are something you need to adjust for yourself.

There's also Laplacian sharpening, you should find something on that when you google.

Storing database records into array

$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();

// look through query
while($row = mysql_fetch_assoc($query)){

  // add each row returned into an array
  $array[] = $row;
  $c++;
}

for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}

how to use DEXtoJar

  1. Download Dex2jar and Extract it.
  2. Go to Download path ./d2j-dex2jar.sh /path-to-your/someApk.apk if .sh is not compilable, update the permission: chmod a+x d2j-dex2jar.sh.
  3. It will generate .jar file.
  4. Now use the jar with JD-GUI to decompile it

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

Start/Stop and Restart Jenkins service on Windows

To stop Jenkins Please avoid shutting down the Java process or the Windows service. These are not usual commands. Use those only if your Jenkins is causing problems.

Use Jenkins' way to stop that protects from data loss.

http://[jenkins-server]/[command]

where [command] can be any one of the following

  • exit
  • restart
  • reload

Example: if my local PC is running Jenkins at port 8080, it will be

http://localhost:8080/exit

Postgresql 9.2 pg_dump version mismatch

If you have docker installed you can do something like:

$ docker run postgres:9.2 pg_dump books > books.out

That will download the Docker container with Postgres 9.2 in it, run pg_dump inside of the container, and write the output.

javascript: using a condition in switch case

You can use fall-through method in switch case.

const x = 'Welcome';

switch (x) {
  case 'Come':
    console.log(1)
    break;

  case 'Welcome':
  case 'Wel':
  case 'come':
    console.log(2)
    break;

  case 'Wel':
    console.log(3)
    break;

  default:
    break;
}

    
> Result => 2

How to make a progress bar

I was writing up an answer to a similar question that got deleted, so I'm posting it here in case it's of use to anyone.

The markup can be dropped in anywhere and takes up 50px of vertical real estate even when hidden. (To have it take up no vertical space and instead overlay the top 50px, we can just give the progressContainerDiv absolute positioning (inside any positioned element) and style the display property instead of the visible property.)

The general structure is based on code presented in this Geeks for Geeks article.

_x000D_
_x000D_
const_x000D_
  progressContainerDiv = document.getElementById("progressContainerDiv");_x000D_
  progressShownDiv = document.getElementById("progressShownDiv");_x000D_
let_x000D_
  progress = 0,_x000D_
  percentageIncrease = 10;_x000D_
_x000D_
function animateProgress(){_x000D_
  progressContainerDiv.style.visibility = "visible";_x000D_
  const repeater = setInterval(increaseRepeatedly, 100);_x000D_
  function increaseRepeatedly(){_x000D_
    if(progress >= 100){_x000D_
      clearInterval(repeater);_x000D_
      progressContainerDiv.style.visibility = "hidden";_x000D_
      progressNumberSpan.innerHTML = "";_x000D_
      progress = 1;_x000D_
    }_x000D_
    else{_x000D_
      progress = Math.min(100, progress + percentageIncrease);_x000D_
      progressShownDiv.style.width = progress + "%";_x000D_
      progressNumberSpan.innerHTML = progress + "%";_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
#progressContainerDiv{_x000D_
  visibility: hidden;_x000D_
  height: 40px;_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
#progressBackgroundDiv {_x000D_
  width: 50%;_x000D_
  margin-left: 24%;_x000D_
  background-color: #ddd;_x000D_
}_x000D_
  _x000D_
#progressShownDiv {_x000D_
  width: 1%;_x000D_
  height: 20px;_x000D_
  background-color: #4CAF50;_x000D_
}_x000D_
_x000D_
#progressNumberSpan{_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<div id="progressContainerDiv">_x000D_
  <div id="progressBackgroundDiv">_x000D_
    <div id="progressShownDiv"></div>_x000D_
  </div>_x000D_
  <div id="progressNumberContainerDiv">_x000D_
    <span id="progressNumberSpan"></span>_x000D_
  </div>_x000D_
</div>_x000D_
<button type="button" onclick="animateProgress()">Go</button>_x000D_
<div id="display"></div>
_x000D_
_x000D_
_x000D_

How to call a SOAP web service on Android

To call a web service from a mobile device (especially on an Android phone), I have used a very simple way to do it. I have not used any web service client API in attempt to call the web service. My approach is as follows to make a call.

  1. Create a simple HTTP connection by using the Java standard API HttpURLConnection.
  2. Form a SOAP request. (You can make help of SOAPUI to make a SOAP request.)
  3. Set doOutPut flag as true.
  4. Set HTTP header values like content-length, Content type, and User-agent. Do not forget to set Content-length value as it is a mandatory.
  5. Write entire the SOAP request to the output stream.
  6. Call the method to make a connection and receive the response (In my case I used getResonseCode).
  7. If your received response code as
    1. It means you are succeeded to call web service.
  8. Now take an input stream on the same HTTP connection and receive the string object. This string object is a SOAP response.
  9. If the response code is other than 200 then take a ErrorInput stream on same HTTPobject and receive the error if any.
  10. Parse the received response using SAXParser (in my case) or DOMParaser or any other parsing mechanism.

I have implemented this procedure for the Android phone, and it is successfully running. I am able to parse the response even if it is more than 700 KB.

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

If you want to generate a file in the Windows, then, please follow the below steps:

  1. Go to a directory where you want to save the generated file
  2. Open the command prompt on that directory
  3. Run this fsutil file createnew [filename].[extension] [# of bytes] command. For example fsutil file createnew test.pdf 999999999
  4. 95.3 MB File will be generated

Update: The generated file will not be a valid pdf file. It just holds the given size.

Why I get 411 Length required error?

When you're using HttpWebRequest and POST method, you have to set a content (or a body if you prefer) via the RequestStream. But, according to your code, using authRequest.Method = "GET" should be enough.

In case you're wondering about POST format, here's what you have to do :

ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes(serializedObject); // a json object, or xml, whatever...

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
request.Expect = "application/json";

request.GetRequestStream().Write(data, 0, data.Length);

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

Using global variables between files?

Using from your_file import * should fix your problems. It defines everything so that it is globally available (with the exception of local variables in the imports of course).

for example:

##test.py:

from pytest import *

print hello_world

and:

##pytest.py

hello_world="hello world!"

mysqld: Can't change dir to data. Server doesn't start

First run

mysqld -u root --initialize-insecure 

It will create data folder with root as user without password. Then run

mysqld.exe -u root --console

WCF error - There was no endpoint listening at

You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding, and the default value for securityMode\transport for that binding is Message.

Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration attribute:

<bindings>
  <wsHttpBinding>
    <binding name="ota2010AEndpoint" 
             .......>
      <readerQuotas maxDepth="32" ... />
        <reliableSession ordered="true" .... />
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None"
                       realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
                     establishSecurityContext="true" />
          </security>
    </binding>
  </wsHttpBinding>
</bindings>    

(Snipped parts of the config to save space in the answer).

<service name="Synxis" behaviorConfiguration="SynxisWCF">
    <endpoint address="" name="wsHttpEndpoint" 
              binding="wsHttpBinding" 
              bindingConfiguration="ota2010AEndpoint"
              contract="Synxis" />

This will then assign your defined binding (with Transport security) to the endpoint.

Delete empty lines using sed

I believe this is the easiest and fastest one:

cat file.txt | grep .

If you need to ignore all white-space lines as well then try this:

cat file.txt | grep '\S'

Example:

s="\
\
a\
 b\
\
Below is TAB:\
    \
Below is space:\
 \
c\
\
"; echo "$s" | grep . | wc -l; echo "$s" | grep '\S' | wc -l

outputs

7
5

How do I create a link to add an entry to a calendar?

The links in Dave's post are great. Just to put a few technical details about the google links into an answer here on SO:

Google Calendar Link

<a href="http://www.google.com/calendar/event?action=TEMPLATE&text=Example%20Event&dates=20131124T010000Z/20131124T020000Z&details=Event%20Details%20Here&location=123%20Main%20St%2C%20Example%2C%20NY">Add to gCal</a>

the parameters being:

  • action=TEMPLATE (required)
  • text (url encoded name of the event)
  • dates (ISO date format, startdate/enddate - must have both start and end time - the button generator will let you leave the endtime blank, but you must have one or it won't work.)
    • to use the user's timezone: 20131208T160000/20131208T180000
    • to use global time, convert to UTC, then use 20131208T160000Z/20131208T180000Z
    • all day events, you can use 20131208/20131209 - note that the button generator gets it wrong. You must use the following date as the end date for a one day all day event, or +1 day to whatever you want the end date to be.
  • details (url encoded event description/details)
  • location (url encoded location of the event - make sure it's an address google maps can read easily)

Update Feb 2018:

Here's a new link structure that seems to support the new google version of google calendar w/o requiring API interaction:

https://calendar.google.com/calendar/r/eventedit?text=My+Custom+Event&dates=20180512T230000Z/20180513T030000Z&details=For+details,+link+here:+https://example.com/tickets-43251101208&location=Garage+Boston+-+20+Linden+Street+-+Allston,+MA+02134

New base url: https://calendar.google.com/calendar/r/eventedit

New parameters:

  • text (name of the event)
  • dates (ISO date format, startdate/enddate - must have both start and end time)
    • an event w/ start/end times: 20131208T160000/20131208T180000
    • all day events, you can use 20131208/20131209 - end date must be +1 day to whatever you want the end date to be.
  • ctz (timezone such as America/New_York - leave blank to use the user's default timezone. Highly recommended to include this in almost all situations. For example, a reminder for a video conference: if three people in different timezones clicked this link and set a reminder for their "own" Tuesday at 10:00am, this would not work out well.)
  • details (url encoded event description/details)
  • location (url encoded location of the event - make sure it's an address google maps can read easily)
  • add (comma separated list of emails - adds guests to your new event)

Notes:

  • the old url structure above now redirects here
  • supports https
  • deals w/ timezones better
  • accepts + for space in addition to %20 (urlencode vs rawurlencode in php - both work)

How to get .app file of a xcode application

Under Xcode 4.5.2, you can find the .app file in this way:

  1. Select Window > Organizer in the Xcode's menu(or just press 'Shift+Command+2')
  2. Select your project on the left side of Organizer, and you will find the Derived Data path on the right side. Just click the mini arrow in the end of the path, this will open Finder at the path.
  3. In the Finder, click "Build > Products > Release", you will find the .app.

"ssl module in Python is not available" when installing package with pip3

Step by step guide to install Python 3.6 and pip3 in Ubuntu

  1. Install the necessary packages for Python and ssl: $ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev

  2. Download and unzip "Python-3.6.8.tar.xz" from https://www.python.org/ftp/python/ into your home directory.

  3. Open terminal in that directory and run: $ ./configure

  4. Build and install: $ make && sudo make install

  5. Install packages with: $ pip3 install package_name

Disclaimer: The above commands are not tested in Ubuntu 20.04 LTS.

Reading settings from app.config or web.config in .NET

You'll need to add a reference to System.Configuration in your project's references folder.

You should definitely be using the ConfigurationManager over the obsolete ConfigurationSettings.

How to fix Ora-01427 single-row subquery returns more than one row in select?

The only subquery appears to be this - try adding a ROWNUM limit to the where to be sure:

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE on the matched date.

For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.

 SELECT 
    ...
    REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
            ' ',
            '') AS WORKDATE,
    ...
 INNER JOIN T_EMPLOYEE_MS E
    ...
     LEFT OUTER JOIN T_COMPENSATION C
          ON C.I_COMPENSATEDDATE = A.I_REQDATE
          AND C.I_EMPID = A.I_EMPID
    ...

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

How do I check if a given string is a legal/valid file name under Windows?

Try to use it, and trap for the error. The allowed set may change across file systems, or across different versions of Windows. In other words, if you want know if Windows likes the name, hand it the name and let it tell you.

Convert xlsx to csv in Linux with command line

If you are OK to run Java command line then you can do it with Apache POI HSSF's Excel Extractor. It has a main method that says to be the command line extractor. This one seems to just dump everything out. They point out to this example that converts to CSV. You would have to compile it before you can run it but it too has a main method so you should not have to do much coding per se to make it work.

Another option that might fly but will require some work on the other end is to make your Excel files come to you as Excel XML Data or XML Spreadsheet of whatever MS calls that format these days. It will open a whole new world of opportunities for you to slice and dice it the way you want.

Pandas column of lists, create a row for each list element

Trying to work through Roman Pekar's solution step-by-step to understand it better, I came up with my own solution, which uses melt to avoid some of the confusing stacking and index resetting. I can't say that it's obviously a clearer solution though:

items_as_cols = df.apply(lambda x: pd.Series(x['samples']), axis=1)
# Keep original df index as a column so it's retained after melt
items_as_cols['orig_index'] = items_as_cols.index

melted_items = pd.melt(items_as_cols, id_vars='orig_index', 
                       var_name='sample_num', value_name='sample')
melted_items.set_index('orig_index', inplace=True)

df.merge(melted_items, left_index=True, right_index=True)

Output (obviously we can drop the original samples column now):

                 samples  subject  trial_num sample_num  sample
0    [1.84, 1.05, -0.66]        1          1          0    1.84
0    [1.84, 1.05, -0.66]        1          1          1    1.05
0    [1.84, 1.05, -0.66]        1          1          2   -0.66
1    [-0.24, -0.9, 0.65]        1          2          0   -0.24
1    [-0.24, -0.9, 0.65]        1          2          1   -0.90
1    [-0.24, -0.9, 0.65]        1          2          2    0.65
2    [1.15, -0.87, -1.1]        1          3          0    1.15
2    [1.15, -0.87, -1.1]        1          3          1   -0.87
2    [1.15, -0.87, -1.1]        1          3          2   -1.10
3   [-0.8, -0.62, -0.68]        2          1          0   -0.80
3   [-0.8, -0.62, -0.68]        2          1          1   -0.62
3   [-0.8, -0.62, -0.68]        2          1          2   -0.68
4    [0.91, -0.47, 1.43]        2          2          0    0.91
4    [0.91, -0.47, 1.43]        2          2          1   -0.47
4    [0.91, -0.47, 1.43]        2          2          2    1.43
5  [-1.14, -0.24, -0.91]        2          3          0   -1.14
5  [-1.14, -0.24, -0.91]        2          3          1   -0.24
5  [-1.14, -0.24, -0.91]        2          3          2   -0.91

JavaScript - populate drop down list with array

You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:

// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?

See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.

LEFT JOIN only first row

Version without subselect:

   SELECT f.title,
          f.content,
          MIN(a.artist_name) artist_name
     FROM feeds f
LEFT JOIN feeds_artists fa ON fa.feed_id = f.id
LEFT JOIN artists a ON fa.artist_id = a.artist_id
 GROUP BY f.id

jQuery: Scroll down page a set increment (in pixels) on click?

You might be after something that the scrollTo plugin from Ariel Flesler does really well.

http://demos.flesler.com/jquery/scrollTo/

Is Spring annotation @Controller same as @Service?

You can declare a @service as @Controller.

You can NOT declare an @Controller as @Service

@Service

It is regular. You are just declaring class as a Component.

@Controller

It is a little more special than Component. The dispatcher will search for @RequestMapping here. So a class annotated with @Controller, will be additionally empowered with declaring URLs through which APIs are called

How can I add new dimensions to a Numpy array?

You can use np.concatenate() specifying which axis to append, using np.newaxis:

import numpy as np
movie = np.concatenate((img1[:,np.newaxis], img2[:,np.newaxis]), axis=3)

If you are reading from many files:

import glob
movie = np.concatenate([cv2.imread(p)[:,np.newaxis] for p in glob.glob('*.jpg')], axis=3)

How to use a Java8 lambda to sort a stream in reverse order?

You can use a method reference:

import static java.util.Comparator.*;
import static java.util.stream.Collectors.*;

Arrays.asList(files).stream()
    .filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
    .sorted(comparing(File::lastModified).reversed())
    .skip(numOfNewestToLeave)
    .forEach(item -> item.delete());

In alternative of method reference you can use a lambda expression, so the argument of comparing become:

.sorted(comparing(file -> file.lastModified()).reversed());

calling another method from the main method in java

You can do it multiple ways. Here are two. Cheers!

package learningjava;

public class helloworld {
    public static void main(String[] args) {
        new helloworld().go();
        // OR
        helloworld.get();
    }

    public void go(){
        System.out.println("Hello World");
    }
    public static void get(){
        System.out.println("Hello World, Again");
    }
}

Colors in JavaScript console

// log in color 
// consolelog({"color":"red","background-color":"blue"},1,2,3)

// consolelog({"color":"red"},1,2,3)
// consolelog(1,2,3)
function consolelog()
{
    var style=Array.prototype.slice.call(arguments,0,1)||["black"];
    var vars=(Array.prototype.slice.call(arguments,1)||[""])
    var message=vars.join(" ")
    var colors = 
        {
            warn:
                {
                    "background-color"  :"yellow",
                    "color"             :"red"
                },
            error:
                {
                    "background-color"  :"red",
                    "color"             :"yellow"
                },
            highlight:
                {
                    "background-color"  :"yellow",
                    "color"             :"black"
                },
            success : "green", 
            info    : "dodgerblue"  

        }
    var givenstyle=style[0];
    var colortouse= colors[givenstyle] || givenstyle;
    if(typeof colortouse=="object")
    {
        colortouse= printobject(colortouse)
    }
    if(colortouse)
    {
        colortouse=(colortouse.match(/\W/)?"":"color:")+colortouse;
    }
    function printobject(o){
        var str='';

        for(var p in o){
            if(typeof o[p] == 'string'){
                str+= p + ': ' + o[p]+'; \n';
            }else{
            str+= p + ': { \n' + print(o[p]) + '}';
            }
        }

        return str;
    }
    if(colortouse)
    {
        console.log("%c" + message, colortouse);
    }
    else
    {
        console.log.apply(null,vars);
    }
}
console.logc=consolelog;

Angular2 *ngFor in select list, set active based on string from object

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.

View:

<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
}
class ValueAndText {
  constructor(public Value: string, public Text: string) { }
}

...
export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];

}

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

I have just copied UUID toString() method and just updated it to remove "-" from it. It will be much more faster and straight forward than any other solution

public String generateUUIDString(UUID uuid) {
    return (digits(uuid.getMostSignificantBits() >> 32, 8) +
            digits(uuid.getMostSignificantBits() >> 16, 4) +
            digits(uuid.getMostSignificantBits(), 4) +
            digits(uuid.getLeastSignificantBits() >> 48, 4) +
            digits(uuid.getLeastSignificantBits(), 12));
}

/** Returns val represented by the specified number of hex digits. */
private String digits(long val, int digits) {
    long hi = 1L << (digits * 4);
    return Long.toHexString(hi | (val & (hi - 1))).substring(1);
}

Usage:

generateUUIDString(UUID.randomUUID())

Another implementation using reflection

public String generateString(UUID uuid) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

    if (uuid == null) {
        return "";
    }

    Method digits = UUID.class.getDeclaredMethod("digits", long.class, int.class);
    digits.setAccessible(true);

    return ( (String) digits.invoke(uuid, uuid.getMostSignificantBits() >> 32, 8) +
            digits.invoke(uuid, uuid.getMostSignificantBits() >> 16, 4) +
            digits.invoke(uuid, uuid.getMostSignificantBits(), 4) +
            digits.invoke(uuid, uuid.getLeastSignificantBits() >> 48, 4) +
            digits.invoke(uuid, uuid.getLeastSignificantBits(), 12));

}

How to transfer data from JSP to servlet when submitting HTML form

Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet and inside it you will have two methods that look like

public void doPost(HttpServletRequest req, HttpServletResponse resp){

}

and

public void doGet(HttpServletRequest req, HttpServletResponse resp){

}

One of them is called to handle GET operations and another is used to handle POST operations. You will then use the HttpServletRequest object to get the parameters that were passed as part of the form like so:

String name = req.getParameter("name");

Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.

Export database schema into SQL file

Have you tried the Generate Scripts (Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?

String escape into XML

WARNING: Necromancing

Still Darin Dimitrov's answer + System.Security.SecurityElement.Escape(string s) isn't complete.

In XML 1.1, the simplest and safest way is to just encode EVERYTHING.
Like &#09; for \t.
It isn't supported at all in XML 1.0.
For XML 1.0, one possible workaround is to base-64 encode the text containing the character(s).

//string EncodedXml = SpecialXmlEscape("?????? ???");
//Console.WriteLine(EncodedXml);
//string DecodedXml = XmlUnescape(EncodedXml);
//Console.WriteLine(DecodedXml);
public static string SpecialXmlEscape(string input)
{
    //string content = System.Xml.XmlConvert.EncodeName("\t");
    //string content = System.Security.SecurityElement.Escape("\t");
    //string strDelimiter = System.Web.HttpUtility.HtmlEncode("\t"); // XmlEscape("\t"); //XmlDecode("&#09;");
    //strDelimiter = XmlUnescape("&#59;");
    //Console.WriteLine(strDelimiter);
    //Console.WriteLine(string.Format("&#{0};", (int)';'));
    //Console.WriteLine(System.Text.Encoding.ASCII.HeaderName);
    //Console.WriteLine(System.Text.Encoding.UTF8.HeaderName);


    string strXmlText = "";

    if (string.IsNullOrEmpty(input))
        return input;


    System.Text.StringBuilder sb = new StringBuilder();

    for (int i = 0; i < input.Length; ++i)
    {
        sb.AppendFormat("&#{0};", (int)input[i]);
    }

    strXmlText = sb.ToString();
    sb.Clear();
    sb = null;

    return strXmlText;
} // End Function SpecialXmlEscape

XML 1.0:

public static string Base64Encode(string plainText)
{
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
    return System.Convert.ToBase64String(plainTextBytes);
}

public static string Base64Decode(string base64EncodedData)
{
    var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
    return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

How to display special characters in PHP

In PHP there is a pretty good function utf8_encode() to solve this issue.

echo utf8_encode("Résumé");

//will output Résumé instead of R?sum?

Check the official PHP page.

Invoke(Delegate)

If you want to modify a control it must be done in the thread in which the control was created. This Invoke method allows you to execute methods in the associated thread (the thread that owns the control's underlying window handle).

In below sample thread1 throws an exception because SetText1 is trying to modify textBox1.Text from another thread. But in thread2, Action in SetText2 is executed in the thread in which the TextBox was created

private void btn_Click(object sender, EvenetArgs e)
{
    var thread1 = new Thread(SetText1);
    var thread2 = new Thread(SetText2);
    thread1.Start();
    thread2.Start();
}

private void SetText1() 
{
    textBox1.Text = "Test";
}

private void SetText2() 
{
    textBox1.Invoke(new Action(() => textBox1.Text = "Test"));
}

Change default icon

If you are using Forms you can use the icon setting in the properties pane. To do this select the form and scroll down in the properties pane till you see the icon setting. When you open the application it will have the icon wherever you have it in your application and in the task bar

Icon settings

Truncating a table in a stored procedure

try the below code

execute immediate 'truncate table tablename' ;

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

How to increase dbms_output buffer?

Here you go:

DECLARE
BEGIN
  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !
END;

What is the difference between npm install and npm run build?

NPM in 2019

npm build no longer exists. You must call npm run build now. More info below.

TLDR;

npm install: installs dependencies, then calls the install from the package.json scripts field.

npm run build: runs the build field from the package.json scripts field.


NPM Scripts Field

https://docs.npmjs.com/misc/scripts

There are many things you can put into the npm package.json scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.


To Complicate Things

  • npm install is not the same as npm run install
  • npm install installs package.json dependencies, then runs the package.json scripts.install
    • (Essentially calls npm run install after dependencies are installed.
  • npm run install only runs the package.json scripts.install, it will not install dependencies.
  • npm build used to be a valid command (used to be the same as npm run build) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build? You can read more on the documentation: https://docs.npmjs.com/cli/build

Extra Notes

There are still two top level commands that will run scripts, they are:

  • npm start which is the same as npm run start
  • npm test ==> npm run test

What is RSS and VSZ in Linux memory management

I think much has already been said, about RSS vs VSZ. From an administrator/programmer/user perspective, when I design/code applications I am more concerned about the RSZ, (Resident memory), as and when you keep pulling more and more variables (heaped) you will see this value shooting up. Try a simple program to build malloc based space allocation in loop, and make sure you fill data in that malloc'd space. RSS keeps moving up. As far as VSZ is concerned, it's more of virtual memory mapping that linux does, and one of its core features derived out of conventional operating system concepts. The VSZ management is done by Virtual memory management of the kernel, for more info on VSZ, see Robert Love's description on mm_struct and vm_struct, which are part of basic task_struct data structure in kernel.

How do I check for null values in JavaScript?

To check for null SPECIFICALLY you would use this:

if (variable === null)

This test will ONLY pass for null and will not pass for "", undefined, false, 0, or NaN.

Additionally, I've provided absolute checks for each "false-like" value (one that would return true for !variable).

Note, for some of the absolute checks, you will need to implement use of the absolutely equals: === and typeof.

I've created a JSFiddle here to show all of the individual tests working

Here is the output of each check:

Null Test:

if (variable === null)

- variable = ""; (false) typeof variable = string

- variable = null; (true) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



Empty String Test:

if (variable === '')

- variable = ''; (true) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number




Undefined Test:

if (typeof variable == "undefined")

-- or --

if (variable === undefined)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (true) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



False Test:

if (variable === false)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (true) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



Zero Test:

if (variable === 0)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (true) typeof variable = number

- variable = NaN; (false) typeof variable = number



NaN Test:

if (typeof variable == 'number' && !parseFloat(variable) && variable !== 0)

-- or --

if (isNaN(variable))

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (true) typeof variable = number

As you can see, it's a little more difficult to test against NaN;

javascript window.location in new tab

Rather going for pop up,I personally liked this solution, mentioned on this Question thread JavaScript: location.href to open in new window/tab?

$(document).on('click','span.external-link',function(){
        var t               = $(this), 
            URL             = t.attr('data-href');        
        $('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();

    });

Working example.

What is the difference between a var and val definition in Scala?

It's as simple as it name.

var means it can vary

val means invariable

Take nth column in a text file

iirc :

cat filename.txt | awk '{ print $2 $4 }'

or, as mentioned in the comments :

awk '{ print $2 $4 }' filename.txt

Creating a div element inside a div element in javascript

Your code works well you just mistyped this line of code:

document.getElementbyId('lc').appendChild(element);

change it with this: (The "B" should be capitalized.)

document.getElementById('lc').appendChild(element);  

HERE IS MY EXAMPLE:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
    var element = document.createElement("div");_x000D_
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
    document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();">  _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to animate CSS Translate

There are jQuery-plugins that help you achieve this like: http://ricostacruz.com/jquery.transit/

Excel VBA date formats

Use value(cellref) on the side to evaluate the cells. Strings will produce the "#Value" error, but dates resolve to a number (e.g. 43173).

Deleting all files from a folder using PHP?

Here is a more modern approach using the Standard PHP Library (SPL).

$dir = "path/to/directory";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
    $file->isDir() ?  rmdir($file) : unlink($file);
}
return true;

How can I find last row that contains data in a specific column?

The first line moves the cursor to the last non-empty row in the column. The second line prints that columns row.

Selection.End(xlDown).Select
MsgBox(ActiveCell.Row)

Search of table names

I am assuming you want to pass the database name as a parameter and not just run:

SELECT  *
FROM    DBName.sys.tables
WHERE   Name LIKE '%XXX%'

If so, you could use dynamic SQL to add the dbname to the query:

DECLARE @DBName NVARCHAR(200) = 'YourDBName',
        @TableName NVARCHAR(200) = 'SomeString';

IF NOT EXISTS (SELECT 1 FROM master.sys.databases WHERE Name = @DBName)
    BEGIN
        PRINT 'DATABASE NOT FOUND';
        RETURN;
    END;

DECLARE @SQL NVARCHAR(MAX) = '  SELECT  Name
                                FROM    ' + QUOTENAME(@DBName) + '.sys.tables
                                WHERE   Name LIKE ''%'' + @Table + ''%''';

EXECUTE SP_EXECUTESQL @SQL, N'@Table NVARCHAR(200)', @TableName;

What data type to use for money in Java?

I like using Tiny Types which would wrap either a double, BigDecimal, or int as previous answers have suggested. (I would use a double unless precision problems crop up).

A Tiny Type gives you type safety so you don't confused a double money with other doubles.

How to style SVG with external CSS?

You can do what you want, with one (important) caveat: the paths within your symbol can't be styled independently via external CSS -- you can only set the properties for the entire symbol with this method. So, if you have two paths in your symbol and want them to have different fill colors, this won't work, but if you want all your paths to be the same, this should work.

In your html file, you want something like this:

<style>
  .fill-red { fill: red; }
  .fill-blue { fill: blue; }
</style>

<a href="//www.example.com/">
  <svg class="fill-red">
    <use xlink:href="images/icons.svg#example"></use>
  </svg>
</a>

And in the external SVG file you want something like this:

<svg xmlns="http://www.w3.org/2000/svg">
   <symbol id="example" viewBox="0 0 256 256">
    <path d="M120.... />
  </symbol>
</svg>

Swap the class on the svg tag (in your html) from fill-red to fill-blue and ta-da... you have blue instead of red.

You can partially get around the limitation of being able to target the paths separately with external CSS by mixing and matching the external CSS with some in-line CSS on specific paths, since the in-line CSS will take precedence. This approach would work if you're doing something like a white icon against a colored background, where you want to change the color of the background via the external CSS but the icon itself is always white (or vice-versa). So, with the same HTML as before and something like this svg code, you'll get you a red background and a white foreground path:

<svg xmlns="http://www.w3.org/2000/svg">
  <symbol id="example" viewBox="0 0 256 256">
    <path class="background" d="M120..." />
    <path class="icon" style="fill: white;" d="M20..." />
  </symbol>
</svg>

How to set or change the default Java (JDK) version on OS X?

If you are using fish and you are using mac and you want to be able to switch between JDK's, then below works for me on mac.

@kenglxn's answer didn't work for me and I figured out it bcos didn't set -g which is global !

Put below under ~/.config/fish/config.fish

alias j8="jhome  -v 1.8.0_162"
alias j9="jhome  -v 9.0.1"

function jhome
    set -g -x JAVA_HOME (/usr/libexec/java_home $argv)
    echo "JAVA_HOME:" $JAVA_HOME
    echo "java -version:"
    java -version
end

funcsave jhome

To know which version /minor version you have installed, you can do :

/usr/libexec/java_home -V                                                                              579ms ? Wed 14 Feb 11:44:01 2018
Matching Java Virtual Machines (3):
    9.0.1, x86_64:  "Java SE 9.0.1" /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
    1.8.0_162, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_162.jdk/Contents/Home
    1.8.0_121, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home

Disable output buffering

You can also run Python with stdbuf utility:

stdbuf -oL python <script>

TypeError: $.browser is undefined

I did solved using this jquery for Github

<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>

Please Refer this link for more info. https://github.com/Studio-42/elFinder/issues/469

force css grid container to fill full screen of device

You can add position: fixed; with top left right bottom 0 attribute, that solution work on older browsers too.

If you want to embed it, add position: absolute; to the wrapper, and position: relative to the div outside of the wrapper.

_x000D_
_x000D_
.wrapper {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
_x000D_
  display: grid;_x000D_
  border-style: solid;_x000D_
  border-color: red;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-template-rows: repeat(3, 1fr);_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
.one {_x000D_
  border-style: solid;_x000D_
  border-color: blue;_x000D_
  grid-column: 1 / 3;_x000D_
  grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
  border-style: solid;_x000D_
  border-color: yellow;_x000D_
  grid-column: 2 / 4;_x000D_
  grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
  border-style: solid;_x000D_
  border-color: violet;_x000D_
  grid-row: 2 / 5;_x000D_
  grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
  border-style: solid;_x000D_
  border-color: aqua;_x000D_
  grid-column: 3;_x000D_
  grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
  border-style: solid;_x000D_
  border-color: green;_x000D_
  grid-column: 2;_x000D_
  grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
  border-style: solid;_x000D_
  border-color: purple;_x000D_
  grid-column: 3;_x000D_
  grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
  <div class="one">One</div>_x000D_
  <div class="two">Two</div>_x000D_
  <div class="three">Three</div>_x000D_
  <div class="four">Four</div>_x000D_
  <div class="five">Five</div>_x000D_
  <div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I find a stored procedure containing <text>?

First ensure that you're running the query under your user credentials, and also in the right database context.

USE YOUR_DATABASE_NAME;

Otherwise, sys.procedures won't return anything. Now run the query as below:

select * from sys.procedures p 
join sys.syscomments s on p.object_id = s.id 
where text like '%YOUR_TEXT%';

Another option is to use INFORMATION_SCHEMA.ROUTINES.ROUTINE_DEFINITION, but be aware that it only holds limited number of characters (i.e., first 4000 characters) of the routine.

select * from YOUR_DATABASE_NAME.INFORMATION_SCHEMA.ROUTINES
where ROUTINE_DEFINITION like '%YOUR_TEXT%';

I tested on Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

If you really don't care about props then the widest possible type is React.ReactType.

This would allow passing native dom elements as string. React.ReactType covers all of these:

renderGreeting('button');
renderGreeting(() => 'Hello, World!');
renderGreeting(class Foo extends React.Component {
   render() {
      return 'Hello, World!'
   }
});

Use of "this" keyword in C++

Either way works, but many places have coding standards in place that will guide the developer one way or the other. If such a policy is not in place, just follow your heart. One thing, though, it REALLY helps the readability of the code if you do use it. especially if you are not following a naming convention on class-level variable names.

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.

There are different types of joins available in SQL:

INNER JOIN: returns rows when there is a match in both tables.

LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.

RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.

FULL JOIN: It combines the results of both left and right outer joins.

The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.

SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.

CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.

WE can take each first four joins in Details :

We have two tables with the following values.

TableA

id  firstName                  lastName
.......................................
1   arun                        prasanth                 
2   ann                         antony                   
3   sruthy                      abc                      
6   new                         abc                                           

TableB

id2 age Place
................
1   24  kerala
2   24  usa
3   25  ekm
5   24  chennai

....................................................................

INNER JOIN

Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
 INNER JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
 INNER JOIN TableB
    ON TableA.id = TableB.id2;

Result Will Be

firstName       lastName       age  Place
..............................................
arun            prasanth        24  kerala
ann             antony          24  usa
sruthy          abc             25  ekm

LEFT JOIN

Note : will give all selected rows in TableA, plus any common selected rows in TableB.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
  LEFT JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
  LEFT JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age   Place
...............................................................................
arun                        prasanth                    24    kerala
ann                         antony                      24    usa
sruthy                      abc                         25    ekm
new                         abc                         NULL  NULL

RIGHT JOIN

Note : will give all selected rows in TableB, plus any common selected rows in TableA.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
 RIGHT JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
 RIGHT JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age     Place
...............................................................................
arun                        prasanth                    24     kerala
ann                         antony                      24     usa
sruthy                      abc                         25     ekm
NULL                        NULL                        24     chennai

FULL JOIN

Note :It will return all selected values from both tables.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
  FULL JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
  FULL JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age    Place
...............................................................................
arun                        prasanth                    24    kerala
ann                         antony                      24    usa
sruthy                      abc                         25    ekm
new                         abc                         NULL  NULL
NULL                        NULL                        24    chennai

Interesting Fact

For INNER joins the order doesn't matter

For (LEFT, RIGHT or FULL) OUTER joins,the order matter

Better to go check this Link it will give you interesting details about join order

How to open a new form from another form

Use this.Hide() instead of this.Close()

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

How can one tell the version of React running at runtime in the browser?

In an existing project a simple way to see the React version is to go to a render method of any component and add:

<p>{React.version}</p>

This assumes you import React like this: import React from 'react'

Ruby: How to turn a hash into HTTP parameters?

class Hash
  def to_params
    params = ''
    stack = []

    each do |k, v|
      if v.is_a?(Hash)
        stack << [k,v]
      elsif v.is_a?(Array)
        stack << [k,Hash.from_array(v)]
      else
        params << "#{k}=#{v}&"
      end
    end

    stack.each do |parent, hash|
      hash.each do |k, v|
        if v.is_a?(Hash)
          stack << ["#{parent}[#{k}]", v]
        else
          params << "#{parent}[#{k}]=#{v}&"
        end
      end
    end

    params.chop! 
    params
  end

  def self.from_array(array = [])
    h = Hash.new
    array.size.times do |t|
      h[t] = array[t]
    end
    h
  end

end

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Django 1.7 - makemigrations not detecting changes

Adding this answer because only this method helped me.

I deleted the migrations folder run makemigrations and migrate.
It still said: No migrations to apply.

I went to migrate folder and opened the last created file,
comment the migration I wanted(It was detected and entered there)
and run migrate again.

This basically editing the migrations file manually.
Do this only if you understand the file content.

How to enable scrolling on website that disabled scrolling?

In a browser like Chrome etc.:

  1. Inspect the code (for e.g. in Chrome press ctrl + shift + c);
  2. Set overflow: visible on body element (for e.g., <body style="overflow: visible">)
  3. Find/Remove any JavaScripts that may routinely be checking for removal of the overflow property:
    • To find such JavaScript code, you could for example, go through the code, or click on different JavaScript code in the code debugger console and hit backspace on your keyboard to remove it.
    • If you're having trouble finding it, you can simply try removing a couple of JavaScripts (you can of course simply press ctrl + z to undo whatever code you delete, or hit refresh to start over).

Good luck!

How to open Console window in Eclipse?

The easiest way is to just click on the 'Console' icon in Eclipse, like this:

enter image description here

How to ignore ansible SSH authenticity checking?

forward to nikobelia

For those who using jenkins to run the play book, I just added to my jenkins job before running the ansible-playbook the he environment variable ANSIBLE_HOST_KEY_CHECKING = False For instance this:

export ANSIBLE_HOST_KEY_CHECKING=False
ansible-playbook 'playbook.yml' \
--extra-vars="some vars..." \
--tags="tags_name..." -vv

How to add key,value pair to dictionary?

I am not sure what you mean by "dynamic". If you mean adding items to a dictionary at runtime, it is as easy as dictionary[key] = value.

If you wish to create a dictionary with key,value to start with (at compile time) then use (surprise!)

dictionary[key] = value

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

Should I use alias or alias_method?

alias_method new_method, old_method

old_method will be declared in a class or module which is being inherited now to our class where new_method will be used.

these can be variable or method both.

Suppose Class_1 has old_method, and Class_2 and Class_3 both of them inherit Class_1.

If, initialization of Class_2 and Class_3 is done in Class_1 then both can have different name in Class_2 and Class_3 and its usage.

Nginx -- static file serving confusion with root & alias

I have found answers to my confusions.

There is a very important difference between the root and the alias directives. This difference exists in the way the path specified in the root or the alias is processed.

In case of the root directive, full path is appended to the root including the location part, whereas in case of the alias directive, only the portion of the path NOT including the location part is appended to the alias.

To illustrate:

Let's say we have the config

location /static/ {
    root /var/www/app/static/;
    autoindex off;
}

In this case the final path that Nginx will derive will be

/var/www/app/static/static

This is going to return 404 since there is no static/ within static/

This is because the location part is appended to the path specified in the root. Hence, with root, the correct way is

location /static/ {
    root /var/www/app/;
    autoindex off;
}

On the other hand, with alias, the location part gets dropped. So for the config

location /static/ {
    alias /var/www/app/static/;
    autoindex off;           ?
}                            |
                             pay attention to this trailing slash

the final path will correctly be formed as

/var/www/app/static

The case of trailing slash for alias directive

There is no definitive guideline about whether a trailing slash is mandatory per Nginx documentation, but a common observation by people here and elsewhere seems to indicate that it is.

A few more places have discussed this, not conclusively though.

https://serverfault.com/questions/376162/how-can-i-create-a-location-in-nginx-that-works-with-and-without-a-trailing-slas

https://serverfault.com/questions/375602/why-is-my-nginx-alias-not-working

Hexadecimal value 0x00 is a invalid character

I also get the same error in an ASP.NET application when I saved some unicode data (Hindi) in the Web.config file and saved it with "Unicode" encoding.

It fixed the error for me when I saved the Web.config file with "UTF-8" encoding.