Programs & Examples On #Perspective

In Eclipse, a perspective defines the initial set and layout of views in the Workbench window. In CSS, perspective is a property and concept used in 3D transforms.

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

This way you have more control over the output - i.e - if you wanted the time format to be '4:30 pm' instead of '04:30 P.M.' - you can convert to whatever format you decide you want - and change it later too. Instead of being constrained to some old method that does not allow any flexibility.

and you only need to convert the first 2 digits as the minute and seconds digits are the same in 24 hour time or 12 hour time.

var my_time_conversion_arr = {'01':"01", '02':"02", '03':"03", '04':"04", '05':"05", '06':"06", '07':"07", '08':"08", '09':"09", '10':"10", '11':"11", '12': "12", '13': "1", '14': "2", '15': "3", '16': "4", '17': "5", '18': "6", '19': "7", '20': "8", '21': "9", '22': "10", '23': "11", '00':"12"};

                var AM_or_PM = "";
                var twenty_four_hour_time = "16:30";
                var twenty_four_hour_time_arr = twenty_four_hour_time.split(":");
                var twenty_four_hour_time_first_two_digits = twenty_four_hour_time_arr[0];

                var first_two_twelve_hour_digits_converted = my_time_conversion_arr[twenty_four_hour_time_first_two_digits];

                var time_strng_to_nmbr = parseInt(twenty_four_hour_time_first_two_digits);
                if(time_strng_to_nmbr >12){
                    //alert("GREATER THAN 12");
                    AM_or_PM = "pm";
                }else{
                    AM_or_PM = "am";
                }

                var twelve_hour_time_conversion = first_two_twelve_hour_digits_converted+":"+twenty_four_hour_time_arr[1]+" "+AM_or_PM;

Is there a method to generate a UUID with go language

You can generate UUIDs using the go-uuid library. This can be installed with:

go get github.com/nu7hatch/gouuid

You can generate random (version 4) UUIDs with:

import "github.com/nu7hatch/gouuid"

...

u, err := uuid.NewV4()

The returned UUID type is a 16 byte array, so you can retrieve the binary value easily. It also provides the standard hex string representation via its String() method.

The code you have also looks like it will also generate a valid version 4 UUID: the bitwise manipulation you perform at the end set the version and variant fields of the UUID to correctly identify it as version 4. This is done to distinguish random UUIDs from ones generated via other algorithms (e.g. version 1 UUIDs based on your MAC address and time).

Set System.Drawing.Color values

You could do:

Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components

Why do I keep getting Delete 'cr' [prettier/prettier]?

Add this to your .prettierrc file and open the VSCODE

"endOfLine": "auto"

.jar error - could not find or load main class

Had this problem couldn't find the answer so i went looking on other threads, I found that i was making my app with 1.8 but for some reason my jre was out dated even though i remember updating it. I downloaded the lastes jre 8 and the jar file runs perfectly. Hope this helps.

"document.getElementByClass is not a function"

The getElementByClass does not exists, probably you want to use getElementsByClassName. However you can use alternative approach (used in angular/vue/react... templates)

_x000D_
_x000D_
function stop(ta) {_x000D_
  console.log(ta.value) // document['player'].stopMusicExt(ta.value);_x000D_
  ta.value='';_x000D_
}
_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 1'>_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 2'>
_x000D_
_x000D_
_x000D_

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

Is jQuery $.browser Deprecated?

"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."

From http://api.jquery.com/jQuery.browser/

Select only rows if its value in a particular column is less than the value in the other column

df[df$aged <= df$laclen, ] 

Should do the trick. The square brackets allow you to index based on a logical expression.

DBCC CHECKIDENT Sets Identity to 0

Borrowing from Zyphrax's answer ...

USE DatabaseName

DECLARE @ReseedBit BIT = 
    COALESCE((SELECT SUM(CONVERT(BIGINT, ic.last_value))
                FROM sys.identity_columns ic
                INNER JOIN sys.tables t ON ic.object_id = t.object_id), 0)
DECLARE @Reseed INT = 
CASE 
    WHEN @ReseedBit = 0 THEN 1 
    WHEN @ReseedBit = 1 THEN 0 
END

DBCC CHECKIDENT ('dbo.table_name', RESEED, @Reseed);

Caveats: This is intended for use in reference data population situations where a DB is being initialized with enum type definition tables, where the ID values in those tables must always start at 1. The first time the DB is being created (e.g. during SSDT-DB publishing) @Reseed must be 0, but when resetting the data i.e. removing the data and re-inserting it, then @Reseed must be 1. So this code is intended for use in a stored procedure for resetting the DB data, which can be called manually but is also called from the post-deployment script in the SSDT-DB project. In that way the reference data inserts are only defined in one place but aren't restricted to be used only in post-deployment during publishing, they are also available for subsequent use (to support dev and automated test etc.) by calling the stored procedure to reset the DB back to a known good state.

How do I get a plist as a Dictionary in Swift?

This answer uses Swift native objects rather than NSDictionary.

Swift 3.0

//get the path of the plist file
guard let plistPath = Bundle.main.path(forResource: "level1", ofType: "plist") else { return }
//load the plist as data in memory
guard let plistData = FileManager.default.contents(atPath: plistPath) else { return }
//use the format of a property list (xml)
var format = PropertyListSerialization.PropertyListFormat.xml
//convert the plist data to a Swift Dictionary
guard let  plistDict = try! PropertyListSerialization.propertyList(from: plistData, options: .mutableContainersAndLeaves, format: &format) as? [String : AnyObject] else { return }
//access the values in the dictionary 
if let value = plistDict["aKey"] as? String {
  //do something with your value
  print(value)
}
//you can also use the coalesce operator to handle possible nil values
var myValue = plistDict["aKey"] ?? ""

How do I get a list of locked users in an Oracle database?

This suits the requirement:

select username, account_status, EXPIRY_DATE from dba_users where 
username='<username>';

Output:

USERNAME        ACCOUNT_STATUS                   EXPIRY_DA
--------------------------------------------------------------------------------
SYSTEM          EXPIRED                          13-NOV-17

What is the difference between varchar and nvarchar?

nVarchar will help you to store Unicode characters. It is the way to go if you want to store localized data.

How to get df linux command output always in GB

If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:

alias df-gb='df -BG'

So if you type:

df-gb

into a terminal, you'll get your intended output of the disk usage in GB.

EDIT: or even use just df -h to get it in a standard, human readable format.

http://www.thegeekstuff.com/2012/05/df-examples/

Save multiple sheets to .pdf

I recommend adding the following line after the export to PDF:

ThisWorkbook.Sheets("Sheet1").Select

(where eg. Sheet1 is the single sheet you want to be active afterwards)

Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)

Simplest way to do grouped barplot

There are several ways to do plots in R; lattice is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:

Reasonstats <- read.table(text="Category         Reason  Species
                                 Decline        Genuine       24
                                Improved        Genuine       16
                                Improved  Misclassified       85
                                 Decline  Misclassified       41
                                 Decline      Taxonomic        2
                                Improved      Taxonomic        7
                                 Decline        Unclear       41
                                Improved        Unclear      117", header=T)

ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3   <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason

windows()
  barplot(t(Reasonstats3), beside=TRUE, ylab="number of species", 
          cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
  box(bty="l")

enter image description here

Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline and for Improved. Then I made those categories the column names. I also made the Reasons the row names. The barplot() function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot() function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot() wants for your intended output.

How to open SharePoint files in Chrome/Firefox

Thanks to @LyphTEC that gave a very interesting way to open an Office file in edit mode!

It gave me the idea to change the function _DispEx that is called when the user clicks on a file into a document library. By hacking the original function we can them be able to open a dialog (for Firefox/Chrome) and ask the user if he/she wants to readonly or edit the file: enter image description here

See below the JavaScript code I used. My code is for Excel files, but it could be modified to work with Word documents too:

    /**
 * fix problem with Excel documents on Firefox/Chrome (see https://blog.kodono.info/wordpress/2017/02/09/how-to-open-an-excel-document-from-sharepoint-files-into-chromefirefox-in-readonlyedit-mode/)
 * @param  {HTMLElement} p the <A> element
 * @param  {HTMLEvent} a the click event
 * @param  {Boolean} h TRUE
 * @param  {Boolean} e FALSE
 * @param  {Boolean} g FALSE
 * @param  {Strin} k the ActiveX command (e.g. "SharePoint.OpenDocuments.3")
 * @param  {Number} c 0
 * @param  {String} o the activeX command, here we look at "SharePoint.OpenDocuments"
 * @param  {String} m
 * @param  {String} b the replacement URL to the xslviewer
 */
var bak_DispEx;
var modalOpenDocument; // it will be use with the modal
SP.SOD.executeOrDelayUntilEventNotified(function() {
  bak_DispEx = _DispEx;
  _DispEx=function(p, a, h, e, g, k, c, o, m, b, j, l, i, f, d) {
    // if o==="SharePoint.OpenDocuments" && !IsClientAppInstalled(o)
    // in that case we want to open ask the user if he/she wants to readonly or edit the file
    var fileURL = b.replace(/.*_layouts\/xlviewer\.aspx\?id=(.*)/, "$1");
    if (o === "SharePoint.OpenDocuments" && !IsClientAppInstalled(o) && /\.xlsx?$/.test(fileURL)) {
      // if the URL doesn't start with http
      if (!/^http/.test(fileURL)) {
        fileURL = window.location.protocol + "//" + window.location.host + fileURL;
      }
      var ohtml = document.createElement('div');
      ohtml.style.padding = "10px";
      ohtml.style.display = "inline-block";
      ohtml.style.width = "200px";
      ohtml.style.width = "200px";
      ohtml.innerHTML = '<style>'
                      + '.opendocument_button { background-color:#fdfdfd; border:1px solid #ababab; color:#444; display:inline-block; padding: 7px 10px; }'
                      + '.opendocument_button:hover { box-shadow: none }'
                      + '#opendocument_readonly,#opendocument_edit { float:none; font-size: 100%; line-height: 1.15; margin: 0; overflow: visible; box-sizing: border-box; padding: 0; height:auto }'
                      + '.opendocument_ul { list-style-type:none;margin-top:10px;margin-bottom:10px;padding-top:0;padding-bottom:0 }'
                      + '</style>'
                      + 'You are about to open:'
                      + '<ul class="opendocument_ul">'
                      + '  <li>Name: <b>'+fileURL.split("/").slice(-1)+'</b></li>'
                      + '  <li>From: <b>'+window.location.hostname+'</b></li>'
                      + '</ul>'
                      + 'How would like to open this file?'
                      + '<ul class="opendocument_ul">'
                      + '  <li><label><input type="radio" name="opendocument_choices" id="opendocument_readonly" checked> Read Only</label></li>'
                      + '  <li><label><input type="radio" name="opendocument_choices" id="opendocument_edit"> Edit</label></li>'
                      + '</ul>'
                      + '<div style="text-align: center;margin-top: 20px;"><button type="button" class="opendocument_button" style="background-color: #2d9f2d;color: #fff;" onclick="modalOpenDocument.close(document.getElementById(\'opendocument_edit\').checked)">Open</button> <button type="button" class="opendocument_button" style="margin-left:10px" onclick="modalOpenDocument.close(-1)">Cancel</button></div>';
      // show the modal
      modalOpenDocument=SP.UI.ModalDialog.showModalDialog({
        html:ohtml,
        dialogReturnValueCallback:function(ret) {
          if (ret!==-1) {
            if (ret === true) { // edit
              // reformat the fileURL
              var ext;
              if (/\.xlsx?$/.test(b)) ext = "ms-excel";
              if (/\.docx?$/.test(b)) ext = "ms-word"; // not currently supported
              fileURL = ext + ":ofe|u|" + fileURL;
            }
            window.location.href = fileURL; // open the file
          }
        }
      });
      a.preventDefault();
      a.stopImmediatePropagation()
      a.cancelBubble = true;
      a.returnValue = false;
      return false;
    }
    return bak_DispEx.apply(this, arguments);
  }
}, "sp.scriptloaded-core.js")

I use SP.SOD.executeOrDelayUntilEventNotified to make sure the function will be executed when core.js is loaded.

Is there a “not in” operator in JavaScript for checking object properties?

Personally I find

if (id in tutorTimes === false) { ... }

easier to read than

if (!(id in tutorTimes)) { ... }

but both will work.

How to merge 2 JSON objects from 2 files using jq?

Use jq -s add:

$ echo '{"a":"foo","b":"bar"} {"c":"baz","a":0}' | jq -s add
{
  "a": 0,
  "b": "bar",
  "c": "baz"
}

This reads all JSON texts from stdin into an array (jq -s does that) then it "reduces" them.

(add is defined as def add: reduce .[] as $x (null; . + $x);, which iterates over the input array's/object's values and adds them. Object addition == merge.)

Display current time in 12 hour format with AM/PM

use "hh:mm a" instead of "HH:mm a". Here hh for 12 hour format and HH for 24 hour format.

Live Demo

To check if string contains particular word

Maybe this post is old, but I came across it and used the "wrong" usage. The best way to find a keyword is using .contains, example:

if ( d.contains("hello")) {
            System.out.println("I found the keyword");
}

Hide keyboard in react-native

Keyboard module is used to control keyboard events.

  • import { Keyboard } from 'react-native'
  • Add below code in render method.

    render() { return <TextInput onSubmitEditing={Keyboard.dismiss} />; }

You can use -

Keyboard.dismiss()

static dismiss() Dismisses the active keyboard and removes focus as per react native documents.

What does if __name__ == "__main__": do?

It is a special for when a Python file is called from the command line. This is typically used to call a "main()" function or execute other appropriate startup code, like commandline arguments handling for instance.

It could be written in several ways. Another is:

def some_function_for_instance_main():
    dosomething()


__name__ == '__main__' and some_function_for_instance_main()

I am not saying you should use this in production code, but it serves to illustrate that there is nothing "magical" about if __name__ == '__main__'. It is a good convention for invoking a main function in Python files.

How can I align YouTube embedded video in the center in bootstrap

For a fully responsive IFramed YouTube video, try this:

<div class="blogwidevideo">
<iframe width="854" height="480" style="margin: auto;" src="https://www.youtube-nocookie.com/embed/h5ag-3nnenc" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

.blogwidevideo {    
    overflow:hidden;
    padding-bottom:56.25%;
    position:relative;
    height:0;    
}

.blogwidevideo iframe {   
    left:10%; //centers for the 80% width - not needed if width is 100%
    top:0;
    height:80%; //change to 100% if going full width
    width:80%;
    position:absolute;
}

Round button with text and icon in flutter

You can do something like,

RaisedButton.icon( elevation: 4.0,
                    icon: Image.asset('images/image_upload.png' ,width: 20,height: 20,) ,
                      color: Theme.of(context).primaryColor,
                    onPressed: getImage,
                    label: Text("Add Team Image",style: TextStyle(
                        color: Colors.white, fontSize: 16.0))
                  ),

How can I get a precise time, for example in milliseconds in Objective-C?

You can get current time in milliseconds since January 1st, 1970 using an NSDate:

- (double)currentTimeInMilliseconds {
    NSDate *date = [NSDate date];
    return [date timeIntervalSince1970]*1000;
}

Trigger Change event when the Input value changed programmatically?

Vanilla JS solution:

var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));

