Programs & Examples On #Records

A record is a value that contains other values, typically in fixed number and sequence and typically indexed by names.

SQL Delete Records within a specific Range

My worry is if I say delete evertything with an ID (>79 AND < 296) then it may literally wipe the whole table...

That wont happen because you will have a where clause. What happens is that, if you have a statement like delete * from Table1 where id between 70 and 1296 , the first thing that sql query processor will do is to scan the table and look for those records in that range and then apply a delete.

Using Sockets to send and receive data

    //Client

    import java.io.*;
    import java.net.*;

    public class Client {
        public static void main(String[] args) {

        String hostname = "localhost";
        int port = 6789;

        // declaration section:
        // clientSocket: our client socket
        // os: output stream
        // is: input stream

            Socket clientSocket = null;  
            DataOutputStream os = null;
            BufferedReader is = null;

        // Initialization section:
        // Try to open a socket on the given port
        // Try to open input and output streams

            try {
                clientSocket = new Socket(hostname, port);
                os = new DataOutputStream(clientSocket.getOutputStream());
                is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: " + hostname);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: " + hostname);
            }

        // If everything has been initialized then we want to write some data
        // to the socket we have opened a connection to on the given port

        if (clientSocket == null || os == null || is == null) {
            System.err.println( "Something is wrong. One variable is null." );
            return;
        }

        try {
            while ( true ) {
            System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String keyboardInput = br.readLine();
            os.writeBytes( keyboardInput + "\n" );

            int n = Integer.parseInt( keyboardInput );
            if ( n == 0 || n == -1 ) {
                break;
            }

            String responseLine = is.readLine();
            System.out.println("Server returns its square as: " + responseLine);
            }

            // clean up:
            // close the output stream
            // close the input stream
            // close the socket

            os.close();
            is.close();
            clientSocket.close();   
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
        }           
    }





//Server




import java.io.*;
import java.net.*;

public class Server1 {
    public static void main(String args[]) {
    int port = 6789;
    Server1 server = new Server1( port );
    server.startServer();
    }

    // declare a server socket and a client socket for the server

    ServerSocket echoServer = null;
    Socket clientSocket = null;
    int port;

    public Server1( int port ) {
    this.port = port;
    }

    public void stopServer() {
    System.out.println( "Server cleaning up." );
    System.exit(0);
    }

    public void startServer() {
    // Try to open a server socket on the given port
    // Note that we can't choose a port less than 1024 if we are not
    // privileged users (root)

        try {
        echoServer = new ServerSocket(port);
        }
        catch (IOException e) {
        System.out.println(e);
        }   

    System.out.println( "Waiting for connections. Only one connection is allowed." );

    // Create a socket object from the ServerSocket to listen and accept connections.
    // Use Server1Connection to process the connection.

    while ( true ) {
        try {
        clientSocket = echoServer.accept();
        Server1Connection oneconnection = new Server1Connection(clientSocket, this);
        oneconnection.run();
        }   
        catch (IOException e) {
        System.out.println(e);
        }
    }
    }
}

class Server1Connection {
    BufferedReader is;
    PrintStream os;
    Socket clientSocket;
    Server1 server;

    public Server1Connection(Socket clientSocket, Server1 server) {
    this.clientSocket = clientSocket;
    this.server = server;
    System.out.println( "Connection established with: " + clientSocket );
    try {
        is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        os = new PrintStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        System.out.println(e);
    }
    }

    public void run() {
        String line;
    try {
        boolean serverStop = false;

            while (true) {
                line = is.readLine();
        System.out.println( "Received " + line );
                int n = Integer.parseInt(line);
        if ( n == -1 ) {
            serverStop = true;
            break;
        }
        if ( n == 0 ) break;
                os.println("" + n*n ); 
            }

        System.out.println( "Connection closed." );
            is.close();
            os.close();
            clientSocket.close();

        if ( serverStop ) server.stopServer();
    } catch (IOException e) {
        System.out.println(e);
    }
    }
}

How to get the URL without any parameters in JavaScript?

You can concat origin and pathname, if theres present a port such as example.com:80, that will be included as well.

location.origin + location.pathname

how to compare two string dates in javascript?

You can simply compare 2 strings

function isLater(dateString1, dateString2) {
  return dateString1 > dateString2
}

Then

isLater("2012-12-01", "2012-11-01")

returns true while

isLater("2012-12-01", "2013-11-01")

returns false

How can I reference a commit in an issue comment on GitHub?

If you are trying to reference a commit in another repo than the issue is in, you can prefix the commit short hash with reponame@.

Suppose your commit is in the repo named dev, and the GitLab issue is in the repo named test. You can leave a comment on the issue and reference the commit by dev@e9c11f0a (where e9c11f0a is the first 8 letters of the sha hash of the commit you want to link to) if that makes sense.

How can I perform an inspect element in Chrome on my Galaxy S3 Android device?

Mainly follow the guide here https://developers.google.com/chrome-developer-tools/docs/remote-debugging. But ...

  • For Samsung devices don't forget to install Samsung Kies.
  • For me it worked only with Chrome Canary, not with Chrome.
  • You might also need to install Android SDK.

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

How to remove underline from a link in HTML?

I suggest to use :hover to avoid underline if mouse pointer is over an anchor

a:hover {
   text-decoration:none;
}

How to finish current activity in Android

I found many answers but not one is simple... I hope this will help you...

try{
    Intent intent = new Intent(CurrentActivity.this, NewActivity.class);
    startActivity(intent);
} finally {
    finish();
}

so, Very simple logic is here, as we know that in java we write code that has some chances of exception in a try block and handle that exception in catch block but in finally block we write code that has to be executed in any cost (Either the exception comes or not).

Error: " 'dict' object has no attribute 'iteritems' "

In Python2, dictionary.iteritems() is more efficient than dictionary.items() so in Python3, the functionality of dictionary.iteritems() has been migrated to dictionary.items() and iteritems() is removed. So you are getting this error.

Use dict.items() in Python3 which is same as dict.iteritems() of Python2.

SQL Server Group By Month

SELECT CONVERT(NVARCHAR(10), PaymentDate, 120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(10), PaymentDate, 120)
ORDER BY [Month]

You could also try:

SELECT DATEPART(Year, PaymentDate) Year, DATEPART(Month, PaymentDate) Month, SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY DATEPART(Year, PaymentDate), DATEPART(Month, PaymentDate)
ORDER BY Year, Month

Validate phone number with JavaScript

This will work:

/^(()?\d{3}())?(-|\s)?\d{3}(-|\s)?\d{4}$/

The ? character signifies that the preceding group should be matched zero or one times. The group (-|\s) will match either a - or a | character. Adding ? after the second occurrence of this group in your regex allows you to match a sequence of 10 consecutive digits.

How to use z-index in svg elements?

As others here have said, z-index is defined by the order the element appears in the DOM. If manually reordering your html isn't an option or would be difficult, you can use D3 to reorder SVG groups/objects.

Use D3 to Update DOM Order and Mimic Z-Index Functionality

Updating SVG Element Z-Index With D3

