Programs & Examples On #Codaset

0

Change Timezone in Lumen or Laravel 5

I modify it in the .env APP_TIMEZONE.

For Colombia: APP_TIMEZONE = America / Bogota also for paris like this: APP_TIMEZONE = Europe / Paris

Source: https://www.php.net/manual/es/timezones.europe.php

window.close and self.close do not close the window in Chrome

I am using the method posted by Brock Adams and it even works in Firefox, if it's user initiated.

open(location, '_self').close();

I am calling it from a button press so it is user initiated, and it is still working fine using Chrome 35-40, Internet Explorer 11, Safari 7-8 and ALSO Firefox 29-35. I tested using version 8.1 of Windows and Mac OS X 10.6, 10.9 & 10.10 if that is different.


Self-Closing Window Code (on the page that closes itself)

The complete code to be used on the user-opened window that can close itself:

window_to_close.htm

JavaScript:

function quitBox(cmd)
{   
    if (cmd=='quit')
    {
        open(location, '_self').close();
    }   
    return false;   
}

HTML:

<input type="button" name="Quit" id="Quit" value="Quit" onclick="return quitBox('quit');" />

Try this test page: (Now tested in Chrome 40 and Firefox 35)

http://browserstrangeness.bitbucket.io/window_close_tester.htm


Window Opener Code (on a page that opens the above page)

To make this work, security-imposed cross browser compatibility requires that the window that is to be closed must have already been opened by the user clicking a button within the same site domain.

For example, the window that uses the method above to close itself, can be opened from a page using this code (code provided from my example page linked above):

window_close_tester.htm

JavaScript:

function open_a_window() 
{
    window.open("window_to_close.htm"); 

    return false;
}

HTML:

<input type="button" onclick="return open_a_window();" value="Open New Window/Tab" />

Displaying a 3D model in JavaScript/HTML5

I also needed what you've been searching for and did some research.

I found JSC3D (https://code.google.com/p/jsc3d/). It's a project written entirely in Javascript and uses the HTML canvas. It has been tested for Opera, Chrome, Firefox, Safari, IE9 and more.

Then you have services as p3d.in and Sketchfab that give you a nice reader to view 3D models on a web page: they use HTML5 and WebGL. They both have a free version.

Getting the closest string match

You might find this library helpful! http://code.google.com/p/google-diff-match-patch/

It is currently available in Java, JavaScript, Dart, C++, C#, Objective C, Lua and Python

It works pretty well too. I use it in a couple of my Lua projects.

And I don't think it would be too difficult to port it to other languages!

Generating a PDF file from React Components

Only few steps. We can download or generate PDF from our HTML page or we can generate PDF of specific div from a HTML page.

Steps : HTML -> Image (PNG or JPEG) -> PDF

Please Follow the below steps,

Step 1 :-

npm install --save html-to-image
npm install jspdf --save

Step 2 :-

/* ES6 */
import * as htmlToImage from 'html-to-image';
import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'html-to-image';
 
/* ES5 */
var htmlToImage = require('html-to-image');

-------------------------
import { jsPDF } from "jspdf";

Step 3 :-

   ******  With out PDF properties given below  ******

 htmlToImage.toPng(document.getElementById('myPage'), { quality: 0.95 })
        .then(function (dataUrl) {
          var link = document.createElement('a');
          link.download = 'my-image-name.jpeg';
          const pdf = new jsPDF();          
          pdf.addImage(dataUrl, 'PNG', 0, 0);
          pdf.save("download.pdf"); 
        });


    ******  With PDF properties given below ******

    htmlToImage.toPng(document.getElementById('myPage'), { quality: 0.95 })
        .then(function (dataUrl) {
          var link = document.createElement('a');
          link.download = 'my-image-name.jpeg';
          const pdf = new jsPDF();
          const imgProps= pdf.getImageProperties(dataUrl);
          const pdfWidth = pdf.internal.pageSize.getWidth();
          const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
          pdf.addImage(dataUrl, 'PNG', 0, 0,pdfWidth, pdfHeight);
          pdf.save("download.pdf"); 
        });

I think this is helpful. Please try

Difference between TCP and UDP?

From the Skullbox article:

TCP (Transmission Control Protocol) is the most commonly used protocol on the Internet. The reason for this is because TCP offers error correction. When the TCP protocol is used there is a "guaranteed delivery." This is due largely in part to a method called "flow control." Flow control determines when data needs to be re-sent, and stops the flow of data until previous packets are successfully transferred. This works because if a packet of data is sent, a collision may occur. When this happens, the client re-requests the packet from the server until the whole packet is complete and is identical to its original.

UDP (User Datagram Protocol) is anther commonly used protocol on the Internet. However, UDP is never used to send important data such as webpages, database information, etc; UDP is commonly used for streaming audio and video. Streaming media such as Windows Media audio files (.WMA) , Real Player (.RM), and others use UDP because it offers speed! The reason UDP is faster than TCP is because there is no form of flow control or error correction. The data sent over the Internet is affected by collisions, and errors will be present. Remember that UDP is only concerned with speed. This is the main reason why streaming media is not high quality.

1) TCP is connection oriented and reliable where as UDP is connection less and unreliable.

2) TCP needs more processing at network interface level where as in UDP it’s not.

3) TCP uses, 3 way handshake, congestion control, flow control and other mechanism to make sure the reliable transmission.

4) UDP is mostly used in cases where the packet delay is more serious than packet loss.

How to create a DataFrame from a text file in Spark

You will not able to convert it into data frame until you use implicit conversion.

val sqlContext = new SqlContext(new SparkContext())

import sqlContext.implicits._

After this only you can convert this to data frame

case class Test(id:String,filed2:String)

val myFile = sc.textFile("file.txt")

val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()

Visual Studio Code: Auto-refresh file changes

{
    "files.useExperimentalFileWatcher" : true
}

in Code -> Preferences -> Settings

Tested with Visual Studio Code Version 1.26.1 on mac and win

Any way to break if statement in PHP?

No.

But how about:

$a="test";
if("test"==$a)
{
  if ($someOtherCondition)
  {
    echo "yes";
  }
}
echo "finish";

Bash integer comparison

I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)

case "$1" in
    0|1) xinput set-prop 12 "Device Enabled" $1 ;;
      *) echo "This script requires a 1 or 0 as first parameter." ;;
esac

Authorize attribute in ASP.NET MVC

It exists because it is more convenient to use, also it is a whole different ideology using attributes to mark the authorization parameters rather than xml configuration. It wasn't meant to beat general purpose config or any other authorization frameworks, just MVC's way of doing it. I'm saying this, because it seems you are looking for a technical feature advantages which are probably non... just superb convenience.

BobRock already listed the advantages. Just to add to his answer, another scenarios are that you can apply this attribute to whole controller, not just actions, also you can add different role authorization parameters to different actions in same controller to mix and match.

How to detect a mobile device with JavaScript?

I use mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)

deleted object would be re-saved by cascade (remove deleted object from associations)

I also ran into this error on a badly designed database, where there was a Person table with a one2many relationship with a Code table and an Organization table with a one2many relationship with the same Code table. The Code could apply to both an Organization and Or a Person depending on situation. Both the Person object and the Organization object were set to Cascade=All delete orphans.

What became of this overloaded use of the Code table however was that neither the Person nor the Organization could cascade delete because there was always another collection that had a reference to it. So no matter how it was deleted in the Java code out of whatever referencing collections or objects the delete would fail. The only way to get it to work was to delete it out of the collection I was trying to save then delete it out of the Code table directly then save the collection. That way there was no reference to it.

How can I make my own event in C#?

to do it we have to know the three components

  1. the place responsible for firing the Event
  2. the place responsible for responding to the Event
  3. the Event itself

    a. Event

    b .EventArgs

    c. EventArgs enumeration

now lets create Event that fired when a function is called

but I my order of solving this problem like this: I'm using the class before I create it

  1. the place responsible for responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };
    

NetLog is a static class I will Explain it later

the next step is

  1. the place responsible for firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
    

the third step

  1. the Event itself

I warped The Event within a class called NetLog

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

this class now contain the Event, EventArgs and EventArgs Enums and the function responsible for firing the event

sorry for this long answer

nodejs mysql Error: Connection lost The server closed the connection

I do not recall my original use case for this mechanism. Nowadays, I cannot think of any valid use case.

Your client should be able to detect when the connection is lost and allow you to re-create the connection. If it important that part of program logic is executed using the same connection, then use transactions.

tl;dr; Do not use this method.


A pragmatic solution is to force MySQL to keep the connection alive:

setInterval(function () {
    db.query('SELECT 1');
}, 5000);

I prefer this solution to connection pool and handling disconnect because it does not require to structure your code in a way thats aware of connection presence. Making a query every 5 seconds ensures that the connection will remain alive and PROTOCOL_CONNECTION_LOST does not occur.

Furthermore, this method ensures that you are keeping the same connection alive, as opposed to re-connecting. This is important. Consider what would happen if your script relied on LAST_INSERT_ID() and mysql connection have been reset without you being aware about it?

However, this only ensures that connection time out (wait_timeout and interactive_timeout) does not occur. It will fail, as expected, in all others scenarios. Therefore, make sure to handle other errors.

Split text with '\r\n'

I took a more compact approach to split an input resulting from a text area into a list of string . You can use this if suits your purpose.

the problem is you cannot split by \r\n so i removed the \n beforehand and split only by \r

var serials = model.List.Replace("\n","").Split('\r').ToList<string>();

I like this approach because you can do it in just one line.

How to get the selected value from drop down list in jsp?

Direct value should work just fine:

var sel = document.getElementsByName('item');
var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

#if DEBUG vs. Conditional("DEBUG")

This one can be useful as well:

if (Debugger.IsAttached)
{
...
}

How to connect TFS in Visual Studio code

It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".

Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

Call PHP function from jQuery?

AJAX does the magic:

$(document).ready(function(

    $.ajax({ url: 'script.php?argument=value&foo=bar' });

));

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

Some solutions didn't work for me but the best option I found was the example below when i decided to use the flex option.

_x000D_
_x000D_
html, body{
    height: 100%;   
}

body{
    display: flex;
    flex-direction: column;
}

.main-contents{ 
    flex: 1 0 auto;
    min-height: 100%;
    margin-bottom: -77px;
  background-color: #CCC;
}

.footer{
    height:  77px;
    min-height: 77px;
    width: 100%;
    bottom: 0;
    left: 0;
    background: #000000;
    flex-shrink: 0;
    flex-direction: row;
    position: relative;
    
    
}

.footer-text{
  color: #FFF;
}

@media screen and (max-width: 767px){
    #content{
        padding-bottom: 0;
    }
    .footer{
        position: relative;
        /*position: absolute;*/
        height: 77px;
        width: 100%;
        bottom: 0;
        left: 0;
    }

}
_x000D_
<html>
  <body>
    <div class="main-contents" >
      this is the main content
    </div>
  </body>

  <footer class="footer">
    <p class="footer-text">This is the sticky footer</p>
  </footer>

</html>
_x000D_
_x000D_
_x000D_

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

You can use concat:

In [11]: pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])
Out[11]: 
                 df1       df2
2014-01-01       NaN -0.978535
2014-01-02 -0.106510 -0.519239
2014-01-03 -0.846100 -0.313153
2014-01-04 -0.014253 -1.040702
2014-01-05  0.315156 -0.329967
2014-01-06 -0.510577 -0.940901
2014-01-07       NaN -0.024608
2014-01-08       NaN -1.791899

[8 rows x 2 columns]

The axis argument determines the way the DataFrames are stacked:

df1 = pd.DataFrame([1, 2, 3])
df2 = pd.DataFrame(['a', 'b', 'c'])

pd.concat([df1, df2], axis=0)
   0
0  1
1  2
2  3
0  a
1  b
2  c

pd.concat([df1, df2], axis=1)

   0  0
0  1  a
1  2  b
2  3  c

How to hide navigation bar permanently in android activity?

It's my solution:

First, define boolean that indicate if navigation bar is visible or not.

boolean navigationBarVisibility = true //because it's visible when activity is created

Second create method that hide navigation bar.

private void setNavigationBarVisibility(boolean visibility){
    if(visibility){
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
        navigationBarVisibility = false;
    }

    else
        navigationBarVisibility = true;
}

