Programs & Examples On #Firefox addon

A Firefox add-on is a way of adding to or modifying the Firefox web browser. Most commonly, questions in this tag are about Firefox extensions, which add new functionality to the browser, although "add-on" may also refer to themes or plugins.

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

Postman addon's like in firefox

I liked PostMan, it was the main reason why I kept using Chrome, now I'm good with HttpRequester

https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search

Firefox Add-on RESTclient - How to input POST parameters?

I tried the methods mentioned in some other answers, but they look like workarounds to me. Using Firefox Add-on RESTclient to send HTTP POST requests with parameters is not straightforward in my opinion, at least for the version I'm currently using, 2.0.1.

Instead, try using other free open source tools, such as Apache JMeter. It is simple and straightforward (see the screenshot as below)

enter image description here

Convert URL to File or Blob for FileReader.readAsDataURL

This information is outdated as of now, but cannot be deleted.

  1. You can create File instances just by specifying a path when your code is chrome-privileged:

    new File("/path/to/file");
    

    File is a sub-class of Blob, so all File instances are also valid Blobs. Please note that this requires a platform path, and not a file URL.

  2. Yes, FileReader is available to addons.

File and FileReader are available in all windows. If you want to use them in a non-window scope (like bootstrap.js or a code module), you may use nsIDOMFile/nsIDOMFileReader.

.setAttribute("disabled", false); changes editable attribute to false

the disabled attributes value is actally not considered.. usually if you have noticed the attribute is set as disabled="disabled" the "disabled" here is not necessary persay.. thus the best thing to do is to remove the attribute.

element.removeAttribute("disabled");     

also you could do

element.disabled=false;

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Common sources of unterminated string literal

I've had trouble with angled quotes in the past ( ‘ ) usually from copy and pasting from Word. Replacing them with regular single quotes ( ' ) does the trick.

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

On WebStorm 2016.3

  1. Press ALT+F12 (open terminal)

  2. Run this command:

    npm install require.js
    

What is a MIME type?

MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format.

For example, using the Content-type header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.

Internet Media Type (also Content-type) is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".

A MIME type is a string identifier composed of two parts: a type and a subtype.

  • The "type" refers to a logical grouping of many MIME types that are closely related to each other; it's no more than a high level category.
  • "subtypes" are specific to one file type within the "type".

The x- prefix of a MIME subtype simply means that it's non-standard.
The vnd prefix means that the MIME value is vendor specific.

Source

Parsing JSON from XmlHttpRequest.responseJSON

I think you have to include jQuery to use responseJSON.

Without jQuery, you could try with responseText and try like eval("("+req.responseText+")");

UPDATE:Please read the comment regarding eval, you can test with eval, but don't use it in working extension.

OR

use json_parse : it does not use eval

Remap values in pandas column with a dict

Adding to this question if you ever have more than one columns to remap in a data dataframe:

def remap(data,dict_labels):
    """
    This function take in a dictionnary of labels : dict_labels 
    and replace the values (previously labelencode) into the string.

    ex: dict_labels = {{'col1':{1:'A',2:'B'}}

    """
    for field,values in dict_labels.items():
        print("I am remapping %s"%field)
        data.replace({field:values},inplace=True)
    print("DONE")

    return data

Hope it can be useful to someone.

Cheers

Get unique values from arraylist in java

If you have an array of a some kind of object (bean) you can do this:

List<aBean> gasList = createDuplicateGasBeans();
Set<aBean> uniqueGas = new HashSet<aBean>(gasList);

like said Mathias Schwarz above, but you have to provide your aBean with the methods hashCode() and equals(Object obj) that can be done easily in Eclipse by dedicated menu 'Generate hashCode() and equals()' (while in the bean Class). Set will evaluate the overridden methods to discriminate equals objects.

Pass a variable to a PHP script running from the command line

Parameters send by index like other applications:

php myfile.php type=daily

And then you can get them like this:

<?php
    if (count($argv) == 0) 
        exit;

    foreach ($argv as $arg)
        echo $arg;
?>

Center a button in a Linear layout

You can also set the width of the LinearLayout to wrap_content and use android:layout_centerInParent, android:layout_centerVertical="true":

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
>

<ImageButton android:id="@+id/btnFindMe" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"       
    android:background="@drawable/findme"/>

How can I select the first day of a month in SQL?

If you are looking at this today, and using SQL server 2012 or newer you have the EOMONTH function which makes things easier:

SELECT DATEADD(day, 1, EOMONTH(DATEADD(month, -1, GETDATE()))) as firstdateofmonth

You can change GETDATE() with whatever date variable you want.

Suppress console output in PowerShell

Try redirecting the output like this:

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1

How to execute a function when page has fully loaded?

In modern browsers with modern javascript (>= 2015) you can add type="module" to your script tag, and everything inside that script will execute after whole page loads. e.g:

<script type="module">
  alert("runs after") // Whole page loads before this line execute
</script>
<script>
  alert("runs before")
</script>

also older browsers will understand nomodule attribute. Something like this:

<script nomodule>
  alert("tuns after")
</script>

For more information you can visit javascript.info.

html - table row like a link

This saves you having to duplicate the link in the tr - just fish it out of the first a.

$(".link-first-found").click(function() {
 var href;
href = $(this).find("a").attr("href");
if (href !== "") {
return document.location = href;
}
});

Passing an array by reference in C?

The C language does not support pass by reference of any type. The closest equivalent is to pass a pointer to the type.

Here is a contrived example in both languages

C++ style API

void UpdateValue(int& i) {
  i = 42;
}

Closest C equivalent

void UpdateValue(int *i) {
  *i = 42;
}

Return Boolean Value on SQL Select Statement

Use 'Exists' which returns either 0 or 1.

The query will be like:

SELECT EXISTS(SELECT * FROM USER WHERE UserID = 20070022)

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

Unfortunately the web.config setting is ignored by the default JsonResult implementation. So I guess you will need to implement a custom json result to overcome this issue.

How to pass object from one component to another in Angular 2?

you could also store your data in an service with an setter and get it over a getter

import { Injectable } from '@angular/core';

@Injectable()
export class StorageService {

    public scope: Array<any> | boolean = false;

    constructor() {
    }

    public getScope(): Array<any> | boolean {
        return this.scope;
    }

    public setScope(scope: any): void {
        this.scope = scope;
    }
}

Find a string within a cell using VBA

For a search routine you should look to use Find, AutoFilter or variant array approaches. Range loops are nomally too slow, worse again if they use Select

The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2 which you can then further process

Option Explicit

Const strText As String = "%"

Sub ColSearch_DelRows()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim cel1 As Range
    Dim cel2 As Range
    Dim strFirstAddress As String
    Dim lAppCalc As Long


    'Get working range from user
    On Error Resume Next
    Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub

    With Application
        lAppCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)

    'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
    If Not cel1 Is Nothing Then
        Set rng2 = cel1
        strFirstAddress = cel1.Address
        Do
            Set cel1 = rng1.FindNext(cel1)
            Set rng2 = Union(rng2, cel1)
        Loop While strFirstAddress <> cel1.Address
    End If

    If Not rng2 Is Nothing Then
        For Each cel2 In rng2
            Debug.Print cel2.Address & " contained " & strText
        Next
    Else
        MsgBox "No " & strText
    End If

    With Application
        .ScreenUpdating = True
        .Calculation = lAppCalc
    End With

End Sub

How do I resolve "Run-time error '429': ActiveX component can't create object"?

The file msrdo20.dll is missing from the installation.

According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.

I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:

regsvr32 c:\windows\system32\msrdo20.dll

In an ideal world you would package this up with the redistributable.

How do you make an array of structs in C?

Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.

Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:

typedef struct
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
}Body;

Then declare your array of structs. Initialization of each element goes along with the declaration:

Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};

To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.

Can I set state inside a useEffect hook

Generally speaking, using setState inside useEffect will create an infinite loop that most likely you don't want to cause. There are a couple of exceptions to that rule which I will get into later.

useEffect is called after each render and when setState is used inside of it, it will cause the component to re-render which will call useEffect and so on and so on.

One of the popular cases that using useState inside of useEffect will not cause an infinite loop is when you pass an empty array as a second argument to useEffect like useEffect(() => {....}, []) which means that the effect function should be called once: after the first mount/render only. This is used widely when you're doing data fetching in a component and you want to save the request data in the component's state.

Difference between classification and clustering in data mining?

Classification

Is the assignment of predefined classes to new observations, based on learning from examples.

It is one of the key tasks in machine learning.

Clustering (or Cluster Analysis)

While popularly dismissed as "unsupervised classification" it is quite different.

In contrast to what many machine learners will teach you, it is not about assigning "classes" to objects, but without having them predefined. This is the very limited view of people who did too much classification; a typical example of if you have a hammer (classifier), everything looks like a nail (classification problem) to you. But it is also why classification people do not get a hang of clustering.

Instead, consider it as structure discovery. The task of clustering is to find structure (e.g. groups) in your data that you did not know before. Clustering has been successful if you learned something new. It failed, if you only got the structure you already knew.

Cluster analysis is a key task of data mining (and the ugly duckling in machine-learning, so don't listen to machine learners dismissing clustering).

"Unsupervised learning" is somewhat an Oxymoron

This has been iterated up and down the literature, but unsupervised learning is bllsht. It does not exist, but it is an oxymoron like "military intelligence".

Either the algorithm learns from examples (then it is "supervised learning"), or it does not learn. If all the clustering methods are "learning", then computing the minimum, maximum and average of a data set is "unsupervised learning", too. Then any computation "learned" its output. Thus the term 'unsupervised learning' is totally meaningless, it means everything and nothing.

Some "unsupervised learning" algorithms do, however, fall into the optimization category. For example k-means is a least-squares optimization. Such methods are all over statistics, so I don't think we need to label them "unsupervised learning", but instead should continue to call them "optimization problems". It's more precise, and more meaningful. There are plenty of clustering algorithms who do not involve optimization, and who do not fit into machine-learning paradigms well. So stop squeezing them in there under the umbrella "unsupervised learning".

There is some "learning" associated with clustering, but it is not the program that learns. It is the user that is supposed to learn new things about his data set.

iOS 7 - Status bar overlaps the view

If using xibs, a very easy implementation is to encapsulate all subviews inside a container view with resizing flags (which you'll already be using for 3.5" and 4" compatibility) so that the view hierarchy looks something like this

xib heirarchy

and then in viewDidLoad, do something like this:

- (void)viewDidLoad
{
  [super viewDidLoad];
  // initializations
  if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) // only for iOS 7 and above
  {
    CGRect frame = containerView.frame;
    frame.origin.y += 20;
    frame.size.height -= 20;
    containerView.frame = frame;
  }
}

This way, the nibs need not be modified for iOS 7 compatibility. If you have a background, it can be kept outside containerView and let it cover the whole screen.

see if two files have the same content in python

I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.

There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can

  • Compare file sizes first, discarding all which doesn't match
  • If file sizes match, compare using the biggest hash you can handle, hashing chunks of files to avoid reading the whole big file

Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)

Preferred Java way to ping an HTTP URL for availability

Is this any good at all (will it do what I want?)

You can do so. Another feasible way is using java.net.Socket.

public static boolean pingHost(String host, int port, int timeout) {
    try (Socket socket = new Socket()) {
        socket.connect(new InetSocketAddress(host, port), timeout);
        return true;
    } catch (IOException e) {
        return false; // Either timeout or unreachable or failed DNS lookup.
    }
}

There's also the InetAddress#isReachable():

boolean reachable = InetAddress.getByName(hostname).isReachable();

This however doesn't explicitly test port 80. You risk to get false negatives due to a Firewall blocking other ports.


Do I have to somehow close the connection?

No, you don't explicitly need. It's handled and pooled under the hoods.


I suppose this is a GET request. Is there a way to send HEAD instead?

You can cast the obtained URLConnection to HttpURLConnection and then use setRequestMethod() to set the request method. However, you need to take into account that some poor webapps or homegrown servers may return HTTP 405 error for a HEAD (i.e. not available, not implemented, not allowed) while a GET works perfectly fine. Using GET is more reliable in case you intend to verify links/resources not domains/hosts.


Testing the server for availability is not enough in my case, I need to test the URL (the webapp may not be deployed)

Indeed, connecting a host only informs if the host is available, not if the content is available. It can as good happen that a webserver has started without problems, but the webapp failed to deploy during server's start. This will however usually not cause the entire server to go down. You can determine that by checking if the HTTP response code is 200.

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
    // Not OK.
}

// < 100 is undetermined.
// 1nn is informal (shouldn't happen on a GET/HEAD)
// 2nn is success
// 3nn is redirect
// 4nn is client error
// 5nn is server error

For more detail about response status codes see RFC 2616 section 10. Calling connect() is by the way not needed if you're determining the response data. It will implicitly connect.

For future reference, here's a complete example in flavor of an utility method, also taking account with timeouts:

/**
 * Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code is in 
 * the 200-399 range.
 * @param url The HTTP URL to be pinged.
 * @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
 * the total timeout is effectively two times the given timeout.
 * @return <code>true</code> if the given HTTP URL has returned response code 200-399 on a HEAD request within the
 * given timeout, otherwise <code>false</code>.
 */
public static boolean pingURL(String url, int timeout) {
    url = url.replaceFirst("^https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        return (200 <= responseCode && responseCode <= 399);
    } catch (IOException exception) {
        return false;
    }
}

How to debug Angular JavaScript Code

IMHO, the most frustrating experience comes from getting / setting a value of a specific scope related to an visual element. I did a lot of breakpoints not only in my own code, but also in angular.js itself, but sometimes it is simply not the most effective way. Although the methods below are very powerful, they are definitely considered to be bad practice if you actually use in production code, so use them wisely!

Get a reference in console from a visual element

In many non-IE browsers, you can select an element by right clicking an element and clicking "Inspect Element". Alternatively you can also click on any element in Elements tab in Chrome, for example. The latest selected element will be stored in variable $0 in console.

Get a scope linked to an element

Depending on whether there exists a directive that creates an isolate scope, you can retrieve the scope by angular.element($0).scope() or angular.element($0).isolateScope() (use $($0).scope() if $ is enabled). This is exactly what you get when you are using the latest version of Batarang. If you are changing the value directly, remember to use scope.$digest() to reflect the changes on UI.

$eval is evil

Not necessarily for debugging. scope.$eval(expression) is very handy when you want to quickly check whether an expression has the expected value.

The missing prototype members of scope

The difference between scope.bla and scope.$eval('bla') is the former does not consider the prototypically inherited values. Use the snippet below to get the whole picture (you cannot directly change the value, but you can use $eval anyway!)

scopeCopy = function (scope) {
    var a = {}; 
    for (x in scope){ 
        if (scope.hasOwnProperty(x) && 
            x.substring(0,1) !== '$' && 
            x !== 'this') {
            a[x] = angular.copy(scope[x])
        }
    }
    return a
};

scopeEval = function (scope) {
    if (scope.$parent === null) {
        return hoho(scope)
    } else {
        return angular.extend({}, haha(scope.$parent), hoho(scope))
    }
};