Note that dispatchEvent doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).

So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional comments to warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for: typeof document.body.dispatchEvent === 'function'.

Excel VBA Run-time Error '32809' - Trying to Understand it

I did the following and worked like a charm:

  1. Install Office 2013 (I haven't tried with 2010 but I think it would work too).
  2. Install Office 2013 SP1.
  3. Run Windows Updates and install all Office and Windows updates.
  4. Reboot computer.
  5. Done.

This worked for me in two different computers. I hope this will work in yours too!

CFLAGS vs CPPFLAGS

To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:

make -p

For instance:

%.o: %.c
    $(COMPILE.c) $(OUTPUT_OPTION) $<

which expands

COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c

This will also print # environment data. Here, you will find GCC's include path among other useful info.

C_INCLUDE_PATH=/usr/include

In make, when it comes to search, the paths are many, the light is one... or something to that effect.

  1. C_INCLUDE_PATH is system-wide, set it in your shell's *.rc.
  2. $(CPPFLAGS) is for the preprocessor include path.
  3. If you need to add a general search path for make, use:
VPATH = my_dir_to_search

... or even more specific

vpath %.c src
vpath %.h include

make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.

Rails: call another controller action from a controller

Separate these functions from controllers and put them into model file. Then include the model file in your controller.

Hashcode and Equals for Hashset

  1. There's no need to call equals if hashCode differs.
  2. There's no need to call hashCode if (obj1 == obj2).
  3. There's no need for hashCode and/or equals just to iterate - you're not comparing objects
  4. When needed to distinguish in between objects.

How can I download HTML source in C#

You can download files with the WebClient class:

using System.Net;

using (WebClient client = new WebClient ()) // WebClient class inherits IDisposable
{
    client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");

    // Or you can get the file content without saving it
    string htmlCode = client.DownloadString("http://yoursite.com/page.html");
}

Set the value of a variable with the result of a command in a Windows batch file

Here's how I do it when I need a database query's results in my batch file:

sqlplus -S schema/schema@db @query.sql> __query.tmp
set /p result=<__query.tmp
del __query.tmp

The key is in line 2: "set /p" sets the value of "result" to the value of the first line (only) in "__query.tmp" via the "<" redirection operator.

How to return a custom object from a Spring Data JPA GROUP BY query

Solution for JPQL queries

This is supported for JPQL queries within the JPA specification.

Step 1: Declare a simple bean class

package com.path.to;

public class SurveyAnswerStatistics {
  private String answer;
  private Long   cnt;

  public SurveyAnswerStatistics(String answer, Long cnt) {
    this.answer = answer;
    this.count  = cnt;
  }
}

Step 2: Return bean instances from the repository method

public interface SurveyRepository extends CrudRepository<Survey, Long> {
    @Query("SELECT " +
           "    new com.path.to.SurveyAnswerStatistics(v.answer, COUNT(v)) " +
           "FROM " +
           "    Survey v " +
           "GROUP BY " +
           "    v.answer")
    List<SurveyAnswerStatistics> findSurveyCount();
}

Important notes

  1. Make sure to provide the fully-qualified path to the bean class, including the package name. For example, if the bean class is called MyBean and it is in package com.path.to, the fully-qualified path to the bean will be com.path.to.MyBean. Simply providing MyBean will not work (unless the bean class is in the default package).
  2. Make sure to call the bean class constructor using the new keyword. SELECT new com.path.to.MyBean(...) will work, whereas SELECT com.path.to.MyBean(...) will not.
  3. Make sure to pass attributes in exactly the same order as that expected in the bean constructor. Attempting to pass attributes in a different order will lead to an exception.
  4. Make sure the query is a valid JPA query, that is, it is not a native query. @Query("SELECT ..."), or @Query(value = "SELECT ..."), or @Query(value = "SELECT ...", nativeQuery = false) will work, whereas @Query(value = "SELECT ...", nativeQuery = true) will not work. This is because native queries are passed without modifications to the JPA provider, and are executed against the underlying RDBMS as such. Since new and com.path.to.MyBean are not valid SQL keywords, the RDBMS then throws an exception.

Solution for native queries

As noted above, the new ... syntax is a JPA-supported mechanism and works with all JPA providers. However, if the query itself is not a JPA query, that is, it is a native query, the new ... syntax will not work as the query is passed on directly to the underlying RDBMS, which does not understand the new keyword since it is not part of the SQL standard.

In situations like these, bean classes need to be replaced with Spring Data Projection interfaces.

Step 1: Declare a projection interface

package com.path.to;

public interface SurveyAnswerStatistics {
  String getAnswer();

  int getCnt();
}

Step 2: Return projected properties from the query

public interface SurveyRepository extends CrudRepository<Survey, Long> {
    @Query(nativeQuery = true, value =
           "SELECT " +
           "    v.answer AS answer, COUNT(v) AS cnt " +
           "FROM " +
           "    Survey v " +
           "GROUP BY " +
           "    v.answer")
    List<SurveyAnswerStatistics> findSurveyCount();
}

Use the SQL AS keyword to map result fields to projection properties for unambiguous mapping.

Connecting client to server using Socket.io

You need to make sure that you add forward slash before your link to socket.io:

<script src="/socket.io/socket.io.js"></script>

Then in the view/controller just do:

var socket = io.connect()

That should solve your problem.

How to convert index of a pandas dataframe into a column?

For MultiIndex you can extract its subindex using

df['si_name'] = R.index.get_level_values('si_name') 

where si_name is the name of the subindex.

How do I change the figure size for a seaborn plot?

In addition to elz answer regarding "figure level" methods that return multi-plot grid objects it is possible to set the figure height and width explicitly (that is without using aspect ratio) using the following approach:

import seaborn as sns 

g = sns.catplot(data=df, x='xvar', y='yvar', hue='hue_bar')
g.fig.set_figwidth(8.27)
g.fig.set_figheight(11.7)

How to convert interface{} to string?

To expand on what Peter said: Since you are looking to go from interface{} to string, type assertion will lead to headaches since you need to account for multiple incoming types. You'll have to assert each type possible and verify it is that type before using it.

Using fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) automatically handles the interface conversion. Since you know your desired output type is always a string, Sprintf will handle whatever type is behind the interface without a bunch of extra code on your behalf.

How do you read a file into a list in Python?

with open('C:/path/numbers.txt') as f:
    lines = f.read().splitlines()

this will give you a list of values (strings) you had in your file, with newlines stripped.

also, watch your backslashes in windows path names, as those are also escape chars in strings. You can use forward slashes or double backslashes instead.

Transfer data between databases with PostgreSQL

  1. If your source and target database resides in the same local machine, you can use:

Note:- Sourcedb already exists in your database.

CREATE DATABASE targetdb WITH TEMPLATE sourcedb;

This statement copies the sourcedb to the targetdb.

  1. If your source and target databases resides on different servers, you can use following steps:

Step 1:- Dump the source database to a file.

pg_dump -U postgres -O sourcedb sourcedb.sql

Note:- Here postgres is the username so change the name accordingly.

Step 2:- Copy the dump file to the remote server.

Step 3:- Create a new database in the remote server

CREATE DATABASE targetdb;

Step 4:- Restore the dump file on the remote server

psql -U postgres -d targetdb -f sourcedb.sql

(pg_dump is a standalone application (i.e., something you run in a shell/command-line) and not an Postgres/SQL command.)

This should do it.

undefined reference to 'std::cout'

Yes, using g++ command worked for me:

g++ my_source_code.cpp

jQuery ajax success error

Try to set response dataType property directly:

dataType: 'text'

and put

die(''); 

in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.

How to split a comma separated string and process in a loop using JavaScript

My two cents, adding trim to remove the initial whitespaces left in sAc's answer.

var str = 'Hello, World, etc';
var str_array = str.split(',');

for(var i = 0; i < str_array.length; i++) {
   // Trim the excess whitespace.
   str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
   // Add additional code here, such as:
   alert(str_array[i]);
}

Edit:

After getting several upvotes on this answer, I wanted to revisit this. If you want to split on comma, and perform a trim operation, you can do it in one method call without any explicit loops due to the fact that split will also take a regular expression as an argument:

'Hello, cruel , world!'.split(/\s*,\s*/);
//-> ["Hello", "cruel", "world!"]

This solution, however, will not trim the beginning of the first item and the end of the last item which is typically not an issue.

And so to answer the question in regards to process in a loop, if your target browsers support ES5 array extras such as the map or forEach methods, then you could just simply do the following:

myStringWithCommas.split(/\s*,\s*/).forEach(function(myString) {
    console.log(myString);
});

Redirect with CodeIgniter

Here is .htacess file that hide index file

#RewriteEngine on
#RewriteCond $1 !^(index\.php|images|robots\.txt)
#RewriteRule ^(.*)$ /index.php/$1 [L]

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

        # Removes index.php from ExpressionEngine URLs
        RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
        RewriteCond %{REQUEST_URI} !/system/.* [NC]
        RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

        # Directs all EE web requests through the site index file
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

To kill the puma process first run

    lsof -wni tcp:3000 

to show what is using port 3000. Then use the PID that comes with the result to run the kill process.

For example after running lsof -wni tcp:3000 you might get something like

    COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
    ruby    3366 dummy    8u  IPv4  16901      0t0  TCP 127.0.0.1:3000 (LISTEN)

Now run the following to kill the process. (where 3366 is the PID)

kill -9 3366

Should resolve the issue

Returning a boolean value in a JavaScript function

An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. @pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:

function validatePassword() {
   const password = document.getElementById("password");
   const confirm_password = document.getElementById("password_confirm");

   if (password.value.length === 0) {
      return false;
   }

   if (password.value !== confirm_password.value) {
      return false;
   }
  
   return true;
}

Internal and external fragmentation

First of all the term fragmentation cues there's an entity divided into parts — fragments.

  • Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"

  • External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous

Visual Studio 2010 shortcut to find classes and methods?

try: ctrl + P

type: @

followed by the name of the class,method or variable name you search for.

Python Pandas Counting the Occurrences of a Specific value

An elegant way to count the occurrence of '?' or any symbol in any column, is to use built-in function isin of a dataframe object.

Suppose that we have loaded the 'Automobile' dataset into df object. We do not know which columns contain missing value ('?' symbol), so let do:

df.isin(['?']).sum(axis=0)

DataFrame.isin(values) official document says:

it returns boolean DataFrame showing whether each element in the DataFrame is contained in values

Note that isin accepts an iterable as input, thus we need to pass a list containing the target symbol to this function. df.isin(['?']) will return a boolean dataframe as follows.

    symboling   normalized-losses   make    fuel-type   aspiration-ratio ...
0   False       True                False   False       False
1   False       True                False   False       False
2   False       True                False   False       False
3   False       False               False   False       False
4   False       False               False   False       False
5   False       True                False   False       False
...

To count the number of occurrence of the target symbol in each column, let's take sum over all the rows of the above dataframe by indicating axis=0. The final (truncated) result shows what we expect:

symboling             0
normalized-losses    41
...
bore                  4
stroke                4
compression-ratio     0
horsepower            2
peak-rpm              2
city-mpg              0
highway-mpg           0
price                 4

Simplest way to display current month and year like "Aug 2016" in PHP?

Full version:

<? echo date('F Y'); ?>

Short version:

<? echo date('M Y'); ?>

Here is a good reference for the different date options.

update

To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp parameter for the date() function. Like this:

echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));

This will also work (it's typically used to get the last day of the previous month):

echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));

Hope that helps.

Showing empty view when ListView is empty

A programmatically solution will be:

TextView textView = new TextView(context);
textView.setId(android.R.id.empty);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setText("No result found");
listView.setEmptyView(textView);

Return JSON for ResponseEntity<String>

@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String so() {
    return "This is a String";
}

Angular: Cannot find a differ supporting object '[object Object]'

I think that the object you received in your response payload isn't an array. Perhaps the array you want to iterate is contained into an attribute. You should check the structure of the received data...

You could try something like that:

getusers() {
  this.http.get(`https://api.github.com/search/users?q=${this.input1.value}`)
    .map(response => response.json().items) // <------
    .subscribe(
      data => this.users = data,
      error => console.log(error)
    );
}

Edit