By default, if you click to activity after hide navigation bar, navigation bar will be visible. So we got it's state if it visible we will hide it.

Now set OnClickListener to your view. I use a surfaceview so for me:

    playerSurface.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setNavigationBarVisibility(navigationBarVisibility);
        }
    });

Also, we must call this method when activity is launched. Because we want hide it at the beginning.

        setNavigationBarVisibility(navigationBarVisibility);

How to create an array from a CSV file using PHP and the fgetcsv function

Please fin below a link to the function from @knagode, enhanced with a skip rows parameter. https://gist.github.com/gabrieljenik/47fc38ae47d99868d5b3#file-csv_to_array

<?php
    /**
     * Convert a CSV string into an array.
     * 
     * @param $string
     * @param $separatorChar
     * @param $enclosureChar
     * @param $newlineChar
     * @param $skip_rows
     * @return array
     */
    public static function csvstring_to_array($string, $skip_rows = 0, $separatorChar = ';', $enclosureChar = '"', $newlineChar = "\n") {
        // @author: Klemen Nagode 
        // @source: http://stackoverflow.com/questions/1269562/how-to-create-an-array-from-a-csv-file-using-php-and-the-fgetcsv-function
        $array = array();
        $size = strlen($string);
        $columnIndex = 0;
        $rowIndex = 0;
        $fieldValue="";
        $isEnclosured = false;
        for($i=0; $i<$size;$i++) {

            $char = $string{$i};
            $addChar = "";

            if($isEnclosured) {
                if($char==$enclosureChar) {

                    if($i+1<$size && $string{$i+1}==$enclosureChar){
                        // escaped char
                        $addChar=$char;
                        $i++; // dont check next char
                    }else{
                        $isEnclosured = false;
                    }
                }else {
                    $addChar=$char;
                }
            }else {
                if($char==$enclosureChar) {
                    $isEnclosured = true;
                }else {

                    if($char==$separatorChar) {

                        $array[$rowIndex][$columnIndex] = $fieldValue;
                        $fieldValue="";

                        $columnIndex++;
                    }elseif($char==$newlineChar) {
                        echo $char;
                        $array[$rowIndex][$columnIndex] = $fieldValue;
                        $fieldValue="";
                        $columnIndex=0;
                        $rowIndex++;
                    }else {
                        $addChar=$char;
                    }
                }
            }
            if($addChar!=""){
                $fieldValue.=$addChar;

            }
        }

        if($fieldValue) { // save last field
            $array[$rowIndex][$columnIndex] = $fieldValue;
        }


        /**
         * Skip rows. 
         * Returning empty array if being told to skip all rows in the array.
         */ 
        if ($skip_rows > 0) {
            if (count($array) == $skip_rows)
                $array = array();
            elseif (count($array) > $skip_rows)
                $array = array_slice($array, $skip_rows);           

        }

        return $array;
    }

Escape double quotes for JSON in Python

Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:

>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

Downcasting in Java

Downcasting is allowed when there is a possibility that it succeeds at run time:

Object o = getSomeObject(),
String s = (String) o; // this is allowed because o could reference a String

In some cases this will not succeed:

Object o = new Object();
String s = (String) o; // this will fail at runtime, because o doesn't reference a String

When a cast (such as this last one) fails at runtime a ClassCastException will be thrown.

In other cases it will work:

Object o = "a String";
String s = (String) o; // this will work, since o references a String

Note that some casts will be disallowed at compile time, because they will never succeed at all:

Integer i = getSomeInteger();
String s = (String) i; // the compiler will not allow this, since i can never reference a String.

Drop view if exists

DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS 
SELECT * from {TableName}  
Go

Is it possible to serialize and deserialize a class in C++?

Boost is a good suggestion. But if you would like to roll your own, it's not so hard.

Basically you just need a way to build up a graph of objects and then output them to some structured storage format (JSON, XML, YAML, whatever). Building up the graph is as simple as utilizing a marking recursive decent object algorithm and then outputting all the marked objects.

I wrote an article describing a rudimentary (but still powerful) serialization system. You may find it interesting: Using SQLite as an On-disk File Format, Part 2.

What exactly is nullptr?

Let me first give you an implementation of unsophisticated nullptr_t

struct nullptr_t 
{
    void operator&() const = delete;  // Can't take address of nullptr

    template<class T>
    inline operator T*() const { return 0; }

    template<class C, class T>
    inline operator T C::*() const { return 0; }
};

nullptr_t nullptr;

nullptr is a subtle example of Return Type Resolver idiom to automatically deduce a null pointer of the correct type depending upon the type of the instance it is assigning to.

int *ptr = nullptr;                // OK
void (C::*method_ptr)() = nullptr; // OK
  • As you can above, when nullptr is being assigned to an integer pointer, a int type instantiation of the templatized conversion function is created. And same goes for method pointers too.
  • This way by leveraging template functionality, we are actually creating the appropriate type of null pointer every time we do, a new type assignment.
  • As nullptr is an integer literal with value zero, you can not able to use its address which we accomplished by deleting & operator.

Why do we need nullptr in the first place?

  • You see traditional NULL has some issue with it as below:

1?? Implicit conversion

char *str = NULL; // Implicit conversion from void * to char *
int i = NULL;     // OK, but `i` is not pointer type

2?? Function calling ambiguity

void func(int) {}
void func(int*){}
void func(bool){}

func(NULL);     // Which one to call?

  • Compilation produces the following error:
error: call to 'func' is ambiguous
    func(NULL);
    ^~~~
note: candidate function void func(bool){}
                              ^
note: candidate function void func(int*){}
                              ^
note: candidate function void func(int){}
                              ^
1 error generated.
compiler exit status 1

3?? Constructor overload

struct String
{
    String(uint32_t)    {   /* size of string */    }
    String(const char*) {       /* string */        }
};

String s1( NULL );
String s2( 5 );

  • In such cases, you need explicit cast (i.e., String s((char*)0)).

Check if application is installed - Android

isFakeGPSInstalled = Utils.isPackageInstalled(Utils.PACKAGE_ID_FAKE_GPS, this.getPackageManager());

//method to check package installed true/false

  public static boolean isPackageInstalled(String packageName, PackageManager packageManager) {
    boolean found = true;
    try {
      packageManager.getPackageInfo(packageName, 0);
    } catch (PackageManager.NameNotFoundException e) {
      found = false;
    }

    return found;
  }

Google Maps API v3 adding an InfoWindow to each marker

The add_marker still has a closure issue, cause it uses the marker variable outside the google.maps.event.addListener scope.

A better implementation would be:

function add_marker(racer_id, point, note) {
    var marker = new google.maps.Marker({map: map, position: point, clickable: true});
    marker.note = note;
    google.maps.event.addListener(marker, 'click', function() {
        info_window.content = this.note;
        info_window.open(this.getMap(), this);
    });
    return marker;
}

I also used the map from the marker, this way you don't need to pass the google map object, you probably want to use the map where the marker belongs to anyway.

show loading icon until the page is load?

HTML

<body>
    <div id="load"></div>
    <div id="contents">
          jlkjjlkjlkjlkjlklk
    </div>
</body>

JS

document.onreadystatechange = function () {
  var state = document.readyState
  if (state == 'interactive') {
       document.getElementById('contents').style.visibility="hidden";
  } else if (state == 'complete') {
      setTimeout(function(){
         document.getElementById('interactive');
         document.getElementById('load').style.visibility="hidden";
         document.getElementById('contents').style.visibility="visible";
      },1000);
  }
}

CSS

#load{
    width:100%;
    height:100%;
    position:fixed;
    z-index:9999;
    background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}

Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.

DEMO

http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)

update

http://jsfiddle.net/d9ngT/

'adb' is not recognized as an internal or external command, operable program or batch file

Set the path of adb into System Variables. You can find adb in "ADT Bundle/sdk/platform-tools" Set the path and restart the cmd n then try again.

Or

You can also goto the dir where adb.exe is located and do the same thing if you don't wanna set the PATH.

If you wanna see all the paths, just do

echo %PATH%

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

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

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

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

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

sudo apt install gddrescue

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

java.util.NoSuchElementException - Scanner reading user input

the reason of the exception has been explained already, however the suggested solution isn't really the best.

You should create a class that keeps a Scanner as private using Singleton Pattern, that makes that scanner unique on your code.

Then you can implement the methods you need or you can create a getScanner ( not recommended ) and you can control it with a private boolean, something like alreadyClosed.

If you are not aware how to use Singleton Pattern, here's a example:

public class Reader {
    
    
    private Scanner reader;
    private static Reader singleton = null;
    private boolean alreadyClosed;
    
    private Reader() {
        alreadyClosed = false;
        reader = new Scanner(System.in);
    }
    
    public static Reader getInstance() {
        if(singleton == null) {
            singleton = new Reader();
        }
        return singleton;
    }
    
    public int nextInt() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextInt();
        }
        throw new AlreadyClosedException(); //Custom exception
    }
    
    public double nextDouble() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextDouble();
        }
        throw new AlreadyClosedException();
    }
    
    public String nextLine() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextLine();
        }
        throw new AlreadyClosedException();
    }
    
    public void close() {
        alreadyClosed = true;
        reader.close();
    }   
}

how to add value to a tuple?

As other people have answered, tuples in python are immutable and the only way to 'modify' one is to create a new one with the appended elements included.

But the best solution is a list. When whatever function or method that requires a tuple needs to be called, create a tuple by using tuple(list).

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

Is it bad to have my virtualenv directory inside my git repository?

I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu.

It becomes an utter nightmare to manage the repository.

Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It's cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated...

'Class' does not contain a definition for 'Method'

I just ran into this problem; the issue seems different from the other answers posted here, so I'll mention it in case it helps someone.

In my case, I have an internal base class defined in one assembly ("A"), an internal derived class defined in a second assembly ("B"), and a test assembly ("TEST"). I exposed internals defined in assembly "B" to "TEST" using InternalsVisibleToAttribute, but neglected to do so for assembly "A". This produced the error mentioned at top with no further indication of the problem; using InternalsVisibleToAttribute to expose assembly "A" to "TEST" resolved the issue.

How to fix broken paste clipboard in VNC on Windows

You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.

Create XML in Javascript

this work for me..

var xml  = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?><root></root>', "application/xml");

developer.mozilla.org/en-US/docs/Web/API/DOMParser

JavaScript closures vs. anonymous functions

Let's look at both ways:

(function(){
    var i2 = i;
    setTimeout(function(){
        console.log(i2);
    }, 1000)
})();

Declares and immediately executes an anonymous function that runs setTimeout() within its own context. The current value of i is preserved by making a copy into i2 first; it works because of the immediate execution.

setTimeout((function(i2){
    return function() {
        console.log(i2);
    }
})(i), 1000);

Declares an execution context for the inner function whereby the current value of i is preserved into i2; this approach also uses immediate execution to preserve the value.

Important

It should be mentioned that the run semantics are NOT the same between both approaches; your inner function gets passed to setTimeout() whereas his inner function calls setTimeout() itself.

Wrapping both codes inside another setTimeout() doesn't prove that only the second approach uses closures, there's just not the same thing to begin with.

Conclusion

Both methods use closures, so it comes down to personal taste; the second approach is easier to "move" around or generalize.

How does JavaScript .prototype work?

Javascript doesn't have inheritance in the usual sense, but it has the prototype chain.

prototype chain

If a member of an object can't be found in the object it looks for it in the prototype chain. The chain consists of other objects. The prototype of a given instance can be accessed with the __proto__ variable. Every object has one, as there is no difference between classes and instances in javascript.

The advantage of adding a function / variable to the prototype is that it has to be in the memory only once, not for every instance.

It's also useful for inheritance, because the prototype chain can consist of many other objects.

Extract value of attribute node via XPath

//Parent/Children[@  Attribute='value']/@Attribute

This is the case which can be used where element is having 2 attribute and we can get the one attribute with the help of another one.

How to preview an image before and after upload?

On input type=file add an event onchange="preview()"

For the function preview() type:

thumb.src=URL.createObjectURL(event.target.files[0]);

Live example:

_x000D_
_x000D_
function preview() {
   thumb.src=URL.createObjectURL(event.target.files[0]);
}
_x000D_
<form>
    <input type="file" onchange="preview()">
    <img id="thumb" src="" width="150px"/>
</form>
_x000D_
_x000D_
_x000D_

Creating PHP class instance with a string

Lets say ClassOne is defined as:

public class ClassOne
{
    protected $arg1;
    protected $arg2;

    //Contructor
    public function __construct($arg1, $arg2)
    {
        $this->arg1 = $arg1;
        $this->arg2 = $arg2;
    }

    public function echoArgOne
    {
        echo $this->arg1;
    }

}

Using PHP Reflection;

$str = "One";
$className = "Class".$str;
$class = new \ReflectionClass($className);

Create a new Instance:

$instance = $class->newInstanceArgs(["Banana", "Apple")]);

Call a method:

$instance->echoArgOne();
//prints "Banana"

Use a variable as a method:

$method = "echoArgOne";
$instance->$method();

//prints "Banana"

Using Reflection instead of just using the raw string to create an object gives you better control over your object and easier testability (PHPUnit relies heavily on Reflection)

nginx: send all requests to a single html page

I think this will do it for you:

location / {
    try_files /base.html =404;
}

Sorting a Data Table

private void SortDataTable(DataTable dt, string sort)
{
DataTable newDT = dt.Clone();
int rowCount = dt.Rows.Count;

DataRow[] foundRows = dt.Select(null, sort);
// Sort with Column name
for (int i = 0; i < rowCount; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = foundRows[i][j];
}
DataRow data_row = newDT.NewRow();
data_row.ItemArray = arr;
newDT.Rows.Add(data_row);
}

//clear the incoming dt
dt.Rows.Clear();

for (int i = 0; i < newDT.Rows.Count; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = newDT.Rows[i][j];
}

DataRow data_row = dt.NewRow();
data_row.ItemArray = arr;
dt.Rows.Add(data_row);
}
}

Questions every good .NET developer should be able to answer?

I'd not ask those "know something from the textbook" questions, but rather ask some tinkering stuff like:

  • What does the foreach loop do in plain C#? (Expecting him to write a iterator loop.)
  • What's a singleton?
  • Let him/her parse a String to Datetime (expecting him/her to use TryParse instead of try/catch)
  • Implement the singleton, strategy and command patterns
  • Let him/her Refactor a piece of code for testing. Expecting him/her to abstract the external services away from the Unit under Test and implement his own Test-double of the service (providing no mocking framework)

These are not 100% sure, depending on the person I may ask them:

  • let him/her guard a method from null input (expecting him/her to use multiple returns to reduce nesting)
  • how does a object initializer work (Expecting him/her to write the thread-safe assignment)

Also I'd ask him how he/she learned his/her stuff and what he/she is reading (what blogs, books).

Upload file to SFTP using PowerShell

There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.

Here is an example using Posh-SSH:

# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)

# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'

# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'

# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH

# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential

# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath

#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath

Some additional notes:

  • You'll have to download the Posh-SSH module which you can install to your user module directory (e.g. C:\Users\jon_dechiro\Documents\WindowsPowerShell\Modules) and just load using the name or put it anywhere and load it like I have in the code above.
  • If having the credentials in the script is not acceptable you'll have to use a credential file. If you need help with that I can update with some details or point you to some links.
  • Change the paths, IPs, etc. as needed.

That should give you a decent starting point.

Is it a good practice to use try-except-else in Python?

Just because no-one else has posted this opinion, I would say

avoid else clauses in try/excepts because they're unfamiliar to most people

Unlike the keywords try, except, and finally, the meaning of the else clause isn't self-evident; it's less readable. Because it's not used very often, it'll cause people that read your code to want to double-check the docs to be sure they understand what's going on.