Use it with scopeEval($($0).scope()).

Where is my controller?

Sometimes you may want to monitor the values in ngModel when you are writing a directive. Use $($0).controller('ngModel') and you will get to check the $formatters, $parsers, $modelValue, $viewValue $render and everything.

Where do I find the Instagram media ID of a image

Here is python solution to do this without api call.

def media_id_to_code(media_id):
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    short_code = ''
    while media_id > 0:
        remainder = media_id % 64
        media_id = (media_id-remainder)/64
        short_code = alphabet[remainder] + short_code
    return short_code


def code_to_media_id(short_code):
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    media_id = 0;
    for letter in short_code:
        media_id = (media_id*64) + alphabet.index(letter)

    return media_id

Reactjs: Unexpected token '<' Error

For correct tag parsing you'll need to use this babel version : https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js and attribute "type='text/babel'" in the script. Besides, your custom script should be within "body" tags.

Apply function to each column in a data frame observing each columns existing data type

df <- head(mtcars)
df$string <- c("a","b", "c", "d","e", "f"); df

my.min <- unlist(lapply(df, min))
my.max <- unlist(lapply(df, max))

BOOLEAN or TINYINT confusion

Just a note for php developers (I lack the necessary stackoverflow points to post this as a comment) ... the automagic (and silent) conversion to TINYINT means that php retrieves a value from a "BOOLEAN" column as a "0" or "1", not the expected (by me) true/false.

A developer who is looking at the SQL used to create a table and sees something like: "some_boolean BOOLEAN NOT NULL DEFAULT FALSE," might reasonably expect to see true/false results when a row containing that column is retrieved. Instead (at least in my version of PHP), the result will be "0" or "1" (yes, a string "0" or string "1", not an int 0/1, thank you php).

It's a nit, but enough to cause unit tests to fail.

Line Break in XML?

@icktoofay was close with the CData

<myxml>
    <record>
        <![CDATA[
        Line 1 <br />
        Line 2 <br />
        Line 3 <br />
        ]]>
    </record>
</myxml>

Console logging for react?

If you're just after console logging here's what I'd do:

export default class App extends Component {
  componentDidMount() {
    console.log('I was triggered during componentDidMount')
  }

  render() {
    console.log('I was triggered during render')
    return ( 
      <div> I am the App component </div>
    )
  }
}

Shouldn't be any need for those packages just to do console logging.

How to compile and run C files from within Notepad++ using NppExec plugin?

I've written just this to execute compiling and run the file after, plus fileinputname = fileoutputname on windowsmashines, if your compilerpath is registred in the windows PATH-var:

NPP_SAVE
cd "$(CURRENT_DIRECTORY)"
set LEN~ strrfind $(FILE_NAME) .
set EXENAME ~ substr 0 $(LEN) $(FILE_NAME)
set $(EXENAME) = $(EXENAME).exe
c++.exe "$(FILE_NAME)" -o "$(EXENAME)"
"$(EXENAME)"

should work for any compiler if you change c++.exe to what you want

A warning - comparison between signed and unsigned integer expressions

The important difference between signed and unsigned ints is the interpretation of the last bit. The last bit in signed types represent the sign of the number, meaning: e.g:

0001 is 1 signed and unsigned 1001 is -1 signed and 9 unsigned

(I avoided the whole complement issue for clarity of explanation! This is not exactly how ints are represented in memory!)

You can imagine that it makes a difference to know if you compare with -1 or with +9. In many cases, programmers are just too lazy to declare counting ints as unsigned (bloating the for loop head f.i.) It is usually not an issue because with ints you have to count to 2^31 until your sign bit bites you. That's why it is only a warning. Because we are too lazy to write 'unsigned' instead of 'int'.

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

This is a simple way from XML only

spanCount for number of columns

layoutManager for making it grid or linear(Vertical or Horizontal)

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/personListRecyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Unpivot with column name

You may also try standard sql un-pivoting method by using a sequence of logic with the following code.. The following code has 3 steps:

  1. create multiple copies for each row using cross join (also creating subject column in this case)
  2. create column "marks" and fill in relevant values using case expression ( ex: if subject is science then pick value from science column)
  3. remove any null combinations ( if exists, table expression can be fully avoided if there are strictly no null values in base table)

     select *
     from 
     (
        select name, subject,
        case subject
        when 'Maths' then maths
        when 'Science' then science
        when 'English' then english
        end as Marks
    from studentmarks
    Cross Join (values('Maths'),('Science'),('English')) AS Subjct(Subject)
    )as D
    where marks is not null;
    

JQuery Number Formatting

http://jquerypriceformat.com/#examples

https://github.com/flaviosilveira/Jquery-Price-Format

html input runing for live chance.

<input type="text" name="v7"  class="priceformat"/>
<input type="text" name="v8"  class="priceformat"/>


$('.priceformat').each(function( index ) {
    $(this).priceFormat({ prefix: '',  thousandsSeparator: '' });
});

//5000.00

//5.000,00

//5,000.00

Update built-in vim on Mac OS X

On Yosemite, install vim using brew and the override-system-vi option. This will automatically install vim with the features of the 'huge' vim install.

brew install vim --with-override-system-vi

The output of this command will show you where brew installed vim. In that folder, go down into /bin/vim to actually run vim. This is your command to run vim from any folder:

/usr/local/Cellar/vim/7.4.873/bin/vim

Then alias this command by adding the following line in your .bashrc:

alias vim="/usr/local/Cellar/vim/7.4.873/bin/vim"

EDIT: Brew flag --override-system-vi has been deprecated. Changed for --with-override-system-vi. Source: https://github.com/Shougo/neocomplete.vim/issues/401

document.getElementById().value and document.getElementById().checked not working for IE

For non-grouped elements, name and id should be same. In this case you gave name as 'sp' and id as 'sp_100'. Don't do that, do it like this:

HTML:

<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp">

Javascript:

var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp').checked = true;

For more details

please visit : http://www.impressivewebs.com/avoiding-problems-with-javascript-getelementbyid-method-in-internet-explorer-7/

How to initialize a variable of date type in java?

Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:

Date firstDate = new Date(ConstructorArgsHere);

Now you have a bit of a choice. If you don't pass in any arguments, and just do this,

Date firstDate = new Date();

it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:

Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);

How to create enum like type in TypeScript?

Update:

As noted by @iX3, Typescript 2.4 has support for enum strings.

See:Create an enum with string values in Typescript


Original answer:

For String member values, TypeScript only allows numbers as enum member values. But there are a few solutions/hacks you can implement;

Solution 1:

copied from: https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/

There is a simple solution: Just cast the string literal to any before assigning:

export enum Language {
    English = <any>"English",
    German = <any>"German",
    French = <any>"French",
    Italian = <any>"Italian"
}

solution 2:

copied from: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html

You can use a string literal as a type. For example:

let foo: 'Hello';

Here we have created a variable called foo that will only allow the literal value 'Hello' to be assigned to it. This is demonstrated below:

let foo: 'Hello';
foo = 'Bar'; // Error: "Bar" is not assignable to type "Hello"

They are not very useful on their own but can be combined in a type union to create a powerful (and useful) abstraction e.g.:

type CardinalDirection =
    "North"
    | "East"
    | "South"
    | "West";

function move(distance: number, direction: CardinalDirection) {
    // ...
}

move(1,"North"); // Okay
move(1,"Nurth"); // Error!

React Hooks useState() with Object

, do it like this example :

first creat state of the objects:

const [isSelected, setSelection] = useState({ id_1: false }, { id_2: false }, { id_3: false });

then change the value on of them:

// if the id_1 is false make it true or return it false.

onValueChange={() => isSelected.id_1 == false ? setSelection({ ...isSelected, id_1: true }) : setSelection({ ...isSelected, id_1: false })}

How to get HTTP Response Code using Selenium WebDriver

It is possible to get the response code of a http request using Selenium and Chrome or Firefox. All you have to do is start either Chrome or Firefox in logging mode. I will show you some examples below.