Following the Github doc (developer.github.com/v3/search/#search-users), the format of the response is:

{
  "total_count": 12,
  "incomplete_results": false,
  "items": [
    {
      "login": "mojombo",
      "id": 1,
      (...)
      "type": "User",
      "score": 105.47857
    }
  ]
}

So the list of users is contained into the items field and you should use this:

getusers() {
  this.http.get(`https://api.github.com/search/users?q=${this.input1.value}`)
    .map(response => response.json().items) // <------
    .subscribe(
      data => this.users = data,
      error => console.log(error)
    );
}

How can I time a code segment for testing performance with Pythons timeit?

Here's a simple wrapper for steven's answer. This function doesn't do repeated runs/averaging, just saves you from having to repeat the timing code everywhere :)

'''function which prints the wall time it takes to execute the given command'''
def time_func(func, *args): #*args can take 0 or more 
  import time
  start_time = time.time()
  func(*args)
  end_time = time.time()
  print("it took this long to run: {}".format(end_time-start_time))

jQuery 'input' event

As claustrofob said, oninput is supported for IE9+.

However, "The oninput event is buggy in Internet Explorer 9. It is not fired when characters are deleted from a text field through the user interface only when characters are inserted. Although the onpropertychange event is supported in Internet Explorer 9, but similarly to the oninput event, it is also buggy, it is not fired on deletion.

Since characters can be deleted in several ways (Backspace and Delete keys, CTRL + X, Cut and Delete command in context menu), there is no good solution to detect all changes. If characters are deleted by the Delete command of the context menu, the modification cannot be detected in JavaScript in Internet Explorer 9."

I have good results binding to both input and keyup (and keydown, if you want it to fire in IE while holding down the Backspace key).

Convert char to int in C and C++

For char or short to int, you just need to assign the value.

char ch = 16;
int in = ch;

Same to int64.

long long lo = ch;

All values will be 16.

How to check if a file is a valid image file?

Update

I also implemented the following solution in my Python script here on GitHub.

I also verified that damaged files (jpg) frequently are not 'broken' images i.e, a damaged picture file sometimes remains a legit picture file, the original image is lost or altered but you are still able to load it with no errors. But, file truncation cause always errors.

End Update

You can use Python Pillow(PIL) module, with most image formats, to check if a file is a valid and intact image file.

In the case you aim at detecting also broken images, @Nadia Alramli correctly suggests the im.verify() method, but this does not detect all the possible image defects, e.g., im.verify does not detect truncated images (that most viewers often load with a greyed area).

Pillow is able to detect these type of defects too, but you have to apply image manipulation or image decode/recode in or to trigger the check. Finally I suggest to use this code:

try:
  im = Image.load(filename)
  im.verify() #I perform also verify, don't know if he sees other types o defects
  im.close() #reload is necessary in my case
  im = Image.load(filename) 
  im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
  im.close()
except: 
  #manage excetions here

In case of image defects this code will raise an exception. Please consider that im.verify is about 100 times faster than performing the image manipulation (and I think that flip is one of the cheaper transformations). With this code you are going to verify a set of images at about 10 MBytes/sec with standard Pillow or 40 MBytes/sec with Pillow-SIMD module (modern 2.5Ghz x86_64 CPU).

For the other formats psd,xcf,.. you can use Imagemagick wrapper Wand, the code is as follows:

im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()

But, from my experiments Wand does not detect truncated images, I think it loads lacking parts as greyed area without prompting.

I red that Imagemagick has an external command identify that could make the job, but I have not found a way to invoke that function programmatically and I have not tested this route.

I suggest to always perform a preliminary check, check the filesize to not be zero (or very small), is a very cheap idea:

statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
  #manage here the 'faulty image' case

How can I parse JSON with C#?

I am assuming you are not using Json.NET (Newtonsoft.Json NuGet package). If this the case, then you should try it.

It has the following features:

  1. LINQ to JSON
  2. The JsonSerializer for quickly converting your .NET objects to JSON and back again
  3. Json.NET can optionally produce well formatted, indented JSON for debugging or display
  4. Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized
  5. Ability to convert JSON to and from XML
  6. Supports multiple platforms: .NET, Silverlight and the Compact Framework

Look at the example below. In this example, JsonConvert class is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj) and DeserializeObject<T>(String json):

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

What are the default access modifiers in C#?

Short answer: minimum possible access (cf Jon Skeet's answer).

Long answer:

Non-nested types, enumeration and delegate accessibilities (may only have internal or public accessibility)

                     | Default   | Permitted declared accessibilities
------------------------------------------------------------------
namespace            | public    | none (always implicitly public)

enum                 | public    | public, internal

interface            | internal  | public, internal

class                | internal  | public, internal

struct               | internal  | public, internal

delegate             | internal  | public, internal

Nested type and member accessiblities

                     | Default   | Permitted declared accessibilities
------------------------------------------------------------------
namespace            | public    | none (always implicitly public)

enum                 | public    | All¹

interface            | public    | All¹

class                | private   | All¹

struct               | private   | public, internal, private²

delegate             | private   | All¹

constructor          | private   | All¹

enum member          | public    | none (always implicitly public)

interface member     | public    | none (always implicitly public)
     
method               | private   | All¹

field                | private   | All¹

user-defined operator| none      | public (must be declared public)

¹ All === public, protected, internal, private, protected internal

² structs cannot inherit from structs or classes (although they can, interfaces), hence protected is not a valid modifier

The accessibility of a nested type depends on its accessibility domain, which is determined by both the declared accessibility of the member and the accessibility domain of the immediately containing type. However, the accessibility domain of a nested type cannot exceed that of the containing type.

Note: CIL also has the provision for protected and internal (as opposed to the existing protected "or" internal), but to my knowledge this is not currently available for use in C#.


See:

http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx
http://msdn.microsoft.com/en-us/library/ms173121.aspx
http://msdn.microsoft.com/en-us/library/cx03xt0t.aspx
(Man I love Microsoft URLs...)

Sorting rows in a data table

Maybe the following can help:

DataRow[] dataRows = table.Select().OrderBy(u => u["EmailId"]).ToArray();

Here, you can use other Lambda expression queries too.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

How can I get the application's path in a .NET console application?

You can create a folder name as Resources within the project using Solution Explorer,then you can paste a file within the Resources.

private void Form1_Load(object sender, EventArgs e) {
    string appName = Environment.CurrentDirectory;
    int l = appName.Length;
    int h = appName.LastIndexOf("bin");
    string ll = appName.Remove(h);                
    string g = ll + "Resources\\sample.txt";
    System.Diagnostics.Process.Start(g);
}

How to add multiple font files for the same font?

To have font variation working correctly, I had to reverse the order of @font-face in CSS.

@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-BoldOblique.ttf");
    font-weight: bold;
    font-style: italic, oblique;
}   
@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-Oblique.ttf");
    font-style: italic, oblique;
}
@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-Bold.ttf");
    font-weight: bold;
}
 @font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono.ttf");
}

The executable was signed with invalid entitlements

I had not agreed to the new updated licensed agreement from apple.

Briefly : Please log in to your developer's account -> profile's -> review -> read the agreement or get your lawyer read it for you -> agree (at your own will) -> and again click profile's to check the status of your profile.

In my scenario the valid code signing entity was not showing up. When i followed the above procedure it was visible and i was able to run the app on the device and/or create the iPA file without much difficulty.

How to close a GUI when I push a JButton?

You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.

The System.exit(0) will terminates the currently running Java Virtual Machine.

Create autoincrement key in Java DB using NetBeans IDE

If you look at this url: http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/

this part of the schema may be what you are looking for.

 ID          INTEGER NOT NULL 
                PRIMARY KEY GENERATED ALWAYS AS IDENTITY 
                (START WITH 1, INCREMENT BY 1),

Bootstrap 3 with remote Modal

I did this:

$('#myModal').on 'shown.bs.modal', (e) ->  
  $(e.target).find('.modal-body').load('http://yourserver.com/content')

Can I use jQuery with Node.js?

A simple crawler using Cheerio

This is my formula to make a simple crawler in Node.js. It is the main reason for wanting to do DOM manipulation on the server side and probably it's the reason why you got here.

First, use request to download the page to be parsed. When the download is complete, handle it to cheerio and begin DOM manipulation just like using jQuery.

Working example:

var
    request = require('request'),
    cheerio = require('cheerio');

function parse(url) {
    request(url, function (error, response, body) {
        var
            $ = cheerio.load(body);

        $('.question-summary .question-hyperlink').each(function () {
            console.info($(this).text());
        });
    })
}

parse('http://stackoverflow.com/');

This example will print to the console all top questions showing on SO home page. This is why I love Node.js and its community. It couldn't get easier than that :-)

Install dependencies:

npm install request cheerio

And run (assuming the script above is in file crawler.js):

node crawler.js


Encoding

Some pages will have non-english content in a certain encoding and you will need to decode it to UTF-8. For instance, a page in brazilian portuguese (or any other language of latin origin) will likely be encoded in ISO-8859-1 (a.k.a. "latin1"). When decoding is needed, I tell request not to interpret the content in any way and instead use iconv-lite to do the job.

Working example:

var
    request = require('request'),
    iconv = require('iconv-lite'),
    cheerio = require('cheerio');

var
    PAGE_ENCODING = 'utf-8'; // change to match page encoding

function parse(url) {
    request({
        url: url,
        encoding: null  // do not interpret content yet
    }, function (error, response, body) {
        var
            $ = cheerio.load(iconv.decode(body, PAGE_ENCODING));

        $('.question-summary .question-hyperlink').each(function () {
            console.info($(this).text());
        });
    })
}

parse('http://stackoverflow.com/');

Before running, install dependencies:

npm install request iconv-lite cheerio

And then finally:

node crawler.js


Following links

The next step would be to follow links. Say you want to list all posters from each top question on SO. You have to first list all top questions (example above) and then enter each link, parsing each question's page to get the list of involved users.

When you start following links, a callback hell can begin. To avoid that, you should use some kind of promises, futures or whatever. I always keep async in my toolbelt. So, here is a full example of a crawler using async:

var
    url = require('url'),
    request = require('request'),
    async = require('async'),
    cheerio = require('cheerio');

var
    baseUrl = 'http://stackoverflow.com/';

// Gets a page and returns a callback with a $ object
function getPage(url, parseFn) {
    request({
        url: url
    }, function (error, response, body) {
        parseFn(cheerio.load(body))
    });
}

getPage(baseUrl, function ($) {
    var
        questions;

    // Get list of questions
    questions = $('.question-summary .question-hyperlink').map(function () {
        return {
            title: $(this).text(),
            url: url.resolve(baseUrl, $(this).attr('href'))
        };
    }).get().slice(0, 5); // limit to the top 5 questions

    // For each question
    async.map(questions, function (question, questionDone) {

        getPage(question.url, function ($$) {

            // Get list of users
            question.users = $$('.post-signature .user-details a').map(function () {
                return $$(this).text();
            }).get();

            questionDone(null, question);
        });

    }, function (err, questionsWithPosters) {

        // This function is called by async when all questions have been parsed

        questionsWithPosters.forEach(function (question) {

            // Prints each question along with its user list
            console.info(question.title);
            question.users.forEach(function (user) {
                console.info('\t%s', user);
            });
        });
    });
});

Before running:

npm install request async cheerio

Run a test:

node crawler.js

Sample output:

Is it possible to pause a Docker image build?
    conradk
    Thomasleveil
PHP Image Crop Issue
    Elyor
    Houston Molinar
Add two object in rails
    user1670773
    Makoto
    max
Asymmetric encryption discrepancy - Android vs Java
    Cookie Monster
    Wand Maker
Objective-C: Adding 10 seconds to timer in SpriteKit
    Christian K Rider

And that's the basic you should know to start making your own crawlers :-)


Libraries used

How to hide the border for specified rows of a table?

You can simply add these lines of codes here to hide a row,

Either you can write border:0 or border-style:hidden; border: none or it will happen the same thing

_x000D_
_x000D_
<style type="text/css">_x000D_
              table, th, td {_x000D_
               border: 1px solid;_x000D_
              }_x000D_
              _x000D_
              tr.hide_all > td, td.hide_all{_x000D_
                 border: 0;_x000D_
                _x000D_
              }_x000D_
          }_x000D_
        </style>_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th>Firstname</th>_x000D_
        <th>Lastname</th>_x000D_
        <th>Savings</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Peter</td>_x000D_
        <td>Griffin</td>_x000D_
        <td>$100</td>_x000D_
      </tr>_x000D_
      <tr class= hide_all>_x000D_
        <td>Lois</td>_x000D_
        <td>Griffin</td>_x000D_
        <td>$150</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Joe</td>_x000D_
        <td>Swanson</td>_x000D_
        <td>$300</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Cleveland</td>_x000D_
        <td>Brown</td>_x000D_
        <td>$250</td>_x000D_
      </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

running these lines of codes can solve the problem easily

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

Insert multiple lines into a file after specified pattern using shell script

Using GNU sed:

sed "/cdef/aline1\nline2\nline3\nline4" input.txt

If you started with:

abcd
accd
cdef
line
web

this would produce:

abcd
accd
cdef
line1
line2
line3
line4
line
web

If you want to save the changes to the file in-place, say:

sed -i "/cdef/aline1\nline2\nline3\nline4" input.txt

SQL to generate a list of numbers from 1 to 100

I created an Oracle function that returns a table of numbers

CREATE OR REPLACE FUNCTION [schema].FN_TABLE_NUMBERS(
    NUMINI INTEGER,
    NUMFIN INTEGER,
    EXPONENCIAL INTEGER DEFAULT 0
) RETURN TBL_NUMBERS
IS
    NUMEROS TBL_NUMBERS;
    INDICE NUMBER;
BEGIN
    NUMEROS := TBL_NUMBERS();

    FOR I IN (
        WITH TABLA AS (SELECT NUMINI, NUMFIN FROM DUAL)
        SELECT NUMINI NUM FROM TABLA UNION ALL
        SELECT 
            (SELECT NUMINI FROM TABLA) + (LEVEL*TO_NUMBER('1E'||TO_CHAR(EXPONENCIAL))) NUM
        FROM DUAL
        CONNECT BY 
            (LEVEL*TO_NUMBER('1E'||TO_CHAR(EXPONENCIAL))) <= (SELECT NUMFIN-NUMINI FROM TABLA)
    ) LOOP
        NUMEROS.EXTEND;
        INDICE := NUMEROS.COUNT; 
        NUMEROS(INDICE):= i.NUM;
    END LOOP;

    RETURN NUMEROS;

EXCEPTION
  WHEN NO_DATA_FOUND THEN
       RETURN NUMEROS;
  WHEN OTHERS THEN
       RETURN NUMEROS;
END;
/

Is necessary create a new data type:

CREATE OR REPLACE TYPE [schema]."TBL_NUMBERS" IS TABLE OF NUMBER;
/

Usage:

SELECT COLUMN_VALUE NUM FROM TABLE([schema].FN_TABLE_NUMBERS(1,10))--integers difference: 1;2;.......;10

And if you need decimals between numbers by exponencial notation:

SELECT COLUMN_VALUE NUM FROM TABLE([schema].FN_TABLE_NUMBERS(1,10,-1));--with 0.1 difference: 1;1.1;1.2;.......;10
SELECT COLUMN_VALUE NUM FROM TABLE([schema].FN_TABLE_NUMBERS(1,10,-2));--with 0.01 difference: 1;1.01;1.02;.......;10

How do I change the default application icon in Java?

Example:

URL imageURL = this.getClass().getClassLoader().getResource("Gui/icon/report-go-icon.png");
ImageIcon iChing = new ImageIcon("C:\\Users\\RrezartP\\Documents\\NetBeansProjects\\Inventari\\src\\Gui\\icon\\report-go-icon.png");      
btnReport.setIcon(iChing); 
System.out.println(imageURL);

Maven – Always download sources and javadocs