(I'm writing this answer precisely because I found a try/except/else in my codebase and it caused a wtf moment and forced me to do some googling).

So, wherever I see code like the OP example:

try:
    try_this(whatever)
except SomeException as the_exception:
    handle(the_exception)
else:
    # do some more processing in non-exception case
    return something

I would prefer to refactor to

try:
    try_this(whatever)
except SomeException as the_exception:
    handle(the_exception)
    return  # <1>
# do some more processing in non-exception case  <2>
return something
  • <1> explicit return, clearly shows that, in the exception case, we are finished working

  • <2> as a nice minor side-effect, the code that used to be in the else block is dedented by one level.

Reading Data From Database and storing in Array List object

 while (rs.next()) {

            customer.setId(rs.getInt("id"));
            customer.setName(rs.getString("name"));

            customer.setAddress(rs.getString("address"));
            customer.setPhone(rs.getString("phone"));
            customer.setEmail(rs.getString("email"));
            customer.setBountPoints(rs.getInt("bonuspoint"));
            customer.setTotalsale(rs.getInt("totalsale"));

            customers.add(customer);
             customer = null;
        }

Try replacing your while loop code with above mentioned code. Here what we have done is after doing customers.add(customer) we are doing customer = null;`

PHP CURL & HTTPS

I was trying to use CURL to do some https API calls with php and ran into this problem. I noticed a recommendation on the php site which got me up and running: http://php.net/manual/en/function.curl-setopt.php#110457

Please everyone, stop setting CURLOPT_SSL_VERIFYPEER to false or 0. If your PHP installation doesn't have an up-to-date CA root certificate bundle, download the one at the curl website and save it on your server:

http://curl.haxx.se/docs/caextract.html

Then set a path to it in your php.ini file, e.g. on Windows:

curl.cainfo=c:\php\cacert.pem

Turning off CURLOPT_SSL_VERIFYPEER allows man in the middle (MITM) attacks, which you don't want!

What is __pycache__?

A __pycache__ folder is created when you use the line:

import file_name

or try to get information from another file you have created. This makes it a little faster when running your program the second time to open the other file.

UIImage: Resize, then Crop

- (UIImage*)imageScale:(CGFloat)scaleFactor cropForSize:(CGSize)targetSize
{
    targetSize = !targetSize.width?self.size:targetSize;
    UIGraphicsBeginImageContext(targetSize); // this will crop

    CGRect thumbnailRect = CGRectZero;

    thumbnailRect.size.width  = targetSize.width*scaleFactor;
    thumbnailRect.size.height = targetSize.height*scaleFactor;
    CGFloat xOffset = (targetSize.width- thumbnailRect.size.width)/2;
    CGFloat yOffset = (targetSize.height- thumbnailRect.size.height)/2;
    thumbnailRect.origin = CGPointMake(xOffset,yOffset);

    [self drawInRect:thumbnailRect];

    UIImage *newImage  = UIGraphicsGetImageFromCurrentImageContext();

    if(newImage == nil)
    {
        NSLog(@"could not scale image");
    }

    UIGraphicsEndImageContext();

    return newImage;
}

Below the example of work: Left image - (origin image) ; Right image with scale x2

enter image description here

If you want to scale image but retain its frame(proportions), call method this way:

[yourImage imageScale:2.0f cropForSize:CGSizeZero];

How to append new data onto a new line

You need to change parameter "a" => "a+". Follow this code bellows:

def storescores():
hs = open("hst.txt","a+")

How to obtain Telegram chat_id for a specific user?

Straight out from the documentation:

Suppose the website example.com would like to send notifications to its users via a Telegram bot. Here's what they could do to enable notifications for a user with the ID 123.

  1. Create a bot with a suitable username, e.g. @ExampleComBot
  2. Set up a webhook for incoming messages
  3. Generate a random string of a sufficient length, e.g. $memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
  4. Put the value 123 with the key $memcache_key into Memcache for 3600 seconds (one hour)
  5. Show our user the button https://telegram.me/ExampleComBot?start=vCH1vGWJxfSeofSAs0K5PA
  6. Configure the webhook processor to query Memcached with the parameter that is passed in incoming messages beginning with /start. If the key exists, record the chat_id passed to the webhook as telegram_chat_id for the user 123. Remove the key from Memcache.
  7. Now when we want to send a notification to the user 123, check if they have the field telegram_chat_id. If yes, use the sendMessage method in the Bot API to send them a message in Telegram.

Receiving login prompt using integrated windows authentication

If your URL has dots in the domain name, IE will treat it like it's an internet address and not local. You have at least two options:

  1. Get an alias to use in the URL to replace server.domain. For example, myapp.
  2. Follow the steps below on your computer.

Go to the site and cancel the login dialog. Let this happen:

enter image description here

In IE’s settings:

enter image description here

enter image description here

enter image description here

"id cannot be resolved or is not a field" error?

Just Clean your project so R will be generated automatically. This worked for me.

Changing element style attribute dynamically using JavaScript

In addition to other answers, if you want to use the dash notition for style properties, you can also use:

document.getElementById("xyz").style["padding-top"] = "10px";

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

I Have faced the same issue.After a lot of struggle I found that the real issue is with the com.amazonaws dependencies.After adding dependencies this error got disappeared.

Getting Unexpected Token Export

My two cents

Export

ES6

myClass.js

export class MyClass1 {
}
export class MyClass2 {
}

other.js

import { MyClass1, MyClass2 } from './myClass';

CommonJS Alternative

myClass.js

class MyClass1 {
}
class MyClass2 {
}
module.exports = { MyClass1, MyClass2 }
// or
// exports = { MyClass1, MyClass2 };

other.js

const { MyClass1, MyClass2 } = require('./myClass');

Export Default

ES6

myClass.js

export default class MyClass {
}

other.js

import MyClass from './myClass';

CommonJS Alternative

myClass.js

module.exports = class MyClass1 {
}

other.js

const MyClass = require('./myClass');

Hope this helps

Check if string contains \n Java

The second one:

word.contains("\n");

How to add background image for input type="button"?

background-image takes an url as a value. Use either

background-image: url ('/image/btn.png');

or

background: url ('/image/btn.png') no-repeat;

which is a shorthand for

background-image: url ('/image/btn.png');
background-repeat: no-repeat;

Also, you might want to look at the button HTML element for fancy submit buttons.

Java using enum with switch statement

enumerations accessing is very simple in switch case

private TYPE currentView;

//declaration of enum 
public enum TYPE {
        FIRST, SECOND, THIRD
    };

//handling in switch case
switch (getCurrentView())
        {
        case FIRST:
            break;
        case SECOND:
            break;
        case THIRD:
            break;
        }

//getter and setter of the enum
public void setCurrentView(TYPE currentView) {
        this.currentView = currentView;
    }

    public TYPE getCurrentView() {
        return currentView;
    }

//usage of setting the enum 
setCurrentView(TYPE.FIRST);

avoid the accessing of TYPE.FIRST.ordinal() it is not recommended always

Java, How do I get current index/key in "for each" loop

Not possible in Java.


Here's the Scala way:

val m = List(5, 4, 2, 89)

for((el, i) <- m.zipWithIndex)
  println(el +" "+ i)

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

WE had this issue. everything was setup fine in terms of permissions and security.

after MUCH needling around in the haystack. the issue was some sort of heuristics. in the email body , anytime a certain email address was listed, we would get the above error message from our exchange server.

it took 2 days of crazy testing and hair pulling to find this.

so if you have checked everything out, try changing the email body to only the word 'test'. If after that, your email goes out fine, you are having some sort of spam/heuristic filter issue like we were

Elegant way to read file into byte[] array in Java

A long time ago:

Call any of these

byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 

From

http://commons.apache.org/io/

If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library

Today (Java 7+ or Android API Level 26+)

Luckily, we now have a couple of convenience methods in the nio packages. For instance:

byte[] java.nio.file.Files.readAllBytes(Path path)

Javadoc here

Calling Java from Python

I'm assuming that if you can get from C++ to Java then you are all set. I've seen a product of the kind you mention work well. As it happens the one we used was CodeMesh. I'm not specifically endorsing this vendor, or making any statement about their product's relative quality, but I have seen it work in quite a high volume scenario.

I would say generally that if at all possible I would recommend keeping away from direct integration via JNI if you can. Some simple REST service approach, or queue-based architecture will tend to be simpler to develop and diagnose. You can get quite decent perfomance if you use such decoupled technologies carefully.

LINQ Join with Multiple Conditions in On Clause

You just need to name the anonymous property the same on both sides

on new { t1.ProjectID, SecondProperty = true } equals 
   new { t2.ProjectID, SecondProperty = t2.Completed } into j1

Based on the comments of @svick, here is another implementation that might make more sense:

from t1 in Projects
from t2 in Tasks.Where(x => t1.ProjectID == x.ProjectID && x.Completed == true)
                .DefaultIfEmpty()
select new { t1.ProjectName, t2.TaskName }

Converting an integer to binary in C

You need to initialise bin, e.g.

bin = malloc(1);
bin[0] = '\0';

or use calloc:

bin = calloc(1, 1);

You also have a bug here:

 bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));

this needs to be:

 bin = (char *)realloc(bin, sizeof(char) * (strlen(bin)+1));

(i.e. use strlen, not sizeof).

And you should increase the size before calling strcat.

And you're not freeing bin, so you have a memory leak.

And you need to convert 0, 1 to '0', '1'.

And you can't strcat a char to a string.

So apart from that, it's close, but the code should probably be more like this (warning, untested !):

int int_to_bin(int k)
{
   char *bin;
   int tmp;

   bin = calloc(1, 1);
   while (k > 0)
   {
      bin = realloc(bin, strlen(bin) + 2);
      bin[strlen(bin) - 1] = (k % 2) + '0';
      bin[strlen(bin)] = '\0';
      k = k / 2;
   }
   tmp = atoi(bin);
   free(bin);
   return tmp;
}

What exactly does Perl's "bless" do?

Short version: it's marking that hash as attached to the current package namespace (so that that package provides its class implementation).

top -c command in linux to filter processes listed based on processname

@perreal's command works great! If you forget, try in two steps...

example: filter top to display only application called yakuake:

$ pgrep yakuake
1755

$ top -p 1755

useful top interactive commands 'c' : toggle full path vs. command name 'k' : kill by PID 'F' : filter by... select with arrows... then press 's' to set the sort

the answer below is good too... I was looking for that today but couldn't find it. Thanks

Change UITextField and UITextView Cursor / Caret Color

This worked for me in swift:

UITextField.tintColor = UIColor.blackColor()

You can also set this in storyboard: https://stackoverflow.com/a/18759577/3075340

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

Try this

Installing with Anaconda

conda create --name tensorflow python=3.5
activate tensorflow
conda install jupyter
conda install scipy
pip install tensorflow
or
pip install tensorflow-gpu

It is important to add python=3.5 at the end of the first line, because it will install Python 3.5.

Deleting Row in SQLite in Android

Try this one:

public void deleteEntry(long rowId) {
    database.delete(DATABASE_TABLE , KEY_ROWID 
        + " = " + rowId, null);}

using if else with eval in aspx page

If you absolutely do not want to use code-behind, you can try conditional operator for this:

<%# ((int)Eval("Percentage") < 50) ? "0 %" : Eval("Percentage") %>

That is assuming field Percentage contains integer.

Update: Version for VB.NET, just in case, provided by tomasofen:

<%# If(Eval("Status") < 50, "0 %", Eval("Percentage")) %>

WPF Add a Border to a TextBlock

No, you need to wrap your TextBlock in a Border. Example:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />
</Border>

Of course, you can set these properties (BorderThickness, BorderBrush) through styles as well:

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />
</Border>

How to pass a datetime parameter?

It used to be a painful task, but now we can use toUTCString():

Example:

[HttpPost]
public ActionResult Query(DateTime Start, DateTime End)

Put the below into Ajax post request

data: {
    Start: new Date().toUTCString(),
    End: new Date().toUTCString()
},

What are major differences between C# and Java?

Comparing Java 7 and C# 3

(Some features of Java 7 aren't mentioned here, but the using statement advantage of all versions of C# over Java 1-6 has been removed.)

Not all of your summary is correct:

  • In Java methods are virtual by default but you can make them final. (In C# they're sealed by default, but you can make them virtual.)
  • There are plenty of IDEs for Java, both free (e.g. Eclipse, Netbeans) and commercial (e.g. IntelliJ IDEA)

Beyond that (and what's in your summary already):

  • Generics are completely different between the two; Java generics are just a compile-time "trick" (but a useful one at that). In C# and .NET generics are maintained at execution time too, and work for value types as well as reference types, keeping the appropriate efficiency (e.g. a List<byte> as a byte[] backing it, rather than an array of boxed bytes.)
  • C# doesn't have checked exceptions
  • Java doesn't allow the creation of user-defined value types
  • Java doesn't have operator and conversion overloading
  • Java doesn't have iterator blocks for simple implemetation of iterators
  • Java doesn't have anything like LINQ
  • Partly due to not having delegates, Java doesn't have anything quite like anonymous methods and lambda expressions. Anonymous inner classes usually fill these roles, but clunkily.
  • Java doesn't have expression trees
  • C# doesn't have anonymous inner classes
  • C# doesn't have Java's inner classes at all, in fact - all nested classes in C# are like Java's static nested classes
  • Java doesn't have static classes (which don't have any instance constructors, and can't be used for variables, parameters etc)
  • Java doesn't have any equivalent to the C# 3.0 anonymous types
  • Java doesn't have implicitly typed local variables
  • Java doesn't have extension methods
  • Java doesn't have object and collection initializer expressions
  • The access modifiers are somewhat different - in Java there's (currently) no direct equivalent of an assembly, so no idea of "internal" visibility; in C# there's no equivalent to the "default" visibility in Java which takes account of namespace (and inheritance)
  • The order of initialization in Java and C# is subtly different (C# executes variable initializers before the chained call to the base type's constructor)
  • Java doesn't have properties as part of the language; they're a convention of get/set/is methods
  • Java doesn't have the equivalent of "unsafe" code
  • Interop is easier in C# (and .NET in general) than Java's JNI
  • Java and C# have somewhat different ideas of enums. Java's are much more object-oriented.
  • Java has no preprocessor directives (#define, #if etc in C#).
  • Java has no equivalent of C#'s ref and out for passing parameters by reference
  • Java has no equivalent of partial types
  • C# interfaces cannot declare fields
  • Java has no unsigned integer types
  • Java has no language support for a decimal type. (java.math.BigDecimal provides something like System.Decimal - with differences - but there's no language support)
  • Java has no equivalent of nullable value types
  • Boxing in Java uses predefined (but "normal") reference types with particular operations on them. Boxing in C# and .NET is a more transparent affair, with a reference type being created for boxing by the CLR for any value type.

This is not exhaustive, but it covers everything I can think of off-hand.

Is there a portable way to get the current username in Python?

These might work. I don't know how they behave when running as a service. They aren't portable, but that's what os.name and ifstatements are for.

win32api.GetUserName()

win32api.GetUserNameEx(...) 

See: http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html

How to horizontally align ul to center of div?

ul {
width: 90%; 
    list-style-type:none;
    margin:auto;
    padding:0;
    position:relative;
    left:5%;
}

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

You can do this:

class MyStudentDetails{
    public static void main (String args[]){
         Scanner s = new Scanner(System.in);
         System.out.println("Enter Your Name: ");
         String name = s.nextLine();
         System.out.println("Enter Your Age: ");
         String age = s.nextLine();
         System.out.println("Enter Your E-mail: ");
         String email = s.nextLine();
         System.out.println("Enter Your Address: ");
         String address = s.nextLine();


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

    }
}

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

Disable eslint rules for folder

To ignore some folder from eslint rules we could create the file .eslintignore in root directory and add there the path to the folder we want omit (the same way as for .gitignore).

Here is the example from the ESLint docs on Ignoring Files and Directories:

# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default

# Ignore built files except build/index.js
build/*
!build/index.js

Which comment style should I use in batch files?

After I realized that I could use label :: to make comments and comment out code REM just looked plain ugly to me. As has been mentioned the double-colon can cause problems when used inside () blocked code, but I've discovered a work-around by alternating between the labels :: and :space

:: This, of course, does
:: not cause errors.

(
  :: But
   : neither
  :: does
   : this.
)

It's not ugly like REM, and actually adds a little style to your code.

So outside of code blocks I use :: and inside them I alternate between :: and :.

By the way, for large hunks of comments, like in the header of your batch file, you can avoid special commands and characters completely by simply gotoing over your comments. This let's you use any method or style of markup you want, despite that fact that if CMD ever actually tried to processes those lines it'd throw a hissy.

@echo off
goto :TopOfCode

=======================================================================
COOLCODE.BAT

Useage:
  COOLCODE [/?] | [ [/a][/c:[##][a][b][c]] INPUTFILE OUTPUTFILE ]

Switches:
       /?    - This menu
       /a    - Some option
       /c:## - Where ## is which line number to begin the processing at.
         :a  - Some optional method of processing
         :b  - A third option for processing
         :c  - A forth option
  INPUTFILE  - The file to process.
  OUTPUTFILE - Store results here.

 Notes:
   Bla bla bla.

:TopOfCode
CODE
.
.
.

Use what ever notation you wish *'s, @'s etc.

print spaces with String.format()

You need to specify the minimum width of the field.

String.format("%" + numberOfSpaces + "s", ""); 

Why do you want to generate a String of spaces of a certain length.

If you want a column of this length with values then you can do:

String.format("%" + numberOfSpaces + "s", "Hello"); 

which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.

selenium - chromedriver executable needs to be in PATH

You can download ChromeDriver here: https://sites.google.com/a/chromium.org/chromedriver/downloads

Then you have multiple options:

  • add it to your system path
  • put it in the same directory as your python script
  • specify the location directly via executable_path

    driver = webdriver.Chrome(executable_path='C:/path/to/chromedriver.exe')
    

How to extract table as text from the PDF using Python?

This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.

Here are the steps I found to work.

  1. Use pdfimages from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.

  2. Use Tesseract to detect rotation and ImageMagick mogrify to fix it.

  3. Use OpenCV to find and extract tables.

  4. Use OpenCV to find and extract each cell from the table.

  5. Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.

  6. Use Tesseract to OCR each cell.

  7. Combine the extracted text of each cell into the format you need.

I wrote a python package with modules that can help with those steps.

Repo: https://github.com/eihli/image-table-ocr

Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html

Some of the steps don't require code, they take advantage of external tools like pdfimages and tesseract. I'll provide some brief examples for a couple of the steps that do require code.

  1. Finding tables:

This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/

import cv2

def find_tables(image):
    BLUR_KERNEL_SIZE = (17, 17)
    STD_DEV_X_DIRECTION = 0
    STD_DEV_Y_DIRECTION = 0
    blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
    MAX_COLOR_VAL = 255
    BLOCK_SIZE = 15
    SUBTRACT_FROM_MEAN = -2

    img_bin = cv2.adaptiveThreshold(
        ~blurred,
        MAX_COLOR_VAL,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY,
        BLOCK_SIZE,
        SUBTRACT_FROM_MEAN,
    )
    vertical = horizontal = img_bin.copy()
    SCALE = 5
    image_width, image_height = horizontal.shape
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
    horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
    vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
    vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)

    horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
    vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))

    mask = horizontally_dilated + vertically_dilated
    contours, hierarchy = cv2.findContours(
        mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
    )

    MIN_TABLE_AREA = 1e5
    contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
    perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
    epsilons = [0.1 * p for p in perimeter_lengths]
    approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
    bounding_rects = [cv2.boundingRect(a) for a in approx_polys]

    # The link where a lot of this code was borrowed from recommends an
    # additional step to check the number of "joints" inside this bounding rectangle.
    # A table should have a lot of intersections. We might have a rectangular image
    # here though which would only have 4 intersections, 1 at each corner.
    # Leaving that step as a future TODO if it is ever necessary.
    images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
    return images
  1. Extract cells from table.

This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.

We want to identify the cells from left-to-right, top-to-bottom.

We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.

def cell_in_same_row(c1, c2):
    c1_center = c1[1] + c1[3] - c1[3] / 2
    c2_bottom = c2[1] + c2[3]
    c2_top = c2[1]
    return c2_top < c1_center < c2_bottom

orig_cells = [c for c in cells]
rows = []
while cells:
    first = cells[0]
    rest = cells[1:]
    cells_in_same_row = sorted(
        [
            c for c in rest
            if cell_in_same_row(c, first)
        ],
        key=lambda c: c[0]
    )

    row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
    rows.append(row_cells)
    cells = [
        c for c in rest
        if not cell_in_same_row(c, first)
    ]

# Sort rows by average height of their center.
def avg_height_of_center(row):
    centers = [y + h - h / 2 for x, y, w, h in row]
    return sum(centers) / len(centers)

rows.sort(key=avg_height_of_center)

Markdown open a new window link

As suggested by this answer:

[link](url){:target="_blank"}

Works for jekyll or more specifically kramdown, which is a superset of markdown, as part of Jekyll's (default) configuration. But not for plain markdown. ^_^

Generate a random number in a certain range in MATLAB

if you are looking to generate all the number within a specific rang randomly then you can try

r = randi([a b],1,d)

a = start point

b = end point

d = how many number you want to generate but keep in mind that d should be less than or equal to b-a

Why is textarea filled with mysterious white spaces?

The text area shows mysterious spaces because there is a real space exists in the tags. <textarea> <php? echo $var; ?> </textarea> after removing these extra spaces between the tags will solve the issue , as following. <textarea><php? echo $var; ?></textarea>

How to resolve TypeError: can only concatenate str (not "int") to str

Use f-strings to resolve the TypeError

# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'

# same intent with a f-string
i = 15

test = f'Here is a test that can be run {i} times'

print(test)

# output
'Here is a test that can be run 15 times'
i = 15
# t = 'test' + i  # will cause a TypeError

# should be
t = f'test{i}'

print(t)

# output
'test15'
  • The issue may be attempting to evaluate an expression where a variable is the string of a numeric.
  • Convert the string to an int.
  • This scenario is specific to this question
  • When iterating, it's important to be aware of the dtype
i = '15'
# t = 15 + i  # will cause a TypeError

# convert the string to int
t = 15 + int(i)
print(t)

# output
30

Note

  • The preceding part of the answer addresses the TypeError shown in the question title, which is why people seem to be coming to this question.
  • However, this doesn't resolve the issue in relation to the example provided by the OP, which is addressed below.

Original Code Issues

  • TypeError is caused because message type is a str.
  • The code iterates each character and attempts to add char, a str type, to an int
  • That issue can be resolved by converting char to an int
  • As the code is presented, secret_string needs to be initialized with 0 instead of "".
  • The code also results in a ValueError: chr() arg not in range(0x110000) because 7429146 is out of range for chr().
  • Resolved by using a smaller number
  • The output is not a string, as was intended, which leads to the Updated Code in the question.
message = input("Enter a message you want to be revealed: ")

secret_string = 0

for char in message:
    char = int(char)
    value = char + 742146
    secret_string += ord(chr(value))
    
print(f'\nRevealed: {secret_string}')

# Output
Enter a message you want to be revealed:  999

Revealed: 2226465

Updated Code Issues

  • message is now an int type, so for char in message: causes TypeError: 'int' object is not iterable
  • message is converted to int to make sure the input is an int.
  • Set the type with str()
  • Only convert value to Unicode with chr
  • Don't use ord
while True:
    try:
        message = str(int(input("Enter a message you want to be decrypt: ")))
        break
    except ValueError:
        print("Error, it must be an integer")
        
secret_string = ""
for char in message:
    
    value = int(char) + 10000
    
    secret_string += chr(value)

print("Decrypted", secret_string)

# output
Enter a message you want to be decrypt:  999
Decrypted ???

Enter a message you want to be decrypt:  100
Decrypted ???

Parse strings to double with comma and point

Make two static cultures, one for comma and one for point.

    var commaCulture = new CultureInfo("en")
    {
        NumberFormat =
        {
            NumberDecimalSeparator = ","
        }
    };

    var pointCulture = new CultureInfo("en")
    {
        NumberFormat =
        {
            NumberDecimalSeparator = "."
        }
    };

Then use each one respectively, depending on the input (using a function):

    public double ConvertToDouble(string input)
    {
        input = input.Trim();

        if (input == "0") {
            return 0;
        }

        if (input.Contains(",") && input.Split(',').Length == 2)
        {
            return Convert.ToDouble(input, commaCulture);
        }

        if (input.Contains(".") && input.Split('.').Length == 2)
        {
            return Convert.ToDouble(input, pointCulture);
        }

        throw new Exception("Invalid input!");
    }

Then loop through your arrays

    var strings = new List<string> {"0,12", "0.122", "1,23", "00,0", "0.00", "12.5000", "0.002", "0,001"};
    var doubles = new List<double>();

    foreach (var value in strings) {
        doubles.Add(ConvertToDouble(value));
    }

This should work even though the host environment and culture changes.

httpd-xampp.conf: How to allow access to an external IP besides localhost?

Open for new app "HTTPD" (Apache server) in your Firewall

Take a look at this: https://www.youtube.com/watch?v=eqgUGF3NnuM

how to get the selected index of a drop down

<select name="CCards" id="ccards">
    <option value="0">Select Saved Payment Method:</option>
    <option value="1846">test  xxxx1234</option>
    <option value="1962">test2  xxxx3456</option>
</select>

<script type="text/javascript">

    /** Jquery **/
    var selectedValue = $('#ccards').val();

    //** Regular Javascript **/
    var selectedValue2 = document.getElementById('ccards').value;


</script>

mvn clean install vs. deploy vs. release

The clean, install and deploy phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.

mvn clean install

This command invokes the clean phase and then the install phase sequentially:

  • clean: removes files generated at build-time in a project's directory (target by default)
  • install: installs the package into the local repository, for use as a dependency in other projects locally.

mvn deploy

This command invokes the deploy phase:

  • deploy: copies the final package to the remote repository for sharing with other developers and projects.

mvn release

This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare and perform. As documented:

Preparing a release goes through the following release phases:

  • Check that there are no uncommitted changes in the sources
  • Check that there are no SNAPSHOT dependencies
  • Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
  • Transform the SCM information in the POM to include the final destination of the tag
  • Run the project tests against the modified POMs to confirm everything is in working order
  • Commit the modified POMs
  • Tag the code in the SCM with a version name (this will be prompted for)
  • Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
  • Commit the modified POMs

And then:

Performing a release runs the following release phases:

  • Checkout from an SCM URL with optional tag
  • Run the predefined Maven goals to release the project (by default, deploy site-deploy)

See also

How do I add an existing Solution to GitHub from Visual Studio 2013

There is a lot easier way to do this that doesn't even require you to do anything outside Visual Studio.

  • Open your project in Visual Studio
  • File> Add to source control
  • Open Team Explorer, click on Home button, proceed to "Sync" and there you'd find the "Publish to GitHub". Click on "Get Started"
  • Type title of your repository and description (optionally).
  • Click on "Publish"

That's all. Visual Studio github plugin automatically created repository for you and configured everything. Now just click on Home and choose "Changes" tab and finally commit your first commit.

How can I select rows with most recent timestamp for each key value?

You can only select columns that are in the group or used in an aggregate function. You can use a join to get this working

select s1.* 
from sensorTable s1
inner join 
(
  SELECT sensorID, max(timestamp) as mts
  FROM sensorTable 
  GROUP BY sensorID 
) s2 on s2.sensorID = s1.sensorID and s1.timestamp = s2.mts

Image Greyscale with CSS & re-color on mouse-over?

You can use a sprite which has both version—the colored and the monochrome—stored into it.

Git submodule head 'reference is not a tree' error

Your branch may not be up to date, a simple solution but try git fetch

How to dynamically add elements to String array?

when using String array, you have to give size of array while initializing

eg

String[] str = new String[10];

you can use index 0-9 to store values

str[0] = "value1"
str[1] = "value2"
str[2] = "value3"
str[3] = "value4"
str[4] = "value5"
str[5] = "value6"
str[6] = "value7"
str[7] = "value8"
str[8] = "value9"
str[9] = "value10"

if you are using ArrayList instread of string array, you can use it without initializing size of array ArrayList str = new ArrayList();

you can add value by using add method of Arraylist

str.add("Value1");

get retrieve a value from arraylist, you can use get method

String s = str.get(0);

find total number of items by size method

int nCount = str.size();

read more from here

Error: free(): invalid next size (fast):

We need the code, but that usually pops up when you try to free() memory from a pointer that is not allocated. This often happens when you're double-freeing.

How to remove an element from the flow?

Another option is to set height: 0; overflow: visible; to an element, though it won't be really outside the flow and therefore may break margin collapsing.

How to ORDER BY a SUM() in MySQL?

Don'y forget that if you are mixing grouped (ie. SUM) fields and non-grouped fields, you need to GROUP BY one of the non-grouped fields.

Try this:

SELECT SUM(something) AS fieldname
FROM tablename
ORDER BY fieldname

OR this:

SELECT Field1, SUM(something) AS Field2
FROM tablename
GROUP BY Field1
ORDER BY Field2

And you can always do a derived query like this:

SELECT
   f1, f2
FROM
    (
        SELECT SUM(x+y) as f1, foo as F2
        FROM tablename 
        GROUP BY f2
    ) as table1
ORDER BY 
    f1

Many possibilities!

Maximum packet size for a TCP connection

Generally, this will be dependent on the interface the connection is using. You can probably use an ioctl() to get the MTU, and if it is ethernet, you can usually get the maximum packet size by subtracting the size of the hardware header from that, which is 14 for ethernet with no VLAN.

This is only the case if the MTU is at least that large across the network. TCP may use path MTU discovery to reduce your effective MTU.

The question is, why do you care?

Convert object to JSON in Android

As of Android 3.0 (API Level 11) Android has a more recent and improved JSON Parser.

http://developer.android.com/reference/android/util/JsonReader.html

Reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

If we get the latest from VSTS, all files will be in read only mode. While running project all class library classes get read only and brakepoints turn empty and say "Breakpoint will not currently be hit. No symbols loaded for this document".

Solution 1

Go to the project location and right lick the folder ---> Properties ---> General Tab ---> UNCHECK read-only (Only applies to files in the folder) ---> Apply ---> Ok

Solution 2

Start debugging, Go to Debug ---> Windows ---> Modules.Select one assembly and Right-click ---> (Select) Symbol Setting. Set Your Bin path in Cache symbol in this directory and select Microsoft Servers in Symbol of PDB location. Click Load All Symbols. It will take time.Then click OK.

Now the symbol status of all assembly has been changed from "can not find or open PDB" to "Symbols loaded".

Git push error '[remote rejected] master -> master (branch is currently checked out)'

I had the same issue. For me, I use Git push to move code to my servers. I never change the code on the server side, so this is safe.

In the repository, you are pushing to type:

git config receive.denyCurrentBranch ignore

This will allow you to change the repository while it's a working copy.

After you run a Git push, go to the remote machine and type this:

git checkout -f

This will make the changes you pushed be reflected in the working copy of the remote machine.

Please note, this isn't always safe if you make changes on in the working copy that you're pushing to.

Extracting .jar file with command line

From the docs:

To extract the files from a jar file, use x, as in:

C:\Java> jar xf myFile.jar

To extract only certain files from a jar file, supply their filenames:

C:\Java> jar xf myFile.jar foo bar

The folder where jar is probably isn't C:\Java for you, on my Windows partition it's:

C:\Program Files (x86)\Java\jdk[some_version_here]\bin

Unless the location of jar is in your path environment variable, you'll have to specify the full path/run the program from inside the folder.

EDIT: Here's another article, specifically focussed on extracting JARs: http://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html

Angular2 - Input Field To Accept Only Numbers

You need to use type="number" instead text. You can also specify max and min numbers

<input type="number" name="quantity" min="1" max="5">

callback to handle completion of pipe

Here's a solution that handles errors in requests and calls a callback after the file is written:

request(opts)
    .on('error', function(err){ return callback(err)})
    .pipe(fs.createWriteStream(filename))
    .on('finish', function (err) {
        return callback(err);
    });

Disable scrolling in webview?

Set a listener on your WebView:

webView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return(event.getAction() == MotionEvent.ACTION_MOVE));
            }
        });

What is the correct JSON content type?

A part of your question is relevant to me as I just came across it.

A third-party provider is providing a REST service that is used by multiple clients. It's a straight-forward REST called with query parameters that returns a well-formed JSON. I have tested it with PHP and Java where it worked as expected.

My client uses Oracle Service Bus as a gateway between his application server and the Internet. When I made the OSB service, it crashed with an Invalid message format error. Turned out that the content-type being returned was text/html. OSB treats responses as per this header; converting between text, XML and JSON. In this case, the response was JSON but the header didn't say so. Contacting the provider, I got the reply: "We're not going to change it as it doesn't effect anyone else".

The Content-Type header specifies what the content should be, not what it actually is. That is to say, in your consuming program, it's up to you to check or ignore it and process the content in any manner. Another example, you can return GIF data but specify the content type as JSON, then go ahead and ignore the header and read the image data. This won't hurt your program, but may hurt others.

Moral of the story: Play nice.

How can I sort a dictionary by key?

For the way how question is formulated, the most answers here are answering it correctly.

However, considering how the things should be really done, taking to acount decades and decades of computer science, it comes to my total suprise that there is actually only one answer here (from GrantJ user) suggesting usage of sorted associative containers (sortedcontainers) which sorts elements based on key at their insertions point.

That will avoid massive performance impact per each calling of sort(...) (at minimum O(N*log(N)), where N is in number of elements (logically, this applies for all such solutions here which suggest to use the sort(...)). Take to account that for all such solutions, the sort(...) will need to be called every time when colletion needs to be accessed as sorted AFTER it was modified by adding/removing elements ...

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

I managed to hit this error when simply creating a table! There was obviously no contention problem on a table that didn't yet exist. The CREATE TABLE statement contained a CONSTRAINT fk_name FOREIGN KEY clause referencing a well-populated table. I had to:

  • Remove the FOREIGN KEY clause from the CREATE TABLE statement
  • Create an INDEX on the FK column
  • Create the FK

How do I fix the multiple-step OLE DB operation errors in SSIS?

You can use SELECT * FROM INFORMATION_SCHEMA.COLUMNS but I suspect you created the destination database from a script of the source database so it is very likely that they columns will be the same.

Some comparisons might bring something up though.

These sorts of errors sometimes come from trying to insert too much data into varchar columns too.

Android emulator doesn't take keyboard input - SDK tools rev 20

Confirmed. I had the same problem after upgrading to Tools version 20. I had to Edit the AVD to add an option as follows:

  1. From Eclipse, Go to AVD Mananger.
  2. Select the particular AVD and click on Edit
  3. Go to the Hardware section, click on New.
  4. Select the Property Name : Keyboard Support
  5. By default, it is added with a value of 'no'. Just click on the value column and change it to 'yes'.
  6. Click on Edit AVD again.

This will add a property hw.keyboard=yes in config.ini file for the AVD.

You also have to set hw.mainKeys = yes

NodeJS - Error installing with NPM

npm install --global --production windows-build-tools

Node.js global proxy setting

While not a Nodejs setting, I suggest you use proxychains which I find rather convenient. It is probably available in your package manager.

After setting the proxy in the config file (/etc/proxychains.conf for me), you can run proxychains npm start or proxychains4 npm start (i.e. proxychains [command_to_proxy_transparently]) and all your requests will be proxied automatically.

Config settings for me:

These are the minimal settings you will have to append

## Exclude all localhost connections (dbs and stuff)
localnet 0.0.0.0/0.0.0.0
## Set the proxy type, ip and port here
http    10.4.20.103 8080

(You can get the ip of the proxy by using nslookup [proxyurl])

c# - How to get sum of the values from List?

You can use LINQ for this

var list = new List<int>();
var sum = list.Sum();

and for a List of strings like Roy Dictus said you have to convert

list.Sum(str => Convert.ToInt32(str));

How to map with index in Ruby?

Here are two more options for 1.8.6 (or 1.9) without using enumerator:

# Fun with functional
arr = ('a'..'g').to_a
arr.zip( (2..(arr.length+2)).to_a )
#=> [["a", 2], ["b", 3], ["c", 4], ["d", 5], ["e", 6], ["f", 7], ["g", 8]]

# The simplest
n = 1
arr.map{ |c| [c, n+=1 ] }
#=> [["a", 2], ["b", 3], ["c", 4], ["d", 5], ["e", 6], ["f", 7], ["g", 8]]

Module 'tensorflow' has no attribute 'contrib'

This issue might be helpful for you, it explains how to achieve TPUStrategy, a popular functionality of tf.contrib in TF<2.0.

So, in TF 1.X you could do the following:

resolver = tf.contrib.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.contrib.distribute.initialize_tpu_system(resolver)
strategy = tf.contrib.distribute.TPUStrategy(resolver)

And in TF>2.0, where tf.contrib is deprecated, you achieve the same by:

tf.config.experimental_connect_to_host('grpc://' + os.environ['COLAB_TPU_ADDR'])
resolver = tf.distribute.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver) 

starting file download with JavaScript

I'd suggest window.open() to open a popup window. If it's a download, there will be no window and you will get your file. If there is a 404 or something, the user will see it in a new window (hence, their work will not be bothered, but they will still get an error message).

How to use paths in tsconfig.json?

Its kind of relative path Instead of the below code

import { Something } from "../../../../../lib/src/[browser/server/universal]/...";

We can avoid the "../../../../../" its looking odd and not readable too.

So Typescript config file have answer for the same. Just specify the baseUrl, config will take care of your relative path.

way to config: tsconfig.json file add the below properties.

"baseUrl": "src",
    "paths": {
      "@app/*": [ "app/*" ],
      "@env/*": [ "environments/*" ]
    }

So Finally it will look like below

import { Something } from "@app/src/[browser/server/universal]/...";

Its looks simple,awesome and more readable..

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

On groupby object, the agg function can take a list to apply several aggregation methods at once. This should give you the result you need:

df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean', 'count'])

How do I remove the height style from a DIV using jQuery?

just to add to the answers here, I was using the height as a function with two options either specify the height if it is less than the window height, or set it back to auto

var windowHeight = $(window).height();
$('div#someDiv').height(function(){
    if ($(this).height() < windowHeight)
        return windowHeight;
    return 'auto';
});

I needed to center the content vertically if it was smaller than the window height or else let it scroll naturally so this is what I came up with

C# equivalent to Java's charAt()?

string sample = "ratty";
Console.WriteLine(sample[0]);

And

Console.WriteLine(sample.Chars(0));
Reference: http://msdn.microsoft.com/en-us/library/system.string.chars%28v=VS.71%29.aspx

The above is same as using indexers in c#.

How to resolve the error on 'react-native start'

It is due to mismatched blacklist file configuration.

To resolve that,

  1. We have to move to the project folder.

  2. Open \node_modules\metro-config\src\defaults\blacklist.js

  3. Replace the following.

From

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

To

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

Javascript/Jquery Convert string to array

Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:

var traingIds = ${triningIdArray};

not

var traingIds = "${triningIdArray}";

Set field value with reflection

You can try this:

//Your class instance
Publication publication = new Publication();

//Get class with full path(with package name)
Class<?> c = Class.forName("com.example.publication.models.Publication");

//Get method
Method  method = c.getDeclaredMethod ("setTitle", String.class);

//set value
method.invoke (publication,  "Value to want to set here...");

Can I make a phone call from HTML on Android?

Generally on Android, if you simply display the phone number, and the user taps on it, it will pull it up in the dialer. So, you could simply do

For more information, call us at <b>416-555-1234</b>

When the user taps on the bold part, since it's formatted like a phone number, the dialer will pop up, and show 4165551234 in the phone number field. The user then just has to hit the call button.

You might be able to do

For more information, call us at <a href='tel:416-555-1234'>416-555-1234</a>

to cover both devices, but I'm not sure how well this would work. I'll give it a try shortly and let you know.

EDIT: I just gave this a try on my HTC Magic running a rooted Rogers 1.5 with SenseUI:

For more information, call us at <a href='tel:416-555-1234'>416-555-1234</a><br />
<br />
Call at <a href='tel:416-555-1234'>our number</a>
<br />
<br />
<a href='416-555-1234'>Blah</a>
<br />
<br />
For more info, call <b>416-555-1234</b>

The first one, surrounding with the link and printing the phone number, worked perfectly. Pulled up the dialer with the hyphens and all. The second, saying our number with the link, worked exactly the same. This means that using <a href='tel:xxx-xxx-xxxx'> should work across the board, but I wouldn't suggest taking my one test as conclusive.

Linking straight to the number did the expected: Tried to pull up the nonexistent file from the server.

The last one did as I mentioned above, and pulled up the dialer, but without the nice formatting hyphens.

Execute command on all files in a directory

The following bash code will pass $file to command where $file will represent every file in /dir

for file in /dir/*
do
  cmd [option] "$file" >> results.out
done

Example

el@defiant ~/foo $ touch foo.txt bar.txt baz.txt
el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done
hello bar.txt
hello baz.txt
hello foo.txt

Disable output buffering

(I've posted a comment, but it got lost somehow. So, again:)

  1. As I noticed, CPython (at least on Linux) behaves differently depending on where the output goes. If it goes to a tty, then the output is flushed after each '\n'
    If it goes to a pipe/process, then it is buffered and you can use the flush() based solutions or the -u option recommended above.

  2. Slightly related to output buffering:
    If you iterate over the lines in the input with

    for line in sys.stdin:
    ...

then the for implementation in CPython will collect the input for a while and then execute the loop body for a bunch of input lines. If your script is about to write output for each input line, this might look like output buffering but it's actually batching, and therefore, none of the flush(), etc. techniques will help that. Interestingly, you don't have this behaviour in pypy. To avoid this, you can use

while True: line=sys.stdin.readline()
...

Copy / Put text on the clipboard with FireFox, Safari and Chrome

There is now a way to easily do this in most modern browsers using

document.execCommand('copy');

This will copy currently selected text. You can select a textArea or input field using

document.getElementById('myText').select();

To invisibly copy text you can quickly generate a textArea, modify the text in the box, select it, copy it, and then delete the textArea. In most cases this textArea wont even flash onto the screen.

For security reasons, browsers will only allow you copy if a user takes some kind of action (ie. clicking a button). One way to do this would be to add an onClick event to a html button that calls a method which copies the text.

A full example:

_x000D_
_x000D_
function copier(){_x000D_
  document.getElementById('myText').select();_x000D_
  document.execCommand('copy');_x000D_
}
_x000D_
<button onclick="copier()">Copy</button>_x000D_
<textarea id="myText">Copy me PLEASE!!!</textarea>
_x000D_
_x000D_
_x000D_

How does EL empty operator work in JSF?

Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable using not empty operator on my dataModel that extends javax.faces.model.ListDataModel

Code sample:

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;

public class EntityDataModel extends ListDataModel<Entity> implements
        Collection<Entity>, SelectableDataModel<Entity>, Serializable {

    public EntityDataModel(List<Entity> data) { super(data); }

    @Override
    public Entity getRowData(String rowKey) {
        // In a real app, a more efficient way like a query by rowKey should be
        // implemented to deal with huge data
        List<Entity> entitys = (List<Entity>) getWrappedData();
        for (Entity entity : entitys) {
            if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
        }
        return null;
    }

    @Override
    public Object getRowKey(Entity entity) {
        return entity.getId();
    }

    @Override
    public boolean isEmpty() {
        List<Entity> entity = (List<Entity>) getWrappedData();
        return (entity == null) || entity.isEmpty();
    }
    // ... other not implemented methods of Collection...
}

How do you implement a circular buffer in C?

Can you enumerate the types needed at the time you code up the buffer, or do you need to be able to add types at run time via dynamic calls? If the former, then I would create the buffer as a heap-allocated array of n structs, where each struct consists of two elements: an enum tag identifying the data type, and a union of all the data types. What you lose in terms of extra storage for small elements, you make up in terms of not having to deal with allocation/deallocation and the resulting memory fragmentation. Then you just need to keep track of the start and end indices that define the head and tail elements of the buffer, and make sure to compute mod n when incrementing/decrementing the indices.

How to disable Paste (Ctrl+V) with jQuery?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
   $('input').on("cut copy paste",function(e) {_x000D_
      e.preventDefault();_x000D_
   });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" />
_x000D_
_x000D_
_x000D_

Hide text within HTML?

Not sure if this was what you were asking for, but I was personally trying to 'hide' some info in my html so that if someone inspected it, they would see the text in the source code.

It turns out that you can add ANY attribute, and so long as it isn't understood by the browser, it will just be left buried in the tag. My code was an easter egg: For people who couldn't afford to do the Makers Academy course, I basically encouraged them to inspect the element, where they would be given a secret URL where they could apply for a special, cut-price course (it's in haml, but it's the same idea in HTML):

.entry
        %h2 I can't afford to do the course... What should I do?
        %p{:url_you_should_visit => 'http://ronin.makersacademy.com'} Inspect and you shall find.

Or in html:

<p url_you_should_visit="http://ronin.makersacademy.com">Inspect and you shall find.</p>

Because 'url' is not a recognised html attribute, it makes no difference but is still discoverable. You could do the same with anything you wanted. You could have an attribute (in html) like:

<p thanks="Thanks to all the bloggers that helped me"> Some text </p>

And they'll be able to find your little easter egg if they want it... Hope that helps - it certainly helped me :)

How to update gradle in android studio?

Step 1 (Use default gradle wrapper)

File?Settings?Build, Execution, Deployment?Build Tools?Gradle?Use default Gradle wrapper (recommended)

Android studio settings Gradle wrapper

Step 2 (Select desired gradle version)

File?Project Structure?Project

Android Studio project structure

The following table shows compatibility between Android plugin for Gradle and Gradle:

Compatibility table

Latest stable versions you can use with Android Studio 4.1.1 (November 2020):

Android Gradle Plugin version: 4.1.1
Gradle version: 6.5

Official links

How do I add Git version control (Bitbucket) to an existing source code folder?

Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:

  1. Suppose you have your project folder on PC;
  2. Create a new repository on bitbucket: enter image description here

  3. Press on I have an existing project: enter image description here

  4. Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)

  5. Type command git init

  6. Type command git add --all

  7. Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO)

  8. Type command git commit -m "my first commit"

  9. Type command git push -u origin master

Note: if you get error unable to detect email or name, just type following commands after 5th step:

 git config --global user.email "yourEmail"  #your email at Bitbucket
 git config --global user.name "yourName"  #your name at Bitbucket

Launch Android application without main Activity and start Service on launching application

Yes you can do that by just creating a BroadcastReceiver that calls your Service when your Application boots. Here is a complete answer given by me.
Android - Start service on boot

If you don't want any icon/launcher for you Application you can do that also, just don't create any Activity with

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Just declare your Service as declared normally.

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

If you're wanting to use Environment variables using apache/tomcat, I found that the only way they could be found was setting them in tomcat/bin/setenv.sh (where catalina_opts are set - might be catalina.sh in your setup)

export AWS_ACCESS_KEY_ID=*********;

export AWS_SECRET_ACCESS_KEY=**************;

If you're using ubuntu, try logging in as ubuntu $printenv then log in as root $printenv, the environmental variables won't necessarily be the same....

If you only want to use environmental variables you can use: com.amazonaws.auth.EnvironmentVariableCredentialsProvider

instead of:

com.amazonaws.auth.DefaultAWSCredentialsProviderChain

(which by default checks all 4 possible locations)

anyway after hours of trying to figure out why my environmental variables weren't being found...this worked for me.

Display UIViewController as Popup in iPhone

Swift 4:

To add an overlay, or the popup view You can also use the Container View with which you get a free View Controller ( you get the Container View from the usual object palette/library)

enter image description here

Steps:

  1. Have a View (ViewForContainer in the pic) that holds this Container View, to dim it when the contents of Container View are displayed. Connect the outlet inside the first View Controller

  2. Hide this View when 1st VC loads

  3. Unhide when Button is clicked enter image description here

  4. To dim this View when the Container View content is displayed, set the Views Background to Black and opacity to 30%

enter image description here

You will get this effect when you click on the Button enter image description here

How do I get a class instance of generic type T?

   public <T> T yourMethodSignature(Class<T> type) {

        // get some object and check the type match the given type
        Object result = ...            

        if (type.isAssignableFrom(result.getClass())) {
            return (T)result;
        } else {
            // handle the error
        }
   }

Best dynamic JavaScript/JQuery Grid

Have a look at agiletoolkit.org as this has a simple to use CRUD which supports 2,4,6,7,9,10 and 12 out of the box (uses Ajax to defender the grid when adding,deleting data and it integrates with jquery.

I would post some examples but on an iPad at the moment.

Eclipse - "Workspace in use or cannot be created, chose a different one."

for windows users: In case of you can't remove .lock file and it gives you the following:

enter image description here

And you know that eclipse is already closed, just open Task Manager then processes then end precess for all eclipse.exe occurrences in the processes list.

Character Limit in HTML

For the <input> element there's the maxlength attribute:

<input type="text" id="Textbox" name="Textbox" maxlength="10" />

(by the way, the type is "text", not "textbox" as others are writing), however, you have to use javascript with <textarea>s. Either way the length should be checked on the server anyway.

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

How to get post slug from post in WordPress?

this simple code worked for me:

$postId = get_the_ID();
$slug = basename(get_permalink($postId));
echo $slug;

How does Facebook Sharer select Images and other metadata when sharing my URL?

When you share for Facebook, you have to add in your html into the head section next meta tags:

<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />

And that's it!

Add the button as you should according to what FB tells you.

All the info you need is in www.facebook.com/share/

Using if elif fi in shell scripts

Use double brackets...

if [[ expression ]]

How to send authorization header with axios

This has worked for me:

let webApiUrl = 'example.com/getStuff';
let tokenStr = 'xxyyzz';
axios.get(webApiUrl, { headers: {"Authorization" : `Bearer ${tokenStr}`} });

Default SQL Server Port

The default port for SQL Server Database Engine is 1433.

And as a best practice it should always be changed after the installation. 1433 is widely known which makes it vulnerable to attacks.

How to remove &quot; from my Json in javascript?

Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from

result.replace(/&quot;/g,'"')

to

result.replace(/&#34;/g,'"')

Instead of this I use that:

result.replace(/(&quot\;)/g,"\"")

By this notation it works.

cannot convert data (type interface {}) to type string: need type assertion

As asked for by @??s???? an explanation can be found at https://golang.org/pkg/fmt/#Sprint. Related explanations can be found at https://stackoverflow.com/a/44027953/12817546 and at https://stackoverflow.com/a/42302709/12817546. Here is @Yuanbo's answer in full.

package main

import "fmt"

func main() {
    var data interface{} = 2
    str := fmt.Sprint(data)
    fmt.Println(str)
}

ResourceDictionary in a separate assembly

Using XAML:

If you know the other assembly structure and want the resources in c# code, then use below code:

 ResourceDictionary dictionary = new ResourceDictionary();
 dictionary.Source = new Uri("pack://application:,,,/WpfControlLibrary1;Component/RD1.xaml", UriKind.Absolute);
 foreach (var item in dictionary.Values)
 {
    //operations
 }

Output: If we want to use ResourceDictionary RD1.xaml of Project WpfControlLibrary1 into StackOverflowApp project.

Structure of Projects:

Structure of Projects

Resource Dictionary: Resource Dictionary

Code Output:

Output

PS: All ResourceDictionary Files should have Build Action as 'Resource' or 'Page'.

Using C#:

If anyone wants the solution in purely c# code then see my this solution.

undefined offset PHP error

If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:

function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}

PHP How to fix Notice: Undefined variable:

Declare them before the while loop.

$hn = "";
$pid = "";
$datereg = "";
$prefix = "";
$fname = "";
$lname = "";
$age = "";
$sex = "";

You are getting the notice because the variables are declared and assigned inside the loop.

Using intents to pass data between activities

Main Activity

public class MainActivity extends Activity {

    EditText user, password;
    Button login;

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

        user = (EditText) findViewById(R.id.username_edit);
        password = (EditText) findViewById(R.id.edit_password);
        login = (Button) findViewById(R.id.btnSubmit);
        login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Second.class);

                String uservalue = user.getText().toString();
                String name_value = password.getText().toString();
                String password_value = password.getText().toString();

                intent.putExtra("username", uservalue);
                intent.putExtra("password", password_value);
                startActivity(intent);
            }
        });
    }
}

Second Activity in which you want to receive Data

public class Second extends Activity{

    EditText name, pass;
    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);

        name = (EditText) findViewById(R.id.editText1);
        pass = (EditText) findViewById(R.id.editText2);

        String value = getIntent().getStringExtra("username");
        String pass_val = getIntent().getStringExtra("password");
        name.setText(value);
        pass.setText(pass_val);
    }
}

Installing J2EE into existing eclipse IDE

Step 1 Go to Help ---> Install New Software...

Step 2 Try to find "http://download.eclipse.org/webtools/updates" under work with drop down. If you find then select and install all the available updates.

If you can not find then click on Add -> Add Repository. Name: Eclipse Webtools Location: http://download.eclipse.org/webtools/updates Select all available updates and Install them.

Visit http://download.eclipse.org/webtools/updates/ for more details.

How do I configure PyCharm to run py.test tests?

It's poorly documented to be sure. Once you get add a new configuration from defaults, you will be in the realm of running the "/Applications/PyCharm CE.app/Contents/helpers/pycharm/pytestrunner.py" script. It's not documented and has its own ideas of command line arguments.

You can:

  1. Try to play around, reverse the script, and see if you can somehow get py.test to accept arguments. It might work; it didn't in the first half hour for me.
  2. Just run "py.test *.py" from a console.

Oddly, you will find it hard to find any discussion as JetBrains does a good job of bombing Google algorithms with its own pages.

What is the difference between "screen" and "only screen" in media queries?

@media screen and (max-width:480px) { … } 

screen here is to set the screen size of the media query. E.g the maximum width of the display area is 480px. So it is specifying the screen as opposed to the other available media types.

@media only screen and (max-width: 480px;) { … } 

only screen here is used to prevent older browsers that do not support media queries with media features from applying the specified styles.

Disable future dates in jQuery UI Datepicker

Try This:

$('#datepicker').datepicker({
    endDate: new Date()
});

It will disable the future date.

Set disable attribute based on a condition for Html.TextBoxFor

If you don't use html helpers you may use simple ternary expression like this:

<input name="Field"
       value="@Model.Field" tabindex="0"
       @(Model.IsDisabledField ? "disabled=\"disabled\"" : "")>

Clear text field value in JQuery

Use jQuery.prototype.val to get/set field values:

var value = $('#doc_title').val();    // get value
$('#doc_title').val('');    // clear value

How to add url parameter to the current url?

Maybe you can write a function as follows:

var addParams = function(key, val, url) {
  var arr = url.split('?');
  if(arr.length == 1) {
    return url + '?' + key + '=' + val;
  }
  else if(arr.length == 2) {
    var params = arr[1].split('&');
    var p = {};
    var a = [];
    var strarr = [];
    $.each(params, function(index, element) {
      a = element.split('=');
      p[a[0]] = a[1];
      })
    p[key] = val;
    for(var o in p) {
      strarr.push(o + '=' + p[o]);
    }
    var str = strarr.join('&');
    return(arr[0] + '?' + str);
  }
}

How can I check if PostgreSQL is installed or not via Linux script?

If it is debian based.

aptitude show postgresql | grep State

But I guess you can just try to launch it with some flag like --version, that simply prints some info and exits.

Updated using "service postgres status". Try:

service postgres status
if [ "$?" -gt "0" ]; then
  echo "Not installed".
else
  echo "Intalled"
fi

Decimal separator comma (',') with numberDecimal inputType in EditText

IMHO the best approach for this problem is to just use the InputFilter. A nice gist is here DecimalDigitsInputFilter. Then you can just:

editText.setInputType(TYPE_NUMBER_FLAG_DECIMAL | TYPE_NUMBER_FLAG_SIGNED | TYPE_CLASS_NUMBER)
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789,.-"))
editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});

jQuery - select all text from a textarea

Selecting text in an element (akin to highlighting with your mouse)

:)

Using the accepted answer on that post, you can call the function like this:

$(function() {
  $('#textareaId').click(function() {
    SelectText('#textareaId');
  });
});

New Array from Index Range Swift

One more variant using extension and argument name range

This extension uses Range and ClosedRange

extension Array {

    subscript (range r: Range<Int>) -> Array {
        return Array(self[r])
    }


    subscript (range r: ClosedRange<Int>) -> Array {
        return Array(self[r])
    }
}

Tests:

func testArraySubscriptRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1..<arr.count] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

func testArraySubscriptClosedRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1...arr.count - 1] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

How to customize the configuration file of the official PostgreSQL Docker image?

You can put your custom postgresql.conf in a temporary file inside the container, and overwrite the default configuration at runtime.

To do that :

  • Copy your custom postgresql.conf inside your container
  • Copy the updateConfig.sh file in /docker-entrypoint-initdb.d/

Dockerfile

FROM postgres:9.6

COPY postgresql.conf      /tmp/postgresql.conf
COPY updateConfig.sh      /docker-entrypoint-initdb.d/_updateConfig.sh

updateConfig.sh

#!/usr/bin/env bash

cat /tmp/postgresql.conf > /var/lib/postgresql/data/postgresql.conf

At runtime, the container will execute the script inside /docker-entrypoint-initdb.d/ and overwrite the default configuration with yout custom one.

Standard Android menu icons, for example refresh

After seeing this post I found a useful link:

http://developer.android.com/design/downloads/index.html

You can download a lot of sources editable with Fireworks, Illustrator, Photoshop, etc...
And there's also fonts and icon packs.

Here is a stencil example.

Converting from a string to boolean in Python?

This version keeps the semantics of constructors like int(value) and provides an easy way to define acceptable string values.

def to_bool(value):
    valid = {'true': True, 't': True, '1': True,
             'false': False, 'f': False, '0': False,
             }   

    if isinstance(value, bool):
        return value

    if not isinstance(value, basestring):
        raise ValueError('invalid literal for boolean. Not a string.')

    lower_value = value.lower()
    if lower_value in valid:
        return valid[lower_value]
    else:
        raise ValueError('invalid literal for boolean: "%s"' % value)


# Test cases
assert to_bool('true'), '"true" is True' 
assert to_bool('True'), '"True" is True' 
assert to_bool('TRue'), '"TRue" is True' 
assert to_bool('TRUE'), '"TRUE" is True' 
assert to_bool('T'), '"T" is True' 
assert to_bool('t'), '"t" is True' 
assert to_bool('1'), '"1" is True' 
assert to_bool(True), 'True is True' 
assert to_bool(u'true'), 'unicode "true" is True'

assert to_bool('false') is False, '"false" is False' 
assert to_bool('False') is False, '"False" is False' 
assert to_bool('FAlse') is False, '"FAlse" is False' 
assert to_bool('FALSE') is False, '"FALSE" is False' 
assert to_bool('F') is False, '"F" is False' 
assert to_bool('f') is False, '"f" is False' 
assert to_bool('0') is False, '"0" is False' 
assert to_bool(False) is False, 'False is False'
assert to_bool(u'false') is False, 'unicode "false" is False'

# Expect ValueError to be raised for invalid parameter...
try:
    to_bool('')
    to_bool(12)
    to_bool([])
    to_bool('yes')
    to_bool('FOObar')
except ValueError, e:
    pass

Java out.println() how is this possible?

static imports do the trick:

import static java.lang.System.out;

or alternatively import every static method and field using

import static java.lang.System.*;

Addendum by @Steve C: note that @sfussenegger said this in a comment on my Answer.

"Using such a static import of System.out isn't suited for more than simple run-once code."

So please don't imagine that he (or I) think that this solution is Good Practice.

How does autowiring work in Spring?

The whole concept of inversion of control means you are free from a chore to instantiate objects manually and provide all necessary dependencies. When you annotate class with appropriate annotation (e.g. @Service) Spring will automatically instantiate object for you. If you are not familiar with annotations you can also use XML file instead. However, it's not a bad idea to instantiate classes manually (with the new keyword) in unit tests when you don't want to load the whole spring context.

Why do we use arrays instead of other data structures?

For O(1) random access, which can not be beaten.

AngularJS disable partial caching on dev machine

Building on @Valentyn's answer a bit, here's one way to always automatically clear the cache whenever the ng-view content changes:

myApp.run(function($rootScope, $templateCache) {
   $rootScope.$on('$viewContentLoaded', function() {
      $templateCache.removeAll();
   });
});

laravel 5 : Class 'input' not found

This clean code snippet works fine for me:

use Illuminate\Http\Request;
Route::post('/register',function(Request $request){

   $user = new \App\User;
   $user->username = $request->input('username');
   $user->email  = $request->input('email');
   $user->password = Hash::make($request->input('username'));
   $user->designation = $request->input('designation');
   $user->save();
});

GROUP_CONCAT ORDER BY

You can use SEPARATOR and ORDER BY inside the GROUP_CONCAT function in this way:

SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC SEPARATOR ',') 
AS views, group_concat(li.percentage ORDER BY li.percentage ASC SEPARATOR ',') FROM li
GROUP BY client_id;

Fragments onResume from back stack

onResume() for the fragment works fine...

public class listBook extends Fragment {

    private String listbook_last_subtitle;
...

    @Override
       public void onCreate(Bundle savedInstanceState) {

        String thisFragSubtitle = (String) getActivity().getActionBar().getSubtitle();
        listbook_last_subtitle = thisFragSubtitle;
       }
...

    @Override
        public void onResume(){
            super.onResume();
            getActivity().getActionBar().setSubtitle(listbook_last_subtitle);
        }
...

How do you convert Html to plain text?

HTTPUtility.HTMLEncode() is meant to handle encoding HTML tags as strings. It takes care of all the heavy lifting for you. From the MSDN Documentation:

If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the receiving end. HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and >, are encoded as &lt; and &gt; for HTTP transmission.

HTTPUtility.HTMLEncode() method, detailed here:

public static void HtmlEncode(
  string s,
  TextWriter output
)

Usage:

String TestString = "This is a <Test String>.";
StringWriter writer = new StringWriter();
Server.HtmlEncode(TestString, writer);
String EncodedString = writer.ToString();

What does it mean when Statement.executeUpdate() returns -1?

For executeUpdate statements against a DB2 for z/OS server, the value that is returned depends on the type of SQL statement that is being executed:

For an SQL statement that can have an update count, such as an INSERT, UPDATE, or DELETE statement, the returned value is the number of affected rows. It can be:

A positive number, if a positive number of rows are affected by the operation, and the operation is not a mass delete on a segmented table space.

0, if no rows are affected by the operation.

-1, if the operation is a mass delete on a segmented table space.

For a DB2 CALL statement, a value of -1 is returned, because the DB2 database server cannot determine the number of affected rows. Calls to getUpdateCount or getMoreResults for a CALL statement also return -1. For any other SQL statement, a value of -1 is returned.

Cannot read property 'style' of undefined -- Uncaught Type Error

Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.

If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.

You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.

This works when you execute it in Dev Tools because the DOM is already loaded.

T-SQL Cast versus Convert

Convert has a style parameter for date to string conversions.

http://msdn.microsoft.com/en-us/library/ms187928.aspx

How can I show a hidden div when a select option is selected?

you can use the following common function.

<div>
     <select class="form-control" 
             name="Extension for area validity sought for" 
             onchange="CommonShowHide('txtc1opt2', this, 'States')"
     >
         <option value="All India">All India</option>
         <option value="States">States</option>
     </select>

     <input type="text" 
            id="txtc1opt2" 
            style="display:none;" 
            name="Extension for area validity sought for details" 
            class="form-control" 
            value="" 
            placeholder="">

</div>
<script>
    function CommonShowHide(ElementId, element, value) {
         document
             .getElementById(ElementId)
             .style
             .display = element.value == value ? 'block' : 'none';
    }
</script>

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

Unix: How to delete files listed in a file

You could use '\n' for define the new line character as delimiter.

xargs -d '\n' rm < 1.txt

Be careful with the -rf because it can delete what you don't want to if the 1.txt contains paths with spaces. That's why the new line delimiter a bit safer.

On BSD systems, you could use -0 option to use new line characters as delimiter like this:

xargs -0 rm < 1.txt

How do I make a C++ macro behave like a function?

I know you said "ignore what the macro does", but people will find this question by searching based on the title, so I think discussion of further techniques to emulate functions with macros are warranted.

Closest I know of is:

#define MACRO(X,Y) \
do { \
    auto MACRO_tmp_1 = (X); \
    auto MACRO_tmp_2 = (Y); \
    using std::cout; \
    using std::endl; \
    cout << "1st arg is:" << (MACRO_tmp_1) << endl;    \
    cout << "2nd arg is:" << (MACRO_tmp_2) << endl;    \
    cout << "Sum is:" << (MACRO_tmp_1 + MACRO_tmp_2) << endl; \
} while(0)

This does the following:

  • Works correctly in each of the stated contexts.
  • Evaluates each of its arguments exactly once, which is a guaranteed feature of a function call (assuming in both cases no exceptions in any of those expressions).
  • Acts on any types, by use of "auto" from C++0x. This is not yet standard C++, but there's no other way to get the tmp variables necessitated by the single-evaluation rule.
  • Doesn't require the caller to have imported names from namespace std, which the original macro does, but a function would not.

However, it still differs from a function in that:

  • In some invalid uses it may give different compiler errors or warnings.
  • It goes wrong if X or Y contain uses of 'MACRO_tmp_1' or 'MACRO_tmp_2' from the surrounding scope.
  • Related to the namespace std thing: a function uses its own lexical context to look up names, whereas a macro uses the context of its call site. There's no way to write a macro that behaves like a function in this respect.
  • It can't be used as the return expression of a void function, which a void expression (such as the comma solution) can. This is even more of an issue when the desired return type is not void, especially when used as an lvalue. But the comma solution can't include using declarations, because they're statements, so pick one or use the ({ ... }) GNU extension.

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

How do I get a YouTube video thumbnail from the YouTube API?

In YouTube Data API v3, you can get video's thumbnails with the videos->list function. From snippet.thumbnails.(key), you can pick the default, medium or high resolution thumbnail, and get its width, height and URL.

You can also update thumbnails with the thumbnails->set functionality.

For examples, you can check out the YouTube API Samples project. (PHP ones.)

Split (explode) pandas dataframe string entry to separate rows

I had a similar problem, my solution was converting the dataframe to a list of dictionaries first, then do the transition. Here is the function:

import re
import pandas as pd

def separate_row(df, column_name):
    ls = []
    for row_dict in df.to_dict('records'):
        for word in re.split(',', row_dict[column_name]):
            row = row_dict.copy()
            row[column_name]=word
            ls.append(row)
    return pd.DataFrame(ls)

Example:

>>> from pandas import DataFrame
>>> import numpy as np
>>> a = DataFrame([{'var1': 'a,b,c', 'var2': 1},
               {'var1': 'd,e,f', 'var2': 2}])
>>> a
    var1  var2
0  a,b,c     1
1  d,e,f     2
>>> separate_row(a, "var1")
  var1  var2
0    a     1
1    b     1
2    c     1
3    d     2
4    e     2
5    f     2

You can also change the function a bit to support separating list type rows.

Yahoo Finance All Currencies quote API Documentation

From the research that I've done, there doesn't appear to be any documentation available for the API you're using. Depending on the data you're trying to get, I'd recommend using Yahoo's YQL API for accessing Yahoo Finance (An example can be found here). Alternatively, you could try using this well documented way to get CSV data from Yahoo Finance.

EDIT:

There has been some discussion on the Yahoo developer forums and it looks like there is no documentation (emphasis mine):

The reason for the lack of documentation is that we don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service (no redistribution of Finance data) in doing this so I would encourage you to avoid using these webservices.

At the same time, the URL you've listed can be accessed using the YQL console, though I'm not savvy enough to know how to extract URL parameters with it.

PHP Fatal error: Call to undefined function mssql_connect()

I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line

; On windows: extension_dir = "ext"

I changed it to:

; On windows: extension_dir = "C:\php\ext"

And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.

Plotting dates on the x-axis with Python's matplotlib

I have too low reputation to add comment to @bernie response, with response to @user1506145. I have run in to same issue.

1

The answer to it is a interval parameter which fixes things up

2

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt

np.random.seed(1)

N = 100
y = np.random.rand(N)

now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.plot(days,y)
plt.gcf().autofmt_xdate()
plt.show()