java + Selenium + Chrome Here is an example of java + Selenium + Chrome, but I guess that it can be done in any language (python, c#, ...).

All you need to do is tell chromedriver to do "Network.enable". This can be done by enabling Performance logging.

LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

After the request is done, all you have to do is get and iterate the Perfomance logs and find "Network.responseReceived" for the requested url:

LogEntries logs = driver.manage().logs().get("performance");

Here is the code:

import java.util.Iterator;
import java.util.logging.Level;

import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class TestResponseCode
{
    public static void main(String[] args)
    {
        // simple page (without many resources so that the output is
        // easy to understand
        String url = "http://www.york.ac.uk/teaching/cws/wws/webpage1.html";

        DownloadPage(url);
    }

    private static void DownloadPage(String url)
    {
        ChromeDriver driver = null;

        try
        {
            ChromeOptions options = new ChromeOptions();
            // add whatever extensions you need
            // for example I needed one of adding proxy, and one for blocking
            // images
            // options.addExtensions(new File(file, "proxy.zip"));
            // options.addExtensions(new File("extensions",
            // "Block-image_v1.1.crx"));

            DesiredCapabilities cap = DesiredCapabilities.chrome();
            cap.setCapability(ChromeOptions.CAPABILITY, options);

            // set performance logger
            // this sends Network.enable to chromedriver
            LoggingPreferences logPrefs = new LoggingPreferences();
            logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
            cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

            driver = new ChromeDriver(cap);

            // navigate to the page
            System.out.println("Navigate to " + url);
            driver.navigate().to(url);

            // and capture the last recorded url (it may be a redirect, or the
            // original url)
            String currentURL = driver.getCurrentUrl();

            // then ask for all the performance logs from this request
            // one of them will contain the Network.responseReceived method
            // and we shall find the "last recorded url" response
            LogEntries logs = driver.manage().logs().get("performance");

            int status = -1;

            System.out.println("\nList of log entries:\n");

            for (Iterator<LogEntry> it = logs.iterator(); it.hasNext();)
            {
                LogEntry entry = it.next();

                try
                {
                    JSONObject json = new JSONObject(entry.getMessage());

                    System.out.println(json.toString());

                    JSONObject message = json.getJSONObject("message");
                    String method = message.getString("method");

                    if (method != null
                            && "Network.responseReceived".equals(method))
                    {
                        JSONObject params = message.getJSONObject("params");

                        JSONObject response = params.getJSONObject("response");
                        String messageUrl = response.getString("url");

                        if (currentURL.equals(messageUrl))
                        {
                            status = response.getInt("status");

                            System.out.println(
                                    "---------- bingo !!!!!!!!!!!!!! returned response for "
                                            + messageUrl + ": " + status);

                            System.out.println(
                                    "---------- bingo !!!!!!!!!!!!!! headers: "
                                            + response.get("headers"));
                        }
                    }
                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            System.out.println("\nstatus code: " + status);
        } finally
        {
            if (driver != null)
            {
                driver.quit();
            }
        }
    }
}

The output looks like this:

    Navigate to http://www.york.ac.uk/teaching/cws/wws/webpage1.html

    List of log entries:

    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameAttached","params":{"parentFrameId":"172.1","frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStartedLoading","params":{"frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameNavigated","params":{"frame":{"securityOrigin":"://","loaderId":"172.1","name":"chromedriver dummy frame","id":"172.2","mimeType":"text/html","parentId":"172.1","url":"about:blank"}}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStoppedLoading","params":{"frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStartedLoading","params":{"frameId":"3928.1"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.requestWillBeSent","params":{"request":{"headers":{"Upgrade-Insecure-Requests":"1","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"},"initialPriority":"VeryHigh","method":"GET","mixedContentType":"none","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html"},"frameId":"3928.1","requestId":"3928.1","documentURL":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","initiator":{"type":"other"},"loaderId":"3928.1","wallTime":1.47619492749007E9,"type":"Document","timestamp":20226.652971}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.responseReceived","params":{"frameId":"3928.1","requestId":"3928.1","response":{"headers":{"Accept-Ranges":"bytes","Keep-Alive":"timeout=4, max=100","Cache-Control":"max-age=300","Server":"Apache/2.2.22 (Ubuntu)","Connection":"Keep-Alive","Content-Encoding":"gzip","Vary":"Accept-Encoding","Expires":"Tue, 11 Oct 2016 14:13:47 GMT","Content-Length":"1957","Date":"Tue, 11 Oct 2016 14:08:47 GMT","Content-Type":"text/html"},"connectionReused":false,"timing":{"pushEnd":0,"workerStart":-1,"proxyEnd":-1,"workerReady":-1,"sslEnd":-1,"pushStart":0,"requestTime":20226.65335,"sslStart":-1,"dnsStart":0,"sendEnd":31.6569999995409,"connectEnd":31.4990000006219,"connectStart":0,"sendStart":31.5860000009707,"dnsEnd":0,"receiveHeadersEnd":115.645999998378,"proxyStart":-1},"encodedDataLength":-1,"remotePort":80,"mimeType":"text/html","headersText":"HTTP/1.1 200 OK\r\nDate: Tue, 11 Oct 2016 14:08:47 GMT\r\nServer: Apache/2.2.22 (Ubuntu)\r\nAccept-Ranges: bytes\r\nCache-Control: max-age=300\r\nExpires: Tue, 11 Oct 2016 14:13:47 GMT\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 1957\r\nKeep-Alive: timeout=4, max=100\r\nConnection: Keep-Alive\r\nContent-Type: text/html\r\n\r\n","securityState":"neutral","requestHeadersText":"GET /teaching/cws/wws/webpage1.html HTTP/1.1\r\nHost: www.york.ac.uk\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nAccept-Encoding: gzip, deflate, sdch\r\nAccept-Language: en-GB,en-US;q=0.8,en;q=0.6\r\n\r\n","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","protocol":"http/1.1","fromDiskCache":false,"fromServiceWorker":false,"requestHeaders":{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Upgrade-Insecure-Requests":"1","Connection":"keep-alive","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36","Host":"www.york.ac.uk","Accept-Encoding":"gzip, deflate, sdch","Accept-Language":"en-GB,en-US;q=0.8,en;q=0.6"},"remoteIPAddress":"144.32.128.84","statusText":"OK","connectionId":11,"status":200},"loaderId":"3928.1","type":"Document","timestamp":20226.770012}}}
    ---------- bingo !!!!!!!!!!!!!! returned response for http://www.york.ac.uk/teaching/cws/wws/webpage1.html: 200
    ---------- bingo !!!!!!!!!!!!!! headers: {"Accept-Ranges":"bytes","Keep-Alive":"timeout=4, max=100","Cache-Control":"max-age=300","Server":"Apache/2.2.22 (Ubuntu)","Connection":"Keep-Alive","Content-Encoding":"gzip","Vary":"Accept-Encoding","Expires":"Tue, 11 Oct 2016 14:13:47 GMT","Content-Length":"1957","Date":"Tue, 11 Oct 2016 14:08:47 GMT","Content-Type":"text/html"}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.dataReceived","params":{"dataLength":2111,"requestId":"3928.1","encodedDataLength":1460,"timestamp":20226.770425}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameNavigated","params":{"frame":{"securityOrigin":"http://www.york.ac.uk","loaderId":"3928.1","id":"3928.1","mimeType":"text/html","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html"}}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.dataReceived","params":{"dataLength":1943,"requestId":"3928.1","encodedDataLength":825,"timestamp":20226.782673}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.loadingFinished","params":{"requestId":"3928.1","encodedDataLength":2285,"timestamp":20226.770199}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.loadEventFired","params":{"timestamp":20226.799391}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStoppedLoading","params":{"frameId":"3928.1"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.domContentEventFired","params":{"timestamp":20226.845769}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.requestWillBeSent","params":{"request":{"headers":{"Referer":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"},"initialPriority":"High","method":"GET","mixedContentType":"none","url":"http://www.york.ac.uk/favicon.ico"},"frameId":"3928.1","requestId":"3928.2","documentURL":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","initiator":{"type":"other"},"loaderId":"3928.1","wallTime":1.47619492768527E9,"type":"Other","timestamp":20226.848174}}}

    status code: 200

java + Selenium + Firefox I have finally found the trick for Firefox too. You need to start firefox using MOZ_LOG and MOZ_LOG_FILE environment variables, and log http requests at debug level (4 = PR_LOG_DEBUG) - map.put("MOZ_LOG", "timestamp,sync,nsHttp:4"). Save the log in a temporary file. After that, get the content of the saved log file and parse it for the response code (using some simple regular expressions). First detect the start of the request, identifying its id (nsHttpChannel::BeginConnect [this=000000CED8094000]), then at the second step, find the response code for that request id (nsHttpChannel::ProcessResponse [this=000000CED8094000 httpStatus=200]).

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.GeckoDriverService;

public class TestFirefoxResponse
{
  public static void main(String[] args)
      throws InterruptedException, IOException
  {
    GeckoDriverService service = null;

    // tell firefox to log http requests
    // at level 4 = PR_LOG_DEBUG: debug messages, notices
    // you could log everything at level 5, but the log file will 
    // be larger. 
    // create a temporary log file that will be parsed for
    // response code
    Map<String, String> map = new HashMap<String, String>();
    map.put("MOZ_LOG", "timestamp,sync,nsHttp:4");
    File tempFile = File.createTempFile("mozLog", ".txt");    
    map.put("MOZ_LOG_FILE", tempFile.getAbsolutePath());      

    GeckoDriverService.Builder builder = new GeckoDriverService.Builder();
    service = builder.usingAnyFreePort()
      .withEnvironment(map)
      .build();

    service.start();      

    WebDriver driver = new FirefoxDriver(service);

    // test 200
     String url = "https://api.ipify.org/?format=text";
    // test 404
    // String url = "https://www.advancedwebranking.com/lsdkjflksdjfldksfj";
    driver.get(url);

    driver.quit();

    String logContent = FileUtils.readFileToString(tempFile);

    ParseLog(logContent, url);
  }

  private static void ParseLog(String logContent, String url) throws MalformedURLException
  {
    // this is how the log looks like when the request starts
    // I have to get the id of the request using a regular expression
    // and use that id later to get the response
    //
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::BeginConnect [this=000000BFF27A5000]
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp host=api.ipify.org port=-1
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp uri=https://api.ipify.org/?format=text
    String pattern = "BeginConnect \\[this=(.*?)\\](?:.*?)uri=(.*?)\\s";

    Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(logContent);

    String urlID = null;
    while (m.find())
    {
      String id = m.group(1);
      String uri = m.group(2);

      if (uri.equals(url))
      {
        urlID = id;
        break;
      }      
    }

    System.out.println("request id = " + urlID);

    // this is how the response looks like in the log file
    // ProcessResponse [this=000000CED8094000 httpStatus=200]
    // I will use another regular espression to get the httpStatus
    //
    //    2017-11-02 14:45:39.296000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::OnStartRequest [this=000000CED8094000 request=000000CED8014BB0 status=0]
    //    2017-11-02 14:45:39.296000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::ProcessResponse [this=000000CED8094000 httpStatus=200]    

    pattern = "ProcessResponse \\[this=" + urlID + " httpStatus=(.*?)\\]";

    p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    m = p.matcher(logContent);

    if (m.find())
    {
      String responseCode = m.group(1);
      System.out.println("response code found " + responseCode);
    }
    else
    {
      System.out.println("response code not found");
    }
  }
}

The output for this will be

request id = 0000007653D67000 response code found 200

The response headers can also be found in the log file. You can get them if you want.

    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp http response [
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   HTTP/1.1 404 Not Found
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Accept-Ranges: bytes
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Cache-control: no-cache="set-cookie"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Type: text/html; charset=utf-8
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Date: Thu, 02 Nov 2017 14:54:36 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   ETag: "7969-55bc076a61e80"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Last-Modified: Tue, 17 Oct 2017 16:17:46 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Server: Apache/2.4.23 (Amazon) PHP/5.6.24
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Set-Cookie: AWSELB=5F256FFA816C8E72E13AE0B12A17A3D540582F804C87C5FEE323AF3C9B638FD6260FF473FF64E44926DD26221AAD2E9727FD739483E7E4C31784C7A495796B416146EE83;PATH=/
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Length: 31081
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Connection: keep-alive
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp     OriginalHeaders
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Accept-Ranges: bytes
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Cache-control: no-cache="set-cookie"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Type: text/html; charset=utf-8
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Date: Thu, 02 Nov 2017 14:54:36 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   ETag: "7969-55bc076a61e80"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Last-Modified: Tue, 17 Oct 2017 16:17:46 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Server: Apache/2.4.23 (Amazon) PHP/5.6.24
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Set-Cookie: AWSELB=5F256FFA816C8E72E13AE0B12A17A3D540582F804C87C5FEE323AF3C9B638FD6260FF473FF64E44926DD26221AAD2E9727FD739483E7E4C31784C7A495796B416146EE83;PATH=/
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Length: 31081
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Connection: keep-alive
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp ]
    2017-11-02 14:54:36.775000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::OnStartRequest [this=0000008A65D85000 request=0000008A65D1F900 status=0]
    2017-11-02 14:54:36.775000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::ProcessResponse [this=0000008A65D85000 httpStatus=404]

how to find my angular version in my project?

  1. Browser > Inspect > Element >

    <.app-root _nghost-hey-c0="" ng-version="8.2.11">

  2. In terminal

    :> ng version
    :> ng --version
    :> ng -v

How to Get True Size of MySQL Database?

None of the answers include the overhead size and the metadata sizes of tables.

Here is a more accurate estimation of the "disk space" allocated by a database.

SELECT ROUND((SUM(data_length+index_length+data_free) + (COUNT(*) * 300 * 1024))/1048576+150, 2) AS MegaBytes FROM information_schema.TABLES WHERE table_schema = 'DATABASE-NAME'

Finding the id of a parent div using Jquery

1.

$(this).parent().attr("id");

2.

There must be a large number of ways! One could be to hide an element that contains the answer, e.g.

<div>
    Volume = <input type="text" />
    <button type="button">Check answer</button>
    <span style="display: hidden">3.93e-6&lt;/span>
    <div></div>
</div>

And then have similar jQuery code to the above to grab that:

$("button").click(function () 
{
    var correct = Number($(this).parent().children("span").text());
    validate ($(this).siblings("input").val(),correct);
    $(this).siblings("div").html(feedback);
});

bear in mind that if you put the answer in client code then they can see it :) The best way to do this is to validate it server-side, but for an app with limited scope this may not be a problem.

Convert java.util.Date to String

Altenative one-liners in plain-old java:

String.format("The date: %tY-%tm-%td", date, date, date);

String.format("The date: %1$tY-%1$tm-%1$td", date);

String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);

String.format("The date and time in ISO format: %tF %<tT", date);

This uses Formatter and relative indexing instead of SimpleDateFormat which is not thread-safe, btw.

Slightly more repetitive but needs just one statement. This may be handy in some cases.

Connecting an input stream to an outputstream

Just because you use a buffer doesn't mean the stream has to fill that buffer. In other words, this should be okay:

public static void copyStream(InputStream input, OutputStream output)
    throws IOException
{
    byte[] buffer = new byte[1024]; // Adjust if you want
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
}

That should work fine - basically the read call will block until there's some data available, but it won't wait until it's all available to fill the buffer. (I suppose it could, and I believe FileInputStream usually will fill the buffer, but a stream attached to a socket is more likely to give you the data immediately.)

I think it's worth at least trying this simple solution first.

X close button only using css

As a pure CSS solution for the close or 'times' symbol you can use the ISO code with the content property. I often use this for :after or :before pseudo selectors.

The content code is \00d7.

Example

div:after{
  display: inline-block;
  content: "\00d7"; /* This will render the 'X' */
}

You can then style and position the pseudo selector in any way you want. Hope this helps someone :).

How to tackle daylight savings using TimeZone in Java

Instead of entering "EST" for the timezone you can enter "EST5EDT" as such. As you noted, just "EDT" does not work. This will account for the daylight savings time issue. The code line looks like this:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST5EDT"));

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

Add MultipleActiveResultSets=true to the provider part of your connection string. See the example below:

<add name="DbContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=dbName;Persist Security Info=True;User ID=userName;Password=password;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

Add a new item to recyclerview programmatically?

First add your item to mItems and then use:

mAdapter.notifyItemInserted(mItems.size() - 1);

this method is better than using:

mAdapter.notifyDataSetChanged();

in performance.

Having links relative to root?

Use this code "./" as root on the server as it works for me

<a href="./fruits/index.html">Back to Fruits List</a>

but when you are on a local machine use the following code "../" as the root relative path

<a href="../fruits/index.html">Back to Fruits List</a>

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

Assuming you are on Windows (this bug is caused by the crappy bat files escaping), It is a bug introduced in the latest versions (7.0.56 and 8.0.14) to workaround another bug. Try to remove the " around the JAVA_OPTS declaration in catalina.bat. It fixed it for me with Tomcat 7.0.56 yesterday.

In 7.0.56 in bin/catalina.bat:179 and 184

:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"

..

:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"

to

:noJuliConfig
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%

.. 

:noJuliManager
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%

For your asterisk, it might only be a configuration of yours somewhere that appends it to the host declaration.

I saw this on Tomcat's bugtracker yesterday but I can't find the link again. Edit Found it! https://issues.apache.org/bugzilla/show_bug.cgi?id=56895

I hope it fixes your problem.

How to change package name in flutter?

Android

In Android the package name is in the AndroidManifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    package="com.example.appname">

iOS

In iOS the package name is the bundle identifier in Info.plist:

<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>

which is found in Runner.xcodeproj/project.pbxproj:

PRODUCT_BUNDLE_IDENTIFIER = com.example.appname;

Changing the name

The package name is found in more than one location, so to change the name you should search the whole project for occurrences of your old project name and change them all.

Android Studio and VS Code:

  • Mac: Command + Shift + F
  • Linux/Windows: Ctrl + Shift + F

Thanks to diegoveloper for help with iOS.

Update:

After coming back to this page a few different times, I'm thinking it's just easier and cleaner to start a new project with the right name and then copy the old files over.

JQuery/Javascript: check if var exists

To test for existence there are two methods.

a. "property" in object

This method checks the prototype chain for existence of the property.

b. object.hasOwnProperty( "property" )

This method does not go up the prototype chain to check existence of the property, it must exist in the object you are calling the method on.

var x; // variable declared in global scope and now exists

"x" in window; // true
window.hasOwnProperty( "x" ); //true

If we were testing using the following expression then it would return false

typeof x !== 'undefined'; // false

Use of exit() function

Use process.h instead of stdlib and iostream... It will work 100%.

How to get a list of all files that changed between two Git commits?

If you want to check the changed files you need to take care of many small things like which will be best to use , like if you want to check which of the files changed just type

git status -- it will show the files with changes

then if you want to know what changes are to be made it can be checked in ways ,

git diff -- will show all the changes in all files

it is good only when only one file is modified

and if you want to check particular file then use

git diff

How to reposition Chrome Developer Tools

In addition, if you want to see Sources and Console on one window, go to:

"Customize and control DevTools -> "Show console drawer"

You can also see it here at the right corner:

"Show console drawer"

How to get JS variable to retain value after page refresh?

You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one

If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage

Ex: using localStorage and cookies library

var mode = getStoredValue('myPageMode');

function buttonClick(mode) {
    mode = mode;
    storeValue('myPageMode', mode);
}

function storeValue(key, value) {
    if (localStorage) {
        localStorage.setItem(key, value);
    } else {
        $.cookies.set(key, value);
    }
}

function getStoredValue(key) {
    if (localStorage) {
        return localStorage.getItem(key);
    } else {
        return $.cookies.get(key);
    }
}

Convert tuple to list and back

Just using the command list did not work for me.

if you have a tuple just iterate until you have the elements there are necessary and after that append to a list. And if you go to the element level you can change it easily.

input:

level1 = (
         (1,1,1,1,1,1),
         (1,0,0,0,0,1),
         (1,0,0,0,0,1),
         (1,0,0,0,0,1),
         (1,0,0,0,0,1),
         (1,1,1,1,1,1))

level1_as_list=[]
for i in level1:
    inside_list=[]
    for j in i:
        inside_list.append(j)
    level1_as_list.append(inside_list)

print(level1_as_list)enter code here

output:

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

Override standard close (X) button in a Windows Form

protected override bool ProcessCmdKey(ref Message msg, Keys dataKey)
    {
        if (dataKey == Keys.Escape)
        {
            this.Close();
            //this.Visible = false;
            //Plus clear values from form, if Visible false.
        }
        return base.ProcessCmdKey(ref msg, dataKey);
    }

How to automatically indent source code?

Also, there's the handy little "increase indent" and "decrease indent" buttons. If you highlight a block of code and click those buttons the entire block will indent.

How to add a "sleep" or "wait" to my Lua Script?

If you have luasocket installed:

local socket = require 'socket'
socket.sleep(0.2)

Why can I not push_back a unique_ptr into a vector?

You need to move the unique_ptr:

vec.push_back(std::move(ptr2x));

unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it.

Note, however, that your current use of unique_ptr is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:

std::unique_ptr<int> ptr(new int(1));

In C++14 we have an even better way to do so:

make_unique<int>(5);

How to display an error message in an ASP.NET Web Application

The errors in ASP.Net are saved on the Server.GetLastError property,

Or i would put a label on the asp.net page for displaying the error.

try
{
    do something
}
catch (YourException ex)
{
    errorLabel.Text = ex.Message;
    errorLabel.Visible = true;
}

How much data can a List can hold at the maximum?

It depends on the List implementation. Since you index arrays with ints, an ArrayList can't hold more than Integer.MAX_VALUE elements. A LinkedList isn't limited in the same way, though, and can contain any amount of elements.

Giving height to table and row in Bootstrap

For the <tr>'s just set

tr {
   line-height: 25px;
   min-height: 25px;
   height: 25px;
}

It works with bootstrap also. For the 100% height, 100% must be 100% of something. Therefore, you must define a fixed height for one of the containers, or the body. I guess you want the entire page to be 100%, so (example) :

body {
    height: 700px;
}
.table100, .row, .container, .table-responsive, .table-bordered  {
    height: 100%;
}

A workaround not to set a static height is by forcing the height in code according to the viewport :

$('body').height(document.documentElement.clientHeight);

all the above in this fiddle -> http://jsfiddle.net/LZuJt/

Note : I do not care that you have 25% height on #description, and 100% height on table. Guess it is just an example. And notice that clientHeight is not right since the documentElement is an iframe, but you'll get the picture in your own projekt :)

AngularJS ui router passing data between states without URL

The params object is included in $stateParams, but won't be part of the url.

1) In the route configuration:

$stateProvider.state('edit_user', {
    url: '/users/:user_id/edit',
    templateUrl: 'views/editUser.html',
    controller: 'editUserCtrl',
    params: {
        paramOne: { objectProperty: "defaultValueOne" },  //default value
        paramTwo: "defaultValueTwo"
    }
});

2) In the controller:

.controller('editUserCtrl', function ($stateParams, $scope) {       
    $scope.paramOne = $stateParams.paramOne;
    $scope.paramTwo = $stateParams.paramTwo;
});

3A) Changing the State from a controller

$state.go("edit_user", {
    user_id: 1,                
    paramOne: { objectProperty: "test_not_default1" },
    paramTwo: "from controller"
});

3B) Changing the State in html