Open your settings.xml file ~/.m2/settings.xml (create it if it doesn't exist). Add a section with the properties added. Then make sure the activeProfiles includes the new profile.

<settings>

   <!-- ... other settings here ... -->

    <profiles>
        <profile>
            <id>downloadSources</id>
            <properties>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
            </properties>
        </profile>
    </profiles>

    <activeProfiles>
        <activeProfile>downloadSources</activeProfile>
    </activeProfiles>
</settings>

String contains - ignore case

If you won't go with regex:

"ABCDEFGHIJKLMNOP".toLowerCase().contains("gHi".toLowerCase())

Can't stop rails server

pkill -9 rails to kill all the process of rails

Updated answer

ps aux|grep 'rails'|grep -v 'grep'|awk '{ print $2 }'|xargs kill -9

This will kill any running rails process. Replace 'rails' with something else to kill any other processes.

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

If you have a version of find (such as GNU find) that supports -printf then there's no need to call stat repeatedly:

find /some/dir -printf "%T+\n" | sort -nr | head -n 1

or

find /some/dir -printf "%TY-%Tm-%Td %TT\n" | sort -nr | head -n 1

If you don't need recursion, though:

stat --printf="%y\n" *

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

"date(): It is not safe to rely on the system's timezone settings..."

If you are using CodeIgniter and can't change php.ini, I added the following to the beginning of index.php:

date_default_timezone_set('GMT');

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

Delete entire row if cell contains the string X

This is not necessarily a VBA task - This specific task is easiest sollowed with Auto filter.

1.Insert Auto filter (In Excel 2010 click on home-> (Editing) Sort & Filter -> Filter)
2. Filter on the 'Websites' column
3. Mark the 'none' and delete them
4. Clear filter

How to install and run phpize

For ubuntu with Plesk installed run apt-get install plesk-php56-dev, for other versions just change XX in phpXX (without the dot)

Split string, convert ToList<int>() in one line

also you can use this Extension method

public static List<int> SplitToIntList(this string list, char separator = ',')
{
    return list.Split(separator).Select(Int32.Parse).ToList();
}

usage:

var numberListString = "1, 2, 3, 4";
List<int> numberList = numberListString.SplitToIntList(',');

How do you list volumes in docker containers?

You can get information about which volumes were specifically baked into the container by inspecting the container and looking in the JSON output and comparing a couple of the fields. When you run docker inspect myContainer, the Volumes and VolumesRW fields give you information about ALL of the volumes mounted inside a container, including volumes mounted in both the Dockerfile with the VOLUME directive, and on the command line with the docker run -v command. However, you can isolate which volumes were mounted in the container using the docker run -v command by checking for the HostConfig.Binds field in the docker inspect JSON output. To clarify, this HostConfig.Binds field tells you which volumes were mounted specifically in your docker run command with the -v option. So if you cross-reference this field with the Volumes field, you will be able to determine which volumes were baked into the container using VOLUME directives in the Dockerfile.

A grep could accomplish this like:

$ docker inspect myContainer | grep -C2 Binds
...
"HostConfig": {
    "Binds": [
        "/var/docker/docker-registry/config:/registry"
    ],

And...

$ docker inspect myContainer | grep -C3 -e "Volumes\":"
...
"Volumes": {
    "/data": "/var/lib/docker...",
    "/config": "/var/lib/docker...",
    "/registry": "/var/docker/docker-registry/config"

And in my example, you can see I've mounted /var/docker/docker-registry/config into the container as /registry using the -v option in my docker run command, and I've mounted the /data and /config volumes using the VOLUME directive in my Dockerfile. The container does not need to be running to get this information, but it needs to have been run at least one time in order to populate the HostConfig JSON output of your docker inspect command.

How to change text transparency in HTML/CSS?

What about the css opacity attribute? 0 to 1 values.

But then you probably need to use a more explicit dom element than "font". For instance:

<html><body><span style=\"opacity: 0.5;\"><font color=\"black\" face=\"arial\" size=\"4\">THIS IS MY TEXT</font></span></body></html>

As an additional information I would of course suggest you use CSS declarations outside of your html elements, but as well try to use the font css style instead of the font html tag.

For cross browser css3 styles generator, have a look at http://css3please.com/

Adding a directory to the PATH environment variable in Windows

Aside from all the answers, if you want a nice GUI tool to edit your Windows environment variables you can use Rapid Environment Editor.

Try it! It's safe to use and is awesome!

jQuery addClass onClick

Using jQuery:

$('#Button').click(function(){
    $(this).addClass("active");
});

This way, you don't have to pollute your HTML markup with onclick handlers.

Is it possible to use Visual Studio on macOS?

I recently purchased a MacBook Air (mid-2011 model) and was really happy to find that Apple officially supports Windows 7. If you purchase Windows 7 (I got DSP), you can use the Boot Camp assistant in OSX to designate part of your hard drive to Windows. Then you can install and run Windows 7 natively as if it were as Windows notebook.

I use Visual Studio 2010 on Windows 7 on my MacBook Air (I kept OSX as well) and I could not be happier. Heck, the initial start-up of the program only takes 3 seconds thanks to the SSD.

As others have mentions, you can run it on OSX using Parallels, etc. but I prefer to run it natively.

Display an image with Python

Using Jupyter Notebook, the code can be as simple as the following.

%matplotlib inline
from IPython.display import Image
Image('your_image.png')

Sometimes you might would like to display a series of images in a for loop, in which case you might would like to combine display and Image to make it work.

%matplotlib inline
from IPython.display import display, Image
for your_image in your_images:
    display(Image('your_image'))

LDAP Authentication using Java

// this class will authenticate LDAP UserName or Email

// simply call LdapAuth.authenticateUserAndGetInfo (username,password);

//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex 

import java.util.*;

import javax.naming.*;

import java.util.regex.*;

import javax.naming.directory.*;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;

public class LdapAuth {


private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";

private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

private  static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};


// see you active directory user OU's hirarchy 

private  static String[] ADSearchPaths = 

{ 

    "OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Migrated Users,OU=TES-Users"

};


private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided


private static void authenticateUserAndGetInfo (String user, String password) throws Exception {

    try {


        Hashtable<String,String> env = new Hashtable <String,String>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

        env.put(Context.PROVIDER_URL, ldapURI);     

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, user);

        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext ctx = new InitialDirContext(env);

        String filter = "(sAMAccountName="+user+")";  // default for search filter username

        if(user.contains("@"))  // if user name is a email then
        {
            //String parts[] = user.split("\\@");
            //use different filter for email
            filter = "(userPrincipalName="+user+")";
        }

        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningAttributes(requiredAttributes);

        NamingEnumeration userInfo = null;


        Integer i = 0;
        do
        {
            userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
            i++;

        } while(!userInfo.hasMore() && i < ADSearchPaths.length );

        if (userInfo.hasMore()) {

            SearchResult UserDetails = (SearchResult) userInfo.next();
            Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());

            System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());

            System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());

            System.out.println("name = "+userAttr.get("cn").get(0).toString());

            System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());

        }

        userInfo.close();

    }
    catch (javax.naming.AuthenticationException e) {

    }
}   
}

Change icon on click (toggle)

If .toggle is not working I would do the next:

var flag = false;
$('#click_advance').click(function(){
    if( flag == false){
       $('#display_advance').show('1000');
         // Add more code
       flag = true;
    }
    else{
       $('#display_advance').hide('1000');
       // Add more code
       flag = false;
    }
}

It's a little bit more code, but it works

How to count the number of occurrences of a character in an Oracle varchar value?

here is a solution that will function for both characters and substrings:

select (length('a') - nvl(length(replace('a','b')),0)) / length('b')
  from dual

where a is the string in which you search the occurrence of b

have a nice day!

How to properly override clone method?

You can implement protected copy constructors like so:

/* This is a protected copy constructor for exclusive use by .clone() */
protected MyObject(MyObject that) {
    this.myFirstMember = that.getMyFirstMember(); //To clone primitive data
    this.mySecondMember = that.getMySecondMember().clone(); //To clone complex objects
    // etc
}

public MyObject clone() {
    return new MyObject(this);
}

error: src refspec master does not match any

Setup username and password in the git config

In terminal, type

vi .git/config

edit url with

url = https://username:[email protected]/username/repo.git

type :wq to save

python ValueError: invalid literal for float()

I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.

In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.

I was getting the error:

> '     0.00'
> 3 0 fast loop, delta =  10.0 weight =  0.0 
> '     0.00'
> 1 800 fast loop, delta = 10.0 weight =  0.0 
> '     0.00'
> 6 0 fast loop, delta =  10.0 weight =  0.0
> '     0\x00.0' 
> Traceback (most recent call last):
>   File "measure_weight_speed.py", line 172, in start
>     valueScale = float(answer_string) 
>     ValueError: invalid literal for float(): 0

After some research I wrote few lines of code that work in my case.

replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)

The answers in these posts helped:

  1. How to get rid of \x00 in my array of bytes?
  2. Invalid literal for float(): 0.000001, how to fix error?

How to format a number as percentage in R?

Base R

I much prefer to use sprintf which is available in base R.

sprintf("%0.1f%%", .7293827 * 100)
[1] "72.9%"

I especially like sprintf because you can also insert strings.

sprintf("People who prefer %s over %s: %0.4f%%", 
        "Coke Classic", 
        "New Coke",
        .999999 * 100)
[1] "People who prefer Coke Classic over New Coke: 99.9999%"

It's especially useful to use sprintf with things like database configurations; you just read in a yaml file, then use sprintf to populate a template without a bunch of nasty paste0's.

Longer motivating example

This pattern is especially useful for rmarkdown reports, when you have a lot of text and a lot of values to aggregate.

Setup / aggregation:

library(data.table) ## for aggregate

approval <- data.table(year = trunc(time(presidents)), 
                       pct = as.numeric(presidents) / 100,
                       president = c(rep("Truman", 32),
                                     rep("Eisenhower", 32),
                                     rep("Kennedy", 12),
                                     rep("Johnson", 20),
                                     rep("Nixon", 24)))
approval_agg <- approval[i = TRUE,
                         j = .(ave_approval = mean(pct, na.rm=T)), 
                         by = president]
approval_agg
#     president ave_approval
# 1:     Truman    0.4700000
# 2: Eisenhower    0.6484375
# 3:    Kennedy    0.7075000
# 4:    Johnson    0.5550000
# 5:      Nixon    0.4859091

Using sprintf with vectors of text and numbers, outputting to cat just for newlines.

approval_agg[, sprintf("%s approval rating: %0.1f%%",
                       president,
                       ave_approval * 100)] %>% 
  cat(., sep = "\n")
# 
# Truman approval rating: 47.0%
# Eisenhower approval rating: 64.8%
# Kennedy approval rating: 70.8%
# Johnson approval rating: 55.5%
# Nixon approval rating: 48.6%

Finally, for my own selfish reference, since we're talking about formatting, this is how I do commas with base R:

30298.78 %>% round %>% prettyNum(big.mark = ",")
[1] "30,299"

Rename Oracle Table or View

One can rename indexes the same way:

alter index owner.index_name rename to new_name;

Difference between int and double

Short answer:

int uses up 4 bytes of memory (and it CANNOT contain a decimal), double uses 8 bytes of memory. Just different tools for different purposes.

How to Use Order By for Multiple Columns in Laravel 4?

You can do as @rmobis has specified in his answer, [Adding something more into it]

Using order by twice:

MyTable::orderBy('coloumn1', 'DESC')
    ->orderBy('coloumn2', 'ASC')
    ->get();

and the second way to do it is,

Using raw order by:

MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
    ->get();

Both will produce same query as follow,

SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC

As @rmobis specified in comment of first answer you can pass like an array to order by column like this,

$myTable->orders = array(
    array('column' => 'coloumn1', 'direction' => 'desc'), 
    array('column' => 'coloumn2', 'direction' => 'asc')
);

one more way to do it is iterate in loop,

$query = DB::table('my_tables');

foreach ($request->get('order_by_columns') as $column => $direction) {
    $query->orderBy($column, $direction);
}

$results = $query->get();

Hope it helps :)

Uninstall Django completely

open the CMD and use this command :

**

pip uninstall django

**

it will easy uninstalled .

Facebook Open Graph Error - Inferred Property

UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.


There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/

But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.

So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/

It allows you to Fetch new scrape information and refresh the Facebook cache:

Open Graph Object Debugger

Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)


Use 'property'-attrs

I also noted that some developers use the name attribute instead of property. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property, not name:

<meta property="og:url" content="http://www.mywebaddress.com"/>

Use full URLs

The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image. So use the full one:

<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

SELECT date1 - date2
  FROM some_table

returns a difference in days. Multiply by 24 to get a difference in hours and 24*60 to get minutes. So

SELECT (date1 - date2) * 24 * 60 difference_in_minutes
  FROM some_table

should be what you're looking for

What is the most appropriate way to store user settings in Android application

I use the Android KeyStore to encrypt the password using RSA in ECB mode and then save it in the SharedPreferences.

When I want the password back I read the encrypted one from the SharedPreferences and decrypt it using the KeyStore.

With this method you generate a public/private Key-pair where the private one is safely stored and managed by Android.

Here is a link on how to do this: Android KeyStore Tutorial

How do I convert date/time from 24-hour format to 12-hour AM/PM?

I think you can use date() function to achive this

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

Updated

This is with DateTime

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

How to identify object types in java

You want instanceof:

if (value instanceof Integer)

This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do

if (value.getClass() == Integer.class)

or