At the most basic level (and if you aren't using IDs for anything else), you can use element IDs as a stand-in for z-index and reorder with those. Beyond that you can pretty much let your imagination run wild.

Examples in code snippet

_x000D_
_x000D_
var circles = d3.selectAll('circle')_x000D_
var label = d3.select('svg').append('text')_x000D_
    .attr('transform', 'translate(' + [5,100] + ')')_x000D_
_x000D_
var zOrders = {_x000D_
    IDs: circles[0].map(function(cv){ return cv.id; }),_x000D_
    xPos: circles[0].map(function(cv){ return cv.cx.baseVal.value; }),_x000D_
    yPos: circles[0].map(function(cv){ return cv.cy.baseVal.value; }),_x000D_
    radii: circles[0].map(function(cv){ return cv.r.baseVal.value; }),_x000D_
    customOrder: [3, 4, 1, 2, 5]_x000D_
}_x000D_
_x000D_
var setOrderBy = 'IDs';_x000D_
var setOrder = d3.descending;_x000D_
_x000D_
label.text(setOrderBy);_x000D_
circles.data(zOrders[setOrderBy])_x000D_
circles.sort(setOrder);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 100"> _x000D_
  <circle id="1" fill="green" cx="50" cy="40" r="20"/> _x000D_
  <circle id="2" fill="orange" cx="60" cy="50" r="18"/>_x000D_
  <circle id="3" fill="red" cx="40" cy="55" r="10"/> _x000D_
  <circle id="4" fill="blue" cx="70" cy="20" r="30"/> _x000D_
  <circle id="5" fill="pink" cx="35" cy="20" r="15"/> _x000D_
</svg>
_x000D_
_x000D_
_x000D_

The basic idea is:

  1. Use D3 to select the SVG DOM elements.

    var circles = d3.selectAll('circle')
    
  2. Create some array of z-indices with a 1:1 relationship with your SVG elements (that you want to reorder). Z-index arrays used in the examples below are IDs, x & y position, radii, etc....

    var zOrders = {
        IDs: circles[0].map(function(cv){ return cv.id; }),
        xPos: circles[0].map(function(cv){ return cv.cx.baseVal.value; }),
        yPos: circles[0].map(function(cv){ return cv.cy.baseVal.value; }),
        radii: circles[0].map(function(cv){ return cv.r.baseVal.value; }),
        customOrder: [3, 4, 1, 2, 5]
    }
    
  3. Then, use D3 to bind your z-indices to that selection.

    circles.data(zOrders[setOrderBy]);
    
  4. Lastly, call D3.sort to reorder the elements in the DOM based on the data.

    circles.sort(setOrder);
    

Examples

enter image description here

  • You can stack by ID

enter image description here

  • With leftmost SVG on top

enter image description here

  • Smallest radii on top

enter image description here

  • Or Specify an array to apply z-index for a specific ordering -- in my example code the array [3,4,1,2,5] moves/reorders the 3rd circle (in the original HTML order) to be 1st in the DOM, 4th to be 2nd, 1st to be 3rd, and so on...

How to hide iOS status bar

Add the following to your Info.plist:

<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>

Image

Find multiple files and rename them in Linux

If you just want to rename and don't mind using an external tool, then you can use rnm. The command would be:

#on current folder
rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' *

-dp -1 will make it recursive to all subdirectories.

-fo implies file only mode.

-ssf '_dbg' searches for files with _dbg in the filename.

-rs '/_dbg//' replaces _dbg with empty string.

You can run the above command with the path of the CURRENT_FOLDER too:

rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' /path/to/the/directory

How do I find all of the symlinks in a directory tree?

This will recursively traverse the /path/to/folder directory and list only the symbolic links:

ls -lR /path/to/folder | grep ^l

If your intention is to follow the symbolic links too, you should use your find command but you should include the -L option; in fact the find man page says:

   -L     Follow symbolic links.  When find examines or prints information
          about files, the information used shall be taken from the  prop-
          erties  of  the file to which the link points, not from the link
          itself (unless it is a broken symbolic link or find is unable to
          examine  the file to which the link points).  Use of this option
          implies -noleaf.  If you later use the -P option,  -noleaf  will
          still  be  in  effect.   If -L is in effect and find discovers a
          symbolic link to a subdirectory during its search, the subdirec-
          tory pointed to by the symbolic link will be searched.

          When the -L option is in effect, the -type predicate will always
          match against the type of the file that a symbolic  link  points
          to rather than the link itself (unless the symbolic link is bro-
          ken).  Using -L causes the -lname and -ilname predicates  always
          to return false.

Then try this:

find -L /var/www/ -type l

This will probably work: I found in the find man page this diamond: if you are using the -type option you have to change it to the -xtype option:

          l      symbolic link; this is never true if the -L option or the
                 -follow option is in effect, unless the symbolic link  is
                 broken.  If you want to search for symbolic links when -L
                 is in effect, use -xtype.

Then:

find -L /var/www/ -xtype l

Use YAML with variables

This is an old post, but I had a similar need and this is the solution I came up with. It is a bit of a hack, but it works and could be refined.

require 'erb'
require 'yaml'

doc = <<-EOF
  theme:
  name: default
  css_path: compiled/themes/<%= data['theme']['name'] %>
  layout_path: themes/<%= data['theme']['name'] %>
  image_path: <%= data['theme']['css_path'] %>/images
  recursive_path: <%= data['theme']['image_path'] %>/plus/one/more
EOF

data = YAML::load("---" + doc)

template = ERB.new(data.to_yaml);
str = template.result(binding)
while /<%=.*%>/.match(str) != nil
  str = ERB.new(str).result(binding)
end

puts str

A big downside is that it builds into the yaml document a variable name (in this case, "data") that may or may not exist. Perhaps a better solution would be to use $ and then substitute it with the variable name in Ruby prior to ERB. Also, just tested using hashes2ostruct which allows data.theme.name type notation which is much easier on the eyes. All that is required is to wrap the YAML::load with this

data = hashes2ostruct(YAML::load("---" + doc))

Then your YAML document can look like this

doc = <<-EOF
  theme:
  name: default
  css_path: compiled/themes/<%= data.theme.name %>
  layout_path: themes/<%= data.theme.name %>
  image_path: <%= data.theme.css_path %>/images
  recursive_path: <%= data.theme.image_path %>/plus/one/more
EOF

CSS :: child set to change color on parent hover, but changes also when hovered itself

Update

The below made sense for 2013. However, now, I would use the :not() selector as described below.


CSS can be overwritten.

DEMO: http://jsfiddle.net/persianturtle/J4SUb/

Use this:

_x000D_
_x000D_
.parent {
  padding: 50px;
  border: 1px solid black;
}

.parent span {
  position: absolute;
  top: 200px;
  padding: 30px;
  border: 10px solid green;
}

.parent:hover span {
  border: 10px solid red;
}

.parent span:hover {
  border: 10px solid green;
}
_x000D_
<a class="parent">
    Parent text
    <span>Child text</span>    
</a>
_x000D_
_x000D_
_x000D_

NuGet Packages are missing

I solved my issue by removing this code from .csproj file:

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
  <PropertyGroup>
    <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
  </PropertyGroup>
  <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

How to predict input image using trained model in Keras?

If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:

# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on

from keras.models import load_model
from keras.preprocessing import image
import numpy as np

# dimensions of our images
img_width, img_height = 320, 240

# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes

# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)

# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)

# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]

Get values from a listbox on a sheet

The accepted answer doesn't cut it because if a user de-selects a row the list is not updated accordingly.

Here is what I suggest instead:

Private Sub CommandButton2_Click()
    Dim lItem As Long

    For lItem = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(lItem) = True Then
            MsgBox(ListBox1.List(lItem))
        End If
    Next
End Sub

Courtesy of http://www.ozgrid.com/VBA/multi-select-listbox.htm

Why would a JavaScript variable start with a dollar sign?

As I have experienced for the last 4 years, it will allow some one to easily identify whether the variable pointing a value/object or a jQuery wrapped DOM element

_x000D_
_x000D_
Ex:_x000D_
var name = 'jQuery';_x000D_
var lib = {name:'jQuery',version:1.6};_x000D_
_x000D_
var $dataDiv = $('#myDataDiv');
_x000D_
_x000D_
_x000D_

in the above example when I see the variable "$dataDiv" i can easily say that this variable pointing to a jQuery wrapped DOM element (in this case it is div). and also I can call all the jQuery methods with out wrapping the object again like $dataDiv.append(), $dataDiv.html(), $dataDiv.find() instead of $($dataDiv).append().

Hope it may helped. so finally want to say that it will be a good practice to follow this but not mandatory.

jquery variable syntax

This is pure JavaScript.

There is nothing special about $. It is just a character that may be used in variable names.

var $ = 1;
var $$ = 2;
alert($ + $$);

jQuery just assigns it's core function to a variable called $. The code you have assigns this to a local variable called self and the results of calling jQuery with this as an argument to a global variable called $self.

It's ugly, dirty, confusing, but $, self and $self are all different variables that happen to have similar names.

How to repeat a string a variable number of times in C++?

Here's an example of the string "abc" repeated 3 times:

#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <iterator>

using namespace std;

int main() {
    ostringstream repeated;
    fill_n(ostream_iterator<string>(repeated), 3, string("abc"));
    cout << "repeated: " << repeated.str() << endl;  // repeated: abcabcabc
    return 0;
}

How do I download/extract font from chrome developers tools?

It's easy (For Chorme only)

  1. Right click > inspect element
  2. Go to 'Resources' tab and find 'Fonts' in dropdown folders
    • 'Resouces' tab may be called 'Application'
  3. Right click on font (in .woff format) > open link in new tab (this should download the font in .woff format
  4. Find a 'Woff to TTf or Otf' font converter online
  5. Enjoy after conversion!

How to move a git repository into another directory and make that directory a git repository?

I am no expert, but I copy the .git folder to a new folder, then invoke: git reset --hard

How to delete stuff printed to console by System.out.println()?

this solution is applicable if you want to remove some System.out.println() output. It restricts that output to print on console and print other outputs.

PrintStream ps = System.out;
System.setOut(new PrintStream(new OutputStream() {
   @Override
   public void write(int b) throws IOException {}
}));

System.out.println("It will not print");

//To again enable it.
System.setOut(ps);

System.out.println("It will print");

WordPress: get author info from post id

If you want it outside of loop then use the below code.

<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id ); 
echo $display_name;
?>

Is it possible to use if...else... statement in React render function?

I used ternary operator and it's working fine for me.

> {item.lotNum == null ? ('PDF'):(item.lotNum)}

How to empty the message in a text area with jquery?

A comment to jarijira

Well I have had many issues with .html and .empty() methods for inputs o. If the id represents an input and not another type of html selector like

or use the .val() function to manipulate.

For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').val('') //clear input value
     $('#someInput').val(newVal) //override w/ the new value
     $('#someInput').val('test2) 
     newVal= $('#someInput').val(newVal) //get input value

}

For improper, but sometimes works For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').html('') //clear input value
     $('#someInput').empty() //clear html inside of the id
     $('#someInput').html(newVal) //override the html inside of text area w/ string could be '<div>test3</div>
     really overriding with a string manipulates the value, but this is not the best practice as you do not put things besides strings or values inside of an input. 
     newVal= $('#someInput').val(newVal) //get input value

}

An issue that I had was I was using the $getJson method and I was indeed able to use .html calls to manipulate my inputs. However, whenever I had an error or fail on the getJSON I could no longer change my inputs using the .clear and .html calls. I could still return the .val(). After some experimentation and research I discovered that you should only use the .val() function to make changes to input fields.

Generating CSV file for Excel, how to have a newline inside a value

UTF files that contain a BOM will cause Excel to treat new lines literally even in that field is surrounded by quotes. (Tested Excel 2008 Mac)

The solution is to make any new lines a carriage return (CHR 13) rather than a line feed.

How to load my app from Eclipse to my Android phone instead of AVD

Thanks this helped. It was a little tricky getting the USB debugging option enabled on the Samsung G3 after the update.

See below Instructions on Samsung G3 Jellybean

  1. Settings
  2. Click --> About the phone
  3. Tap on the build number
  4. “You are now 4 steps away from being a developer.” Keep tapping until it says “You are now a developer.”
  5. Go back to Setting-->System --> Developer option: Enable USB Debugging

How do I append one string to another in Python?

str1 = "Hello"
str2 = "World"
newstr = " ".join((str1, str2))

That joins str1 and str2 with a space as separators. You can also do "".join(str1, str2, ...). str.join() takes an iterable, so you'd have to put the strings in a list or a tuple.

That's about as efficient as it gets for a builtin method.

How to center a navigation bar with CSS or HTML?

Add some CSS:

div#nav{
  text-align: center;
}
div#nav ul{
  display: inline-block;
}

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

My understanding is you don't need to install Anaconda again to start using a different version of python. Instead, conda has the ability to separately manage python 2 and 3 environments.

What is IPV6 for localhost and 0.0.0.0?

Just for the sake of completeness: there are IPv4-mapped IPv6 addresses, where you can embed an IPv4 address in an IPv6 address (may not be supported by every IPv6 equipment).

Example: I run a server on my machine, which can be accessed via http://127.0.0.1:19983/solr. If I access it via an IPv4-mapped IPv6 address then I access it via http://[::ffff:127.0.0.1]:19983/solr (which will be converted to http://[::ffff:7f00:1]:19983/solr)

How to set width and height dynamically using jQuery

$("#mainTable").css("width", "200px");
$("#mainTable").css("height", "2000px");

Create a CSS rule / class with jQuery at runtime

You can create style element and insert it into DOM

$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head");
$("<div/>").addClass("redbold").text("SOME NEW TEXT").appendTo("body");

tested on Opera10 FF3.5 iE8 iE6

How can I see the size of a GitHub repository before cloning it?

You need to follow the GitHub API. See the documentation here for all the details regarding your repository. It requires you to make a GET request as:

GET /repos/:owner/:repository

You need to replace two things:

  1. :owner - the username of the person who owns the repository
  2. :repository - The name of the repository

E.g., my username maheshmnj, and I own a repository, flutter-ui-nice, so my GET URL will be:

https://api.github.com/repos/maheshmnj/flutter-ui-nice

On making a GET request, you will be flooded with some JSON data and probably on line number 78 you should see a key named size that will return the size of the repository.

Tip: When working with JSON I suggest you to add a plugin that formats the JSON data to make reading JSON easy. Install the plugin.

jQuery: click function exclude children.

I personally would add a click handler to the child element that did nothing but stop the propagation of the click. So it would look something like:

$('.example > div').click(function (e) {
    e.stopPropagation();
});

Python how to write to a binary file?

As of Python 3.2+, you can also accomplish this using the to_bytes native int method:

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
    newFile.write(byte.to_bytes(1, byteorder='big'))

I.e., each single call to to_bytes in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte. You can also shorten the last two lines into a single one:

newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))

Find and replace in file and overwrite file doesn't work, it empties the file

With all due respect to the above correct answers, it's always a good idea to "dry run" scripts like that, so that you don't corrupt your file and have to start again from scratch.

Just get your script to spill the output to the command line instead of writing it to the file, for example, like that:

sed -e s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html

OR

less index.html | sed -e s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g 

This way you can see and check the output of the command without getting your file truncated.

How to generate java classes from WSDL file

Yes you can use:

Wsdl2java eclipse plugin

With this all you will need is to supply the wsdl, and the client which is the Java classes will be automatically generated for you.

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

Make WPF Application Fullscreen (Cover startmenu)

window.WindowStyle = WindowStyle.None;
window.ResizeMode = ResizeMode.NoResize;
window.Left = 0;
window.Top = 0;
window.Width = SystemParameters.VirtualScreenWidth;
window.Height = SystemParameters.VirtualScreenHeight;
window.Topmost = true;

Works with multiple screens

Cannot create PoolableConnectionFactory

In my case the solution was to remove the attribute

validationQuery="select 1"

from the (Derby DB) resource tag.

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.

#include <stdio.h>
int main () 
{
    printf("Hello ");
    goto Cleanup;
Cleanup: ; //This is an empty statement.
    char *str = "World\n";
    printf("%s\n", str);
}

How to stop default link click behavior with jQuery

You can use e.preventDefault(); instead of e.stopPropagation();

How do I comment on the Windows command line?

It's "REM".

Example:

REM This is a comment

How do I get bootstrap-datepicker to work with Bootstrap 3?

I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.

You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.

Here is my solution:

<div class="form-group row">
  <div class="col-xs-8">
    <label class="control-label">My Label</label>
    <div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
      <input class="form-control" type="text" readonly="" value="12-02-2012">
      <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
  </div>
</div>

CSS changes in datepicker.css on lines 176-177:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 34:

this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;

UPDATE

Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:

CSS changes in datepicker.css on lines 446-447:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 46:

 this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;

Finally, the JavaScript to enable the datepicker (with some options):

 $(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });

Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.

Sequence contains no elements?

I had a similar situation on a function that calculates the average.

Example:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();

Case Solved:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();

adding a datatable in a dataset

you have to set the tableName you want to your dtimage that is for instance

dtImage.TableName="mydtimage";


if(!ds.Tables.Contains(dtImage.TableName))
        ds.Tables.Add(dtImage);