<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>

Example Plunker

Execute SQLite script

If you are using the windows CMD you can use this command to create a database using sqlite3

C:\sqlite3.exe DBNAME.db ".read DBSCRIPT.sql"

If you haven't a database with that name sqlite3 will create one, and if you already have one, it will run it anyways but with the "TABLENAME already exists" error, I think you can also use this command to change an already existing database (but im not sure)

Select2() is not a function

I was having this problem when I started using select2 with XCrud. I solved it by disabling XCrud from loading JQuery, it was it a second time, and loading it below the body tag. So make sure JQuery isn't getting loaded twice on your page.

How do you overcome the svn 'out of date' error?

I just got this error. What I recommend is you first check on your server if the original file is there. Sometimes the changes aren't made in your local folder. If this is your situation, just delete your folder and checkout again.

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

How to use OrderBy with findAll in Spring Data

Please have a look at the Spring Data JPA - Reference Documentation, section 5.3. Query Methods, especially at section 5.3.2. Query Creation, in "Table 3. Supported keywords inside method names" (links as of 2019-05-03).

I think it has exactly what you need and same query as you stated should work...

WebSocket with SSL

The WebSocket connection starts its life with an HTTP or HTTPS handshake. When the page is accessed through HTTP, you can use WS or WSS (WebSocket secure: WS over TLS) . However, when your page is loaded through HTTPS, you can only use WSS - browsers don't allow to "downgrade" security.

How update the _id of one MongoDB Document?

To do it for your whole collection you can also use a loop (based on Niels example):

db.status.find().forEach(function(doc){ 
    doc._id=doc.UserId; db.status_new.insert(doc);
});
db.status_new.renameCollection("status", true);

In this case UserId was the new ID I wanted to use

Check if input is integer type in C

This method works for everything (integers and even doubles) except zero (it calls it invalid):

The while loop is just for the repetitive user input. Basically it checks if the integer x/x = 1. If it does (as it would with a number), its an integer/double. If it doesn't, it obviously it isn't. Zero fails the test though.

#include <stdio.h> 
#include <math.h>

void main () {
    double x;
    int notDouble;
    int true = 1;
    while(true) {
        printf("Input an integer: \n");
        scanf("%lf", &x);
        if (x/x != 1) {
            notDouble = 1;
            fflush(stdin);
        }
        if (notDouble != 1) {
            printf("Input is valid\n");
        }
        else {
            printf("Input is invalid\n");
        }
        notDouble = 0;
    }
}

How do I calculate the normal vector of a line segment?

Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.

The matrix representation of the general 2D transformation looks like this:

x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)

where (x,y) are the components of the original vector and (x', y') are the transformed components.

If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:

x' = -y
y' = +x

Same result as given earlier, but with a little more explanation as to where it comes from.

Eclipse : Failed to connect to remote VM. Connection refused.

  • The port number in the Eclipse configuration and the port number of your application might not be the same.
  • You might not have been started your application with the right parameters.

    Those are the simple problems when I have faced "Connection refused" error.

Matplotlib discrete colorbar

You can create a custom discrete colorbar quite easily by using a BoundaryNorm as normalizer for your scatter. The quirky bit (in my method) is making 0 showup as grey.

For images i often use the cmap.set_bad() and convert my data to a numpy masked array. That would be much easier to make 0 grey, but i couldnt get this to work with the scatter or the custom cmap.

As an alternative you can make your own cmap from scratch, or read-out an existing one and override just some specific entries.

import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt

fig, ax = plt.subplots(1, 1, figsize=(6, 6))  # setup the plot

x = np.random.rand(20)  # define the data
y = np.random.rand(20)  # define the data
tag = np.random.randint(0, 20, 20)
tag[10:12] = 0  # make sure there are some 0 values to show up as grey

cmap = plt.cm.jet  # define the colormap
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# force the first color entry to be grey
cmaplist[0] = (.5, .5, .5, 1.0)

# create the new map
cmap = mpl.colors.LinearSegmentedColormap.from_list(
    'Custom cmap', cmaplist, cmap.N)

# define the bins and normalize
bounds = np.linspace(0, 20, 21)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# make the scatter
scat = ax.scatter(x, y, c=tag, s=np.random.randint(100, 500, 20),
                  cmap=cmap, norm=norm)

# create a second axes for the colorbar
ax2 = fig.add_axes([0.95, 0.1, 0.03, 0.8])
cb = plt.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm,
    spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i')

ax.set_title('Well defined discrete colors')
ax2.set_ylabel('Very custom cbar [-]', size=12)

enter image description here

I personally think that with 20 different colors its a bit hard to read the specific value, but thats up to you of course.

Any way to select without causing locking in MySQL?

another way to enable dirty read in mysql is add hint: LOCK IN SHARE MODE

SELECT * FROM TABLE_NAME LOCK IN SHARE MODE; 

Map enum in JPA with fixed values?

I would do the folowing:

Declare separetly the enum, in it´s own file:

public enum RightEnum {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      private RightEnum (int value) { this.value = value; }


      @Override
      public static Etapa valueOf(Integer value){
           for( RightEnum r : RightEnum .values() ){
              if ( r.getValue().equals(value))
                 return r;
           }
           return null;//or throw exception
     }

      public int getValue() { return value; }


}

Declare a new JPA entity named Right

@Entity
public class Right{
    @Id
    private Integer id;
    //FIElDS

    // constructor
    public Right(RightEnum rightEnum){
          this.id = rightEnum.getValue();
    }

    public Right getInstance(RightEnum rightEnum){
          return new Right(rightEnum);
    }


}

You will also need a converter for receiving this values (JPA 2.1 only and there´s a problem I´ll not discuss here with these enum´s to be directly persisted using the converter, so it will be a one way road only)

import mypackage.RightEnum;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * 
 * 
 */
@Converter(autoApply = true)
public class RightEnumConverter implements AttributeConverter<RightEnum, Integer>{

    @Override //this method shoudn´t be used, but I implemented anyway, just in case
    public Integer convertToDatabaseColumn(RightEnum attribute) {
        return attribute.getValue();
    }

    @Override
    public RightEnum convertToEntityAttribute(Integer dbData) {
        return RightEnum.valueOf(dbData);
    }

}

The Authority entity:

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "AUTHORITY_ID")
  private Long id;

  // the **Entity** to map : 
  private Right right;

  // the **Enum** to map (not to be persisted or updated) : 
  @Column(name="COLUMN1", insertable = false, updatable = false)
  @Convert(converter = RightEnumConverter.class)
  private RightEnum rightEnum;

}

By doing this way, you can´t set directly to the enum field. However, you can set the Right field in Authority using

autorithy.setRight( Right.getInstance( RightEnum.READ ) );//for example

And if you need to compare, you can use:

authority.getRight().equals( RightEnum.READ ); //for example

Which is pretty cool, I think. It´s not totally correct, since the converter it´s not intended to be use with enum´s. Actually, the documentation says to never use it for this purpose, you should use the @Enumerated annotation instead. The problem is that there are only two enum types: ORDINAL or STRING, but the ORDINAL is tricky and not safe.


However, if it doesn´t satisfy you, you can do something a little more hacky and simpler (or not).

Let´s see.

The RightEnum:

public enum RightEnum {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      private RightEnum (int value) { 
            try {
                  this.value= value;
                  final Field field = this.getClass().getSuperclass().getDeclaredField("ordinal");
                  field.setAccessible(true);
                  field.set(this, value);
             } catch (Exception e) {//or use more multicatch if you use JDK 1.7+
                  throw new RuntimeException(e);
            }
      }


      @Override
      public static Etapa valueOf(Integer value){
           for( RightEnum r : RightEnum .values() ){
              if ( r.getValue().equals(value))
                 return r;
           }
           return null;//or throw exception
     }

      public int getValue() { return value; }


}

and the Authority entity

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "AUTHORITY_ID")
  private Long id;


  // the **Enum** to map (to be persisted or updated) : 
  @Column(name="COLUMN1")
  @Enumerated(EnumType.ORDINAL)
  private RightEnum rightEnum;

}

In this second idea, its not a perfect situation since we hack the ordinal attribute, but it´s a much smaller coding.

I think that the JPA specification should include the EnumType.ID where the enum value field should be annotated with some kind of @EnumId annotation.

What is an efficient way to implement a singleton pattern in Java?

The solution posted by Stu Thompson is valid in Java 5.0 and later. But I would prefer not to use it because I think it is error prone.

It's easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe any more due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of Java Concurrency in Practice. In short: This pattern (prior to Java 5.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.

This pattern was invented for performance optimization. But this is really not a real concern any more. The following lazy initialization code is fast and - more importantly - easier to read.

class Bar {
    private static class BarHolder {
        public static Bar bar = new Bar();
    }

    public static Bar getBar() {
        return BarHolder.bar;
    }
}

Searching a list of objects in Python

Just for completeness, let's not forget the Simplest Thing That Could Possibly Work:

for i in list:
  if i.n == 5:
     # do something with it
     print "YAY! Found one!"

How do I check if the mouse is over an element in jQuery?

I have answered this in another question, with all details you may need:

Detect IF hovering over element with jQuery (has 99 upvotes at the time of writing)

Basically, you can do something like:

var ishovered = oi.is(":hover");

This works only if oi is a jQuery object containing a single element. If there are multiple elements matched, you need to apply to each element, for example:

var hoveredItem = !!$('ol>li').filter(function() { return $(this).is(":hover"); });
                  // not .filter(':hover'), as we can't apply :hover on multiple elements

This was tested starting jQuery 1.7.

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

insert password into database in md5 format?

Darren Davies is partially correct in saying that you should use a salt - there are several issues with his claim that MD5 is insecure.

You've said that you have to insert the password using an Md5 hash, but that doesn't really tell us why. Is it because that's the format used when validatinb the password? Do you have control over the code which validates the password?

The thing about using a salt is that it avoids the problem where 2 users have the same password - they'll also have the same hash - not a desirable outcome. By using a diferent salt for each password then this does not arise (with very large volumes of data there is still a risk of collisions arising from 2 different passwords - but we'll ignore that for now).

So you can aither generate a random value for the salt and store that in the record too, or you could use some of the data you already hold - such as the username:

$query="INSERT INTO ptb_users (id,
        user_id,
        first_name,
        last_name,
        email )
        VALUES('NULL',
        'NULL',
        '".$firstname."',
        '".$lastname."',
        '".$email."',
        MD5('"$user_id.$password."')
        )";

(I am assuming that you've properly escaped all those strings earlier in your code)

How to enable CORS on Firefox?

It's only possible when the server sends this header: Access-Control-Allow-Origin: *

If this is your code then you can setup it like this (PHP):

header('Access-Control-Allow-Origin: *');

Fast way to get the min/max values among properties of object

There's no way to find the maximum / minimum in the general case without looping through all the n elements (if you go from, 1 to n-1, how do you know whether the element n isn't larger (or smaller) than the current max/min)?

You mentioned that the values change every couple of seconds. If you know exactly which values change, you can start with your previous max/min values, and only compare with the new ones, but even in this case, if one of the values which were modified was your old max/min, you may need to loop through them again.

Another alternative - again, only if the number of values which change are small - would be to store the values in a structure such as a tree or a heap, and as the new values arrive you'd insert (or update) them appropriately. But whether you can do that is not clear based on your question.

If you want to get the maximum / minimum element of a given list while looping through all elements, then you can use something like the snippet below, but you will not be able to do that without going through all of them

var list = { "a":4, "b":0.5 , "c":0.35, "d":5 };
var keys = Object.keys(list);
var min = list[keys[0]]; // ignoring case of empty list for conciseness
var max = list[keys[0]];
var i;

for (i = 1; i < keys.length; i++) {
    var value = list[keys[i]];
    if (value < min) min = value;
    if (value > max) max = value;
}

How do I prevent Conda from activating the base environment by default?

One thing that hasn't been pointed out, is that there is little to no difference between not having an active environment and and activating the base environment, if you just want to run applications from Conda's (Python's) scripts directory (as @DryLabRebel wants).

You can install and uninstall via conda and conda shows the base environment as active - which essentially it is:

> echo $Env:CONDA_DEFAULT_ENV
> conda env list
# conda environments:
#
base                  *  F:\scoop\apps\miniconda3\current

> conda activate
> echo $Env:CONDA_DEFAULT_ENV
base
> conda env list
# conda environments:
#
base                  *  F:\scoop\apps\miniconda3\current

How do I convert a Python program to a runnable .exe Windows program?

I've used py2exe in the past and have been very happy with it. I didn't particularly enjoy using cx-freeze as much, though

How can I convert a string to a number in Perl?

Perl is a context-based language. It doesn't do its work according to the data you give it. Instead, it figures out how to treat the data based on the operators you use and the context in which you use them. If you do numbers sorts of things, you get numbers:

# numeric addition with strings:
my $sum = '5.45' + '0.01'; # 5.46

If you do strings sorts of things, you get strings:

# string replication with numbers:
my $string = ( 45/2 ) x 4; # "22.522.522.522.5"

Perl mostly figures out what to do and it's mostly right. Another way of saying the same thing is that Perl cares more about the verbs than it does the nouns.

Are you trying to do something and it isn't working?

'pip' is not recognized as an internal or external command

I continued to receive this error after correcting my PATH.

If your codebase requires that you have an earlier version of Python (2.7 in my case), it may have been a version prior to the existence of pip.

It's not very canonical, but installing a more recent version worked for me. (I used 2.7.13.)

Is ini_set('max_execution_time', 0) a bad idea?

At the risk of irritating you;

You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.

Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.

What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.

It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.

In short, it's just unnecessarily conflating the matter when there is no need to.

Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit() than ini_set().

Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)

How to extract a single value from JSON response?

using json.loads will turn your data into a python dictionary.

Dictionaries values are accessed using ['key']