if (Integer.class.equals(value.getClass())

How do I perform an IF...THEN in an SQL SELECT?

SELECT
if((obsolete = 'N' OR instock = 'Y'), 1, 0) AS saleable, *
FROM
product;

Git merge master into feature branch

Here is a script you can use to merge your master branch into your current branch.

The script does the following:

  • Switches to the master branch
  • Pulls the master branch
  • Switches back to your current branch
  • Merges the master branch into your current branch

Save this code as a batch file (.bat) and place the script anywhere in your repository. Then click on it to run it and you are set.

:: This batch file pulls current master and merges into current branch

@echo off

:: Option to use the batch file outside the repo and pass the repo path as an arg
set repoPath=%1
cd %repoPath%

FOR /F "tokens=*" %%g IN ('git rev-parse --abbrev-ref HEAD') do (SET currentBranch=%%g)

echo current branch is %currentBranch%
echo switching to master
git checkout master
echo.
echo pulling origin master
git pull origin master
echo.
echo switching back to %currentBranch%
git checkout %currentBranch%
echo.
echo attemting merge master into %currentBranch%
git merge master
echo.
echo script finished successfully
PAUSE

Test if a property is available on a dynamic variable

Just in case it helps someone:

If the method GetDataThatLooksVerySimilarButNotTheSame() returns an ExpandoObject you can also cast to a IDictionary before checking.

dynamic test = new System.Dynamic.ExpandoObject();
test.foo = "bar";

if (((IDictionary<string, object>)test).ContainsKey("foo"))
{
    Console.WriteLine(test.foo);
}

Select current date by default in ASP.Net Calendar control

DateTime.Now will not work, use DateTime.Today instead.

onclick event function in JavaScript

Try fixing the capitalization. onclick instead of onClick

Reference: Mozilla Developer Docs

How we can bold only the name in table td tag not the value

Surround what you want to be bold with:

<span style="font-weight:bold">Your bold text</span>

This would go inside your <td> tag.

Conditional HTML Attributes using Razor MVC3

Note you can do something like this(at least in MVC3):

<td align="left" @(isOddRow ? "class=TopBorder" : "style=border:0px") >

What I believed was razor adding quotes was actually the browser. As Rism pointed out when testing with MVC 4(I haven't tested with MVC 3 but I assume behavior hasn't changed), this actually produces class=TopBorder but browsers are able to parse this fine. The HTML parsers are somewhat forgiving on missing attribute quotes, but this can break if you have spaces or certain characters.

<td align="left" class="TopBorder" >

OR

<td align="left" style="border:0px" >

What goes wrong with providing your own quotes

If you try to use some of the usual C# conventions for nested quotes, you'll end up with more quotes than you bargained for because Razor is trying to safely escape them. For example:

<button type="button" @(true ? "style=\"border:0px\"" : string.Empty)>

This should evaluate to <button type="button" style="border:0px"> but Razor escapes all output from C# and thus produces:

style=&quot;border:0px&quot;

You will only see this if you view the response over the network. If you use an HTML inspector, often you are actually seeing the DOM, not the raw HTML. Browsers parse HTML into the DOM, and the after-parsing DOM representation already has some niceties applied. In this case the Browser sees there aren't quotes around the attribute value, adds them:

style="&quot;border:0px&quot;"

But in the DOM inspector HTML character codes display properly so you actually see:

style=""border:0px""

In Chrome, if you right-click and select Edit HTML, it switch back so you can see those nasty HTML character codes, making it clear you have real outer quotes, and HTML encoded inner quotes.

So the problem with trying to do the quoting yourself is Razor escapes these.

If you want complete control of quotes

Use Html.Raw to prevent quote escaping:

<td @Html.Raw( someBoolean ? "rel='tooltip' data-container='.drillDown a'" : "" )>

Renders as:

<td rel='tooltip' title='Drilldown' data-container='.drillDown a'>

The above is perfectly safe because I'm not outputting any HTML from a variable. The only variable involved is the ternary condition. However, beware that this last technique might expose you to certain security problems if building strings from user supplied data. E.g. if you built an attribute from data fields that originated from user supplied data, use of Html.Raw means that string could contain a premature ending of the attribute and tag, then begin a script tag that does something on behalf of the currently logged in user(possibly different than the logged in user). Maybe you have a page with a list of all users pictures and you are setting a tooltip to be the username of each person, and one users named himself '/><script>$.post('changepassword.php?password=123')</script> and now any other user who views this page has their password instantly changed to a password that the malicious user knows.

How can I set the 'backend' in matplotlib in Python?

FYI, I found I needed to put matplotlib.use('Agg') first in Python import order. For what I was doing (unit testing needed to be headless) that meant putting

import matplotlib
matplotlib.use('Agg')

at the top of my master test script. I didn't have to touch any other files.

Split string with delimiters in C

This is a string splitting function that can handle multi-character delimiters. Note that if the delimiter is longer than the string that is being split, then buffer and stringLengths will be set to (void *) 0, and numStrings will be set to 0.

This algorithm has been tested, and works. (Disclaimer: It has not been tested for non-ASCII strings, and it assumes that the caller gave valid parameters)

void splitString(const char *original, const char *delimiter, char ** * buffer, int * numStrings, int * * stringLengths){
    const int lo = strlen(original);
    const int ld = strlen(delimiter);
    if(ld > lo){
        *buffer = (void *)0;
        *numStrings = 0;
        *stringLengths = (void *)0;
        return;
    }

    *numStrings = 1;

    for(int i = 0;i < (lo - ld);i++){
        if(strncmp(&original[i], delimiter, ld) == 0) {
            i += (ld - 1);
            (*numStrings)++;
        }
    }

    *stringLengths = (int *) malloc(sizeof(int) * *numStrings);

    int currentStringLength = 0;
    int currentStringNumber = 0;
    int delimiterTokenDecrementCounter = 0;
    for(int i = 0;i < lo;i++){
        if(delimiterTokenDecrementCounter > 0){
            delimiterTokenDecrementCounter--;
        } else if(i < (lo - ld)){
            if(strncmp(&original[i], delimiter, ld) == 0){
                (*stringLengths)[currentStringNumber] = currentStringLength;
                currentStringNumber++;
                currentStringLength = 0;
                delimiterTokenDecrementCounter = ld - 1;
            } else {
                currentStringLength++;
            }
        } else {
            currentStringLength++;
        }

        if(i == (lo - 1)){
            (*stringLengths)[currentStringNumber] = currentStringLength;
        }
    }

    *buffer = (char **) malloc(sizeof(char *) * (*numStrings));
    for(int i = 0;i < *numStrings;i++){
        (*buffer)[i] = (char *) malloc(sizeof(char) * ((*stringLengths)[i] + 1));
    }

    currentStringNumber = 0;
    currentStringLength = 0;
    delimiterTokenDecrementCounter = 0;
    for(int i = 0;i < lo;i++){
        if(delimiterTokenDecrementCounter > 0){
            delimiterTokenDecrementCounter--;
        } else if(currentStringLength >= (*stringLengths)[currentStringNumber]){
            (*buffer)[currentStringNumber][currentStringLength] = 0;
            delimiterTokenDecrementCounter = ld - 1;
            currentStringLength = 0;
            currentStringNumber++;
        } else {
            (*buffer)[currentStringNumber][currentStringLength] = (char)original[i];
            currentStringLength++;
        }
    }
    buffer[currentStringNumber][currentStringLength] = 0;
}

Sample code:

int main(){
    const char *string = "STRING-1 DELIM string-2 DELIM sTrInG-3";
    char **buffer;
    int numStrings;
    int * stringLengths;

    splitString(string, " DELIM ", &buffer, &numStrings, &stringLengths);

    for(int i = 0;i < numStrings;i++){
        printf("String: %s\n", buffer[i]);
    }
}

Libraries:

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

Cheap way to search a large text file for a string

The following function works for textfiles and binary files (returns only position in byte-count though), it does have the benefit to find strings even if they would overlap a line or buffer and would not be found when searching line- or buffer-wise.

def fnd(fname, s, start=0):
    with open(fname, 'rb') as f:
        fsize = os.path.getsize(fname)
        bsize = 4096
        buffer = None
        if start > 0:
            f.seek(start)
        overlap = len(s) - 1
        while True:
            if (f.tell() >= overlap and f.tell() < fsize):
                f.seek(f.tell() - overlap)
            buffer = f.read(bsize)
            if buffer:
                pos = buffer.find(s)
                if pos >= 0:
                    return f.tell() - (len(buffer) - pos)
            else:
                return -1

The idea behind this is:

  • seek to a start position in file
  • read from file to buffer (the search strings has to be smaller than the buffer size) but if not at the beginning, drop back the - 1 bytes, to catch the string if started at the end of the last read buffer and continued on the next one.
  • return position or -1 if not found

I used something like this to find signatures of files inside larger ISO9660 files, which was quite fast and did not use much memory, you can also use a larger buffer to speed things up.

Why does this code using random strings print "hello world"?

I'll just leave it here. Whoever has a lot of (CPU) time to spare, feel free to experiment :) Also, if you have mastered some fork-join-fu to make this thing burn all CPU cores (just threads are boring, right?), please share your code. I would greatly appreciate it.

public static void main(String[] args) {
    long time = System.currentTimeMillis();
    generate("stack");
    generate("over");
    generate("flow");
    generate("rulez");

    System.out.println("Took " + (System.currentTimeMillis() - time) + " ms");
}

private static void generate(String goal) {
    long[] seed = generateSeed(goal, Long.MIN_VALUE, Long.MAX_VALUE);
    System.out.println(seed[0]);
    System.out.println(randomString(seed[0], (char) seed[1]));
}

public static long[] generateSeed(String goal, long start, long finish) {
    char[] input = goal.toCharArray();
    char[] pool = new char[input.length];
    label:
    for (long seed = start; seed < finish; seed++) {
        Random random = new Random(seed);

        for (int i = 0; i < input.length; i++)
            pool[i] = (char) random.nextInt(27);

        if (random.nextInt(27) == 0) {
            int base = input[0] - pool[0];
            for (int i = 1; i < input.length; i++) {
                if (input[i] - pool[i] != base)
                    continue label;
            }
            return new long[]{seed, base};
        }

    }

    throw new NoSuchElementException("Sorry :/");
}

public static String randomString(long i, char base) {
    System.out.println("Using base: '" + base + "'");
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    for (int n = 0; ; n++) {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char) (base + k));
    }

    return sb.toString();
}

Output:

-9223372036808280701
Using base: 'Z'
stack
-9223372036853943469
Using base: 'b'
over
-9223372036852834412
Using base: 'e'
flow
-9223372036838149518
Using base: 'd'
rulez
Took 7087 ms

Getting time difference between two times in PHP

<?php
$start = strtotime("12:00");
$end = // Run query to get datetime value from db
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>

Getter and Setter declaration in .NET

With this, you can perform some code in the get or set scope.

private string _myProperty;
public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

You also can use automatic properties:

public string myProperty
{
    get;
    set;
}

And .Net Framework will manage for you. It was create because it is a good pratice and make it easy to do.

You also can control the visibility of these scopes, for sample:

public string myProperty
{
    get;
    private set;
}

public string myProperty2
{
    get;
    protected set;
}

public string myProperty3
{
    get; 
}

Update

Now in C# you can initialize the value of a property. For sample:

public int Property { get; set; } = 1;

If also can define it and make it readonly, without a set.

public int Property { get; } = 1;

And finally, you can define an arrow function.

public int Property => GetValue();

Memory address of variables in Java

This is not memory address This is classname@hashcode
Which is the default implementation of Object.toString()

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

where

Class name = full qualified name or absolute name (ie package name followed by class name) hashcode = hexadecimal format (System.identityHashCode(obj) or obj.hashCode() will give you hashcode in decimal format).

Hint:
The confusion root cause is that the default implementation of Object.hashCode() use the internal address of the object into an integer

This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.

And of course, some classes can override both default implementations either for toString() or hashCode()

If you need the default implementation value of hashcode() for a object which overriding it,
You can use the following method System.identityHashCode(Object x)

How to set up devices for VS Code for a Flutter emulator

To select a device you must first start both, android studio and your virtual device. Then visual studio code will display that virtual device as an option.

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

To jump between words and start/end of lines in iTerm2 pick one of the two solutions below.

1. Simple solution (recommended)

  1. Open Preferences
  2. Click "Profile" tab
  3. Select a profile in the list on the left (eg "Default") and click "Keys" tab
  4. Click the "Presets" dropdown and select "Natural Text Editing"

enter image description here


2. Mapping keys manually (Advanced)

If you don't want to use the "Natural Text Editing" preset mentioned above, you can map the keys you need manually:

  1. Open Preferences
  2. Click “Keys” tab
  3. Click the [+] icon

You can now add the following keyboard shortcuts:

Move cursor one word left

  • Keyboard shortcut: ? + ?
  • Action: Send Hex Code
  • Code: 0x1b 0x62

enter image description here

Move cursor one word right

  • Keyboard Combination: ? + ?
  • Action: Send Hex Code
  • Code: 0x1b 0x66

Move cursor to beginning of line

  • Keyboard Combination: ? + ?
  • Action: Send Hex Code
  • Code: 0x01

Move cursor to end of line

  • Keyboard Combination: ? + ?
  • Action: Send Hex Code
  • Code: 0x05

Delete word

  • Keyboard Combination: ? + ?Delete
  • Action: Send Hex Code
  • Code: 0x1b 0x08

Delete line

  • Keyboard Combination: ? + ?Delete
  • Action: Send Hex Code
  • Code: 0x15

Undo

  • Keyboard Combination: ? + z
  • Action: Send Hex Code
  • Code: 0x1f

Don't forget to remove the previous bindings:

  • Open the “Profiles” tab
  • Click the sub-tab ”Keys”
  • Remove the mappings for key combinations ? + ? and ? + ?

How to pass a value from one Activity to another in Android?

Implement in this way

String i="hi";
Intent i = new Intent(this, ActivityTwo.class);
//Create the bundle
Bundle b = new Bundle();
//Add your data to bundle
b.putString(“stuff”, i);
i.putExtras(b);
startActivity(i);

Begin that second activity, inside this class to utilize the Bundle values use this code

Bundle bundle = getIntent().getExtras();
String text= bundle.getString("stuff");

How To change the column order of An Existing Table in SQL Server 2008

I got the answer for the same , Go on SQL Server ? Tools ? Options ? Designers ? Table and Database Designers and unselect Prevent saving changes that require table re-creation

enter image description here

2- Open table design view and that scroll your column up and down and save your changes.

enter image description here

In VBA get rid of the case sensitivity when comparing words?

You can convert both the values to lower case and compare.

Here is an example:

If LCase(Range("J6").Value) = LCase("Tawi") Then
   Range("J6").Value = "Tawi-Tawi"
End If

What are the differences between Pandas and NumPy+SciPy in Python?

pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.

How do I format a number to a dollar amount in PHP

PHP also has money_format().

Here's an example:

echo money_format('$%i', 3.4); // echos '$3.40'

This function actually has tons of options, go to the documentation I linked to to see them.

Note: money_format is undefined in Windows.


UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php

WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.

Instead, look into NumberFormatter::formatCurrency.

    $number = "123.45";
    $formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
    return $formatter->formatCurrency($number, 'USD');

How can I send JSON response in symfony2 controller

Symfony 2.1

$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');

return $response;

Symfony 2.2 and higher

You have special JsonResponse class, which serialises array to JSON:

return new JsonResponse(array('name' => $name));

But if your problem is How to serialize entity then you should have a look at JMSSerializerBundle

Assuming that you have it installed, you'll have simply to do

$serializedEntity = $this->container->get('serializer')->serialize($entity, 'json');

return new Response($serializedEntity);

You should also check for similar problems on StackOverflow:

Best way to define error codes/strings in Java?

There are many ways to solve this. My preferred approach is to have interfaces:

public interface ICode {
     /*your preferred code type here, can be int or string or whatever*/ id();
}

public interface IMessage {
    ICode code();
}

Now you can define any number of enums which provide messages:

public enum DatabaseMessage implements IMessage {
     CONNECTION_FAILURE(DatabaseCode.CONNECTION_FAILURE, ...);
}

Now you have several options to turn those into Strings. You can compile the strings into your code (using annotations or enum constructor parameters) or you can read them from a config/property file or from a database table or a mixture. The latter is my preferred approach because you will always need some messages that you can turn into text very early (ie. while you connect to the database or read the config).

I'm using unit tests and reflection frameworks to find all types that implement my interfaces to make sure each code is used somewhere and that the config files contain all expected messages, etc.

Using frameworks that can parse Java like https://github.com/javaparser/javaparser or the one from Eclipse, you can even check where the enums are used and find unused ones.

How to detect a mobile device with JavaScript?

Determine what the User Agent is for the devices that you need to simulate and then test a variable against that.

for example:

// var userAgent = navigator.userAgent.toLowerCase(); // this would actually get the user agent

var userAgent = "iphone"; /* Simulates User Agent for iPhone */
if (userAgent.indexOf('iphone') != -1) {
   // some code here
}

How to check if input date is equal to today's date?

TodayDate = new Date();
if (TodayDate > AnotherDate) {} else{}

< = also works, Although with =, it might have to match the milliseconds.

Switching users inside Docker image to a non-root user

You should not use su in a dockerfile, however you should use the USER instruction in the Dockerfile.

At each stage of the Dockerfile build, a new container is created so any change you make to the user will not persist on the next build stage.

For example:

RUN whoami
RUN su test
RUN whoami

This would never say the user would be test as a new container is spawned on the 2nd whoami. The output would be root on both (unless of course you run USER beforehand).

If however you do:

RUN whoami
USER test
RUN whoami

You should see root then test.

Alternatively you can run a command as a different user with sudo with something like

sudo -u test whoami

But it seems better to use the official supported instruction.

Get data from JSON file with PHP

Try:
$data = file_get_contents ("file.json");
        $json = json_decode($data, true);
        foreach ($json as $key => $value) {
            if (!is_array($value)) {
                echo $key . '=>' . $value . '<br/>';
            } else {
                foreach ($value as $key => $val) {
                    echo $key . '=>' . $val . '<br/>';
                }
            }
        }

How to write to a CSV line by line?

What about this:

with open("your_csv_file.csv", "w") as f:
    f.write("\n".join(text))

str.join() Return a string which is the concatenation of the strings in iterable. The separator between elements is the string providing this method.

Merge two (or more) lists into one, in C# .NET

You need to use Concat operation

How to send email to multiple recipients using python smtplib?

The solution below worked for me. It successfully sends an email to multiple recipients, including "CC" and "BCC."

toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n  !! Hello... !!"

msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject

s.sendmail(fromaddr, (toaddr+cc+bcc) , message)

Suppress warning messages using mysql from within Terminal, but password written in bash script

Here's how I got my bash script for my daily mysqldump database backups to work more securely. This is an expansion of Cristian Porta's great answer.

  1. First use mysql_config_editor (comes with mysql 5.6+) to set up the encrypted password file. Suppose your username is "db_user". Running from the shell prompt:

    mysql_config_editor set --login-path=local --host=localhost --user=db_user --password
    

    It prompts for the password. Once you enter it, the user/pass are saved encrypted in your home/system_username/.mylogin.cnf

    Of course, change "system_username" to your username on the server.

  2. Change your bash script from this:

    mysqldump -u db_user -pInsecurePassword my_database | gzip > db_backup.tar.gz
    

    to this:

    mysqldump --login-path=local my_database | gzip > db_backup.tar.gz
    

No more exposed passwords.

how to run mysql in ubuntu through terminal

If you want to run your scripts, then

mysql -u root -p < yourscript.sql

JavaScript Promises - reject vs. throw

There's one difference — which shouldn't matter — that the other answers haven't touched on, so:

There's no difference that's likely to matter, no. Yes, there is a very small difference.

If the fulfillment handler passed to then throws, the promise returned by that call to then is rejected with what was thrown.

If it returns a rejected promise, the promise returned by the call to then is resolved to that promise (and will ultimately be rejected, since the promise it's resolved to is rejected), which may introduce one extra async "tick" (one more loop in the microtask queue, to put it in browser terms).

Any code that relies on that difference is fundamentally broken, though. :-) It shouldn't be that sensitive to the timing of the promise settlement.

Here's an example:

_x000D_
_x000D_
function usingThrow(val) {
    return Promise.resolve(val)
        .then(v => {
            if (v !== 42) {
                throw new Error(`${v} is not 42!`);
            }
            return v;
        });
}
function usingReject(val) {
    return Promise.resolve(val)
        .then(v => {
            if (v !== 42) {
                return Promise.reject(new Error(`${v} is not 42!`));
            }
            return v;
        });
}

// The rejection handler on this chain may be called **after** the
// rejection handler on the following chain
usingReject(1)
.then(v => console.log(v))
.catch(e => console.error("Error from usingReject:", e.message));

// The rejection handler on this chain may be called **before** the
// rejection handler on the preceding chain
usingThrow(2)
.then(v => console.log(v))
.catch(e => console.error("Error from usingThrow:", e.message));
_x000D_
_x000D_
_x000D_

If you run that, as of this writing you get:

Error from usingThrow: 2 is not 42!
Error from usingReject: 1 is not 42!

Note the order.

Compare that to the same chains but both using usingThrow:

_x000D_
_x000D_
function usingThrow(val) {
    return Promise.resolve(val)
        .then(v => {
            if (v !== 42) {
                throw new Error(`${v} is not 42!`);
            }
            return v;
        });
}

usingThrow(1)
.then(v => console.log(v))
.catch(e => console.error("Error from usingThrow:", e.message));

usingThrow(2)
.then(v => console.log(v))
.catch(e => console.error("Error from usingThrow:", e.message));
_x000D_
_x000D_
_x000D_

which shows that the rejection handlers ran in the other order:

Error from usingThrow: 1 is not 42!
Error from usingThrow: 2 is not 42!

I said "may" above because there's been some work in other areas that removed this unnecessary extra tick in other similar situations if all of the promises involved are native promises (not just thenables). (Specifically: In an async function, return await x originally introduced an extra async tick vs. return x while being otherwise identical; ES2020 changed it so that if x is a native promise, the extra tick is removed.)

Again, any code that's that sensitive to the timing of the settlement of a promise is already broken. So really it doesn't/shouldn't matter.