it will be reflected in dataset because dataset is a container of your datatable dtimage and you have a reference on your dtimage

How to determine whether a given Linux is 32 bit or 64 bit?

If you have a 64-bit OS, instead of i686, you have x86_64 or ia64 in the output of uname -a. In that you do not have any of these two strings; you have a 32-bit OS (note that this does not mean that your CPU is not 64-bit).

Get full path without filename from path that includes filename

I used this and it works well:

string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));

foreach (string file in filePaths)
{   
    if (comboBox1.SelectedItem.ToString() == "")
    {
        if (file.Contains("c"))
        {
            comboBox2.Items.Add(Path.GetFileName(file));
        }
    }
}

How to redirect on another page and pass parameter in url from table?

Here is a general solution that doesn't rely on JQuery. Simply modify the definition of window.location.

<html>
   <head>
      <script>
         function loadNewDoc(){ 
            var loc = window.location;
            window.location = loc.hostname + loc.port + loc.pathname + loc.search; 
         };
      </script>
   </head>
   <body onLoad="loadNewDoc()">
   </body>  
</html>

How to concatenate two numbers in javascript?

To add to all answers above I want the share the background logic:

Plus is an addition operator that is also used for concatenation of strings. When we want to concatenate numbers. It should be the understanding that we want to concatenate the strings, as the concatenation of numbers doesn't make valid use cases to me.

We can achieve it in multiple ways,

Through type conversion

let a = 5;
a.toString()+5 // Output 55 type "string"

This will also work and doing type conversion in the background,

5 +""+ 5 // Output 55 type "string"

If you are determined to concatenate two string and type of output should be int, parseInt() works here

parseInt(5 +""+ 5)  //Output 55 Type "number"

How to use (install) dblink in PostgreSQL?

It can be added by using:

$psql -d databaseName -c "CREATE EXTENSION dblink"

It is more efficient to use if-return-return or if-else-return?

With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.

Convert blob URL to normal URL

As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.

However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.

<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>

Insert this to the page containing blob url and click the button, you get the content.

Another way is to intercept the ajax call via a proxy server, then you could view the true image url.

addEventListener not working in IE8

Mayb it's easier (and has more performance) if you delegate the event handling to another element, for example your table

$('idOfYourTable').on("click", "input:checkbox", function(){

});

in this way you will have only one event handler, and this will work also for newly added elements. This requires jQuery >= 1.7

Otherwise use delegate()

$('idOfYourTable').delegate("input:checkbox", "click", function(){

});

How does strtok() split the string into tokens in C?

strtok replaces the characters in the second argument with a NULL and a NULL character is also the end of a string.

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

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

In C++11 you can use std::to_string:

#include <string>

std::string s = std::to_string(5);

If you're working with prior to C++11, you could use C++ streams:

#include <sstream>

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/

How to concatenate multiple column values into a single column in Panda dataframe

If you have even more columns you want to combine, using the Series method str.cat might be handy:

df["combined"] = df["foo"].str.cat(df[["bar", "new"]].astype(str), sep="_")

Basically, you select the first column (if it is not already of type str, you need to append .astype(str)), to which you append the other columns (separated by an optional separator character).

How to fix syntax error, unexpected T_IF error in php?

add semi-colon the line before:

$total_pages = ceil($total_result / $per_page);

how to change class name of an element by jquery

Instead of removeClass and addClass, you can also do it like this:

$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

I came here specifically to work out how I could convert my timezoneoffset to a timezone string for converting dates to DATETIMEOFFSET in SQL Server 2008. Gross, but necessary.

So I need 1 method that will cope with negative and positive numbers, formatting them to two characters with a leading zero if needed. Anons answer got me close, but negative timezone values would come out as 0-5 rather than the required -05

So with a bit of a tweak on his answer, this works for all timezone hour conversions

DECLARE @n INT = 13 -- Works with -13, -5, 0, 5, etc
SELECT CASE 
    WHEN @n < 0 THEN '-' + REPLACE(STR(@n * -1 ,2),' ','0') 
    ELSE '+' + REPLACE(STR(@n,2),' ','0') END + ':00'

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

Note: This issue was fixed on windows 10 I was facing same issue with virtual environment on windows 10. Issue was solved with running CMD as administrator and creating new virtual environment.

  • Run cmd as administrator
  • create virtual environment (virtualenv .venv )
  • activate virtual environment .venv\Scripts\activate
  • Pip install requests

Proper indentation for Python multiline strings

I'm having a similar issue, code got really unreadable using multilines, I came out with something like

print("""aaaa
"""   """bbb
""")

yes, at beginning could look terrible but the embedded syntax was quite complex and adding something at the end (like '\n"') was not a solution

Stop UIWebView from "bouncing" vertically?

To disable UIWebView scrolling you could use the following line of code:

[ObjWebview setUserInteractionEnabled:FALSE];

In this example, ObjWebview is of type UIWebView.

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

It could also mean something like "Lexical Environment Type or Tied".. It bothers me that it would simply be "let this be that". And let rec wouldn't make sense in lambda calculus.

jQuery UI Dialog OnBeforeUnload

The correct way to display the alert is to simply return a string. Don't call the alert() method yourself.

<script type="text/javascript">
    $(window).on('beforeunload', function() {
        if (iWantTo) {
            return 'you are an idiot!';
        }
    }); 
</script>

See also: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

How do you dynamically add elements to a ListView on Android?

Create an XML layout first in your project's res/layout/main.xml folder:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button
        android:id="@+id/addBtn"
        android:text="Add New Item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="addItems"/>
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
    />
</LinearLayout>

This is a simple layout with a button on the top and a list view on the bottom. Note that the ListView has the id @android:id/list which defines the default ListView a ListActivity can use.

public class ListViewDemo extends ListActivity {
    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayList<String> listItems=new ArrayList<String>();

    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;

    //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
    int clickCounter=0;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        adapter=new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,
            listItems);
        setListAdapter(adapter);
    }

    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }
}

android.R.layout.simple_list_item_1 is the default list item layout supplied by Android, and you can use this stock layout for non-complex things.

listItems is a List which holds the data shown in the ListView. All the insertion and removal should be done on listItems; the changes in listItems should be reflected in the view. That's handled by ArrayAdapter<String> adapter, which should be notified using:

adapter.notifyDataSetChanged();

An Adapter is instantiated with 3 parameters: the context, which could be your activity/listactivity; the layout of your individual list item; and lastly, the list, which is the actual data to be displayed in the list.

How do I type a TAB character in PowerShell?

If it helps you can embed a tab character in a double quoted string:

PS> "`t hello"

How can I declare dynamic String array in Java

The Array.newInstance(Class<?> componentType, int length) method is to be used to create an array with dynamically length.

Multi-dimensional arrays can be created similarly with the Array.newInstance(Class<?> componentType, int... dimensions) method.

Array of an unknown length in C#

Arrays must be assigned a length. To allow for any number of elements, use the List class.

For example:

List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3

How to use adb command to push a file on device without sd card

In my case, I had an already removed SDCard still registered in Android. So I longpressed the entry for my old SDCard under:

Settings | Storage & USB

and selected "Forget".

Afterwards a normal

adb push myfile.zip /sdcard/

worked fine.

How to obtain the total numbers of rows from a CSV file in Python?

This works for csv and all files containing strings in Unix-based OSes:

import os

numOfLines = int(os.popen('wc -l < file.csv').read()[:-1])

In case the csv file contains a fields row you can deduct one from numOfLines above:

numOfLines = numOfLines - 1

SVN change username

I’ve had the exact same problem and found the solution in Where does SVN client store user authentication data?:

  1. cd to ~/.subversion/auth/.
  2. Do fgrep -l <yourworkmatesusernameORtheserverurl> */*.
  3. Delete the file found.
  4. The next operation on the repository will ask you again for username/password information.

(For Windows, the steps are analogous; the auth directory is in %APPDATA%\Subversion\).

Note that this will only work for SVN access schemes where the user name is part of the server login so it’s no use for repositories accessed using file://.

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

Adding header for HttpURLConnection

Finally this worked for me

private String buildBasicAuthorizationString(String username, String password) {

    String credentials = username + ":" + password;
    return "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.NO_WRAP));
}

Finding an element in an array in Java

You can use one of the many Arrays.binarySearch() methods. Keep in mind that the array must be sorted first.

How to check ASP.NET Version loaded on a system?

You can see which version gets executed when you load the page with Google Chrome + developer tools (preinstalled) or Firefox + Firebug (add-on).

I use Google Chrome:

  1. Open Chrome and use Ctrl+Shift+I to open the developer tools.
  2. Go to the "Network" Tab
  3. Click on the small button at the bottom "Preserve log upon Navigation"
  4. Load any of your pages
  5. Click on the response header

It looks like this:

enter image description here

How to run wget inside Ubuntu Docker image?

If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

How to declare array of zeros in python (or an array of a certain size)

Just for completeness: To declare a multidimensional list of zeros in python you have to use a list comprehension like this:

buckets = [[0 for col in range(5)] for row in range(10)]

to avoid reference sharing between the rows.

This looks more clumsy than chester1000's code, but is essential if the values are supposed to be changed later. See the Python FAQ for more details.

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

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

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

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

Usage:

generateUUIDString(UUID.randomUUID())

Another implementation using reflection

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

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

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

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

}

How to turn a vector into a matrix in R?

A matrix is really just a vector with a dim attribute (for the dimensions). So you can add dimensions to vec using the dim() function and vec will then be a matrix:

vec <- 1:49
dim(vec) <- c(7, 7)  ## (rows, cols)
vec

> vec <- 1:49
> dim(vec) <- c(7, 7)  ## (rows, cols)
> vec
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    8   15   22   29   36   43
[2,]    2    9   16   23   30   37   44
[3,]    3   10   17   24   31   38   45
[4,]    4   11   18   25   32   39   46
[5,]    5   12   19   26   33   40   47
[6,]    6   13   20   27   34   41   48
[7,]    7   14   21   28   35   42   49

Immutable vs Mutable types

Whether an object is mutable or not depends on its type. This doesn't depend on whether or not it has certain methods, nor on the structure of the class hierarchy.

User-defined types (i.e. classes) are generally mutable. There are some exceptions, such as simple sub-classes of an immutable type. Other immutable types include some built-in types such as int, float, tuple and str, as well as some Python classes implemented in C.

A general explanation from the "Data Model" chapter in the Python Language Reference":

The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable.

(The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.)

An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

How do I get indices of N maximum values in a NumPy array?

If you happen to be working with a multidimensional array then you'll need to flatten and unravel the indices:

def largest_indices(ary, n):
    """Returns the n largest indices from a numpy array."""
    flat = ary.flatten()
    indices = np.argpartition(flat, -n)[-n:]
    indices = indices[np.argsort(-flat[indices])]
    return np.unravel_index(indices, ary.shape)

For example:

>>> xs = np.sin(np.arange(9)).reshape((3, 3))
>>> xs
array([[ 0.        ,  0.84147098,  0.90929743],
       [ 0.14112001, -0.7568025 , -0.95892427],
       [-0.2794155 ,  0.6569866 ,  0.98935825]])
>>> largest_indices(xs, 3)
(array([2, 0, 0]), array([2, 2, 1]))
>>> xs[largest_indices(xs, 3)]
array([ 0.98935825,  0.90929743,  0.84147098])

How can I put CSS and HTML code in the same file?

There's a style tag, so you could do something like this:

<style type="text/css">
  .title 
  {
    color: blue;
    text-decoration: bold;
    text-size: 1em;
  }
</style>

Python dictionary get multiple values

There already exists a function for this:

from operator import itemgetter

my_dict = {x: x**2 for x in range(10)}

itemgetter(1, 3, 2, 5)(my_dict)
#>>> (1, 9, 4, 25)

itemgetter will return a tuple if more than one argument is passed. To pass a list to itemgetter, use

itemgetter(*wanted_keys)(my_dict)

Keep in mind that itemgetter does not wrap its output in a tuple when only one key is requested, and does not support zero keys being requested.

How do I make a dictionary with multiple keys to one value?

It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.

let's go to the code example,

In [6]: a = 10

In [7]: id(a)
Out[7]: 10914656

In [8]: b = 10

In [9]: id(b)
Out[9]: 10914656

In [10]: c = 11

In [11]: id(c)
Out[11]: 10914688

In [12]: d = 21

In [13]: id(d)
Out[13]: 10915008

In [14]: e = 11

In [15]: id(e)
Out[15]: 10914688

In [16]: e = 21

In [17]: id(e)
Out[17]: 10915008

In [18]: e is d
Out[18]: True
In [19]: e = 30

In [20]: id(e)
Out[20]: 10915296

From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.

so any variable which is having same value shares the memory.

Not for list and dictionary objects

let's come to your question.

when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.

you can simply use it like this

In [49]: dictionary = {
    ...:     'k1':1,
    ...:     'k2':1,
    ...:     'k3':2,
    ...:     'k4':2}
    ...:     
    ...:     

In [50]: id(dictionary['k1'])
Out[50]: 10914368

In [51]: id(dictionary['k2'])
Out[51]: 10914368

In [52]: id(dictionary['k3'])
Out[52]: 10914400

In [53]: id(dictionary['k4'])
Out[53]: 10914400

From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P

What do \t and \b do?

Backspace and tab both move the cursor position. Neither is truly a 'printable' character.

Your code says:

  1. print "foo"
  2. move the cursor back one space
  3. move the cursor forward to the next tabstop
  4. output "bar".

To get the output you expect, you need printf("foo\b \tbar"). Note the extra 'space'. That says:

  1. output "foo"
  2. move the cursor back one space
  3. output a ' ' (this replaces the second 'o').
  4. move the cursor forward to the next tabstop
  5. output "bar".

Most of the time it is inappropriate to use tabs and backspace for formatting your program output. Learn to use printf() formatting specifiers. Rendering of tabs can vary drastically depending on how the output is viewed.

This little script shows one way to alter your terminal's tab rendering. Tested on Ubuntu + gnome-terminal:

#!/bin/bash
tabs -8 
echo -e "\tnormal tabstop"
for x in `seq 2 10`; do
  tabs $x
  echo -e "\ttabstop=$x"
 done

tabs -8
echo -e "\tnormal tabstop"

Also see man setterm and regtabs.

And if you redirect your output or just write to a file, tabs will quite commonly be displayed as fewer than the standard 8 chars, especially in "programming" editors and IDEs.

So in otherwords:

printf("%-8s%s", "foo", "bar"); /* this will ALWAYS output "foo     bar" */
printf("foo\tbar"); /* who knows how this will be rendered */