resp_str = {
  "name" : "ns1:timeSeriesResponseType",
  "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
  "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
  "value" : {
    "queryInfo" : {
      "creationTime" : 1349724919000,
      "queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
      "criteria" : {
        "locationParam" : "[ALL:103232434]",
        "variableParam" : "[00060, 00065]"
      },
      "note" : [ {
        "value" : "[ALL:103232434]",
        "title" : "filter:sites"
      }, {
        "value" : "[mode=LATEST, modifiedSince=null]",
        "title" : "filter:timeRange"
      }, {
        "value" : "sdas01",
        "title" : "server"
      } ]
    }
  },
  "nil" : false,
  "globalScope" : true,
  "typeSubstituted" : false
}

would translate into a python diction

resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000

jquery ui Dialog: cannot call methods on dialog prior to initialization

The new jQuery UI version will not allow you to call UI methods on dialog which is not initialized. As a workaround, you can use the below check to see if the dialog is alive.

if (modalDialogObj.hasClass('ui-dialog-content')) {
    // call UI methods like modalDialogObj.dialog('isOpen')
} else {
    // it is not initialized yet
}

data.map is not a function

data needs to be Json object, to do so please make sure the follow:

data = $.parseJSON(data);

Now you can do something like:

data.map(function (...) {
            ...
        });

I hope this help some one

Python: Find a substring in a string and returning the index of the substring

There is one other option in regular expression, the search method

import re

string = 'Happy Birthday'
pattern = 'py'
print(re.search(pattern, string).span()) ## this prints starting and end indices
print(re.search(pattern, string).span()[0]) ## this does what you wanted

By the way, if you would like to find all the occurrence of a pattern, instead of just the first one, you can use finditer method

import re

string = 'i think that that that that student wrote there is not that right'
pattern = 'that'

print([match.start() for match in re.finditer(pattern, string)])

which will print all the starting positions of the matches.

How to convert a Title to a URL slug in jQuery?

function slugify(text){
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\u0100-\uFFFF\w\-]/g,'-') // Remove all non-word chars ( fix for UTF-8 chars )
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
}

*based on https://gist.github.com/mathewbyrne/1280286

now you can transform this string:

Barack_Obama       ?????_????? ~!@#$%^&*()+/-+?><:";'{}[]\|`

into:

barack_obama-?????_?????

applying to your code:

$("#Restaurant_Name").keyup(function(){
    var Text = $(this).val();
    Text = slugify(Text);
    $("#Restaurant_Slug").val(Text);
});

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

The PYTHONPATH environment variable is used by Python to specify a list of directories that modules can be imported from on Windows. When running, you can inspect the sys.path variable to see which directories will be searched when you import something.

To set this variable from the Command Prompt, use: set PYTHONPATH=list;of;paths.

To set this variable from PowerShell, use: $env:PYTHONPATH=’list;of;paths’ just before you launch Python.

Setting this variable globally through the Environment Variables settings is not recommended, as it may be used by any version of Python instead of the one that you intend to use. Read more in the Python on Windows FAQ docs.

jQuery - Check if DOM element already exists

Just to confirm that you are selecting the element in the right way. Try this one

if ($('#some_element').length == 0) {
    //Add it to the dom
}

Read contents of a local file into a variable in Rails

Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read} and all was fine.

Server configuration is missing in Eclipse

I faced the same problem once. THe reason for this is that even though the server is available, the config files are missing. You can see the server at Windows -> Show view -> Servers. Their configuration files can be seen at Project Explorer -> Servers. For some reason this second mentioned config files were missing.

I simply deleted the existing server and created a new one with this the config files were also created and the problem was solved!

Similar solution is given at here by Emertana EM java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

Open Facebook page from Android app?

Answering this in October 2018. The working code is the one using the pageID. I just tested it and it is functional.

public static void openUrl(Context ctx, String url){
    Uri uri = Uri.parse(url);
    if (url.contains(("facebook"))){
        try {
            ApplicationInfo applicationInfo = ctx.getPackageManager().getApplicationInfo("com.facebook.katana", 0);
            if (applicationInfo.enabled) {
                uri = Uri.parse("fb://page/<page_id>");
                openURI(ctx, uri);
                return;
            }
        } catch (PackageManager.NameNotFoundException ignored) {
            openURI(ctx, uri);
            return;
        }
    }

CSS: how do I create a gap between rows in a table?

In my opinion, the easiest way to do is adding padding to your tag.

td {
 padding: 10px 0
}

Hope this will help you! Cheer!

Filter element based on .data() key/value

We can make a plugin pretty easily:

$.fn.filterData = function(key, value) {
    return this.filter(function() {
        return $(this).data(key) == value;
    });
};

Usage (checking a radio button):

$('input[name=location_id]').filterData('my-data','data-val').prop('checked',true);

Formatting Decimal places in R

if you just want to round a number or a list, simply use

round(data, 2)

Then, data will be round to 2 decimal place.

git - Server host key not cached

The message means that the host key of origin is not present in your trusted hosts file.

To get around this, open a plain SSH connection to origin and SSH will ask you if you want to trust the remote host (from the Git console):

$ ssh 127.0.0.1
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
RSA key fingerprint is <FINGERPRINT>.
Are you sure you want to continue connecting (yes/no)?

If you trust the remote host (i.e. type yes), SSH will add its key to the list of known hosts.

After that, you should be able to do your git push origin.

As an alternative, you could also manually add the key of origin to .ssh/known_hosts but this requires that you adhere to the format of the known_hosts file as described in the man page of sshd (Section AUTHORIZED_KEYS FILE FORMAT).

How do I change the JAVA_HOME for ant?

Set the env var: JAVACMD - full path of the Java executable. Use this to invoke a different JVM than JAVA_HOME/bin/java(.exe).

Reference: http://ant.apache.org/manual/running.html

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

The first part:

.Cells(.Rows.Count,"A")

Sends you to the bottom row of column A, which you knew already.

The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:

Sheet1.Cells(4,"C").End(xlToRight).Select

The program will select E4, the rightmost cell with text in it.

In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?

How to read files and stdout from a running Docker container

The stdout of the process started by the docker container is available through the docker logs $containerid command (use -f to keep it going forever). Another option would be to stream the logs directly through the docker remote API.

For accessing log files (only if you must, consider logging to stdout or other standard solution like syslogd) your only real-time option is to configure a volume (like Marcus Hughes suggests) so the logs are stored outside the container and available for processing from the host or another container.

If you do not need real-time access to the logs, you can export the files (in tar format) with docker export

Any easy way to use icons from resources?

How I load Icons: Using Visual Studio 2010: Go to the project properties, click Add Resource > Existing File, select your Icon.

You'll see that a Resources folder appeared. This was my problem, I had to click the loaded icon (in Resources directory), and set "Copy to Output Directory" to "Copy always". (was set "Do not copy").

Now simply do:

Icon myIcon = new Icon("Resources/myIcon.ico");

SSL: CERTIFICATE_VERIFY_FAILED with Python3

Go to the folder where Python is installed, e.g., in my case (Mac OS) it is installed in the Applications folder with the folder name 'Python 3.6'. Now double click on 'Install Certificates.command'. You will no longer face this error.

For those not running a mac, or having a different setup and can't find this file, the file merely runs:

pip install --upgrade certifi

Hope that helps someone :)

How can I shrink the drawable on a button?

You can call setBounds on the "compound" drawables to modify the size of the image.

Try this code to autosize the drawable of your button:

DroidUtils.scaleButtonDrawables((Button) findViewById(R.id.ButtonTest), 1.0);

defined by this function:

public final class DroidUtils {

    /** scale the Drawables of a button to "fit"
     *  For left and right drawables: height is scaled 
     *  eg. with fitFactor 1 the image has max. the height of the button.
     *  For top and bottom drawables: width is scaled: 
     *  With fitFactor 0.9 the image has max. 90% of the width of the button 
     *  */
    public static void scaleButtonDrawables(Button btn, double fitFactor) {
        Drawable[] drawables = btn.getCompoundDrawables();

        for (int i = 0; i < drawables.length; i++) {
            if (drawables[i] != null) {
                int imgWidth = drawables[i].getIntrinsicWidth();
                int imgHeight = drawables[i].getIntrinsicHeight();
                if ((imgHeight > 0) && (imgWidth > 0)) {    //might be -1
                    float scale;
                    if ((i == 0) || (i == 2)) { //left or right -> scale height
                        scale = (float) (btn.getHeight() * fitFactor) / imgHeight;
                    } else { //top or bottom -> scale width
                        scale = (float) (btn.getWidth() * fitFactor) / imgWidth;                    
                    }
                    if (scale < 1.0) {
                        Rect rect = drawables[i].getBounds();
                        int newWidth = (int)(imgWidth * scale);
                        int newHeight = (int)(imgHeight * scale);
                        rect.left = rect.left + (int)(0.5 * (imgWidth - newWidth)); 
                        rect.top = rect.top + (int)(0.5 * (imgHeight - newHeight));
                        rect.right = rect.left + newWidth;
                        rect.bottom = rect.top + newHeight;
                        drawables[i].setBounds(rect);
                    }
                }
            }
        }
    }
}

Be aware, that this may not be called in onCreate() of an activity, because button height and width are not (yet) available there. Call this in on onWindowFocusChanged() or use this solution to call the function.

Edited:

The first incarnation of this function did not work correctly. It used userSeven7s code to scale the image, but returning ScaleDrawable.getDrawable() does not seem to work (neither does returning ScaleDrawable) for me.

The modified code uses setBounds to provide the bounds for the image. Android fits the image into these bounds.

JavaScript Array to Set

Just pass the array to the Set constructor. The Set constructor accepts an iterable parameter. The Array object implements the iterable protocol, so its a valid parameter.

_x000D_
_x000D_
var arr = [55, 44, 65];_x000D_
var set = new Set(arr);_x000D_
console.log(set.size === arr.length);_x000D_
console.log(set.has(65));
_x000D_
_x000D_
_x000D_

See here

MySql server startup error 'The server quit without updating PID file '

its a problem in 5.5 version

Here's an example for the [mysqld] section of your my.cnf:

 skip-character-set-client-handshake
 collation_server=utf8_unicode_ci
 character_set_server=utf8

refers :http://dev.mysql.com/doc/refman/5.6/en/charset-server.html

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

Using phpMyAdmin (or whatever you prefer), I just created a database called "forge" and re-ran the php artisan migrate command and it all worked.

Building a fat jar using maven

actually, adding the

<archive>
   <manifest>
    <addClasspath>true</addClasspath>
    <packageName>com.some.pkg</packageName>                     
    <mainClass>com.MainClass</mainClass>
  </manifest>
</archive>

declaration to maven-jar-plugin does not add the main class entry to the manifest file for me. I had to add it to the maven-assembly-plugin in order to get that in the manifest

How to print the current Stack Trace in .NET without any exception?

   private void ExceptionTest()
    {
        try
        {
            int j = 0;
            int i = 5;
            i = 1 / j;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            var stList = ex.StackTrace.ToString().Split('\\');
            Console.WriteLine("Exception occurred at " + stList[stList.Count() - 1]);
        }
    }

Seems to work for me

AddRange to a Collection

Here is a bit more advanced/production-ready version:

    public static class CollectionExtensions
    {
        public static TCol AddRange<TCol, TItem>(this TCol destination, IEnumerable<TItem> source)
            where TCol : ICollection<TItem>
        {
            if(destination == null) throw new ArgumentNullException(nameof(destination));
            if(source == null) throw new ArgumentNullException(nameof(source));

            // don't cast to IList to prevent recursion
            if (destination is List<TItem> list)
            {
                list.AddRange(source);
                return destination;
            }

            foreach (var item in source)
            {
                destination.Add(item);
            }

            return destination;
        }
    }

How to compare dates in datetime fields in Postgresql?

@Nicolai is correct about casting and why the condition is false for any data. i guess you prefer the first form because you want to avoid date manipulation on the input string, correct? you don't need to be afraid:

SELECT *
FROM table
WHERE update_date >= '2013-05-03'::date
AND update_date < ('2013-05-03'::date + '1 day'::interval);

How to make code wait while calling asynchronous calls like Ajax

If you need wait until the ajax call is completed all do you need is make your call synchronously.

Android studio takes too much memory

Try switching your JVM to eclipse openj9. Its gonna use way less memory. I swapped it and its using 600Mb constantly.

Android SDK installation doesn't find JDK

Android SDK is 32 bit app, and it requires the 32 bit of JDK to work... the 64 bit JDK won't make any use for it...

How would I access variables from one class to another?

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2
    def method(self):
        self.var1 = self.var1 + self.var2
        return self.var1

class ClassB(ClassA):
    def __init__(self):
        ClassA.__init__(self)

object1 = ClassA() 
sum = object1.method()  
object2 = ClassB() 
print sum

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

Use the pattern from Joshua Bloch, Effective Java:

(simplified for brevity)

enum MyEnum {
    ENUM_1("A"),
    ENUM_2("B");

    private String name;

    private static final Map<String,MyEnum> ENUM_MAP;

    MyEnum (String name) {
        this.name = name;
    }

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

    // Build an immutable map of String name to enum pairs.
    // Any Map impl can be used.

    static {
        Map<String,MyEnum> map = new ConcurrentHashMap<String, MyEnum>();
        for (MyEnum instance : MyEnum.values()) {
            map.put(instance.getName().toLowerCase(),instance);
        }
        ENUM_MAP = Collections.unmodifiableMap(map);
    }

    public static MyEnum get (String name) {
        return ENUM_MAP.get(name.toLowerCase());
    }
}

Also see:

Oracle Java Example using Enum and Map of instances

Execution order of of static blocks in an Enum type

How can I lookup a Java enum from its String value

A cron job for rails: best practices?

The problem with whenever (and cron) is that it reloads the rails environment every time it's executed, which is a real problem when your tasks are frequent or have a lot of initialization work to do. I have had issues in production because of this and must warn you.