In practical terms, as other answers have mentioned:

  • As Kevin B pointed out, throw won't work if you're in a callback to some other function you've used within your fulfillment handler — this is the biggie
  • As lukyer pointed out, throw abruptly terminates the function, which can be useful (but you're using return in your example, which does the same thing)
  • As Vencator pointed out, you can't use throw in a conditional expression (? :), at least not for now

Other than that, it's mostly a matter of style/preference, so as with most of those, agree with your team what you'll do (or that you don't care either way), and be consistent.

"register" keyword in C?

You are messing with the compiler's sophisticated graph-coloring algorithm. This is used for register allocation. Well, mostly. It acts as a hint to the compiler -- that's true. But not ignored in its entirety since you are not allowed to take the address of a register variable (remember the compiler, now on your mercy, will try to act differently). Which in a way is telling you not to use it.

The keyword was used long, long back. When there were only so few registers that could count them all using your index finger.

But, as I said, deprecated doesn't mean you cannot use it.

How to bind Events on Ajax loaded Content?

Use event delegation for dynamically created elements:

$(document).on("click", '.mylink', function(event) { 
    alert("new link clicked!");
});

This does actually work, here's an example where I appended an anchor with the class .mylink instead of data - http://jsfiddle.net/EFjzG/

href="file://" doesn't work

%20 is the space between AmberCRO SOP.

Try -

href="http://file:///K:/AmberCRO SOP/2011-07-05/SOP-SOP-3.0.pdf"

Or rename the folder as AmberCRO-SOP and write it as -

href="http://file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf"

replacing NA's with 0's in R dataframe

Here are two quickie approaches I know of:

In base

AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1

Not in base

library(qdap)
NAer(airquality)

PS P.S. Does my command above create a new dataframe called AQ1?

Look at AQ1 and see

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

Create a class which extends HttpServlet and put @WebServlet annotation on it containing the desired URL the servlet should listen on.

@WebServlet("/yourServletURL")
public class YourServlet extends HttpServlet {}

And just let <form action> point to this URL. I would also recommend to use POST method for non-idempotent requests. You should make sure that you have specified the name attribute of the HTML form input fields (<input>, <select>, <textarea> and <button>). This represents the HTTP request parameter name. Finally, you also need to make sure that the input fields of interest are enclosed inside the desired form and thus not outside.

Here are some examples of various HTML form input fields:

<form action="${pageContext.request.contextPath}/yourServletURL" method="post">
    <p>Normal text field.        
    <input type="text" name="name" /></p>

    <p>Secret text field.        
    <input type="password" name="pass" /></p>

    <p>Single-selection radiobuttons.        
    <input type="radio" name="gender" value="M" /> Male
    <input type="radio" name="gender" value="F" /> Female</p>

    <p>Single-selection checkbox.
    <input type="checkbox" name="agree" /> Agree?</p>

    <p>Multi-selection checkboxes.
    <input type="checkbox" name="role" value="USER" /> User
    <input type="checkbox" name="role" value="ADMIN" /> Admin</p>

    <p>Single-selection dropdown.
    <select name="countryCode">
        <option value="NL">Netherlands</option>
        <option value="US">United States</option>
    </select></p>

    <p>Multi-selection listbox.
    <select name="animalId" multiple="true" size="2">
        <option value="1">Cat</option>
        <option value="2">Dog</option>
    </select></p>

    <p>Text area.
    <textarea name="message"></textarea></p>

    <p>Submit button.
    <input type="submit" name="submit" value="submit" /></p>
</form>

Create a doPost() method in your servlet which grabs the submitted input values as request parameters keyed by the input field's name (not id!). You can use request.getParameter() to get submitted value from single-value fields and request.getParameterValues() to get submitted values from multi-value fields.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String name = request.getParameter("name");
    String pass = request.getParameter("pass");
    String gender = request.getParameter("gender");
    boolean agree = request.getParameter("agree") != null;
    String[] roles = request.getParameterValues("role");
    String countryCode = request.getParameter("countryCode");
    String[] animalIds = request.getParameterValues("animalId");
    String message = request.getParameter("message");
    boolean submitButtonPressed = request.getParameter("submit") != null;
    // ...
}

Do if necessary some validation and finally persist it in the DB the usual JDBC/DAO way.

User user = new User(name, pass, roles);
userDAO.save(user);

See also:

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

I add this answer as my solution review from the above.

  1. You simply edit the file .project in the main project folder. Use a proper XML Editor otherwise you will get a fatal error from Eclipse that stats you can not open this project.
  2. I made my project nature Javaby adding this <nature>org.eclipse.jdt.core.javanature</nature> to <natures></natures>.
  3. I then added those lines correctly indented <buildCommand><name>org.eclipse.jdt.core.javabuilder</name><arguments></arguments></buildCommand> to <buildSpec></buildSpec>.
  4. Run as JUnit ... Success

How to find all duplicate from a List<string>?

I use a method like that to check duplicated entrys in a string:

public static IEnumerable<string> CheckForDuplicated(IEnumerable<string> listString)
{
    List<string> duplicateKeys = new List<string>();
    List<string> notDuplicateKeys = new List<string>();
    foreach (var text in listString)
    {
        if (notDuplicateKeys.Contains(text))
        {
            duplicateKeys.Add(text);
        }
        else
        {
            notDuplicateKeys.Add(text);
        }
    }
    return duplicateKeys;
}

Maybe it's not the most shorted or elegant way, but I think that is very readable.

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

This type of solution did the trick for me:

Parent original = db.Parent.SingleOrDefault<Parent>(t => t.ID == updated.ID);
db.Childs.RemoveRange(original.Childs);
updated.Childs.ToList().ForEach(c => original.Childs.Add(c));
db.Entry<Parent>(original).CurrentValues.SetValues(updated);

Its important to say that this deletes all the records and insert them again. But for my case (less then 10) it´s ok.

I hope it helps.

How to reload current page without losing any form data?

I usually submit automatically my own form to the server and reload the page with filled arguments. Replace the placeholder arguments with the params your server received.

Copy existing project with a new name in Android Studio

In android studio 4.1.1:

Step 1 You copy the project in the file explorer and give it a new name.

Step 2 Open the copied project in the android studio and go to the Gradle Scrips files and change the name of the project to the new name in the settings and build files.

Step 3 Go to the properties Gradle file and add the line: android.overridePathCheck=true

ExpressJS How to structure an application?

My structure express 4. https://github.com/odirleiborgert/borgert-express-boilerplate

Packages

View engine: twig
Security: helmet
Flash: express-flash
Session: express-session
Encrypt: bcryptjs
Modules: express-load
Database: MongoDB
    ORM: Mongoose
    Mongoose Paginate
    Mongoose Validator
Logs: winston + winston-daily-rotate-file
Nodemon
CSS: stylus
Eslint + Husky

Structure

|-- app
    |-- controllers
    |-- helpers
    |-- middlewares
    |-- models
    |-- routes
    |-- services
|-- bin
|-- logs
|-- node_modules
|-- public
    |-- components
    |-- images
    |-- javascripts
    |-- stylesheets
|-- views
|-- .env
|-- .env-example
|-- app.js
|-- README.md

How many bytes is unsigned long long?

The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.

Pandas Merging 101

This post aims to give readers a primer on SQL-flavored merging with pandas, how to use it, and when not to use it.

In particular, here's what this post will go through:

  • The basics - types of joins (LEFT, RIGHT, OUTER, INNER)

    • merging with different column names
    • merging with multiple columns
    • avoiding duplicate merge key column in output

What this post (and other posts by me on this thread) will not go through:

  • Performance-related discussions and timings (for now). Mostly notable mentions of better alternatives, wherever appropriate.
  • Handling suffixes, removing extra columns, renaming outputs, and other specific use cases. There are other (read: better) posts that deal with that, so figure it out!

Note
Most examples default to INNER JOIN operations while demonstrating various features, unless otherwise specified.

Furthermore, all the DataFrames here can be copied and replicated so you can play with them. Also, see this post on how to read DataFrames from your clipboard.

Lastly, all visual representation of JOIN operations have been hand-drawn using Google Drawings. Inspiration from here.



Enough Talk, just show me how to use merge!

Setup & Basics

np.random.seed(0)
left = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': np.random.randn(4)})    
right = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value': np.random.randn(4)})
  
left

  key     value
0   A  1.764052
1   B  0.400157
2   C  0.978738
3   D  2.240893

right

  key     value
0   B  1.867558
1   D -0.977278
2   E  0.950088
3   F -0.151357

For the sake of simplicity, the key column has the same name (for now).

An INNER JOIN is represented by

Note
This, along with the forthcoming figures all follow this convention:

  • blue indicates rows that are present in the merge result
  • red indicates rows that are excluded from the result (i.e., removed)
  • green indicates missing values that are replaced with NaNs in the result

To perform an INNER JOIN, call merge on the left DataFrame, specifying the right DataFrame and the join key (at the very least) as arguments.

left.merge(right, on='key')
# Or, if you want to be explicit
# left.merge(right, on='key', how='inner')

  key   value_x   value_y
0   B  0.400157  1.867558
1   D  2.240893 -0.977278

This returns only rows from left and right which share a common key (in this example, "B" and "D).

A LEFT OUTER JOIN, or LEFT JOIN is represented by

This can be performed by specifying how='left'.

left.merge(right, on='key', how='left')

  key   value_x   value_y
0   A  1.764052       NaN
1   B  0.400157  1.867558
2   C  0.978738       NaN
3   D  2.240893 -0.977278

Carefully note the placement of NaNs here. If you specify how='left', then only keys from left are used, and missing data from right is replaced by NaN.

And similarly, for a RIGHT OUTER JOIN, or RIGHT JOIN which is...

...specify how='right':

left.merge(right, on='key', how='right')

  key   value_x   value_y
0   B  0.400157  1.867558
1   D  2.240893 -0.977278
2   E       NaN  0.950088
3   F       NaN -0.151357

Here, keys from right are used, and missing data from left is replaced by NaN.

Finally, for the FULL OUTER JOIN, given by

specify how='outer'.

left.merge(right, on='key', how='outer')

  key   value_x   value_y
0   A  1.764052       NaN
1   B  0.400157  1.867558
2   C  0.978738       NaN
3   D  2.240893 -0.977278
4   E       NaN  0.950088
5   F       NaN -0.151357

This uses the keys from both frames, and NaNs are inserted for missing rows in both.

The documentation summarizes these various merges nicely:

enter image description here


Other JOINs - LEFT-Excluding, RIGHT-Excluding, and FULL-Excluding/ANTI JOINs

If you need LEFT-Excluding JOINs and RIGHT-Excluding JOINs in two steps.

For LEFT-Excluding JOIN, represented as

Start by performing a LEFT OUTER JOIN and then filtering (excluding!) rows coming from left only,

(left.merge(right, on='key', how='left', indicator=True)
     .query('_merge == "left_only"')
     .drop('_merge', 1))

  key   value_x  value_y
0   A  1.764052      NaN
2   C  0.978738      NaN

Where,

left.merge(right, on='key', how='left', indicator=True)

  key   value_x   value_y     _merge
0   A  1.764052       NaN  left_only
1   B  0.400157  1.867558       both
2   C  0.978738       NaN  left_only
3   D  2.240893 -0.977278       both

And similarly, for a RIGHT-Excluding JOIN,

(left.merge(right, on='key', how='right', indicator=True)
     .query('_merge == "right_only"')
     .drop('_merge', 1))

  key  value_x   value_y
2   E      NaN  0.950088
3   F      NaN -0.151357

Lastly, if you are required to do a merge that only retains keys from the left or right, but not both (IOW, performing an ANTI-JOIN),

You can do this in similar fashion—

(left.merge(right, on='key', how='outer', indicator=True)
     .query('_merge != "both"')
     .drop('_merge', 1))

  key   value_x   value_y
0   A  1.764052       NaN
2   C  0.978738       NaN
4   E       NaN  0.950088
5   F       NaN -0.151357

Different names for key columns

If the key columns are named differently—for example, left has keyLeft, and right has keyRight instead of key—then you will have to specify left_on and right_on as arguments instead of on:

left2 = left.rename({'key':'keyLeft'}, axis=1)
right2 = right.rename({'key':'keyRight'}, axis=1)

left2
 
  keyLeft     value
0       A  1.764052
1       B  0.400157
2       C  0.978738
3       D  2.240893

right2

  keyRight     value
0        B  1.867558
1        D -0.977278
2        E  0.950088
3        F -0.151357
left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')

  keyLeft   value_x keyRight   value_y
0       B  0.400157        B  1.867558
1       D  2.240893        D -0.977278

Avoiding duplicate key column in output

When merging on keyLeft from left and keyRight from right, if you only want either of the keyLeft or keyRight (but not both) in the output, you can start by setting the index as a preliminary step.

left3 = left2.set_index('keyLeft')
left3.merge(right2, left_index=True, right_on='keyRight')
    
    value_x keyRight   value_y
0  0.400157        B  1.867558
1  2.240893        D -0.977278

Contrast this with the output of the command just before (that is, the output of left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')), you'll notice keyLeft is missing. You can figure out what column to keep based on which frame's index is set as the key. This may matter when, say, performing some OUTER JOIN operation.


Merging only a single column from one of the DataFrames

For example, consider

right3 = right.assign(newcol=np.arange(len(right)))
right3
  key     value  newcol
0   B  1.867558       0
1   D -0.977278       1
2   E  0.950088       2
3   F -0.151357       3

If you are required to merge only "new_val" (without any of the other columns), you can usually just subset columns before merging:

left.merge(right3[['key', 'newcol']], on='key')

  key     value  newcol
0   B  0.400157       0
1   D  2.240893       1

If you're doing a LEFT OUTER JOIN, a more performant solution would involve map:

# left['newcol'] = left['key'].map(right3.set_index('key')['newcol']))
left.assign(newcol=left['key'].map(right3.set_index('key')['newcol']))

  key     value  newcol
0   A  1.764052     NaN
1   B  0.400157     0.0
2   C  0.978738     NaN
3   D  2.240893     1.0

As mentioned, this is similar to, but faster than

left.merge(right3[['key', 'newcol']], on='key', how='left')

  key     value  newcol
0   A  1.764052     NaN
1   B  0.400157     0.0
2   C  0.978738     NaN
3   D  2.240893     1.0

Merging on multiple columns

To join on more than one column, specify a list for on (or left_on and right_on, as appropriate).

left.merge(right, on=['key1', 'key2'] ...)

Or, in the event the names are different,

left.merge(right, left_on=['lkey1', 'lkey2'], right_on=['rkey1', 'rkey2'])

Other useful merge* operations and functions

This section only covers the very basics, and is designed to only whet your appetite. For more examples and cases, see the documentation on merge, join, and concat as well as the links to the function specs.



Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

To keep this question current it is worth highlighting that AssemblyInformationalVersion is used by NuGet and reflects the package version including any pre-release suffix.

For example an AssemblyVersion of 1.0.3.* packaged with the asp.net core dotnet-cli

dotnet pack --version-suffix ci-7 src/MyProject

Produces a package with version 1.0.3-ci-7 which you can inspect with reflection using:

CustomAttributeExtensions.GetCustomAttribute<AssemblyInformationalVersionAttribute>(asm);

Is it possible to have placeholders in strings.xml for runtime values?

In your string file use this

<string name="redeem_point"> You currently have %s points(%s points = 1 %s)</string>

And in your code use as accordingly

coinsTextTV.setText(String.format(getContext().getString(R.string.redeem_point), rewardPoints.getReward_points()
                        , rewardPoints.getConversion_rate(), getString(R.string.rs)));

In Python, what happens when you import inside of a function?

Might I suggest in general that instead of asking, "Will X improve my performance?" you use profiling to determine where your program is actually spending its time and then apply optimizations according to where you'll get the most benefit?

And then you can use profiling to assure that your optimizations have actually benefited you, too.

Where to change the value of lower_case_table_names=2 on windows xampp

Do these steps:

  1. open your MySQL configuration file: [drive]\xampp\mysql\bin\my.ini
  2. look up for: # The MySQL server [mysqld]
  3. add this right below it: lower_case_table_names = 2
  4. save the file and restart MySQL service

From: http://webdev.issimplified.com/2010/03/02/mysql-on-windows-force-table-names-to-lowercase/

How to sort by Date with DataTables jquery plugin?

Create a hidden column "dateOrder" (for example) with the date as string with the format "yyyyMMddHHmmss" and use the property "orderData" to point to that column.

var myTable = $("#myTable").dataTable({
 columns: [
      { data: "id" },
      { data: "date", "orderData": 4 },
      { data: "name" },
      { data: "total" },
      { data: "dateOrder", visible: false }
 ] });

remove first element from array and return the array minus the first element

This can be done in one line with lodash _.tail:

_x000D_
_x000D_
var arr = ["item 1", "item 2", "item 3", "item 4"];_x000D_
console.log(_.tail(arr));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How to change the integrated terminal in visual studio code or VSCode

It is possible to get this working in VS Code and have the Cmder terminal be integrated (not pop up).

To do so:

  1. Create an environment variable "CMDER_ROOT" pointing to your Cmder directory.
  2. In (Preferences > User Settings) in VS Code add the following settings:

"terminal.integrated.shell.windows": "cmd.exe"

"terminal.integrated.shellArgs.windows": ["/k", "%CMDER_ROOT%\\vendor\\init.bat"]

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

For Those Running on Older Hardware:

You may get this same error due to having an older CPU using tensorflow-gpu 1.6.

If your cpu was made before 2011, then your max tensorflow-gpu version is 1.5.

Tensorflow 1.6 requires AVX instructions on your cpu. Verified here: Tensorflow Github docs

AVX enabled CPUs: Wiki AVX CPUs

What I did in my conda environment for tensorflow:

pip install --ignore-installed --upgrade tensorflow-gpu==1.5

Error "can't use subversion command line client : svn" when opening android project checked out from svn

If you are using ubuntu, check weather subversion is installed or not.

If not then install through command line as

sudo apt-get install subversion

and check following configurations are selected

enter image description here

What is a wrapper class?

It might also be valuable to note that in some environments, much of what wrapper classes might do is being replaced by aspects.

EDIT:

In general a wrapper is going to expand on what the wrappee does, without being concerned about the implementation of the wrappee, otherwise there's no point of wrapping versus extending the wrapped class. A typical example is to add timing information or logging functionality around some other service interface, as opposed to adding it to every implementation of that interface.

This then ends up being a typical example for Aspect programming. Rather than going through an interface function by function and adding boilerplate logging, in aspect programming you define a pointcut, which is a kind of regular expression for methods, and then declare methods that you want to have executed before, after or around all methods matching the pointcut. Its probably fair to say that aspect programming is a kind of use of the Decorator pattern, which wrapper classes can also be used for, but that both technologies have other uses.

Switch to another branch without changing the workspace files

Git. Switch to another branch

git checkout branch_name

How to check if a Docker image with a specific tag exist locally?

With the help of Vonc's answer above I created the following bash script named check.sh:

#!/bin/bash
image_and_tag="$1"
image_and_tag_array=(${image_and_tag//:/ })
if [[ "$(docker images ${image_and_tag_array[0]} | grep ${image_and_tag_array[1]} 2> /dev/null)" != "" ]]; then
  echo "exists"
else
  echo "doesn't exist"
fi

Using it for an existing image and tag will print exists, for example:

./check.sh rabbitmq:3.4.4

Using it for a non-existing image and tag will print doesn't exist, for example:

./check.sh rabbitmq:3.4.3

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

i just restart my mysql server and the problem solved in windows net stop MySQL then net start MySQl ubuntu linux sudo service start mysql

Finding Key associated with max Value in a Java Map

Java 8 way to get all keys with max value.

Integer max = PROVIDED_MAP.entrySet()
            .stream()
            .max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1)
            .get()
            .getValue();

List listOfMax = PROVIDED_MAP.entrySet()
            .stream()
            .filter(entry -> entry.getValue() == max)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

System.out.println(listOfMax);

Also you can parallelize it by using parallelStream() instead of stream()

When to use "new" and when not to, in C++?

You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope. Some examples of this are:

void foo()
{
  Point p = Point(0,0);
} // p is now destroyed.

for (...)
{
  Point p = Point(0,0);
} // p is destroyed after each loop

Some people will say that the use of new decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.

In the example below the location of 'p' will be where its containing object, Foo, is allocated. I prefer to call this 'in-place' allocation.

class Foo
{

  Point p;
}; // p will be automatically destroyed when foo is.

Allocating (and freeing) objects with the use of new is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.

A second example of when to allocate via new is for arrays. You cannot* change the size of an in-place or stack array at run-time so where you need an array of undetermined size it must be allocated via new.

E.g.

void foo(int size)
{
   Point* pointArray = new Point[size];
   ...
   delete [] pointArray;
}

(*pre-emptive nitpicking - yes, there are extensions that allow variable sized stack allocations).

Get environment value in controller

All of the variables listed in .env file will be loaded into the $_ENV PHP super-global when your application receives a request. Check out the Laravel configuration page.

$_ENV['yourkeyhere'];

programmatically add column & rows to WPF Datagrid

If you already have the databinding in place John Myczek answer is complete. If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in line with most guidelines, like MVVM)

Then you just bind to Users collections and columns are autogenerated as you speficy them. Strings passed to property descriptors are names for column headers. At runtime you can add more PropertyDescriptors to 'Users' add another column to the grid.

Add Whatsapp function to website, like sms, tel

I just posted an answer on a thread similiar to this here https://stackoverflow.com/a/43357241/3958617

The approach with:

<a href="whatsapp://send?abid=username&text=Hello%2C%20World!">whatsapp</a>

and with

<a href="intent://send/0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">whatsapp</a>

Only works if the person who clicked on your link have your number on their contact list.

Since not everybody will have it, the other solution is to use Whatsapp API like this:

<a href="https://api.whatsapp.com/send?phone=15551234567">Send Message</a>

Java: How to stop thread?

One possible way is to do something like this:

public class MyThread extends Thread {
    @Override
    public void run() {
        while (!this.isInterrupted()) {
            //
        }
    }
}

And when you want to stop your thread, just call a method interrupt():

myThread.interrupt();

Of course, this won't stop thread immediately, but in the following iteration of the loop above. In the case of downloading, you need to write a non-blocking code. It means, that you will attempt to read new data from the socket only for a limited amount of time. If there are no data available, it will just continue. It may be done using this method from the class Socket:

mySocket.setSoTimeout(50);

In this case, timeout is set up to 50 ms. After this time has gone and no data was read, it throws an SocketTimeoutException. This way, you may write iterative and non-blocking thread, which may be killed using the construction above.

It's not possible to kill thread in any other way and you've to implement such a behavior yourself. In past, Thread had some method (not sure if kill() or stop()) for this, but it's deprecated now. My experience is, that some implementations of JVM doesn't even contain that method currently.

How to see what privileges are granted to schema of another user

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Object cannot be cast from DBNull to other types

I'm thinking that your output parameter is coming back with a DBNull value. Add a check for that like this

var outputParam = dataAccCom.GetParameterValue(IDbCmd, "op_Id");
if(!(outputParam is DBNull))
     DataTO.Id = Convert.ToInt64(outputParam);

What is the default Precision and Scale for a Number in Oracle?

The NUMBER type can be specified in different styles:

                Resulting  Resulting  Precision
Specification   Precision  Scale      Check      Comment
-------------------------------------------------------------------------------
NUMBER          NULL       NULL       NO         'maximum range and precision',
                                                 values are stored 'as given'
NUMBER(P, S)    P          S          YES        Error code: ORA-01438
NUMBER(P)       P          0          YES        Error code: ORA-01438
NUMBER(*, S)    38         S          NO

Where the precision is the total number of digits and scale is the number of digits right or left (negative scale) of the decimal point.

Oracle specifies ORA-01438 as

value larger than specified precision allowed for this column

As noted in the table, this integrity check is only active if the precision is explicitly specified. Otherwise Oracle silently rounds the inserted or updated value using some unspecified method.

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I was also facing this issue

Error- Windows cannot find 'http://127.0.01:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

After some research work, I found out that my HTTPPORT ie. 8080 was occupied by Apace HTTP Server and hence connection by OracleServiceXE could not be established.

What I did to solve this issue was :

  1. Go to Windows -> Services, found out Apache2.4 and manually stopped it to free my 8080 port.
  2. Clicked on Start Database, and I received message :

The OracleServiceXE service is starting.............. The OracleServiceXE service was started successfully.

  1. Manually entered http://127.0.0.1:8080/apex/f?p=4950 url to my browser which auto redirected me to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303

That's it my issue got resolved.

In order to remember this new url and make sure that next time whenever I hit Get Started I should be redirected to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303 instead of http://127.0.0.1:8080/apex/f?p=4950, what I did was :

  1. Browse to Directory:\OracleDatabase\app\oracle\product\11.2.0\server and search for Get_Started.html.
  2. Right Click on Get_Started.html and select Properties
  3. Modify your url and click Apply

Hope this Helps.

Same Navigation Drawer in different Activities

package xxxxxx;



import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.widget.SearchView;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;


public class loginhome extends AppCompatActivity {
    private Toolbar toolbar;
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;

    // Make sure to be using android.support.v7.app.ActionBarDrawerToggle version.
    // The android.support.v4.app.ActionBarDrawerToggle has been deprecated.
    private ActionBarDrawerToggle drawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginhome);

        // Initializing Toolbar and setting it as the actionbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        //Initializing NavigationView


        navigationView = (NavigationView) findViewById(R.id.nav_view);

        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu

            public boolean onNavigationItemSelected(MenuItem menuItem) {


                //Checking if the item is in checked state or not, if not make it in checked state
                if(menuItem.isChecked()) menuItem.setChecked(false);
                else menuItem.setChecked(true);

                //Closing drawer on item click
                drawerLayout.closeDrawers();

                //Check to see which item was being clicked and perform appropriate action
                switch (menuItem.getItemId()){


                    //Replacing the main content with ContentFragment Which is our Inbox View;
                    case R.id.nav_first_fragment:
                        Toast.makeText(getApplicationContext(),"First fragment",Toast.LENGTH_SHORT).show();
                         FirstFragment fragment = new FirstFragment();
                        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                        fragmentTransaction.replace(R.id.frame,fragment);
                        fragmentTransaction.commit();
                        return true;

                    // For rest of the options we just show a toast on click
                    case R.id.nav_second_fragment:
                        Toast.makeText(getApplicationContext(),"Second fragment",Toast.LENGTH_SHORT).show();
                        SecondFragment fragment2 = new SecondFragment();
                        android.support.v4.app.FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction();
                        fragmentTransaction2.replace(R.id.frame,fragment2);
                        fragmentTransaction2.commit();
                        return true;

                    default:
                        Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
                        return true;

                }
            }
        });

        // Initializing Drawer Layout and ActionBarToggle
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open, R.string.drawer_close){

            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

                super.onDrawerOpened(drawerView);
            }
        };

        //Setting the actionbarToggle to drawer layout
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        //calling sync state is necessay or else your hamburger icon wont show up
        actionBarDrawerToggle.syncState();







    }