IMHO, tabs in general are rarely appropriate for anything. An exception might be generating output for a program that requires tab-separated-value input files (similar to comma separated value).

Backspace '\b' is a different story... it should never be used to create a text file since it will just make a text editor spit out garbage. But it does have many applications in writing interactive command line programs that cannot be accomplished with format strings alone. If you find yourself needing it a lot, check out "ncurses", which gives you much better control over where your output goes on the terminal screen. And typically, since it's 2011 and not 1995, a GUI is usually easier to deal with for highly interactive programs. But again, there are exceptions. Like writing a telnet server or console for a new scripting language.

Shell Script Syntax Error: Unexpected End of File

echo"==================PS COMMAND SNAPSHOT=============================================================="

needs to be

echo "==================PS COMMAND SNAPSHOT=============================================================="

Else, a program or command named echo"===... is searched.

more problems:

If you do a grep (-A1: + 1 line context)

grep -A1 "if " cldtest.sh 

you find some embedded ifs, and 4 if/then blocks.

grep "fi " cldtest.sh 

only reveals 3 matching fi statements. So you forgot one fi too.

I agree with camh, that correct indentation from the beginning helps to avoid such errors. Finding the desired way later means double work in such spaghetti code.

Adding a new value to an existing ENUM Type

PostgreSQL 9.1 introduces ability to ALTER Enum types:

ALTER TYPE enum_type ADD VALUE 'new_value'; -- appends to list
ALTER TYPE enum_type ADD VALUE 'new_value' BEFORE 'old_value';
ALTER TYPE enum_type ADD VALUE 'new_value' AFTER 'old_value';

MySQL and PHP - insert NULL rather than empty string

To pass a NULL to MySQL, you do just that.

INSERT INTO table (field,field2) VALUES (NULL,3)

So, in your code, check if $intLat, $intLng are empty, if they are, use NULL instead of '$intLat' or '$intLng'.

$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  $intLat, $intLng)";

Postgres ERROR: could not open file for reading: Permission denied

Assuming the psql command-line tool, you may use \copy instead of copy.

\copy opens the file and feeds the contents to the server, whereas copy tells the server the open the file itself and read it, which may be problematic permission-wise, or even impossible if client and server run on different machines with no file sharing in-between.

Under the hood, \copy is implemented as COPY FROM stdin and accepts the same options than the server-side COPY.

How to calculate the sum of the datatable column in asp.net?

 this.LabelControl.Text = datatable.AsEnumerable()
    .Sum(x => x.Field<int>("Amount"))
    .ToString();

If you want to filter the results:

 this.LabelControl.Text = datatable.AsEnumerable()
    .Where(y => y.Field<string>("SomeCol") != "foo")
    .Sum(x => x.Field<int>("MyColumn") )
    .ToString();

What is the default font of Sublime Text?

On Linux it's Monospace 10 pt. (the exact monospace font used may vary on different Linux distributions or versions), on Windows it's Consolas 10 pt., and on OS X it's Menlo Regular 12 pt.

default platform preferences

(The color scheme is Neon, the syntax highlighting is from PackageDev, and the font is Liberation Mono

This information is found in the Packages/Default directory (where Packages is the directory opened by the Preferences ? Browse Packages... menu option), in the Preferences (OS).sublime-settings file where OS is one of Windows, Linux, or OSX.

You should only customize the font (or any other setting) in Packages/User/Preferences.sublime-settings, opened by Preferences ? Settings—User, as Settings—Default is over-written on upgrade, and also serves as a backup in case you really screw something up in your user settings. This is the case for both the main Sublime settings as well as those for extra packages/plugins.

These default fonts are the same in Sublime Text 2, Sublime Text 3, and the new version currently in development.

How to retry image pull in a kubernetes Pods?

Try with deleting pod it will try to pull image again.

kubectl delete pod <pod_name> -n <namespace_name>

How to make an HTTP get request with parameters

My preferred way is this. It handles the escaping and parsing for you.

WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");

Git commit date

You can use the git show command.

To get the last commit date from git repository in a long(Unix epoch timestamp):

  • Command: git show -s --format=%ct
  • Result: 1605103148

Note: You can visit the git-show documentation to get a more detailed description of the options.

What is a callback in java

In Java, callback methods are mainly used to address the "Observer Pattern", which is closely related to "Asynchronous Programming".

Although callbacks are also used to simulate passing methods as a parameter, like what is done in functional programming languages.

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

After having all the proposed solutions fail my tests one way or the other, (edit: some were updated to pass the tests after I wrote this) I found the mozilla implementation for Array.indexOf and Array.lastIndexOf

I used those to implement my version of String.prototype.regexIndexOf and String.prototype.regexLastIndexOf as follows:

String.prototype.regexIndexOf = function(elt /*, from*/)
  {
    var arr = this.split('');
    var len = arr.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0) ? Math.ceil(from) : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++) {
      if (from in arr && elt.exec(arr[from]) ) 
        return from;
    }
    return -1;
};

String.prototype.regexLastIndexOf = function(elt /*, from*/)
  {
    var arr = this.split('');
    var len = arr.length;

    var from = Number(arguments[1]);
    if (isNaN(from)) {
      from = len - 1;
    } else {
      from = (from < 0) ? Math.ceil(from) : Math.floor(from);
      if (from < 0)
        from += len;
      else if (from >= len)
        from = len - 1;
    }

    for (; from > -1; from--) {
      if (from in arr && elt.exec(arr[from]) )
        return from;
    }
    return -1;
  };

They seem to pass the test functions I provided in the question.

Obviously they only work if the regular expression matches one character but that is enough for my purpose since I will be using it for things like ( [abc] , \s , \W , \D )

I will keep monitoring the question in case someone provides a better/faster/cleaner/more generic implementation that works on any regular expression.

jquery append external html file into my page

Use html instead of append:

$.get("banner.html", function(data){
    $(this).children("div:first").html(data);
});

Fetch first element which matches criteria

This might be what you are looking for:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .get();

And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .orElse(null); /* You could also create a default object here */


An example:
public static void main(String[] args) {
    class Stop {
        private final String stationName;
        private final int    passengerCount;

        Stop(final String stationName, final int passengerCount) {
            this.stationName    = stationName;
            this.passengerCount = passengerCount;
        }
    }

    List<Stop> stops = new LinkedList<>();

    stops.add(new Stop("Station1", 250));
    stops.add(new Stop("Station2", 275));
    stops.add(new Stop("Station3", 390));
    stops.add(new Stop("Station2", 210));
    stops.add(new Stop("Station1", 190));

    Stop firstStopAtStation1 = stops.stream()
            .filter(e -> e.stationName.equals("Station1"))
            .findFirst()
            .orElse(null);

    System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}

Output is:

At the first stop at Station1 there were 250 passengers in the train.

How do I measure time elapsed in Java?

It is worth noting that

  • System.currentTimeMillis() has only millisecond accuracy at best. At worth its can be 16 ms on some windows systems. It has a lower cost that alternatives < 200 ns.
  • System.nanoTime() is only micro-second accurate on most systems and can jump on windows systems by 100 microseconds (i.e sometimes it not as accurate as it appears)
  • Calendar is a very expensive way to calculate time. (i can think of apart from XMLGregorianCalendar) Sometimes its the most appropriate solution but be aware you should only time long intervals.

How do I make HttpURLConnection use a proxy?

Since java 1.5 you can also pass a java.net.Proxy instance to the openConnection(proxy) method:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

If your proxy requires authentication it will give you response 407.

In this case you'll need the following code:

    Authenticator authenticator = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication("user",
                    "password".toCharArray()));
        }
    };
    Authenticator.setDefault(authenticator);

bootstrap jquery show.bs.modal event won't fire

In my case the problem was how travelsize comment.. The order of imports between bootstrap.js and jquery. Because I'am using the template Metronic and doesn't check before

Dynamically Dimensioning A VBA Array?

You need to use a constant.

CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies

or if you want to use a variable you have to do it this way:

Dim NumberOfZombies As Integer
NumberOfZombies = 20000

Dim Zombies() As Zombies

ReDim Zombies(NumberOfZombies)

How to create an empty matrix in R?

To get rid of the first column of NAs, you can do it with negative indexing (which removes indices from the R data set). For example:

output = matrix(1:6, 2, 3) # gives you a 2 x 3 matrix filled with the numbers 1 to 6

# output = 
#           [,1] [,2] [,3]
#     [1,]    1    3    5
#     [2,]    2    4    6

output = output[,-1] # this removes column 1 for all rows

# output = 
#           [,1] [,2]
#     [1,]    3    5
#     [2,]    4    6

So you can just add output = output[,-1]after the for loop in your original code.

Is it not possible to stringify an Error using JSON.stringify?

As no one is talking about the why part, I'm gonna answer it.

Why this JSON.stringify returns an empty object?

> JSON.stringify(error);
'{}'

Answer

From the document of JSON.stringify(),

For all the other Object instances (including Map, Set, WeakMap and WeakSet), only their enumerable properties will be serialized.

and Error object doesn't have its enumerable properties, that's why it prints an empty object.

Jackson serialization: ignore empty values (or null)

I was having similar problem recently with version 2.6.6.

@JsonInclude(JsonInclude.Include.NON_NULL)

Using above annotation either on filed or class level was not working as expected. The POJO was mutable where I was applying the annotation. When I changed the behaviour of the POJO to be immutable the annotation worked its magic.

I am not sure if its down to new version or previous versions of this lib had similar behaviour but for 2.6.6 certainly you need to have Immutable POJO for the annotation to work.

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

Above option mentioned in various answers of setting serialisation inclusion in ObjectMapper directly at global level works as well but, I prefer controlling it at class or filed level.