Rufus scheduler does it for me ( https://github.com/jmettraux/rufus-scheduler )

When I have long jobs to run, I use it with delayed_job ( https://github.com/collectiveidea/delayed_job )

I hope this helps!

How to delete an item in a list if it exists?

try:
    s.remove("")
except ValueError:
    print "new_tag_list has no empty string"

Note that this will only remove one instance of the empty string from your list (as your code would have, too). Can your list contain more than one?

How do you convert an entire directory with ffmpeg?

For Windows:

Here I'm Converting all the (.mp4) files to (.mp3) files.
Just open cmd, goto the desired folder and type the command.

Shortcut: (optional)
1. Goto the folder where your (.mp4) files are present
2. Press Shift and Left click and Choose "Open PowerShell Window Here"
or "Open Command Prompt Window Here"
3. Type "cmd" [NOTE: Skip this step if it directly opens cmd instead of PowerShell]
4. Run the command

for %i in (*.mp4) do ffmpeg -i "%i" "%~ni.mp3"

If you want to put this into a batch file on Windows 10, you need to use %%i.

Convert a tensor to numpy array in Tensorflow?

Any tensor returned by Session.run or eval is a NumPy array.

>>> print(type(tf.Session().run(tf.constant([1,2,3]))))
<class 'numpy.ndarray'>

Or:

>>> sess = tf.InteractiveSession()
>>> print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

Or, equivalently:

>>> sess = tf.Session()
>>> with sess.as_default():
>>>    print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

EDIT: Not any tensor returned by Session.run or eval() is a NumPy array. Sparse Tensors for example are returned as SparseTensorValue:

>>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>

Alternative to itoa() for converting integer to string C++?

Archeology

itoa was a non-standard helper function designed to complement the atoi standard function, and probably hiding a sprintf (Most its features can be implemented in terms of sprintf): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html

The C Way

Use sprintf. Or snprintf. Or whatever tool you find.

Despite the fact some functions are not in the standard, as rightly mentioned by "onebyone" in one of his comments, most compiler will offer you an alternative (e.g. Visual C++ has its own _snprintf you can typedef to snprintf if you need it).

The C++ way.

Use the C++ streams (in the current case std::stringstream (or even the deprecated std::strstream, as proposed by Herb Sutter in one of his books, because it's somewhat faster).

Conclusion

You're in C++, which means that you can choose the way you want it:

  • The faster way (i.e. the C way), but you should be sure the code is a bottleneck in your application (premature optimizations are evil, etc.) and that your code is safely encapsulated to avoid risking buffer overruns.

  • The safer way (i.e., the C++ way), if you know this part of the code is not critical, so better be sure this part of the code won't break at random moments because someone mistook a size or a pointer (which happens in real life, like... yesterday, on my computer, because someone thought it "cool" to use the faster way without really needing it).

How do I call one constructor from another in Java?

Using this keyword we can call one constructor in another constructor within same class.

Example :-

 public class Example {
   
      private String name;
   
      public Example() {
          this("Mahesh");
      }

      public Example(String name) {
          this.name = name;
      }

 }

jQuery - disable selected options

Add this line to your change event handler

    $("#theSelect option:selected").attr('disabled','disabled')
        .siblings().removeAttr('disabled');

This will disable the selected option, and enable any previously disabled options.

EDIT:

If you did not want to re-enable the previous ones, just remove this part of the line:

        .siblings().removeAttr('disabled');

EDIT:

http://jsfiddle.net/pd5Nk/1/

To re-enable when you click remove, add this to your click handler.

$("#theSelect option[value=" + value + "]").removeAttr('disabled');

Convert file: Uri to File in Android

Android + Kotlin

  1. Add dependency for Kotlin Android extensions:

    implementation 'androidx.core:core-ktx:{latestVersion}'

  2. Get file from uri:

    uri.toFile()

Android + Java

Just move to top ;)

Find an element in a list of tuples

>>> [i for i in a if 1 in i]

[(1, 2), (1, 4)]

React.js: Wrapping one component into another

Try:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          {this.props.children}
        after
      </div>
    );
  }
});

See Multiple Components: Children and Type of the Children props in the docs for more info.

How to replace space with comma using sed?

I just confirmed that:

cat file.txt | sed "s/\s/,/g"

successfully replaces spaces with commas in Cygwin terminals (mintty 2.9.0). None of the other samples worked for me.

PHP validation/regex for URL

Peter's Regex doesn't look right to me for many reasons. It allows all kinds of special characters in the domain name and doesn't test for much.

Frankie's function looks good to me and you can build a good regex from the components if you don't want a function, like so:

^(http://|https://)(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z]{2,6}

Untested but I think that should work.

Also, Owen's answer doesn't look 100% either. I took the domain part of the regex and tested it on a Regex tester tool http://erik.eae.net/playground/regexp/regexp.html

I put the following line:

(\S*?\.\S*?)

in the "regexp" section and the following line:

-hello.com

under the "sample text" section.

The result allowed the minus character through. Because \S means any non-space character.

Note the regex from Frankie handles the minus because it has this part for the first character:

[a-z0-9]

Which won't allow the minus or any other special character.

How can I change the current URL?

This will do it:

window.history.pushState(null,null,'https://www.google.com');

pthread_join() and pthread_exit()

It because every time

void pthread_exit(void *ret);

will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().

Now at

int pthread_join(pthread_t tid, void **ret);

will be always called from where thread is created so here to accept that returned pointer you need double pointer ..

i think this code will help you to understand this

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>

void* thread_function(void *ignoredInThisExample)
{
    char *a = malloc(10);
    strcpy(a,"hello world");
    pthread_exit((void*)a);
}
int main()
{
    pthread_t thread_id;
    char *b;

    pthread_create (&thread_id, NULL,&thread_function, NULL);

    pthread_join(thread_id,(void**)&b); //here we are reciving one pointer 
                                        value so to use that we need double pointer 
    printf("b is %s\n",b); 
    free(b); // lets free the memory

}

Best way to encode text data for XML in Java?

While I agree with Jon Skeet in principle, sometimes I don't have the option to use an external XML library. And I find it peculiar the two functions to escape/unescape a simple value (attribute or tag, not full document) are not available in the standard XML libraries included with Java.

As a result and based on the different answers I have seen posted here and elsewhere, here is the solution I've ended up creating (nothing worked as a simple copy/paste):

  public final static String ESCAPE_CHARS = "<>&\"\'";
  public final static List<String> ESCAPE_STRINGS = Collections.unmodifiableList(Arrays.asList(new String[] {
      "&lt;"
    , "&gt;"
    , "&amp;"
    , "&quot;"
    , "&apos;"
  }));

  private static String UNICODE_NULL = "" + ((char)0x00); //null
  private static String UNICODE_LOW =  "" + ((char)0x20); //space
  private static String UNICODE_HIGH = "" + ((char)0x7f);

  //should only be used for the content of an attribute or tag      
  public static String toEscaped(String content) {
    String result = content;
    
    if ((content != null) && (content.length() > 0)) {
      boolean modified = false;
      StringBuilder stringBuilder = new StringBuilder(content.length());
      for (int i = 0, count = content.length(); i < count; ++i) {
        String character = content.substring(i, i + 1);
        int pos = ESCAPE_CHARS.indexOf(character);
        if (pos > -1) {
          stringBuilder.append(ESCAPE_STRINGS.get(pos));
          modified = true;
        }
        else {
          if (    (character.compareTo(UNICODE_LOW) > -1)
               && (character.compareTo(UNICODE_HIGH) < 1)
             ) {
            stringBuilder.append(character);
          }
          else {
            //Per URL reference below, Unicode null character is always restricted from XML
            //URL: https://en.wikipedia.org/wiki/Valid_characters_in_XML
            if (character.compareTo(UNICODE_NULL) != 0) {
              stringBuilder.append("&#" + ((int)character.charAt(0)) + ";");
            }
            modified = true;
          }
        }
      }
      if (modified) {
        result = stringBuilder.toString();
      }
    }
    
    return result;
  }

The above accommodates several different things:

  1. avoids using char based logic until it absolutely has to - improves unicode compatibility
  2. attempts to be as efficient as possible given the probability is the second "if" condition is likely the most used pathway
  3. is a pure function; i.e. is thread-safe
  4. optimizes nicely with the garbage collector by only returning the contents of the StringBuilder if something actually changed - otherwise, the original string is returned

At some point, I will write the inversion of this function, toUnescaped(). I just don't have time to do that today. When I do, I will come update this answer with the code. :)

How to pass data in the ajax DELETE request other than headers

Read this Bug Issue: http://bugs.jquery.com/ticket/11586

Quoting the RFC 2616 Fielding

The DELETE method requests that the origin server delete the resource identified by the Request-URI.

So you need to pass the data in the URI

$.ajax({
    url: urlCall + '?' + $.param({"Id": Id, "bolDeleteReq" : bolDeleteReq}),
    type: 'DELETE',
    success: callback || $.noop,
    error: errorCallback || $.noop
});

How do I create a Linked List Data Structure in Java?

The obvious solution to developers familiar to Java is to use the LinkedList class already provided in java.util. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. Enhancements to this implementation include making it a double-linked list, adding methods to insert and delete from the middle or end, and by adding get and sort methods as well.

Note: In the example, the Link object doesn't actually contain another Link object - nextLink is actually only a reference to another link.

class Link {
    public int data1;
    public double data2;
    public Link nextLink;

    //Link constructor
    public Link(int d1, double d2) {
        data1 = d1;
        data2 = d2;
    }

    //Print Link data
    public void printLink() {
        System.out.print("{" + data1 + ", " + data2 + "} ");
    }
}

class LinkList {
    private Link first;

    //LinkList constructor
    public LinkList() {
        first = null;
    }

    //Returns true if list is empty
    public boolean isEmpty() {
        return first == null;
    }

    //Inserts a new Link at the first of the list
    public void insert(int d1, double d2) {
        Link link = new Link(d1, d2);
        link.nextLink = first;
        first = link;
    }

    //Deletes the link at the first of the list
    public Link delete() {
        Link temp = first;
        if(first == null){
         return null;
         //throw new NoSuchElementException(); // this is the better way. 
        }
        first = first.nextLink;
        return temp;
    }

    //Prints list data
    public void printList() {
        Link currentLink = first;
        System.out.print("List: ");
        while(currentLink != null) {
            currentLink.printLink();
            currentLink = currentLink.nextLink;
        }
        System.out.println("");
    }
}  

class LinkListTest {
    public static void main(String[] args) {
        LinkList list = new LinkList();

        list.insert(1, 1.01);
        list.insert(2, 2.02);
        list.insert(3, 3.03);
        list.insert(4, 4.04);
        list.insert(5, 5.05);

        list.printList();

        while(!list.isEmpty()) {
            Link deletedLink = list.delete();
            System.out.print("deleted: ");
            deletedLink.printLink();
            System.out.println("");
        }
        list.printList();
    }
}

Is it possible to use jQuery to read meta tags

For select twitter meta name , you can add a data attribute.

example :

meta name="twitter:card" data-twitterCard="" content=""
$('[data-twitterCard]').attr('content');

Ignoring NaNs with str.contains

There's a flag for that:

In [11]: df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])

In [12]: df.a.str.contains("foo")
Out[12]:
0     True
1     True
2    False
3      NaN
Name: a, dtype: object

In [13]: df.a.str.contains("foo", na=False)
Out[13]:
0     True
1     True
2    False
3    False
Name: a, dtype: bool

See the str.replace docs:

na : default NaN, fill value for missing values.


So you can do the following:

In [21]: df.loc[df.a.str.contains("foo", na=False)]
Out[21]:
      a
0  foo1
1  foo2

Create JSON object dynamically via JavaScript (Without concate strings)

This topic, especially the answer of Xotic750 was very helpful to me. I wanted to generate a json variable to pass it to a php script using ajax. My values were stored into two arrays, and i wanted them in json format. This is a generic example:

valArray1 = [121, 324, 42, 31];
valArray2 = [232, 131, 443];
myJson = {objArray1: {}, objArray2: {}};
for (var k = 1; k < valArray1.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray1[k];
    myJson.objArray1[objName] = objValue;
}
for (var k = 1; k < valArray2.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray2[k];
    myJson.objArray2[objName] = objValue;
}
console.log(JSON.stringify(myJson));

The result in the console Log should be something like this:

{
   "objArray1": {
        "obj1": 121,
        "obj2": 324,
        "obj3": 42,
        "obj4": 31
   },
   "objArray2": {
        "obj1": 232,
        "obj2": 131,
        "obj3": 443
  }
}

How do I measure request and response times at once using cURL?

From this brilliant blog post... https://blog.josephscott.org/2011/10/14/timing-details-with-curl/

cURL supports formatted output for the details of the request (see the cURL manpage for details, under -w, –write-out <format>). For our purposes we’ll focus just on the timing details that are provided. Times below are in seconds.

  1. Create a new file, curl-format.txt, and paste in:

         time_namelookup:  %{time_namelookup}s\n
            time_connect:  %{time_connect}s\n
         time_appconnect:  %{time_appconnect}s\n
        time_pretransfer:  %{time_pretransfer}s\n
           time_redirect:  %{time_redirect}s\n
      time_starttransfer:  %{time_starttransfer}s\n
                         ----------\n
              time_total:  %{time_total}s\n
    
  2. Make a request:

     curl -w "@curl-format.txt" -o /dev/null -s "http://wordpress.com/"
    

Or on Windows, it's...

    curl -w "@curl-format.txt" -o NUL -s "http://wordpress.com/"

What this does:

-w "@curl-format.txt" tells cURL to use our format file
-o /dev/null redirects the output of the request to /dev/null
-s tells cURL not to show a progress meter
"http://wordpress.com/" is the URL we are requesting. Use quotes particularly if your URL has "&" query string parameters


And here is what you get back:

   time_namelookup:  0.001s
      time_connect:  0.037s
   time_appconnect:  0.000s
  time_pretransfer:  0.037s
     time_redirect:  0.000s
time_starttransfer:  0.092s
                   ----------
        time_total:  0.164s

Make a Linux/Mac shortcut (alias)

alias curltime="curl -w \"@$HOME/.curl-format.txt\" -o /dev/null -s "

Then you can simply call...

curltime wordpress.org

Thanks to commenter Pete Doyle!


Make a Linux/Mac stand-alone script

This script does not require a separate .txt file to contain the formatting.

Create a new file, curltime, somewhere in your executable path, and paste in:

#!/bin/bash

curl -w @- -o /dev/null -s "$@" <<'EOF'
    time_namelookup:  %{time_namelookup}\n
       time_connect:  %{time_connect}\n
    time_appconnect:  %{time_appconnect}\n
   time_pretransfer:  %{time_pretransfer}\n
      time_redirect:  %{time_redirect}\n
 time_starttransfer:  %{time_starttransfer}\n
                    ----------\n
         time_total:  %{time_total}\n
EOF

Call the same way as the alias:

curltime wordpress.org

Make a Windows shortcut (aka BAT file)

Put this command in CURLTIME.BAT (in the same folder as curl.exe)

curl -w "@%~dp0curl-format.txt" -o NUL -s %*

Then you can simply call...

curltime wordpress.org

VBA - Select columns using numbers?