use this for your toolbar.xml

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

    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:elevation="4dp"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"


        >

    </android.support.v7.widget.Toolbar>

use this for navigation header if want to use

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="192dp"
    android:background="?attr/colorPrimaryDark"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:orientation="vertical"
    android:gravity="bottom">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:id="@+id/navhead"
        android:orientation="vertical"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:textColor="#ffffff"
            android:text="tanya"
            android:textSize="14sp"
            android:textStyle="bold"

            />

        <TextView
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="5dp"
            android:text="tanya.com"
            android:textSize="14sp"
            android:textStyle="normal"

            />
    </LinearLayout>
    <de.hdodenhof.circleimageview.CircleImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_below="@+id/imageView"
        android:layout_marginTop="15dp"

        android:src="@drawable/face"
        android:id="@+id/circleView"
        />



</RelativeLayout>

Skip rows during csv import pandas

skip[1] will skip second line, not the first one.

How can I use ":" as an AWK field separator?

"-F" is a command line argument, not AWK syntax. Try:

 echo "1: " | awk -F  ":" '/1/ {print $1}'

Google Play app description formatting

Currently (July 2015), HTML escape sequences (&bull; &#8226;) do not work in browser version of Play Store, they're displayed as text. Though, Play Store app handles them as expected.

So, if you're after the unicode bullet point in your app/update description [that's what's got you here, most likely], just copy-paste the bullet character

PS You can also use unicode input combo to get the character

Linux: CtrlShiftu 2022 Enter or Space

Mac: Hold ? 2022 release ?

Windows: Hold Alt 2022 release Alt

Mac and Windows require some setup, read on Wikipedia

PPS If you're feeling creative, here's a good link with more copypastable symbols, but don't go too crazy, nobody likes clutter in what they read.

MySQL error 1449: The user specified as a definer does not exist

Create the deleted user like this :

mysql> create user 'web2vi';

or

mysql> create user 'web2vi'@'%';

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

just remove "520_"
utf8mb4_unicode_520_ci ? utf8mb4_unicode_ci

Getting checkbox values on submit

Just for printing you can use as below :

print_r($_GET['color']);

or

var_dump($_GET['color']);

Connecting to TCP Socket from browser using javascript

In order to achieve what you want, you would have to write two applications (in either Java or Python, for example):

  1. Bridge app that sits on the client's machine and can deal with both TCP/IP sockets and WebSockets. It will interact with the TCP/IP socket in question.

  2. Server-side app (such as a JSP/Servlet WAR) that can talk WebSockets. It includes at least one HTML page (including server-side processing code if need be) to be accessed by a browser.

It should work like this

  1. The Bridge will open a WS connection to the web app (because a server can't connect to a client).
  2. The Web app will ask the client to identify itself
  3. The bridge client sends some ID information to the server, which stores it in order to identify the bridge.
    1. The browser-viewable page connects to the WS server using JS.
    2. Repeat step 3, but for the JS-based page
    3. The JS-based page sends a command to the server, including to which bridge it must go.
    4. The server forwards the command to the bridge.
    5. The bridge opens a TCP/IP socket and interacts with it (sends a message, gets a response).
    6. The Bridge sends a response to the server through the WS
    7. The WS forwards the response to the browser-viewable page
    8. The JS processes the response and reacts accordingly
    9. Repeat until either client disconnects/unloads

Note 1: The above steps are a vast simplification and do not include information about error handling and keepAlive requests, in the event that either client disconnects prematurely or the server needs to inform clients that it is shutting down/restarting.

Note 2: Depending on your needs, it might be possible to merge these components into one if the TCP/IP socket server in question (to which the bridge talks) is on the same machine as the server app.

How to debug SSL handshake using cURL?

I have used this command to troubleshoot client certificate negotiation:

openssl s_client -connect www.test.com:443 -prexit

The output will probably contain "Acceptable client certificate CA names" and a list of CA certificates from the server, or possibly "No client certificate CA names sent", if the server doesn't always require client certificates.

Removing items from a list

You need to use Iterator and call remove() on iterator instead of using for loop.

is there a post render callback for Angular JS directive?

I had the same issue, but using Angular + DataTable with a fnDrawCallback + row grouping + $compiled nested directives. I placed the $timeout in my fnDrawCallback function to fix pagination rendering.

Before example, based on row_grouping source:

var myDrawCallback = function myDrawCallbackFn(oSettings){
  var nTrs = $('table#result>tbody>tr');
  for(var i=0; i<nTrs.length; i++){
     //1. group rows per row_grouping example
     //2. $compile html templates to hook datatable into Angular lifecycle
  }
}

After example:

var myDrawCallback = function myDrawCallbackFn(oSettings){
  var nTrs = $('table#result>tbody>tr');
  $timeout(function requiredRenderTimeoutDelay(){
    for(var i=0; i<nTrs.length; i++){
       //1. group rows per row_grouping example
       //2. $compile html templates to hook datatable into Angular lifecycle
    }
  ,50); //end $timeout
}

Even a short timeout delay was enough to allow Angular to render my compiled Angular directives.

How to enter ssh password using bash?

Create a new keypair: (go with the defaults)

ssh-keygen

Copy the public key to the server: (password for the last time)

ssh-copy-id [email protected]

From now on the server should recognize your key and not ask you for the password anymore:

ssh [email protected]

insert datetime value in sql database with c#

 DateTime time = DateTime.Now;              // Use current time
 string format = "yyyy-MM-dd HH:mm:ss";    // modify the format depending upon input required in the column in database 
 string insert = @" insert into Table(DateTime Column) values ('" + time.ToString(format) + "')"; 

and execute the query. DateTime.Now is to insert current Datetime..

Is there a good jQuery Drag-and-drop file upload plugin?

If you're looking for one that doesn't rely on Flash then dropzonejs is a good shout. It supports multiple files and drag and drop.

http://www.dropzonejs.com/

Read user input inside a loop

It looks like you read twice, the read inside the while loop is not needed. Also, you don't need to invoke the cat command:

while read input
do
    echo $input
done < filename

PHP Composer update "cannot allocate memory" error (using Laravel 4)

As composer troubleshooting guide here This could be happening because the VPS runs out of memory and has no Swap space enabled.

free -m

To enable the swap you can use for example:

sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo /sbin/swapon /var/swap.1

Or if above not worked then you can try create a swap file

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

CORS header 'Access-Control-Allow-Origin' missing

You have to modify your server side code, as given below

public class CorsResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext,   ContainerResponseContext responseContext)
    throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

  }
}

Max tcp/ip connections on Windows Server 2008

There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:

It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

concatenate two strings

The best way in my eyes is to use the concat() method provided by the String class itself.

The useage would, in your case, look like this:

String myConcatedString = cursor.getString(numcol).concat('-').
       concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)));

Setting Oracle 11g Session Timeout

This is likely caused by your application's connection pool; not an Oracle DBMS issue. Most connection pools have a validate statement that can execute before giving you the connection. In oracle you would want "Select 1 from dual".

The reason it started occurring after you restarted the server is that the connection pool was probably added without a restart and you are just now experiencing the use of the connection pool for the first time. What is the modification dates on your resource files that deal with database connections?

Validate Query example:

 <Resource name="jdbc/EmployeeDB" auth="Container" 
            validationQuery="Select 1 from dual" type="javax.sql.DataSource" username="dbusername" password="dbpassword"
            driverClassName="org.hsql.jdbcDriver" url="jdbc:HypersonicSQL:database"
            maxActive="8" maxIdle="4"/>

EDIT: In the case of Grails, there are similar configuration options for the grails pool. Example for Grails 1.2 (see release notes for Grails 1.2)

dataSource {
    pooled = true
    dbCreate = "update"
    url = "jdbc:mysql://localhost/yourDB"
    driverClassName = "com.mysql.jdbc.Driver"
    username = "yourUser"
    password = "yourPassword"
    properties {
        maxActive = 50
        maxIdle = 25
        minIdle = 5
        initialSize = 5
        minEvictableIdleTimeMillis = 60000
        timeBetweenEvictionRunsMillis = 60000
        maxWait = 10000     
    }   
}

How to convert date to timestamp in PHP?

With DateTime API:

$dateTime = new DateTime('2008-09-22'); 
echo $dateTime->format('U'); 

// or 

$date = new DateTime('2008-09-22');
echo $date->getTimestamp();

The same with the procedural API:

$date = date_create('2008-09-22');
echo date_format($date, 'U');

// or

$date = date_create('2008-09-22');
echo date_timestamp_get($date);

If the above fails because you are using a unsupported format, you can use

$date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
echo $dateTime->format('U'); 

// or

$date = date_parse_from_format('!d-m-Y', '22-09-2008');
echo date_format($date, 'U');

Note that if you do not set the !, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.

Yet another alternative is to use the IntlDateFormatter API:

$formatter = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'GMT',
    IntlDateFormatter::GREGORIAN,
    'dd-MM-yyyy'
);
echo $formatter->parse('22-09-2008');

Unless you are working with localized date strings, the easier choice is likely DateTime.

Bootstrap 3.0: How to have text and input on same line?

You can do it like this:

<form class="form-horizontal" role="form">
    <div class="form-group">
        <label for="inputType" class="col-sm-2 control-label">Label</label>
        <div class="col-sm-4">
            <input type="text" class="form-control" id="input" placeholder="Input text">
        </div>
    </div>
</form>

Fiddle

UILabel text margin

You need to calculate UILabel size when you put insets. It can have different number of lines because of text alignment, line break mode.

override func drawText(in rect: CGRect) {

    let size = self.sizeThatFits(UIEdgeInsetsInsetRect(rect, insets).size);
    super.drawText(in: CGRect.init(origin: CGPoint.init(x: insets.left, y: insets.top), size: size));
}

override var intrinsicContentSize: CGSize {

    var size = super.intrinsicContentSize;

    if text == nil || text?.count == 0 {
        return size;
    }

    size = self.sizeThatFits(UIEdgeInsetsInsetRect(CGRect.init(origin: CGPoint.zero, size: size), insets).size);
    size.width  += self.insets.left + self.insets.right;
    size.height += self.insets.top + self.insets.bottom;

    return size;
}

try iEun/InsetLabel