So if you wanted all the null fields to be ignored while JSON serialisation then use the annotation at class level but if you want only few fields to ignored in a class then use it over those specific fields. This way its more readable & easy for maintenance if you wanted to change behaviour for specific response.

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

Here is a macro that I use for that purpose. It will generate a constructor from fields and properties that have a private setter.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Collections.Generic

Public Module Temp

    Sub AddConstructorFromFields()
        DTE.UndoContext.Open("Add constructor from fields")

        Dim classElement As CodeClass, index As Integer
        GetClassAndInsertionIndex(classElement, index)

        Dim constructor As CodeFunction
        constructor = classElement.AddFunction(classElement.Name, vsCMFunction.vsCMFunctionConstructor, vsCMTypeRef.vsCMTypeRefVoid, index, vsCMAccess.vsCMAccessPublic)

        Dim visitedNames As New Dictionary(Of String, String)
        Dim element As CodeElement, parameterPosition As Integer, isFirst As Boolean = True
        For Each element In classElement.Children
            Dim fieldType As String
            Dim fieldName As String
            Dim parameterName As String

            Select Case element.Kind
                Case vsCMElement.vsCMElementVariable
                    Dim field As CodeVariable = CType(element, CodeVariable)
                    fieldType = field.Type.AsString
                    fieldName = field.Name
                    parameterName = field.Name.TrimStart("_".ToCharArray())

                Case vsCMElement.vsCMElementProperty
                    Dim field As CodeProperty = CType(element, CodeProperty)
                    If field.Setter.Access = vsCMAccess.vsCMAccessPrivate Then
                        fieldType = field.Type.AsString
                        fieldName = field.Name
                        parameterName = field.Name.Substring(0, 1).ToLower() + field.Name.Substring(1)
                    End If
            End Select

            If Not String.IsNullOrEmpty(parameterName) And Not visitedNames.ContainsKey(parameterName) Then
                visitedNames.Add(parameterName, parameterName)

                constructor.AddParameter(parameterName, fieldType, parameterPosition)

                Dim endPoint As EditPoint
                endPoint = constructor.EndPoint.CreateEditPoint()
                endPoint.LineUp()
                endPoint.EndOfLine()

                If Not isFirst Then
                    endPoint.Insert(Environment.NewLine)
                Else
                    isFirst = False
                End If

                endPoint.Insert(String.Format(MemberAssignmentFormat(constructor.Language), fieldName, parameterName))

                parameterPosition = parameterPosition + 1
            End If
        Next

        DTE.UndoContext.Close()

        Try
            ' This command fails sometimes '
            DTE.ExecuteCommand("Edit.FormatDocument")
        Catch ex As Exception
        End Try
    End Sub
    Private Sub GetClassAndInsertionIndex(ByRef classElement As CodeClass, ByRef index As Integer, Optional ByVal useStartIndex As Boolean = False)
        Dim selection As TextSelection
        selection = CType(DTE.ActiveDocument.Selection, TextSelection)

        classElement = CType(selection.ActivePoint.CodeElement(vsCMElement.vsCMElementClass), CodeClass)

        Dim childElement As CodeElement
        index = 0
        For Each childElement In classElement.Children
            Dim childOffset As Integer
            childOffset = childElement.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes).AbsoluteCharOffset
            If selection.ActivePoint.AbsoluteCharOffset < childOffset Or useStartIndex Then
                Exit For
            End If
            index = index + 1
        Next
    End Sub
    Private ReadOnly Property MemberAssignmentFormat(ByVal language As String) As String
        Get
            Select Case language
                Case CodeModelLanguageConstants.vsCMLanguageCSharp
                    Return "this.{0} = {1};"

                Case CodeModelLanguageConstants.vsCMLanguageVB
                    Return "Me.{0} = {1}"

                Case Else
                    Return ""
            End Select
        End Get
    End Property
End Module

Simple way to copy or clone a DataRow?

But to make sure that your new row is accessible in the new table, you need to close the table:

DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);

Pip install Matplotlib error with virtualenv

Under Windows this worked for me:

python -m pip install -U pip setuptools
python -m pip install matplotlib

(from https://matplotlib.org/users/installing.html)

Conda environments not showing up in Jupyter Notebook

This worked for me in windows 10 and latest solution :

1) Go inside that conda environment ( activate your_env_name )

2) conda install -n your_env_name ipykernel

3) python -m ipykernel install --user --name build_central --display-name "your_env_name"

(NOTE : Include the quotes around "your_env_name", in step 3)

How do I get the unix timestamp in C as an int?

With second precision, you can print tv_sec field of timeval structure that you get from gettimeofday() function. For example:

#include <sys/time.h>
#include <stdio.h>

int main()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    printf("Seconds since Jan. 1, 1970: %ld\n", tv.tv_sec);
    return 0;
}

Example of compiling and running:

$ gcc -Wall -o test ./test.c 
$ ./test 
Seconds since Jan. 1, 1970: 1343845834

Note, however, that its been a while since epoch and so long int is used to fit a number of seconds these days.

There are also functions to print human-readable times. See this manual page for details. Here goes an example using ctime():

#include <time.h>
#include <stdio.h>

int main()
{
    time_t clk = time(NULL);
    printf("%s", ctime(&clk));
    return 0;
}

Example run & output:

$ gcc -Wall -o test ./test.c 
$ ./test 
Wed Aug  1 14:43:23 2012
$ 

Show animated GIF

//Class Name
public class ClassName {
//Make it runnable
public static void main(String args[]) throws MalformedURLException{
//Get the URL
URL img = this.getClass().getResource("src/Name.gif");
//Make it to a Icon
Icon icon = new ImageIcon(img);
//Make a new JLabel that shows "icon"
JLabel Gif = new JLabel(icon);

//Make a new Window
JFrame main = new JFrame("gif");
//adds the JLabel to the Window
main.getContentPane().add(Gif);
//Shows where and how big the Window is
main.setBounds(x, y, H, W);
//set the Default Close Operation to Exit everything on Close
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Open the Window
main.setVisible(true);
   }
}

How do you round a floating point number in Perl?

Whilst not disagreeing with the complex answers about half-way marks and so on, for the more common (and possibly trivial) use-case:

my $rounded = int($float + 0.5);

UPDATE

If it's possible for your $float to be negative, the following variation will produce the correct result:

my $rounded = int($float + $float/abs($float*2 || 1));

With this calculation -1.4 is rounded to -1, and -1.6 to -2, and zero won't explode.

How to include *.so library in Android Studio?

To use native-library (so files) You need to add some codes in the "build.gradle" file.

This code is for cleaing "armeabi" directory and copying 'so' files into "armeabi" while 'clean project'.

task copyJniLibs(type: Copy) {
    from 'libs/armeabi'
    into 'src/main/jniLibs/armeabi'
}
tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(copyJniLibs)
}
clean.dependsOn 'cleanCopyJniLibs'

I've been referred from the below. https://gist.github.com/pocmo/6461138

How to publish a website made by Node.js to Github Pages?

I was able to set up github actions to automatically commit the results of a node build command (yarn build in my case but it should work with npm too) to the gh-pages branch whenever a new commit is pushed to master.

While not completely ideal as i'd like to avoid committing the built files, it seems like this is currently the only way to publish to github pages.

I based my workflow off of this guide for a different react library, and had to make the following changes to get it to work for me:

  • updated the "setup node" step to use the version found here since the one from the sample i was basing it off of was throwing errors because it could not find the correct action.
  • remove the line containing yarn export because that command does not exist and it doesn't seem to add anything helpful (you may also want to change the build line above it to suit your needs)
  • I also added an env directive to the yarn build step so that I can include the SHA hash of the commit that generated the build inside my app, but this is optional

Here is my full github action:

name: github pages

on:
    push:
        branches:
        - master

jobs:
    deploy:
        runs-on: ubuntu-18.04
        steps:
        - uses: actions/checkout@v2

        - name: Setup Node
            uses: actions/setup-node@v2-beta
            with:
            node-version: '12'

        - name: Get yarn cache
            id: yarn-cache
            run: echo "::set-output name=dir::$(yarn cache dir)"

        - name: Cache dependencies
            uses: actions/cache@v2
            with:
            path: ${{ steps.yarn-cache.outputs.dir }}
            key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
            restore-keys: |
                ${{ runner.os }}-yarn-
        - run: yarn install --frozen-lockfile
        - run: yarn build
            env:
            REACT_APP_GIT_SHA: ${{ github.SHA }}

        - name: Deploy
            uses: peaceiris/actions-gh-pages@v3
            with:
            github_token: ${{ secrets.GITHUB_TOKEN }}
            publish_dir: ./build

Alternative solution

The docs for next.js also provides instructions for setting up with Vercel which appears to be a hosting service for node.js apps similar to github pages. I have not tried this though and so cannot speak to how well it works.

How do I prevent an Android device from going to sleep programmatically?

One option is to use a wake lock. Example from the docs:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();

// screen and CPU will stay awake during this section

wl.release();

There's also a table on this page that describes the different kinds of wakelocks.

Be aware that some caution needs to be taken when using wake locks. Ensure that you always release() the lock when you're done with it (or not in the foreground). Otherwise your app can potentially cause some serious battery drain and CPU usage.

The documentation also contains a useful page that describes different approaches to keeping a device awake, and when you might choose to use one. If "prevent device from going to sleep" only refers to the screen (and not keeping the CPU active) then a wake lock is probably more than you need.

You also need to be sure you have the WAKE_LOCK permission set in your manifest in order to use this method.

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

You can check that theHref is defined by checking against undefined.

if (undefined !== theHref && theHref.length) {
    // `theHref` is not undefined and has truthy property _length_
    // do stuff
} else {
    // do other stuff
}

If you want to also protect yourself against falsey values like null then check theHref is truthy, which is a little shorter

if (theHref && theHref.length) {
    // `theHref` is truthy and has truthy property _length_
}

What is the correct way to start a mongod service on linux / OS X?

If you feel like having a simple gui to fix this (as I do), then I can recommend the mongodb pref-pane. Description: https://www.mongodb.com/blog/post/macosx-preferences-pane-for-mongodb

On github: https://github.com/remysaissy/mongodb-macosx-prefspane

Python csv string to array

Use this to have a csv loaded into a list

import csv

csvfile = open(myfile, 'r')
reader = csv.reader(csvfile, delimiter='\t')
my_list = list(reader)
print my_list
>>>[['1st_line', '0'],
    ['2nd_line', '0']]

How to clear text area with a button in html using javascript?

You need to attach a click event handler and clear the contents of the textarea from that handler.

HTML

<input type="button" value="Clear" id="clear"> 
<textarea id='output' rows=20 cols=90></textarea>

JS

var input = document.querySelector('#clear');
var textarea = document.querySelector('#output');

input.addEventListener('click', function () {
    textarea.value = '';
}, false);

and here's the working demo.

How do I copy the contents of a String to the clipboard in C#?

Using the solution showed in this question, System.Windows.Forms.Clipboard.SetText(...), results in the exception:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made

To prevent this, you can add the attribute:

[STAThread]

to

static void Main(string[] args)

If statements for Checkboxes

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if (checkBoxImage.Checked)
    {
        groupBoxImage.Show();
    }
    else if (!checkBoxImage.Checked)
    {
        groupBoxImage.Hide(); 
    }
}

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

How can I pretty-print JSON using node.js?

Another workaround would be to make use of prettier to format the JSON. The example below is using 'json' parser but it could also use 'json5', see list of valid parsers.

const prettier = require("prettier");
console.log(prettier.format(JSON.stringify(object),{ semi: false, parser: "json" }));

How do I get cURL to not show the progress bar?

Since curl 7.67.0 (2019-11-06) there is --no-progress-meter, which does exactly this, and nothing else. From the man page:

   --no-progress-meter
         Option to switch off the progress meter output without muting or
         otherwise affecting warning and informational messages like  -s,
         --silent does.

         Note  that  this  is the negated option name documented. You can
         thus use --progress-meter to enable the progress meter again.

         See also -v, --verbose and -s, --silent. Added in 7.67.0.

It's available in Ubuntu =20.04 and Debian =11 (Bullseye).