you can use range with cells to get the effect you want (but it would be better not to use select if you don't have to)

For n = 1 to 5
range(cells(1,n).entirecolumn,cells(1,n+4).entirecolumn).Select
do sth
next n

How can I access an internal class from an external assembly?

Well, you can't. Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.

Eloquent ->first() if ->exists()

(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:

$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();

Oh, also: count() instead if exists but this could be something used after get.

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

Print execution time of a shell command

For a line-by-line delta measurement, try gnonom.

It is a command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.

Piping anything to gnomon will prepend a timestamp to each line, indicating how long that line was the last line in the buffer--that is, how long it took the next line to appear. By default, gnomon will display the seconds elapsed between each line, but that is configurable.

gnomon demo

Get the Year/Month/Day from a datetime in php?

Use DateTime with DateTime::format()

$datetime = new DateTime($dateTimeString);
echo $datetime->format('w');

What is the difference between & vs @ and = in angularJS

@: one-way binding

=: two-way binding

&: function binding

How to append one file to another in Linux from the shell?

Just for reference, using ddrescue provides an interruptible way of achieving the task if, for example, you have large files and the need to pause and then carry on at some later point:

ddrescue -o $(wc --bytes file1 | awk '{ print $1 }') file2 file1 logfile

The logfile is the important bit. You can interrupt the process with Ctrl-C and resume it by specifying the exact same command again and ddrescue will read logfile and resume from where it left off. The -o A flag tells ddrescue to start from byte A in the output file (file1). So wc --bytes file1 | awk '{ print $1 }' just extracts the size of file1 in bytes (you can just paste in the output from ls if you like).

As pointed out by ngks in the comments, the downside is that ddrescue will probably not be installed by default, so you will have to install it manually. The other complication is that there are two versions of ddrescue which might be in your repositories: see this askubuntu question for more info. The version you want is the GNU ddrescue, and on Debian-based systems is the package named gddrescue:

sudo apt install gddrescue

For other distros check your package management system for the GNU version of ddrescue.

ValueError: unsupported format character while forming strings

Well, why do you have %20 url-quoting escapes in a formatting string in first place? Ideally you'd do the interpolation formatting first:

formatting_template = 'Hello World%s'
text = '!'
full_string = formatting_template % text

Then you url quote it afterwards:

result = urllib.quote(full_string)

That is better because it would quote all url-quotable things in your string, including stuff that is in the text part.

C string append

You need to allocate new space as well. Consider this code fragment:

char * new_str ;
if((new_str = malloc(strlen(str1)+strlen(str2)+1)) != NULL){
    new_str[0] = '\0';   // ensures the memory is an empty string
    strcat(new_str,str1);
    strcat(new_str,str2);
} else {
    fprintf(STDERR,"malloc failed!\n");
    // exit?
}

You might want to consider strnlen(3) which is slightly safer.

Updated, see above. In some versions of the C runtime, the memory returned by malloc isn't initialized to 0. Setting the first byte of new_str to zero ensures that it looks like an empty string to strcat.

Zero-pad digits in string

The performance of str_pad heavily depends on the length of padding. For more consistent speed you can use str_repeat.

$padded_string = str_repeat("0", $length-strlen($number)) . $number;

Also use string value of the number for better performance.

$number = strval(123);

Tested on PHP 7.4

str_repeat: 0.086055040359497   (number: 123, padding: 1)
str_repeat: 0.085798978805542   (number: 123, padding: 3)
str_repeat: 0.085641145706177   (number: 123, padding: 10)
str_repeat: 0.091305017471313   (number: 123, padding: 100)

str_pad:    0.086184978485107   (number: 123, padding: 1)
str_pad:    0.096981048583984   (number: 123, padding: 3)
str_pad:    0.14874792098999    (number: 123, padding: 10)
str_pad:    0.85979700088501    (number: 123, padding: 100)

How do I change data-type of pandas data frame to string with a defined format?

I'm unable to reproduce your problem but have you tried converting it to an integer first?

image_name_data['id'] = image_name_data['id'].astype(int).astype('str')

Then, regarding your more general question you could use map (as in this answer). In your case:

image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)

JavaScript Number Split into individual digits

This is my short solution.. with sum of number

    function sum (num) {
    let sNumber = num
        .toString()
        .split('')
        .reduce((el1, el2) => {
            return Number(el1) + Number(el2)
        }, 0)
        return sNumber
     }

console.log(sum(123))
console.log(sum(456))

Python logging not outputting anything

For anyone here that wants a super-simple answer: just set the level you want displayed. At the top of all my scripts I just put:

import logging
logging.basicConfig(level = logging.INFO)

Then to display anything at or above that level:

logging.info("Hi you just set your fleeb to level plumbus")

It is a hierarchical set of five levels so that logs will display at the level you set, or higher. So if you want to display an error you could use logging.error("The plumbus is broken").

The levels, in increasing order of severity, are DEBUG, INFO, WARNING, ERROR, and CRITICAL. The default setting is WARNING.

This is a good article containing this information expressed better than my answer:
https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3

How do you change the character encoding of a postgres database?

First off, Daniel's answer is the correct, safe option.

For the specific case of changing from SQL_ASCII to something else, you can cheat and simply poke the pg_database catalogue to reassign the database encoding. This assumes you've already stored any non-ASCII characters in the expected encoding (or that you simply haven't used any non-ASCII characters).

Then you can do:

update pg_database set encoding = pg_char_to_encoding('UTF8') where datname = 'thedb'

This will not change the collation of the database, just how the encoded bytes are converted into characters (so now length('£123') will return 4 instead of 5). If the database uses 'C' collation, there should be no change to ordering for ASCII strings. You'll likely need to rebuild any indices containing non-ASCII characters though.

Caveat emptor. Dumping and reloading provides a way to check your database content is actually in the encoding you expect, and this doesn't. And if it turns out you did have some wrongly-encoded data in the database, rescuing is going to be difficult. So if you possibly can, dump and reinitialise.

PHP date() format when inserting into datetime in MySQL

There is no need no use the date() method from PHP if you don't use a timestamp. If dateposted is a datetime column, you can insert the current date like this:

$db->query("INSERT INTO table (dateposted) VALUES (now())");

LINQ: Select where object does not contain items from list

I have not tried this, so I am not guarantueeing anything, however

foreach Bar f in filterBars
{
     search(f)
}
Foo search(Bar b)
{
    fooSelect = (from f in fooBunch
                 where !(from b in f.BarList select b.BarId).Contains(b.ID)
                 select f).ToList();

    return fooSelect;
}

How to do join on multiple criteria, returning all combinations of both criteria

create table a1
(weddingTable INT(3),
 tableSeat INT(3),
 tableSeatID INT(6),
 Name varchar(10));

insert into a1
 (weddingTable, tableSeat, tableSeatID, Name)
 values (001,001,001001,'Bob'),
 (001,002,001002,'Joe'),
 (001,003,001003,'Dan'),
 (002,001,002001,'Mark');

create table a2
 (weddingTable int(3),
 tableSeat int(3),
 Meal varchar(10));

insert into a2
(weddingTable, tableSeat, Meal)
values 
(001,001,'Chicken'),
(001,002,'Steak'),
(001,003,'Salmon'),
(002,001,'Steak');

select x.*, y.Meal

from a1 as x
JOIN a2 as y ON (x.weddingTable = y.weddingTable) AND (x.tableSeat = y. tableSeat);

ASP.NET MVC: Custom Validation by DataAnnotation

To improve Darin's answer, it can be bit shorter:

public class UniqueFileName : ValidationAttribute
{
    private readonly NewsService _newsService = new NewsService();

    public override bool IsValid(object value)
    {
        if (value == null) { return false; }

        var file = (HttpPostedFile) value;

        return _newsService.IsFileNameUnique(file.FileName);
    }
}

Model:

[UniqueFileName(ErrorMessage = "This file name is not unique.")]

Do note that an error message is required, otherwise the error will be empty.

What does 'low in coupling and high in cohesion' mean

I think you have red so many definitions but in the case you still have doubts or In case you are new to programming and want to go deep into this then I will suggest you to watch this video, https://youtu.be/HpJTGW9AwX0 It's just reference to get more info about polymorphism... Hope you get better understanding with this

Making RGB color in Xcode

Color picker plugin for Interface Builder

There's a nice color picker from Panic which works well with IB: http://panic.com/~wade/picker/

Xcode plugin

This one gives you a GUI for choosing colors: http://www.youtube.com/watch?v=eblRfDQM0Go

Objective-C

UIColor *color = [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1.0];

Swift

let color = UIColor(red: 160/255, green: 97/255, blue: 5/255, alpha: 1.0)

Pods and libraries

There's a nice pod named MPColorTools: https://github.com/marzapower/MPColorTools

How to run the sftp command with a password from Bash script?

You have a few options other than using public key authentication:

  1. Use keychain
  2. Use sshpass (less secured but probably that meets your requirement)
  3. Use expect (least secured and more coding needed)

If you decide to give sshpass a chance here is a working script snippet to do so:

export SSHPASS=your-password-here
sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host << !
   cd incoming
   put your-log-file.log
   bye
!

Replacing characters in Ant property

Use the propertyregex task from Ant Contrib.

I think you want:

<propertyregex property="propB"
               input="${propA}"
               regexp=" "
               replace="_"
               global="true" />

Unfortunately the examples given aren't terribly clear, but it's worth trying that. You should also check what happens if there aren't any underscores - you may need to use the defaultValue option as well.

How to install Ruby 2.1.4 on Ubuntu 14.04

update ubuntu:

 sudo apt-get update
 sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Install rvm, which manages the ruby versions:

to install rvm use the following command.

 \curl -sSL https://get.rvm.io | bash -s stable
 source ~/.bash_profile
 rvm install ruby-2.1.4

Check ruby versions installed and in use:

rvm list
rvm use --default ruby-2.1.4

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

There is now a new way of addressing this issue - if you remove position: relative from the container which needs to have the overflow-y visible, you can have overflow-y visible and overflow-x hidden, and vice versa (have overflow-x visible and overflow-y hidden, just make sure the container with the visible property is not relatively positioned).

See this post from CSS Tricks for more details - it worked for me: https://css-tricks.com/popping-hidden-overflow/

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Get most recent file in a directory on Linux

Presuming you don't care about hidden files that start with a .

ls -rt | tail -n 1

Otherwise

ls -Art | tail -n 1

Can you use a trailing comma in a JSON object?

No. The JSON spec, as maintained at http://json.org, does not allow trailing commas. From what I've seen, some parsers may silently allow them when reading a JSON string, while others will throw errors. For interoperability, you shouldn't include it.

The code above could be restructured, either to remove the trailing comma when adding the array terminator or to add the comma before items, skipping that for the first one.

How to make an autocomplete TextBox in ASP.NET?

Try this: .aspx page

<td>  
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>  
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"  
   CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"  
   ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">  
      </asp:AutoCompleteExtender>  

Now To auto populate from database :

public static List<string> GetCompletionList(string prefixText, int count)  
    {  
        return AutoFillProducts(prefixText);  

    }  

    private static List<string> AutoFillProducts(string prefixText)  
    {  
        using (SqlConnection con = new SqlConnection())  
        {  
            con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;  
            using (SqlCommand com = new SqlCommand())  
            {  
                com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like @Search + '%'";  
                com.Parameters.AddWithValue("@Search", prefixText);  
                com.Connection = con;  
                con.Open();  
                List<string> countryNames = new List<string>();  
                using (SqlDataReader sdr = com.ExecuteReader())  
                {  
                    while (sdr.Read())  
                    {  
                        countryNames.Add(sdr["ProductName"].ToString());  
                    }  
                }  
                con.Close();  
                return countryNames;  
            }  
        }  
    }  

Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.

Create Procedure GetProductDet  
(  
@ProductName varchar(50)    
)  
as  
begin  
Select BrandName,warranty,Price from ProdcutMaster where ProductName=@ProductName  
End   

Create a function name to get product details ::

private void GetProductMasterDet(string ProductName)  
    {  
        connection();  
        com = new SqlCommand("GetProductDet", con);  
        com.CommandType = CommandType.StoredProcedure;  
        com.Parameters.AddWithValue("@ProductName", ProductName);  
        SqlDataAdapter da = new SqlDataAdapter(com);  
        DataSet ds=new DataSet();  
        da.Fill(ds);  
        DataTable dt = ds.Tables[0];  
        con.Close();  
        //Binding TextBox From dataTable  
        txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();  
        txtwarranty.Text = dt.Rows[0]["warranty"].ToString();  
        txtPrice.Text = dt.Rows[0]["Price"].ToString();   
    }

Auto post back should be true

<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

Now, Just call this function

protected void TextBox1_TextChanged(object sender, EventArgs e)  
  {  
      //calling method and Passing Values  
      GetProductMasterDet(TextBox1.Text);  
  } 

Rails raw SQL example

You can also mix raw SQL with ActiveRecord conditions, for example if you want to call a function in a condition:

my_instances = MyModel.where.not(attribute_a: nil) \
  .where('crc32(attribute_b) = ?', slot) \
  .select(:id)

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I just encountered the same problem and it had to do with some files being lost or corrupted. To correct the issue, just run check disk:

chkdsk /F e:

This can be run from the search windows box or from a cmd prompt. The /F fixes any issues it finds, like recovering the files. Once this finishes running, you can delete the files and folders like normal.

The zip() function in Python 3

The zip() function in Python 3 returns an iterator. That is the reason why when you print test1 you get - <zip object at 0x1007a06c8>. From documentation -

Make an iterator that aggregates elements from each of the iterables.

But once you do - list(test1) - you have exhausted the iterator. So after that anytime you do list(test1) would only result in empty list.

In case of test2, you have already created the list once, test2 is a list, and hence it will always be that list.

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

SyntaxError: unexpected EOF while parsing

The SyntaxError: unexpected EOF while parsing means that the end of your source code was reached before all code blocks were completed. A code block starts with a statement like for i in range(100): and requires at least one line afterwards that contains code that should be in it.

It seems like you were executing your program line by line in the ipython console. This works for single statements like a = 3 but not for code blocks like for loops. See the following example:

In [1]: for i in range(100):
  File "<ipython-input-1-ece1e5c2587f>", line 1
    for i in range(100):
                        ^
SyntaxError: unexpected EOF while parsing

To avoid this error, you have to enter the whole code block as a single input:

In [2]: for i in range(5):
   ...:     print(i, end=', ')
0, 1, 2, 3, 4,

How to determine an interface{} value's "real" type?

You also can do type switches:

switch v := myInterface.(type) {
case int:
    // v is an int here, so e.g. v + 1 is possible.
    fmt.Printf("Integer: %v", v)
case float64:
    // v is a float64 here, so e.g. v + 1.0 is possible.
    fmt.Printf("Float64: %v", v)
case string:
    // v is a string here, so e.g. v + " Yeah!" is possible.
    fmt.Printf("String: %v", v)
default:
    // And here I'm feeling dumb. ;)
    fmt.Printf("I don't know, ask stackoverflow.")
}

Angular 2 Date Input not binding to date value

Angular 2 completely ignores type=date. If you change type to text you'll see that your input has two-way binding.

<input type='text' #myDate [(ngModel)]='demoUser.date'/><br>

Here is pretty bad advise with better one to follow:

My project originally used jQuery. So, I'm using jQuery datepicker for now, hoping that angular team will fix the original issue. Also it's a better replacement because it has cross-browser support. FYI, input=date doesn't work in Firefox.

Good advise: There are few pretty good Angular2 datepickers:

Sort arrays of primitive types in descending order

In Java 8, a better and more concise approach could be:

double[] arr = {13.6, 7.2, 6.02, 45.8, 21.09, 9.12, 2.53, 100.4};

Double[] boxedarr = Arrays.stream( arr ).boxed().toArray( Double[]::new );
Arrays.sort(boxedarr, Collections.reverseOrder());
System.out.println(Arrays.toString(boxedarr));

This would give the reversed array and is more presentable.

Input: [13.6, 7.2, 6.02, 45.8, 21.09, 9.12, 2.53, 100.4]

Output: [100.4, 45.8, 21.09, 13.6, 9.12, 7.2, 6.02, 2.53]

Android SharedPreferences in Fragment