For a bit of history on curl's verbosity options, you can read Daniel Stenberg's blog post.

Adding a Button to a WPF DataGrid

Check this out:

XAML:

<DataGrid Name="DataGrid1">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Click="ChangeText">Show/Hide</Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Method:

private void ChangeText(object sender, RoutedEventArgs e)
{
    DemoModel model = (sender as Button).DataContext as DemoModel;
    model.DynamicText = (new Random().Next(0, 100).ToString());
}

Class:

class DemoModel : INotifyPropertyChanged
{
    protected String _text;
    public String Text
    {
        get { return _text; }
        set { _text = value; RaisePropertyChanged("Text"); }
    }

    protected String _dynamicText;
    public String DynamicText
    {
        get { return _dynamicText; }
        set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null)
        {
            temp(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Initialization Code:

ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;

Why are static variables considered evil?

Seems to me that you're asking about static variables but you also point out static methods in your examples.

Static variables are not evil - they have its adoption as global variables like constants in most cases combined with final modifier, but as it said don't overuse them.

Static methods aka utility method. It isn't generally a bad practice to use them but major concern is that they might obstruct testing.

As a example of great java project that use a lot of statics and do it right way please look at Play! framework. There is also discussion about it in SO.

Static variables/methods combined with static import are also widely used in libraries that facilitate declarative programming in java like: make it easy or Hamcrest. It wouldn't be possible without a lot of static variables and methods.

So static variables (and methods) are good but use them wisely!

Ways to insert javascript into URL?

I believe the right answer is "it depends".

As others have pointed out, if the web application that is processing your request is naively receiving and echoing back the received payload or URL parameters (for GET requests) then it might be subject to code injection.

However, if the web application sanitizes and/or filters payload/parameters, it shouldn't be a problem.

It also depends on the user agent (e.g. browser), a customized user agent might inject code without user notice if it detects any in the request (don't know of any public one, but that is also possible).

Cursor inside cursor

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

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

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

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

Foreign key constraint may cause cycles or multiple cascade paths?

I would point out that (functionally) there's a BIG difference between cycles and/or multiple paths in the SCHEMA and the DATA. While cycles and perhaps multipaths in the DATA could certainly complicated processing and cause performance problems (cost of "properly" handling), the cost of these characteristics in the schema should be close to zero.

Since most apparent cycles in RDBs occur in hierarchical structures (org chart, part, subpart, etc.) it is unfortunate that SQL Server assumes the worst; i.e., schema cycle == data cycle. In fact, if you're using RI constraints you can't actually build a cycle in the data!

I suspect the multipath problem is similar; i.e., multiple paths in the schema don't necessarily imply multiple paths in the data, but I have less experience with the multipath problem.

Of course if SQL Server did allow cycles it'd still be subject to a depth of 32, but that's probably adequate for most cases. (Too bad that's not a database setting however!)

"Instead of Delete" triggers don't work either. The second time a table is visited, the trigger is ignored. So, if you really want to simulate a cascade you'll have to use stored procedures in the presence of cycles. The Instead-of-Delete-Trigger would work for multipath cases however.

Celko suggests a "better" way to represent hierarchies that doesn't introduce cycles, but there are tradeoffs.

How do I test a private function or a class that has private methods, fields or inner classes?

Another approach I have used is to change a private method to package private or protected then complement it with the @VisibleForTesting annotation of the Google Guava library.

This will tell anybody using this method to take caution and not access it directly even in a package. Also a test class need not be in same package physically, but in the same package under the test folder.

For example, if a method to be tested is in src/main/java/mypackage/MyClass.java then your test call should be placed in src/test/java/mypackage/MyClassTest.java. That way, you got access to the test method in your test class.

Disable a link in Bootstrap

It seems that Bootstrap doesn't support disabled links. Instead of trying to add a Bootstrap class, you could add a class by your own and add some styling to it, just like this:

_x000D_
_x000D_
a.disabled {_x000D_
  /* Make the disabled links grayish*/_x000D_
  color: gray;_x000D_
  /* And disable the pointer events */_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<!-- Make the disabled links unfocusable as well -->_x000D_
<a href="#" class="disabled" tabindex="-1">Link to disable</a><br/>_x000D_
<a href="#">Non-disabled Link</a>
_x000D_
_x000D_
_x000D_

Convert JSON to Map

I hope you were joking about writing your own parser. :-)

For such a simple mapping, most tools from http://json.org (section java) would work. For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:

Map<String,Object> result =
        new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);

(where JSON_SOURCE is a File, input stream, reader, or json content String)

Can I stop 100% Width Text Boxes from extending beyond their containers?

What you could do is to remove the default "extras" on the input:

input.wide {display:block; width:100%;padding:0;border-width:0}

This will keep the input inside its container. Now if you do want the borders, wrap the input in a div, with the borders set on the div (that way you can remove the display:block from the input too). Something like:

<div style="border:1px solid gray;">
 <input type="text" class="wide" />
</div>

Edit: Another option is to, instead of removing the style from the input, compensate for it in the wrapped div:

input.wide {width:100%;}

<div style="padding-right:4px;padding-left:1px;margin-right:2px">
  <input type="text" class="wide" />
</div>

This will give you somewhat different results in different browsers, but they will not overlap the container. The values in the div depend on how large the border is on the input and how much space you want between the input and the border.

exceeds the list view threshold 5000 items in Sharepoint 2010

You can increase the List View Threshold beyond the 5,000 default, but it is highly recommended that you don't, as it has performance implications. The recommended fix is to add an index to the field or fields used in the query (usually the ID field for a list or the Title field for a library).

When there is an index, that is used to retrieve the item(s); when there is no index the whole list is opened for a scan (and therefore hits the threshold). You create the index on the List (or Library) settings page.

This article is a good overview: http://office.microsoft.com/en-us/sharepoint-foundation-help/manage-lists-and-libraries-with-many-items-HA010377496.aspx

What is (x & 1) and (x >>= 1)?

In addition to the answer of "dasblinkenlight" I think an example could help. I will only use 8 bits for a better understanding.

x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.

This is because 1 will be represented in bits as 00000001. Only the last bit is set to 1. Let's assume x is 185 which will be represented in bits as 10111001. If you apply a bitwise AND operation on x with 1 this will be the result:

00000001
10111001
--------
00000001

The first seven bits of the operation result will be 0 after the operation and will carry no information in this case (see Logical AND operation). Because whatever the first seven bits of the operand x were before, after the operation they will be 0. But the last bit of the operand 1 is 1 and it will reveal if the last bit of operand x was 0 or 1. So in this example the result of the bitwise AND operation will be 1 because our last bit of x is 1. If the last bit would have been 0, then the result would have been also 0, indicating that the last bit of operand x is 0:

00000001
10111000
--------
00000000

x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift

Let's pick the example from above. For x >>= 1 this would be:

10111001
--------
01011100

And for left shift x <<= 1 it would be:

10111001
--------
01110010

Please pay attention to the note of user "dasblinkenlight" in regard to shifts.

Fastest way to list all primes below N

I collected several prime number sieves over time. The fastest on my computer is this:

from time import time
# 175 ms for all the primes up to the value 10**6
def primes_sieve(limit):
    a = [True] * limit
    a[0] = a[1] = False
    #a[2] = True
    for n in xrange(4, limit, 2):
        a[n] = False
    root_limit = int(limit**.5)+1
    for i in xrange(3,root_limit):
        if a[i]:
            for n in xrange(i*i, limit, 2*i):
                a[n] = False
    return a

LIMIT = 10**6
s=time()
primes = primes_sieve(LIMIT)
print time()-s

Can I have onScrollListener for a ScrollView?

Here's a derived HorizontalScrollView I wrote to handle notifications about scrolling and scroll ending. It properly handles when a user has stopped actively scrolling and when it fully decelerates after a user lets go:

public class ObservableHorizontalScrollView extends HorizontalScrollView {
    public interface OnScrollListener {
        public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY);
        public void onEndScroll(ObservableHorizontalScrollView scrollView);
    }

    private boolean mIsScrolling;
    private boolean mIsTouching;
    private Runnable mScrollingRunnable;
    private OnScrollListener mOnScrollListener;

    public ObservableHorizontalScrollView(Context context) {
        this(context, null, 0);
    }

    public ObservableHorizontalScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ObservableHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        int action = ev.getAction();

        if (action == MotionEvent.ACTION_MOVE) {
            mIsTouching = true;
            mIsScrolling = true;
        } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            if (mIsTouching && !mIsScrolling) {
                if (mOnScrollListener != null) {
                    mOnScrollListener.onEndScroll(this);
                }
            }

            mIsTouching = false;
        }

        return super.onTouchEvent(ev);
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);

        if (Math.abs(oldX - x) > 0) {
            if (mScrollingRunnable != null) {
                removeCallbacks(mScrollingRunnable);
            }

            mScrollingRunnable = new Runnable() {
                public void run() {
                    if (mIsScrolling && !mIsTouching) {
                        if (mOnScrollListener != null) {
                            mOnScrollListener.onEndScroll(ObservableHorizontalScrollView.this);
                        }
                    }

                    mIsScrolling = false;
                    mScrollingRunnable = null;
                }
            };

            postDelayed(mScrollingRunnable, 200);
        }

        if (mOnScrollListener != null) {
            mOnScrollListener.onScrollChanged(this, x, y, oldX, oldY);
        }
    }

    public OnScrollListener getOnScrollListener() {
        return mOnScrollListener;
    }

    public void setOnScrollListener(OnScrollListener mOnEndScrollListener) {
        this.mOnScrollListener = mOnEndScrollListener;
    }

}

What are best practices for REST nested resources?

What you have done is correct. In general there can be many URIs to the same resource - there are no rules that say you shouldn't do that.

And generally, you may need to access items directly or as a subset of something else - so your structure makes sense to me.

Just because employees are accessible under department:

company/{companyid}/department/{departmentid}/employees

Doesn't mean they can't be accessible under company too:

company/{companyid}/employees

Which would return employees for that company. It depends on what is needed by your consuming client - that is what you should be designing for.

But I would hope that all URLs handlers use the same backing code to satisfy the requests so that you aren't duplicating code.

Is there a way to specify a default property value in Spring XML?

The default value can be followed with a : after the property key, e.g.

<property name="port" value="${my.server.port:8080}" />

Or in java code:

@Value("${my.server.port:8080}")
private String myServerPort;

See:

BTW, the Elvis Operator is only available within Spring Expression Language (SpEL),
e.g.: https://stackoverflow.com/a/37706167/537554

Copy files without overwrite

There is an odd way to do this with xcopy:

echo nnnnnnnnnnn | xcopy /-y source target

Just include as many n's as files you're copying, and it will answer n to all of the overwrite questions.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

Ok, so the answer was derived from some other posts about this problem and it is:

If your ViewData contains a SelectList with the same name as your DropDownList i.e. "submarket_0", the Html helper will automatically populate your DropDownList with that data if you don't specify the 2nd parameter which in this case is the source SelectList.

What happened with my error was:

Because the table containing the drop down lists was in a partial view and the ViewData had been changed and no longer contained the SelectList I had referenced, the HtmlHelper (instead of throwing an error) tried to find the SelectList called "submarket_0" in the ViewData (GRRRR!!!) which it STILL couldnt find, and then threw an error on that :)

Please correct me if im wrong

PowerShell and the -contains operator

The -Contains operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.

From the documentation you linked to:

-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.

In the example you provided you're working with a collection containing just one string item.

If you read the documentation you linked to you'll see an example that demonstrates this behaviour:

Examples:

PS C:\> "abc", "def" -Contains "def"
True

PS C:\> "Windows", "PowerShell" -Contains "Shell"
False  #Not an exact match

I think what you want is the -Match operator:

"12-18" -Match "-"

Which returns True.

Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match operator uses regular expressions to perform text matching.

How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?

I have faced this problem when installing the Visual studio 2010 - C# express using the local administrator account, then trying to register the application using another account that doesn't have Admin privileges, due to corporate polices this account can’t edit in the Registry by any means, so suddenly that’s how I figured out how to solve this issue I open VS 2010 as a local administrator then entered the registration key, and it is worked , I don’t understand how do that Microsoft itself didn’t mention this solution or even try hard to investigate or solve this issue