It is possible to get a context from within a Fragment

Just do

public class YourFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        final View root = inflater.inflate(R.layout.yout_fragment_layout, container, false);
        // get context here
        Context context = getContext();
        // do as you please with the context


        // if you decide to go with second option
        SomeViewModel someViewModel = ViewModelProviders.of(this).get(SomeViewModel.class);
        Context context = homeViewModel.getContext();
        // do as you please with the context
        return root;
    }
}

You may also attached an AndroidViewModel in the onCreateView method that implements a method that returns the application context

public class SomeViewModel extends AndroidViewModel {

    private MutableLiveData<ArrayList<String>> someMutableData;
    Context context;

    public SomeViewModel(Application application) {
        super(application);
        context = getApplication().getApplicationContext();
        someMutableData = new MutableLiveData<>();
        .
        .
     }

     public Context getContext() {
         return context
     }
  }

Get all attributes of an element using jQuery

Here is a one-liner for you.

JQuery Users:

Replace $jQueryObject with your jQuery object. i.e $('div').

Object.values($jQueryObject.get(0).attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));

Vanilla Javascript Users:

Replace $domElement with your HTML DOM selector. i.e document.getElementById('demo').

Object.values($domElement.attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));

Cheers!!

C++ int to byte array

Int to byte and vice versa.

unsigned char bytes[4];
unsigned long n = 1024;

bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;

printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);


int num = 0;
for(int i = 0; i < 4; i++)
 {
 num <<= 8;
 num |= bytes[i];
 }


printf("number %d",num);

Last Key in Python Dictionary

Since python 3.7 dict always ordered(insert order),

since python 3.8 keys(), values() and items() of dict returns: view that can be reversed:

to get last key:

next(reversed(my_dict.keys()))  

the same apply for values() and items()

PS, to get first key use: next(iter(my_dict.keys()))

How to see the CREATE VIEW code for a view in PostgreSQL?

GoodNews from v.9.6 and above, View editing are now native from psql. Just invoke \ev command. View definitions will show in your configured editor.

julian@assange=# \ev {your_view_names}

Bonus. Some useful command to interact with query buffer.

Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
  \ev [VIEWNAME [LINE]]  edit view definition with external editor
  \p                     show the contents of the query buffer
  \r                     reset (clear) the query buffer
  \s [FILE]              display history or save it to file
  \w FILE                write query buffer to file

Deep copy in ES6 using the spread syntax

No such functionality is built-in to ES6. I think you have a couple of options depending on what you want to do.

If you really want to deep copy:

  1. Use a library. For example, lodash has a cloneDeep method.
  2. Implement your own cloning function.

Alternative Solution To Your Specific Problem (No Deep Copy)

However, I think, if you're willing to change a couple things, you can save yourself some work. I'm assuming you control all call sites to your function.

  1. Specify that all callbacks passed to mapCopy must return new objects instead of mutating the existing object. For example:

    mapCopy(state, e => {
      if (e.id === action.id) {
        return Object.assign({}, e, {
          title: 'new item'
        });
      } else {  
        return e;
      }
    });
    

    This makes use of Object.assign to create a new object, sets properties of e on that new object, then sets a new title on that new object. This means you never mutate existing objects and only create new ones when necessary.

  2. mapCopy can be really simple now:

    export const mapCopy = (object, callback) => {
      return Object.keys(object).reduce(function (output, key) {
        output[key] = callback.call(this, object[key]);
        return output;
      }, {});
    }
    

Essentially, mapCopy is trusting its callers to do the right thing. This is why I said this assumes you control all call sites.

Can I set variables to undefined or pass undefined as an argument?

I'm a bit confused about Javascript undefined & null.

null generally behaves similarly to other scripting languages' concepts of the out-of-band ‘null’, ‘nil’ or ‘None’ objects.

undefined, on the other hand, is a weird JavaScript quirk. It's a singleton object that represents out-of-band values, essentially a second similar-but-different null. It comes up:

  1. When you call a function with fewer arguments than the arguments list in the function statement lists, the unpassed arguments are set to undefined. You can test for that with eg.:

    function dosomething(arg1, arg2) {
        if (arg2===undefined)
        arg2= DEFAULT_VALUE_FOR_ARG2;
        ...
    }
    

    With this method you can't tell the difference between dosomething(1) and dosomething(1, undefined); arg2 will be the same value in both. If you need to tell the difference you can look at arguments.length, but doing optional arguments like that isn't generally very readable.

  2. When a function has no return value;, it returns undefined. There's generally no need to use such a return result.

  3. When you declare a variable by having a var a statement in a block, but haven't yet assigned a value to it, it is undefined. Again, you shouldn't really ever need to rely on that.

  4. The spooky typeof operator returns 'undefined' when its operand is a simple variable that does not exist, instead of throwing an error as would normally happen if you tried to refer to it. (You can also give it a simple variable wrapped in parentheses, but not a full expression involving a non-existant variable.) Not much use for that, either.

  5. This is the controversial one. When you access a property of an object which doesn't exist, you don't immediately get an error like in every other language. Instead you get an undefined object. (And then when you try to use that undefined object later on in the script it'll go wrong in a weird way that's much more difficult to track down than if JavaScript had just thrown an error straight away.)

    This is often used to check for the existence of properties:

    if (o.prop!==undefined) // or often as truthiness test, if (o.prop)
       ...do something...
    

    However, because you can assign undefined like any other value:

    o.prop= undefined;
    

    that doesn't actually detect whether the property is there reliably. Better to use the in operator, which wasn't in the original Netscape version of JavaScript, but is available everywhere now:

    if ('prop' in o)
        ...
    

In summary, undefined is a JavaScript-specific mess, which confuses everyone. Apart from optional function arguments, where JS has no other more elegant mechanism, undefined should be avoided. It should never have been part of the language; null would have worked just fine for (2) and (3), and (4) is a misfeature that only exists because in the beginning JavaScript had no exceptions.

what does if (!testvar) actually do? Does it test for undefined and null or just undefined?

Such a ‘truthiness’ test checks against false, undefined, null, 0, NaN and empty strings. But in this case, yes, it is really undefined it is concerned with. IMO, it should be more explicit about that and say if (testvar!==undefined).

once a variable is defined can I clear it back to undefined (therefore deleting the variable).

You can certainly assign undefined to it, but that won't delete the variable. Only the delete object.property operator really removes things.

delete is really meant for properties rather than variables as such. Browsers will let you get away with straight delete variable, but it's not a good idea and won't work in ECMAScript Fifth Edition's strict mode. If you want to free up a reference to something so it can be garbage-collected, it would be more usual to say variable= null.

can I pass undefined as a parameter?

Yes.

How to read/write arbitrary bits in C/C++

Some 2+ years after I asked this question I'd like to explain it the way I'd want it explained back when I was still a complete newb and would be most beneficial to people who want to understand the process.

First of all, forget the "11111111" example value, which is not really all that suited for the visual explanation of the process. So let the initial value be 10111011 (187 decimal) which will be a little more illustrative of the process.

1 - how to read a 3 bit value starting from the second bit:

    ___  <- those 3 bits
10111011 

The value is 101, or 5 in decimal, there are 2 possible ways to get it:

  • mask and shift

In this approach, the needed bits are first masked with the value 00001110 (14 decimal) after which it is shifted in place:

    ___
10111011 AND
00001110 =
00001010 >> 1 =
     ___
00000101

The expression for this would be: (value & 14) >> 1

  • shift and mask

This approach is similar, but the order of operations is reversed, meaning the original value is shifted and then masked with 00000111 (7) to only leave the last 3 bits:

    ___
10111011 >> 1
     ___
01011101 AND
00000111
00000101

The expression for this would be: (value >> 1) & 7

Both approaches involve the same amount of complexity, and therefore will not differ in performance.

2 - how to write a 3 bit value starting from the second bit:

In this case, the initial value is known, and when this is the case in code, you may be able to come up with a way to set the known value to another known value which uses less operations, but in reality this is rarely the case, most of the time the code will know neither the initial value, nor the one which is to be written.

This means that in order for the new value to be successfully "spliced" into byte, the target bits must be set to zero, after which the shifted value is "spliced" in place, which is the first step:

    ___ 
10111011 AND
11110001 (241) =
10110001 (masked original value)

The second step is to shift the value we want to write in the 3 bits, say we want to change that from 101 (5) to 110 (6)

     ___
00000110 << 1 =
    ___
00001100 (shifted "splice" value)

The third and final step is to splice the masked original value with the shifted "splice" value:

10110001 OR
00001100 =
    ___
10111101

The expression for the whole process would be: (value & 241) | (6 << 1)

Bonus - how to generate the read and write masks:

Naturally, using a binary to decimal converter is far from elegant, especially in the case of 32 and 64 bit containers - decimal values get crazy big. It is possible to easily generate the masks with expressions, which the compiler can efficiently resolve during compilation:

  • read mask for "mask and shift": ((1 << fieldLength) - 1) << (fieldIndex - 1), assuming that the index at the first bit is 1 (not zero)
  • read mask for "shift and mask": (1 << fieldLength) - 1 (index does not play a role here since it is always shifted to the first bit
  • write mask : just invert the "mask and shift" mask expression with the ~ operator

How does it work (with the 3bit field beginning at the second bit from the examples above)?

00000001 << 3
00001000  - 1
00000111 << 1
00001110  ~ (read mask)
11110001    (write mask)

The same examples apply to wider integers and arbitrary bit width and position of the fields, with the shift and mask values varying accordingly.

Also note that the examples assume unsigned integer, which is what you want to use in order to use integers as portable bit-field alternative (regular bit-fields are in no way guaranteed by the standard to be portable), both left and right shift insert a padding 0, which is not the case with right shifting a signed integer.

Even easier:

Using this set of macros (but only in C++ since it relies on the generation of member functions):

#define GETMASK(index, size) ((((size_t)1 << (size)) - 1) << (index))
#define READFROM(data, index, size) (((data) & GETMASK((index), (size))) >> (index))
#define WRITETO(data, index, size, value) ((data) = (((data) & (~GETMASK((index), (size)))) | (((value) << (index)) & (GETMASK((index), (size))))))
#define FIELD(data, name, index, size) \
  inline decltype(data) name() const { return READFROM(data, index, size); } \
  inline void set_##name(decltype(data) value) { WRITETO(data, index, size, value); }

You could go for something as simple as:

struct A {
  uint bitData;
  FIELD(bitData, one, 0, 1)
  FIELD(bitData, two, 1, 2)
};

And have the bit fields implemented as properties you can easily access:

A a;
a.set_two(3);
cout << a.two();

Replace decltype with gcc's typeof pre-C++11.

Why doesn't JUnit provide assertNotEquals methods?

I wonder same. The API of Assert is not very symmetric; for testing whether objects are the same, it provides assertSame and assertNotSame.

Of course, it is not too long to write:

assertFalse(foo.equals(bar));

With such an assertion, the only informative part of the output is unfortunately the name of the test method, so descriptive message should be formed separately:

String msg = "Expected <" + foo + "> to be unequal to <" + bar +">";
assertFalse(msg, foo.equals(bar));

That is of course so tedious, that it is better to roll your own assertNotEqual. Luckily in future it will maybe be part of the JUnit: JUnit issue 22

how to call a variable in code behind to aspx page

The HelloFromCsharp.aspx look like this

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HelloFromCsharp.aspx.cs" Inherits="Test.HelloFromCsharp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <p>
       <%= clients%>
    </p>
    </form>
</body>
</html>

And the HelloFromCsharp.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test
{
    public partial class HelloFromCsharp : System.Web.UI.Page
    {
        public string clients;
        protected void Page_Load(object sender, EventArgs e)
        {
            clients = "Hello From C#";
        }
    }
}

How to create a listbox in HTML without allowing multiple selection?

Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want

you may want to check this site

http://www.htmlcodetutorial.com/forms/_SELECT.html

update package.json version automatically

I have created a tool that can accomplish automatic semantic versioning based on the tags in commit messages, known as change types. This closely follows the Angular Commit Message Convention along with the Semantic Versioning Specification.

You could use this tool to automatically change the version in the package.json using the npm CLI (this is described here).

In addition, it can create a changelog from these commits and also has a menu (with a spell checker for commit messages) for creating commits based on the change type. I highly recommend checking it out and reading to docs to see everything that can be accomplished with it.

I wrote the tool because I couldn't find anything that suited my needs for my CICD Pipeline to automate semantic versioning. I'd rather focus on what the actual changes are than what the version should be and that's where my tool saves the day.

For more information on the rationale for the tool, please see this.

How would you implement an LRU cache in Java?

Here is my short implementation, please criticize or improve it!

package util.collection;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Limited size concurrent cache map implementation.<br/>
 * LRU: Least Recently Used.<br/>
 * If you add a new key-value pair to this cache after the maximum size has been exceeded,
 * the oldest key-value pair will be removed before adding.
 */

public class ConcurrentLRUCache<Key, Value> {

private final int maxSize;
private int currentSize = 0;

private ConcurrentHashMap<Key, Value> map;
private ConcurrentLinkedQueue<Key> queue;

public ConcurrentLRUCache(final int maxSize) {
    this.maxSize = maxSize;
    map = new ConcurrentHashMap<Key, Value>(maxSize);
    queue = new ConcurrentLinkedQueue<Key>();
}

private synchronized void freeSpace() {
    Key key = queue.poll();
    if (null != key) {
        map.remove(key);
        currentSize = map.size();
    }
}

public void put(Key key, Value val) {
    if (map.containsKey(key)) {// just heat up that item
        put(key, val);
        return;
    }
    while (currentSize >= maxSize) {
        freeSpace();
    }
    synchronized(this) {
        queue.add(key);
        map.put(key, val);
        currentSize++;
    }
}

public Value get(Key key) {
    return map.get(key);
}
}

Hadoop/Hive : Loading data from .csv on a local machine

For csv file formate data will be in below format

"column1", "column2","column3","column4"

And if we will use field terminated by ',' then each column will get values like below.

"column1"    "column2"     "column3"     "column4"

also if any of the column value has comma as value then it will not work at all .

So the correct way to create a table would be by using OpenCSVSerde

create table tableName (column1 datatype, column2 datatype , column3 datatype , column4 datatype)
ROW FORMAT SERDE 
'org.apache.hadoop.hive.serde2.OpenCSVSerde' 
STORED AS TEXTFILE ;

jquery $.each() for objects

Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.

You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.

You could do an outer loop over the array

$.each(data.programs, function(index) {

    // then loop over the object elements
    $.each(data.programs[index], function(key, value) {
        console.log(key + ": " + value);
    }

}

In Python, how to check if a string only contains certain characters?

Use python Sets when you need to compare hm... sets of data. Strings can be represented as sets of characters quite fast. Here I test if string is allowed phone number. First string is allowed, second not. Works fast and simple.

In [17]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(898) 64-901-63 ');p.issubset(allowed)").timeit()

Out[17]: 0.8106249139964348

In [18]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(950) 64-901-63 ???');p.issubset(allowed)").timeit()

Out[18]: 0.9240323599951807

Never use regexps if you can avoid them.