Unit tests vs Functional tests

Unit Tests are written from a programmers or developers perspective. They are made to ensure that a particular method (or a unit) of a class performs a set of specific tasks.

Functional Tests are written from the user's perspective. They ensure that the system is functioning as users are expecting it to.

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

some problem, but I find the solution, this is :


2 February Feb 28 (29 in leap years)

this is my code

 public string GetCountArchiveByMonth(int iii)
        {
// iii: is number of months, use any number other than (**2**)

            con.Open();

            SqlCommand cmd10 = con.CreateCommand();
            cmd10.CommandType = CommandType.Text;
            cmd10.CommandText = "select count(id_post) from posts where dateadded between CONVERT(VARCHAR, @start, 103) and CONVERT(VARCHAR, @end, 103)";
            cmd10.Parameters.AddWithValue("@start", "" + iii + "/01/2019");
            cmd10.Parameters.AddWithValue("@end", "" + iii + "/30/2019");
            string result = cmd10.ExecuteScalar().ToString();

            con.Close();

            return result;
        }

now for test

 lbl1.Text = GetCountArchiveByMonth(**7**).ToString();  // here use any number other than (**2**)

**

because of check **February** is maxed 28 days,

**

Material effect on button with background color

There are two approaches explained in the great tutorial be Alex Lockwood: http://www.androiddesignpatterns.com/2016/08/coloring-buttons-with-themeoverlays-background-tints.html:

Approach #1: Modifying the button’s background color w/ a ThemeOverlay

<!-- res/values/themes.xml -->
<style name="RedButtonLightTheme" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorAccent">@color/googred500</item>
</style>

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/RedButtonLightTheme"/>

Approach #2: Setting the AppCompatButton’s background tint

<!-- res/color/btn_colored_background_tint.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Disabled state. -->
    <item android:state_enabled="false"
          android:color="?attr/colorButtonNormal"
          android:alpha="?android:attr/disabledAlpha"/>

    <!-- Enabled state. -->
    <item android:color="?attr/colorAccent"/>

</selector>

<android.support.v7.widget.AppCompatButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:backgroundTint="@color/btn_colored_background_tint"/>

Copy output of a JavaScript variable to the clipboard

I just want to add, if someone wants to copy two different inputs to clipboard. I also used the technique of putting it to a variable then put the text of the variable from the two inputs into a text area.

Note: the code below is from a user asking how to copy multiple user inputs into clipboard. I just fixed it to work correctly. So expect some old style like the use of var instead of let or const. I also recommend to use addEventListener for the button.

_x000D_
_x000D_
    function doCopy() {_x000D_
_x000D_
        try{_x000D_
            var unique = document.querySelectorAll('.unique');_x000D_
            var msg ="";_x000D_
_x000D_
            unique.forEach(function (unique) {_x000D_
                msg+=unique.value;_x000D_
            });_x000D_
_x000D_
            var temp =document.createElement("textarea");_x000D_
            var tempMsg = document.createTextNode(msg);_x000D_
            temp.appendChild(tempMsg);_x000D_
_x000D_
            document.body.appendChild(temp);_x000D_
            temp.select();_x000D_
            document.execCommand("copy");_x000D_
            document.body.removeChild(temp);_x000D_
            console.log("Success!")_x000D_
_x000D_
_x000D_
        }_x000D_
        catch(err) {_x000D_
_x000D_
            console.log("There was an error copying");_x000D_
        }_x000D_
    }
_x000D_
<input type="text" class="unique" size="9" value="SESA / D-ID:" readonly/>_x000D_
<input type="text" class="unique" size="18" value="">_x000D_
<button id="copybtn" onclick="doCopy()"> Copy to clipboard </button>
_x000D_
_x000D_
_x000D_

How to get textLabel of selected row in swift?

This will work:

let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!

How to change Toolbar home icon color

Here is what you are looking for. But this also changes the color of radioButton etc. So you might want to use a theme for it.

<item name="colorControlNormal">@color/colorControlNormal</item>

Metadata file '.dll' could not be found

Most of the methods explained here did not solved the problem for me.

Finally, I fixed the problem by applying the following steps:

1. Close Visual Studio.

2. Delete all the contents in the bin folders of each project.

3. Open solution and rebuild.

Hope this helps.

Tab key == 4 spaces and auto-indent after curly braces in Vim

Related, if you open a file that uses both tabs and spaces, assuming you've got

set expandtab ts=4 sw=4 ai

You can replace all the tabs with spaces in the entire file with

:%retab

Get the latest record with filter in Django

obj= Model.objects.filter(testfield=12).order_by('-id')[:1] is the right solution

How to change a particular element of a C++ STL vector

at and operator[] both return a reference to the indexed element, so you can simply use:

l.at(4) = -1;

or

l[4] = -1;

Strict Standards: Only variables should be assigned by reference PHP 5.4

It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

Because on Unix, usually, the current directory is not in $PATH.

When you type a command the shell looks up a list of directories, as specified by the PATH variable. The current directory is not in that list.

The reason for not having the current directory on that list is security.

Let's say you're root and go into another user's directory and type sl instead of ls. If the current directory is in PATH, the shell will try to execute the sl program in that directory (since there is no other sl program). That sl program might be malicious.

It works with ./ because POSIX specifies that a command name that contain a / will be used as a filename directly, suppressing a search in $PATH. You could have used full path for the exact same effect, but ./ is shorter and easier to write.

EDIT

That sl part was just an example. The directories in PATH are searched sequentially and when a match is made that program is executed. So, depending on how PATH looks, typing a normal command may or may not be enough to run the program in the current directory.

Can not get a simple bootstrap modal to work

I run into this issue too. I was including bootstrap.js AND bootstrap-modal.js. If you already have bootstrap.js, you don't need to include popover.

Could not find the main class, program will exit

Tweaking MB's answer for windows, will get rid of the console window:

start javaw -jar squirrel-sql.jar

Select 50 items from list at random to write to file

One easy way to select random items is to shuffle then slice.

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables

"Actual or formal argument lists differs in length"

The default constructor has no arguments. You need to specify a constructor:

    public Friends( String firstName, String age) { ... }

git with development, staging and production branches

Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!

https://twitter.com/Beanstalkapp/status/306129447885631488

IE8 support for CSS Media Query

IE didn't add media query support until IE9. So with IE8 you're out of luck.

Check if a Class Object is subclass of another Class Object in Java

A recursive method to check if a Class<?> is a sub class of another Class<?>...

Improved version of @To Kra's answer:

protected boolean isSubclassOf(Class<?> clazz, Class<?> superClass) {
    if (superClass.equals(Object.class)) {
        // Every class is an Object.
        return true;
    }
    if (clazz.equals(superClass)) {
        return true;
    } else {
        clazz = clazz.getSuperclass();
        // every class is Object, but superClass is below Object
        if (clazz.equals(Object.class)) {
            // we've reached the top of the hierarchy, but superClass couldn't be found.
            return false;
        }
        // try the next level up the hierarchy.
        return isSubclassOf(clazz, superClass);
    }
}

PHP output showing little black diamonds with a question mark

This is a charset issue. As such, it can have gone wrong on many different levels, but most likely, the strings in your database are utf-8 encoded, and you are presenting them as iso-8859-1. Or the other way around.

The proper way to fix this problem, is to get your character-sets straight. The simplest strategy, since you're using PHP, is to use iso-8859-1 throughout your application. To do this, you must ensure that:

  • All PHP source-files are saved as iso-8859-1 (Not to be confused with cp-1252).
  • Your web-server is configured to serve files with charset=iso-8859-1
  • Alternatively, you can override the webservers settings from within the PHP-document, using header.
  • In addition, you may insert a meta-tag in you HTML, that specifies the same thing, but this isn't strictly needed.
  • You may also specify the accept-charset attribute on your <form> elements.
  • Database tables are defined with encoding as latin1
  • The database connection between PHP to and database is set to latin1

If you already have data in your database, you should be aware that they are probably messed up already. If you are not already in production phase, just wipe it all and start over. Otherwise you'll have to do some data cleanup.

A note on meta-tags, since everybody misunderstands what they are:

When a web-server serves a file (A HTML-document), it sends some information, that isn't presented directly in the browser. This is known as HTTP-headers. One such header, is the Content-Type header, which specifies the mimetype of the file (Eg. text/html) as well as the encoding (aka charset). While most webservers will send a Content-Type header with charset info, it's optional. If it isn't present, the browser will instead interpret any meta-tags with http-equiv="Content-Type". It's important to realise that the meta-tag is only interpreted if the webserver doesn't send the header. In practice this means that it's only used if the page is saved to disk and then opened from there.

This page has a very good explanation of these things.

How do I split a string by a multi-character delimiter in C#?

You can use String.Replace() to replace your desired split string with a character that does not occur in the string and then use String.Split on that character to split the resultant string for the same effect.

Password must have at least one non-alpha character

A simple method will be like this:

Match match1 = Regex.Match(<input_string>, @"(?=.{7})");   

match1.Success ensures that there are at least 8 characters.

Match match2 = Regex.Match(<input_string>, [^a-zA-Z]);

match2.Success ensures that there is at least one special character or number within the string.

So, match1.Success && match2.Success guarantees will get what you want.

How to define and use function inside Jenkins Pipeline config?

First off, you shouldn't add $ when you're outside of strings ($class in your first function being an exception), so it should be:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
...

Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:

...
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1', null)
    }
}

... or you need to add a default value to the functions' second argument:

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere($projectName)
}

Showing data values on stacked bar chart in ggplot2

As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.

It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.

library(grid)
library(gridExtra)
library(plyr)

# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))

# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") + 
  xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) 
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + 
  labs(title = "Proportion of total Frequency accounted by each Category in given Year")

# bring them together
grid.arrange(totals,proportion)

This will give you a 2 panel display like this:

Vertically stacked 2 panel graphic

If you want to add Frequency values a table is the best format.

IF-THEN-ELSE statements in postgresql

In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). For example,

select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from (     (select 'abc' as x, '' as y)
 union all (select 'def' as x, 'ghi' as y)
 union all (select '' as x, 'jkl' as y)
 union all (select null as x, 'mno' as y)
 union all (select 'pqr' as x, null as y)
) q

gives:

 coalesce | coalesce |  x  |  y  
----------+----------+-----+-----
 abc      | abc      | abc | 
 ghi      | def      | def | ghi
 jkl      | jkl      |     | jkl
 mno      | mno      |     | mno
 pqr      | pqr      | pqr | 
(5 rows)

How do I access Configuration in any class in ASP.NET Core?

I looked into the options pattern sample and saw this:

public class Startup
{
    public Startup(IConfiguration config)
    {
        // Configuration from appsettings.json has already been loaded by
        // CreateDefaultBuilder on WebHost in Program.cs. Use DI to load
        // the configuration into the Configuration property.
        Configuration = config;
    }
...
}

When adding Iconfiguration in the constructor of my class, I could access the configuration options through DI.

Example:

public class MyClass{

    private Iconfiguration _config;

    public MyClass(Iconfiguration config){
        _config = config;
    }

    ... // access _config["myAppSetting"] anywhere in this class
}

Convert a string to an enum in C#

Not sure when this was added but on the Enum class there is now a

Parse<TEnum>(stringValue)

Used like so with example in question:

var MyStatus = Enum.Parse<StatusEnum >("Active")

or ignoring casing by:

var MyStatus = Enum.Parse<StatusEnum >("active", true)

Here is the decompiled methods this uses:

    [NullableContext(0)]
    public static TEnum Parse<TEnum>([Nullable(1)] string value) where TEnum : struct
    {
      return Enum.Parse<TEnum>(value, false);
    }

    [NullableContext(0)]
    public static TEnum Parse<TEnum>([Nullable(1)] string value, bool ignoreCase) where TEnum : struct
    {
      TEnum result;
      Enum.TryParse<TEnum>(value, ignoreCase, true, out result);
      return result;
    }

How to process POST data in Node.js?

You can use the querystring module:

var qs = require('querystring');

function (request, response) {
    if (request.method == 'POST') {
        var body = '';

        request.on('data', function (data) {
            body += data;

            // Too much POST data, kill the connection!
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6)
                request.connection.destroy();
        });

        request.on('end', function () {
            var post = qs.parse(body);
            // use post['blah'], etc.
        });
    }
}

Now, for example, if you have an input field with name age, you could access it using the variable post:

console.log(post.age);

Oracle sqlldr TRAILING NULLCOLS required, but why?

Try giving 5 ',' in every line, similar to line number 4.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.

Do you have the key backed up somewhere?

Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

Single controller with multiple GET methods in ASP.NET Web API

With the newer Web Api 2 it has become easier to have multiple get methods.

If the parameter passed to the GET methods are different enough for the attribute routing system to distinguish their types as is the case with ints and Guids you can specify the expected type in the [Route...] attribute

For example -

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{

    // GET api/values/7
    [Route("{id:int}")]
    public string Get(int id)
    {
       return $"You entered an int - {id}";
    }

    // GET api/values/AAC1FB7B-978B-4C39-A90D-271A031BFE5D
    [Route("{id:Guid}")]
    public string Get(Guid id)
    {
       return $"You entered a GUID - {id}";
    }
} 

For more details about this approach, see here http://nodogmablog.bryanhogan.net/2017/02/web-api-2-controller-with-multiple-get-methods-part-2/

Another options is to give the GET methods different routes.

    [RoutePrefix("api/values")]
    public class ValuesController : ApiController
    {
        public string Get()
        {
            return "simple get";
        }

        [Route("geta")]
        public string GetA()
        {
            return "A";
        }

        [Route("getb")]
        public string GetB()
        {
            return "B";
        }
   }

See here for more details - http://nodogmablog.bryanhogan.net/2016/10/web-api-2-controller-with-multiple-get-methods/

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

Check whether a string matches a regex in JS

I would recommend using the execute method which returns null if no match exists otherwise it returns a helpful object.

let case1 = /^([a-z0-9]{5,})$/.exec("abc1");
console.log(case1); //null

let case2 = /^([a-z0-9]{5,})$/.exec("pass3434");
console.log(case2); // ['pass3434', 'pass3434', index:0, input:'pass3434', groups: undefined]

Send email from localhost running XAMMP in PHP using GMAIL mail server

[sendmail]

smtp_server=smtp.gmail.com  
smtp_port=25  
error_logfile=error.log  
debug_logfile=debug.log  
[email protected] 
auth_password=gmailpassword  
[email protected]

need authenticate username and password of mail then only once can successfully send mail from localhost

What is the difference between "INNER JOIN" and "OUTER JOIN"?

The precise algorithm for INNER JOIN, LEFT/RIGHT OUTER JOIN are as following:

  1. Take each row from the first table: a
  2. Consider all rows from second table beside it: (a, b[i])
  3. Evaluate the ON ... clause against each pair: ON( a, b[i] ) = true/false?
    • When the condition evaluates to true, return that combined row (a, b[i]).
    • When reach end of second table without any match, and this is an Outer Join then return a (virtual) pair using Null for all columns of other table: (a, Null) for LEFT outer join or (Null, b) for RIGHT outer join. This is to ensure all rows of first table exists in final results.

Note: the condition specified in ON clause could be anything, it is not required to use Primary Keys (and you don't need to always refer to Columns from both tables)! For example:

Inner Join vs. Left Outer Join


enter image description here

Note: Left Join = Left Outer Join, Right Join = Right Outer Join.

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

What is the target platform of your application? I think you should set the platform to x86, do not set it to Any CPU.

Display JSON Data in HTML Table

HTML:
 <div id="container"></div>   
JS:


$('#search').click(function() {
    $.ajax({
        type: 'POST',
        url: 'cityResults.htm',
        data: $('#cityDetails').serialize(),
        dataType:"json", //to parse string into JSON object,
        success: function(data){ 

                var len = data.length;
                var txt = "";
                if(len > 0){
                    for(var i=0;i<len;i++){

                            txt = "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
                            $("#container").append(txt);
                    }



        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error: ' + textStatus + ': ' + errorThrown);
        }
    });
    return false;
});

React - uncaught TypeError: Cannot read property 'setState' of undefined

You can also use:

<button onClick={()=>this.delta()}>+</button>

Or:

<button onClick={event=>this.delta(event)}>+</button>

If you are passing some params..

Open a new tab in the background?

UPDATE: By version 41 of Google Chrome, initMouseEvent seemed to have a changed behavior.

this can be done by simulating ctrl + click (or any other key/event combinations that open a background tab) on a dynamically generated a element with its href attribute set to the desired url

In action: fiddle

function openNewBackgroundTab(){
    var a = document.createElement("a");
    a.href = "http://www.google.com/";
    var evt = document.createEvent("MouseEvents");
    //the tenth parameter of initMouseEvent sets ctrl key
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                                true, false, false, false, 0, null);
    a.dispatchEvent(evt);
}

tested only on chrome

How can I throw CHECKED exceptions from inside Java 8 streams?

I use this kind of wrapping exception:

public class CheckedExceptionWrapper extends RuntimeException {
    ...
    public <T extends Exception> CheckedExceptionWrapper rethrow() throws T {
        throw (T) getCause();
    }
}

It will require handling these exceptions statically:

void method() throws IOException, ServletException {
    try { 
        list.stream().forEach(object -> {
            ...
            throw new CheckedExceptionWrapper(e);
            ...            
        });
    } catch (CheckedExceptionWrapper e){
        e.<IOException>rethrow();
        e.<ServletExcepion>rethrow();
    }
}

Try it online!

Though exception will be anyway re-thrown during first rethrow() call (oh, Java generics...), this way allows to get a strict statical definition of possible exceptions (requires to declare them in throws). And no instanceof or something is needed.

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

The Python 3 range() object doesn't produce numbers immediately; it is a smart sequence object that produces numbers on demand. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration.

The object also implements the object.__contains__ hook, and calculates if your number is part of its range. Calculating is a (near) constant time operation *. There is never a need to scan through all possible integers in the range.

From the range() object documentation:

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).

So at a minimum, your range() object would do:

class my_range:
    def __init__(self, start, stop=None, step=1, /):
        if stop is None:
            start, stop = 0, start
        self.start, self.stop, self.step = start, stop, step
        if step < 0:
            lo, hi, step = stop, start, -step
        else:
            lo, hi = start, stop
        self.length = 0 if lo > hi else ((hi - lo - 1) // step) + 1

    def __iter__(self):
        current = self.start
        if self.step < 0:
            while current > self.stop:
                yield current
                current += self.step
        else:
            while current < self.stop:
                yield current
                current += self.step

    def __len__(self):
        return self.length

    def __getitem__(self, i):
        if i < 0:
            i += self.length
        if 0 <= i < self.length:
            return self.start + i * self.step
        raise IndexError('my_range object index out of range')

    def __contains__(self, num):
        if self.step < 0:
            if not (self.stop < num <= self.start):
                return False
        else:
            if not (self.start <= num < self.stop):
                return False
        return (num - self.start) % self.step == 0

This is still missing several things that a real range() supports (such as the .index() or .count() methods, hashing, equality testing, or slicing), but should give you an idea.

I also simplified the __contains__ implementation to only focus on integer tests; if you give a real range() object a non-integer value (including subclasses of int), a slow scan is initiated to see if there is a match, just as if you use a containment test against a list of all the contained values. This was done to continue to support other numeric types that just happen to support equality testing with integers but are not expected to support integer arithmetic as well. See the original Python issue that implemented the containment test.


* Near constant time because Python integers are unbounded and so math operations also grow in time as N grows, making this a O(log N) operation. Since it’s all executed in optimised C code and Python stores integer values in 30-bit chunks, you’d run out of memory before you saw any performance impact due to the size of the integers involved here.

In PHP, how can I add an object element to an array?

Here is a clean method I've discovered:

$myArray = [];

array_push($myArray, (object)[
        'key1' => 'someValue',
        'key2' => 'someValue2',
        'key3' => 'someValue3',
]);

return $myArray;

Run php function on button click

No Problem You can use onClick() function easily without using any other interference of language,

<?php
echo '<br><Button onclick="document.getElementById(';?>'modal-wrapper2'<?php echo ').style.display=';?>'block'<?php echo '" name="comment" style="width:100px; color: white;background-color: black;border-radius: 10px; padding: 4px;">Show</button>';
?>

Download File to server from URL

I use this to download file

function cURLcheckBasicFunctions()
{
  if( !function_exists("curl_init") &&
      !function_exists("curl_setopt") &&
      !function_exists("curl_exec") &&
      !function_exists("curl_close") ) return false;
  else return true;
}

/*
 * Returns string status information.
 * Can be changed to int or bool return types.
 */
function cURLdownload($url, $file)
{
  if( !cURLcheckBasicFunctions() ) return "UNAVAILABLE: cURL Basic Functions";
  $ch = curl_init();
  if($ch)
  {

    $fp = fopen($file, "w");
    if($fp)
    {
      if( !curl_setopt($ch, CURLOPT_URL, $url) )
      {
        fclose($fp); // to match fopen()
        curl_close($ch); // to match curl_init()
        return "FAIL: curl_setopt(CURLOPT_URL)";
      }
      if ((!ini_get('open_basedir') && !ini_get('safe_mode')) || $redirects < 1) {
        curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_REFERER, 'http://domain.com/');
        if( !curl_setopt($ch, CURLOPT_HEADER, $curlopt_header)) return "FAIL: curl_setopt(CURLOPT_HEADER)";
        if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirects > 0)) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
        if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
        if( !curl_setopt($ch, CURLOPT_MAXREDIRS, $redirects) ) return "FAIL: curl_setopt(CURLOPT_MAXREDIRS)";

        return curl_exec($ch);
    } else {
        curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_REFERER, 'http://domain.com/');
        if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false)) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
        if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
        if( !curl_setopt($ch, CURLOPT_HEADER, true)) return "FAIL: curl_setopt(CURLOPT_HEADER)";
        if( !curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)) return "FAIL: curl_setopt(CURLOPT_RETURNTRANSFER)";
        if( !curl_setopt($ch, CURLOPT_FORBID_REUSE, false)) return "FAIL: curl_setopt(CURLOPT_FORBID_REUSE)";
        curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
    }
      // if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true) ) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
      // if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
      // if( !curl_setopt($ch, CURLOPT_HEADER, 0) ) return "FAIL: curl_setopt(CURLOPT_HEADER)";
      if( !curl_exec($ch) ) return "FAIL: curl_exec()";
      curl_close($ch);
      fclose($fp);
      return "SUCCESS: $file [$url]";
    }
    else return "FAIL: fopen()";
  }
  else return "FAIL: curl_init()";
}

AngularJs: How to set radio button checked based on model

One way that I see more powerful and avoid having a isDefault in all the models is by using the ng-attributes ng-model, ng-value and ng-checked.

ng-model: binds the value to your model.

ng-value: the value to pass to the ng-model binding.

ng-checked: value or expression that is evaluated. Useful for radio-button and check-boxes.

Example of use: In the following example, I have my model and a list of languages that my site supports. To display the different languages supported and updating the model with the selecting language we can do it in this way.

<!-- Radio -->
<div ng-repeat="language in languages">

  <div>
    <label>

      <input ng-model="site.lang"
             ng-value="language"
             ng-checked="(site.lang == language)"
             name="localizationOptions"
             type="radio">

      <span> {{language}} </span>

    </label>
  </div>

</div>
<!-- end of Radio -->

Our model site.lang will get a language value whenever the expression under evaluation (site.lang == language) is true. This will allow you to sync it with server easily since your model already has the change.

How to edit a text file in my terminal

Try this command:

sudo gedit helloWorld.txt

it, will open up a text editor to edit your file.

OR

sudo nano helloWorld.txt

Here, you can edit your file in the terminal window.

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

SELECT Id   'PatientId',
       ISNULL(CONVERT(varchar(50),ParentId),'')  'ParentId'
FROM Patients

ISNULL always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar), you'd best make sure that's the type of the first argument.


COALESCE is usually a better function to use than ISNULL, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier has higher precedence than varchar, so that doesn't help.

(It's also generally preferred because it extends to more than two arguments)