Programs & Examples On #Template method pattern

The Template Method pattern is a design pattern that defines the program skeleton of an algorithm in a method, called a template method, which defers some steps to subclasses. It is one of the Gang of Four's behavioral design patterns.

Using sed, Insert a line above or below the pattern?

Insert a new verse after the given verse in your stanza:

sed -i '/^lorem ipsum dolor sit amet$/ s:$:\nconsectetur adipiscing elit:' FILE

Disable-web-security in Chrome 48+

From Chorme v81 the params --user-data-dir= requires an actual parameter, whereas in the past it didn't. Something like this works fine for me

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="\tmp\chrome_test"

DateTime vs DateTimeOffset

There's a few places where DateTimeOffset makes sense. One is when you're dealing with recurring events and daylight savings time. Let's say I want to set an alarm to go off at 9am every day. If I use the "store as UTC, display as local time" rule, then the alarm will be going off at a different time when daylight savings time is in effect.

There are probably others, but the above example is actually one that I've run into in the past (this was before the addition of DateTimeOffset to the BCL - my solution at the time was to explicitly store the time in the local timezone, and save the timezone information along side it: basically what DateTimeOffset does internally).

How to use responsive background image in css3 in bootstrap

I found this:

Full

An easy to use, full page image background template for Bootstrap 3 websites

http://startbootstrap.com/template-overviews/full/

or

using in your main div container:

html

<div class="container-fluid full">


</div>

css:

.full {
    background: url('http://placehold.it/1920x1080') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
    height:100%;
}

No tests found with test runner 'JUnit 4'

No testsuits in JUnit4. Use annotations instead or use old JUnit3 name conventions.

Example:

@RunWith(Suite.class)
@SuiteClasses({YourClassWithTests.class})

how to avoid extra blank page at end while printing?

After struggling with various page-break settings and heights and a million various CSS rules on the body tag, I finally solved it over a year later.

I have a div which is supposed to be the only thing on the page which prints, but I was getting several blank pages after it. My body tag is set to visibility:hidden; but that wasn't enough. Vertically tall page elements still take up 'space'. So I added this in my print CSS rules:

#header, #menu, #sidebar{ height:1px; display:none;}

to target specific divs by their ids which contain tall page layout elements. I shrunk the height and then removed them from the layout. No more blank pages. Years later I'm happy to tell my client I cracked it. Hope this helps someone.

Deleting an SVN branch

For those using TortoiseSVN, you can accomplish this by using the Repository Browser (it's labeled "Repo-browser" in the context menu.)

context menu

Find the branch folder you want to delete, right-click it, and select "Delete."

deleting the folder

Enter your commit message, and you're done.

committing

How do you kill a Thread in Java?

Generally you don't..

You ask it to interrupt whatever it is doing using Thread.interrupt() (javadoc link)

A good explanation of why is in the javadoc here (java technote link)

Base64 encoding and decoding in client-side Javascript

I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

I recently just ran into this issue as well. I had a very large table in the dialog div. It was >15,000 rows. When the .empty() was called on the dialog div, I was getting the error above.

I found a round-about solution where before I call cleaning the dialog box, I would remove every other row from the very large table, then call the .empty(). It seemed to have worked though. It seems that my old version of JQuery can't handle such large elements.

How to check if iframe is loaded or it has a content?

A really great method is use jQuery AJAX. The parent frame would look like this:

<iframe src="iframe_load.php" style="width: 100%; height: 100%;"></iframe>

The iframe_load.php file would load the jQuery library and a JavaScript that attempts to load the destination URL in an AJAX GET:

var the_url_to_load = "http://www.your-website.com" ;
$.ajax({
            type: "GET",
            url: the_url_to_load,
            data: "",
            success: function(data){
                // if can load inside iframe, load the URL
                location.href = the_url_to_load ;
            },
            statusCode: {
                500: function() {
                    alert( 'site has errors' ) ;
                }
            },
            error:function (xhr, ajaxOptions, thrownError){
                // if x-frame-options, site is down or web server is down
                alert( 'URL did not load due to x-frame-options' ) ;
            } });

IMPORTANT The destination must have contain the "Access-Control-Allow-Origin" header. Example in PHP:

HEADER( "Access-Control-Allow-Origin: *" ) ;

Min/Max of dates in an array?

var max_date = dates.sort(function(d1, d2){
    return d2-d1;
})[0];

Taking screenshot on Emulator from Android Studio

Besides using Android Studio, you can also take a screenshot with adb which is faster.

adb shell screencap -p /sdcard/screen.png
adb pull /sdcard/screen.png
adb shell rm /sdcard/screen.png

Shorter one line alternative in Unix/OSX

adb shell screencap -p | perl -pe 's/\x0D\x0A/\x0A/g' > screen.png

Original blog post: Grab Android screenshot to computer via ADB

Reading file using fscanf() in C

In your code:

while(fscanf(fp,"%s %c",item,&status) == 1)  

why 1 and not 2? The scanf functions return the number of objects read.

Python's "in" set operator

Strings, though they are not set types, have a valuable in property during validation in scripts:

yn = input("Are you sure you want to do this? ")
if yn in "yes":
    #accepts 'y' OR 'e' OR 's' OR 'ye' OR 'es' OR 'yes'
    return True
return False

I hope this helps you better understand the use of in with this example.

How do I get HTTP Request body content in Laravel?

Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:

public function foo(Request $request){
    $bodyContent = $request->getContent();
}

How to create Java gradle project

Unfortunately you cannot do it in one command. There is an open issue for the very feature.

Currently you'll have to do it by hand. If you need to do it often, you can create a custom gradle plugin, or just prepare your own project skeleton and copy it when needed.

EDIT

The JIRA issue mentioned above has been resolved, as of May 1, 2013, and fixed in 1.7-rc-1. The documentation on the Build Init Plugin is available, although it indicates that this feature is still in the "incubating" lifecycle.

Axios get access to response header fields

In case of CORS requests, browsers can only access the following response headers by default:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

If you would like your client app to be able to access other headers, you need to set the Access-Control-Expose-Headers header on the server:

Access-Control-Expose-Headers: Access-Token, Uid

Why does ANT tell me that JAVA_HOME is wrong when it is not?

Just set the JDK path from the below steps:

  1. Go to 'Run' ->External Tools -> External Tools Configuration

  2. -> Select 'JRE' Then from the DropDown list select the available JDK . ex. jdk1.8.0_25

How to prevent a background process from being stopped after closing SSH client in Linux

Personally, I like the 'batch' command.

$ batch
> mycommand -x arg1 -y arg2 -z arg3
> ^D

This stuffs it in to the background, and then mails the results to you. It's a part of cron.

How to Troubleshoot Intermittent SQL Timeout Errors

I suggest you have a deep look at the super cool SQL Server's Dynamic Management Views feature:

Dynamic management views and functions return server state information that can be used to monitor the health of a server instance, diagnose problems, and tune performance.

This article is a good start with DMVs, although it was written for SQL 2005 (DMVs feature first appearance): Troubleshooting Performance Problems in SQL Server 2005, especially the 'blocking' chapters.

CURL to pass SSL certifcate and password

Addition to previous answer make sure that your curl installation supports https.
You can use curl --version to get information about supported protocols.

If your curl supports https follow the previous answer.

curl --cert certificate_path:password https://www.example.com

If it does not support https, you need to install a cURL version that supports https.

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

I logged into developer account and revoked the development certificate. After revoking and downloading the development certificate i double clicked the newly downloaded certificate and this time Private Key was there under development certificate in KeyChain Access.

How to loop over a Class attributes in Java?

Simple way to iterate over class fields and obtain values from object:

 Class<?> c = obj.getClass();
 Field[] fields = c.getDeclaredFields();
 Map<String, Object> temp = new HashMap<String, Object>();

 for( Field field : fields ){
      try {
           temp.put(field.getName().toString(), field.get(obj));
      } catch (IllegalArgumentException e1) {
      } catch (IllegalAccessException e1) {
      }
 }

How can the default node version be set using NVM?

change the default node version with nvm alias default 10.15.3 *

(replace mine version with your default version number)

you can check your default lists with nvm list

How to get the number of characters in a string

There is a way to get count of runes without any packages by converting string to []rune as len([]rune(YOUR_STRING)):

package main

import "fmt"

func main() {
    russian := "??????? ? ??????"
    english := "Sputnik & pogrom"

    fmt.Println("count of bytes:",
        len(russian),
        len(english))

    fmt.Println("count of runes:",
        len([]rune(russian)),
        len([]rune(english)))

}

count of bytes 30 16

count of runes 16 16

Concatenate strings from several rows using Pandas groupby

we can groupby the 'name' and 'month' columns, then call agg() functions of Panda’s DataFrame objects.

The aggregation functionality provided by the agg() function allows multiple statistics to be calculated per group in one calculation.

df.groupby(['name', 'month'], as_index = False).agg({'text': ' '.join})

enter image description here

sudo: npm: command not found

Since I have installed node.js using .tar file available on node.js, I had to put the location of the node directory on:

~/.bashrc

of root by changing from normal user to root using command:

sudo -i

then I had to add the path to node where I extracted it into .bashrc file as below: enter image description here

then refereshed .bashrc using

. ~/.bashrc

there after

npm: command not found

went away

How to generate gcc debug symbol outside the build target?

Check out the "--only-keep-debug" option of the strip command.

From the link:

The intention is that this option will be used in conjunction with --add-gnu-debuglink to create a two part executable. One a stripped binary which will occupy less space in RAM and in a distribution and the second a debugging information file which is only needed if debugging abilities are required.

How to set base url for rest in spring boot?

I might be a bit late, BUT... I believe it is the best solution. Set it up in your application.yml (or analogical config file):

spring:
    data:
        rest:
            basePath: /api

As I can remember that's it - all of your repositories will be exposed beneath this URI.

Removing special characters VBA Excel

Here is how removed special characters.

I simply applied regex

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object    
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)

How to change the type of a field?

The only way to change the $type of the data is to perform an update on the data where the data has the correct type.

In this case, it looks like you're trying to change the $type from 1 (double) to 2 (string).

So simply load the document from the DB, perform the cast (new String(x)) and then save the document again.

If you need to do this programmatically and entirely from the shell, you can use the find(...).forEach(function(x) {}) syntax.


In response to the second comment below. Change the field bad from a number to a string in collection foo.

db.foo.find( { 'bad' : { $type : 1 } } ).forEach( function (x) {   
  x.bad = new String(x.bad); // convert field to string
  db.foo.save(x);
});

Convert character to ASCII code in JavaScript

JavaScript stores strings as UTF-16 (double byte) so if you want to ignore the second byte just strip it out with a bitwise & operator on 0000000011111111 (ie 255):

'a'.charCodeAt(0) & 255 === 97; // because 'a' = 97 0 
'b'.charCodeAt(0) & 255 === 98; // because 'b' = 98 0 
'?'.charCodeAt(0) & 255 === 19; // because '?' = 19 39

Pyinstaller setting icons don't change

That's error of a module in pyinstaller. The stuff would be sth like this, right:

File "c:\users\p-stu\appdata\local\programs\python\python38-32\lib\site-packages\PyInstaller\utils\win32\icon.py", line 234, in CopyIcons
    except win32api.error as W32E:
AttrubuteError: module 'win32ctypes.pywin32.win32api' has no attribute 'error'

ASP.NET Button to redirect to another page

u can use this:

protected void btnConfirm_Click(object sender, EventArgs e)
{
  Response.Redirect("Confirm.aspx");
}

Null vs. False vs. 0 in PHP

In pretty much all modern languages, null logically refers to pointers (or references) not having a value, or a variable that is not initialized. 0 is the integer value of zero, and false is the boolean value of, well, false. To make things complicated, in C, for example, null, 0, and false are all represented the exact same way. I don't know how it works in PHP.

Then, to complicate things more, databases have a concept of null, which means missing or not applicable, and most languages don't have a direct way to map a DBNull to their null. Until recently, for example, there was no distinction between an int being null and being zero, but that was changed with nullable ints.

Sorry to make this sound complicated. It's just that this has been a harry sticking point in languages for years, and up until recently, it hasn't had any clear resolution anywhere. People used to just kludge things together or make blank or 0 represent nulls in the database, which doesn't always work too well.

Why is String immutable in Java?

We can not be sure of what was Java designers actually thinking while designing String but we can only conclude these reasons based on the advantages we get out of string immutability, Some of which are

1. Existence of String Constant Pool

As discussed in Why String is Stored in String Constant Pool article, every application creates too many string objects and in order to save JVM from first creating lots of string objects and then garbage collecting them. JVM stores all string objects in a separate memory area called String constant pool and reuses objects from that cached pool.

Whenever we create a string literal JVM first sees if that literal is already present in constant pool or not and if it is there, new reference will start pointing to the same object in SCP.

String a = "Naresh";
String b = "Naresh";
String c = "Naresh";

In above example string object with value Naresh will get created in SCP only once and all reference a, b, c will point to the same object but what if we try to make change in a e.g. a.replace("a", "").

Ideally, a should have value Nresh but b, c should remain unchanged because as an end user we are making the change in a only. And we know a, b, c all are pointing the same object so if we make a change in a, others should also reflect the change.

But string immutability saves us from this scenario and due to the immutability of string object string object Naresh will never change. So when we make any change in a instead of change in string object Naresh JVM creates a new object assign it to a and then make change in that object.

So String pool is only possible because of String's immutability and if String would not have been immutable, then caching string objects and reusing them would not have a possibility because any variable woulds have changed the value and corrupted others.

And That's why it is handled by JVM very specially and have been given a special memory area.

2. Thread Safety

An object is called thread-safe when multiple threads are operating on it but none of them is able to corrupt its state and object hold the same state for every thread at any point in time.

As we an immutable object cannot be modified by anyone after its creation which makes every immutable object is thread safe by default. We do not need to apply any thread safety measures to it such as creating synchronized methods.

So due to its immutable nature string object can be shared by multiple threads and even if it is getting manipulated by many threads it will not change its value.

3. Security

In every application, we need to pass several secrets e.g. user's user-name\passwords, connection URLs and in general, all of this information is passed as the string object.

Now suppose if String would not have been immutable in nature then it would cause a serious security threat to the application because these values are allowed to get changed and if it is allowed then these might get changed due to wrongly written code or any other person who have access to our variable references.

4. Class Loading

As discussed in Creating objects through Reflection in Java with Example, we can use Class.forName("class_name") method to load a class in memory which again calls other methods to do so. And even JVM uses these methods to load classes.

But if you see clearly all of these methods accepts the class name as a string object so Strings are used in java class loading and immutability provides security that correct class is getting loaded by ClassLoader.

Suppose if String would not have been immutable and we are trying to load java.lang.Object which get changed to org.theft.OurObject in between and now all of our objects have a behavior which someone can use to unwanted things.

5. HashCode Caching

If we are going to perform any hashing related operations on any object we must override the hashCode() method and try to generate an accurate hashcode by using the state of the object. If an object's state is getting changed which means its hashcode should also change.

Because String is immutable so the value one string object is holding will never get changed which means its hashcode will also not change which gives String class an opportunity to cache its hashcode during object creation.

Yes, String object caches its hashcode at the time of object creation which makes it the great candidate for hashing related operations because hashcode doesn't need to be calculated again which save us some time. This is why String is mostly used as HashMap keys.

Read More on Why String is Immutable and Final in Java.

All shards failed

It is possible on your restart some shards were not recovered, causing the cluster to stay red.
If you hit:
http://<yourhost>:9200/_cluster/health/?level=shards you can look for red shards.

I have had issues on restart where shards end up in a non recoverable state. My solution was to simply delete that index completely. That is not an ideal solution for everyone.

It is also nice to visualize issues like this with a plugin like:
Elasticsearch Head

OSX - How to auto Close Terminal window after the "exit" command executed.

Actually, you should set a config on your Terminal, when your Terminal is up press ?+, then you will see below screen:

enter image description here

Then press shell tab and you will see below screen:

enter image description here

Now select Close if the shell exited cleanly for When the shell exits.

By the above config each time with exit command the Terminal will close but won't quit.

How to get the size of a varchar[n] field in one SQL statement?

I was looking for the TOTAL size of the column and hit this article, my solution is based off of MarcE's.

SELECT sum(DATALENGTH(your_field)) AS FIELDSIZE FROM your_table

ffprobe or avprobe not found. Please install one

This is an old question. But if you're using a virtualenv with python, place the contents of the downloaded libav bin folder in the Scriptsfolder of your virtualenv.

What is the Java equivalent for LINQ?

Shameless self plug: you could always use https://github.com/amoerie/jstreams

Works on Java 6 and up, a perfect fit for Android development.

It looks a lot like Scala operators, lodash, C# LINQ, etc.

Laravel: How to Get Current Route Name? (v5 ... v7)

You can used this line of code : url()->current()

In blade file : {{url()->current()}}

How do I update/upsert a document in Mongoose?

I needed to update/upsert a document into one collection, what I did was to create a new object literal like this:

notificationObject = {
    user_id: user.user_id,
    feed: {
        feed_id: feed.feed_id,
        channel_id: feed.channel_id,
        feed_title: ''
    }
};

composed from data that I get from somewhere else in my database and then call update on the Model

Notification.update(notificationObject, notificationObject, {upsert: true}, function(err, num, n){
    if(err){
        throw err;
    }
    console.log(num, n);
});

this is the ouput that I get after running the script for the first time:

1 { updatedExisting: false,
    upserted: 5289267a861b659b6a00c638,
    n: 1,
    connectionId: 11,
    err: null,
    ok: 1 }

And this is the output when I run the script for the second time:

1 { updatedExisting: true, n: 1, connectionId: 18, err: null, ok: 1 }

I'm using mongoose version 3.6.16

How to import Google Web Font in CSS file?

Download the font ttf/other format files, then simply add this CSS code example:

_x000D_
_x000D_
@font-face { font-family: roboto-regular; _x000D_
    src: url('../font/Roboto-Regular.ttf'); } _x000D_
h2{_x000D_
 font-family: roboto-regular;_x000D_
}
_x000D_
_x000D_
_x000D_

How to handle AccessViolationException

Compiled from above answers, worked for me, did following steps to catch it.

Step #1 - Add following snippet to config file

<configuration>
   <runtime>
      <legacyCorruptedStateExceptionsPolicy enabled="true" />
   </runtime>
</configuration>

Step #2

Add -

[HandleProcessCorruptedStateExceptions]

[SecurityCritical]

on the top of function you are tying catch the exception

source: http://www.gisremotesensing.com/2017/03/catch-exception-attempted-to-read-or.html

How to get the home directory in Python?

I found that pathlib module also supports this.

from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

To install GLIBC_2.14 or GLIBC_2.15, download package from /gnu/libc/ index at

https://ftp.gnu.org/gnu/libc/

Then follow instructions listed by Timo:

For example glibc-2.14.tar.gz in your case.

  1. tar xvfz glibc-2.14.tar.gz

  2. cd glibc-2.14

  3. mkdir build

  4. cd build

  5. ../configure --prefix=/opt/glibc-2.14

  6. make

  7. sudo make install

  8. export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH

How to redirect to Login page when Session is expired in Java web application?

Until the session timeout we get a normal request, after which we get an Ajax request. We can identify it the following way:

String ajaxRequestHeader = request.getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(ajaxRequestHeader)) {
    response.sendRedirect("/login.jsp");
}

How to determine if a number is odd in JavaScript

function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

Really it's interesting. You need just use javax-mail.jar of "com.sun" not "javax.mail".
dwonload com.sun mail jar

How store a range from excel into a Range variable?

What is currentWorksheet? It works if you use the built-in ActiveSheet.

dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

How to create a file in Android?

I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.content.Context;

public class AndroidFileFunctions {

    public static String getFileValue(String fileName, Context context) {
        try {
            StringBuffer outStringBuf = new StringBuffer();
            String inputLine = "";
            /*
             * We have to use the openFileInput()-method the ActivityContext
             * provides. Again for security reasons with openFileInput(...)
             */
            FileInputStream fIn = context.openFileInput(fileName);
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader inBuff = new BufferedReader(isr);
            while ((inputLine = inBuff.readLine()) != null) {
                outStringBuf.append(inputLine);
                outStringBuf.append("\n");
            }
            inBuff.close();
            return outStringBuf.toString();
        } catch (IOException e) {
            return null;
        }
    }

    public static boolean appendFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context, Context.MODE_APPEND);
    }

    public static boolean setFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context,
                Context.MODE_WORLD_READABLE);
    }

    public static boolean writeToFile(String fileName, String value,
            Context context, int writeOrAppendMode) {
        // just make sure it's one of the modes we support
        if (writeOrAppendMode != Context.MODE_WORLD_READABLE
                && writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
                && writeOrAppendMode != Context.MODE_APPEND) {
            return false;
        }
        try {
            /*
             * We have to use the openFileOutput()-method the ActivityContext
             * provides, to protect your file from others and This is done for
             * security-reasons. We chose MODE_WORLD_READABLE, because we have
             * nothing to hide in our file
             */
            FileOutputStream fOut = context.openFileOutput(fileName,
                    writeOrAppendMode);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            // Write the string to the file
            osw.write(value);
            // save and close
            osw.flush();
            osw.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static void deleteFile(String fileName, Context context) {
        context.deleteFile(fileName);
    }
}

Extract XML Value in bash script

I agree with Charles Duffy that a proper XML parser is the right way to go.

But as to what's wrong with your sed command (or did you do it on purpose?).

  • $data was not quoted, so $data is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.

So given your specific XML structure, this modified sed command should work

title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")

Basically for the line that contains title, extract the text between the tags, then quit (so you don't extract the 2nd <title>)

Removing elements by class name?

This works for me

while (document.getElementsByClassName('my-class')[0]) {
        document.getElementsByClassName('my-class')[0].remove();
    }

gcc warning" 'will be initialized after'

If you're seeing errors from library headers and you're using GCC, then you can disable warnings by including the headers using -isystem instead of -I.

Similar features exist in clang.

If you're using CMake, you can specify SYSTEM for include_directories.

Add Whatsapp function to website, like sms, tel

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

The approach with:

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

and with

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

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

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

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

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

I also had a working system that suddenly stopped working with the described error.

After furtling around in my /lib/modules it would appear that the vboxvfs module is no more. Instead modprobe vboxsf was the required incantation to get things restarted.

Not sure when that change ocurred, but it caught me out.

How can I copy data from one column to another in the same table?

UPDATE table_name SET
    destination_column_name=orig_column_name
WHERE condition_if_necessary

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

.val() or .value is IMHO the best solution because it's useful with Ajax. And .reset() only works after page reload and APIs using Ajax never refresh pages unless it's triggered by a different script.

Can I try/catch a warning?

If dns_get_record() fails, it should return FALSE, so you can suppress the warning with @ and then check the return value.

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

I had to set

Aws.config.update({
  credentials: Aws::Credentials.new(access_key_id, secret_access_key)
})

before with the ruby aws sdk v2 (there is probably something similiar to this in the other languages as well)

How to See the Contents of Windows library (*.lib)

Assuming you're talking about a static library, DUMPBIN /SYMBOLS shows the functions and data objects in the library. If you're talking about an import library (a .lib used to refer to symbols exported from a DLL), then you want DUMPBIN /EXPORTS.

Note that for functions linked with the "C" binary interface, this still won't get you return values, parameters, or calling convention. That information isn't encoded in the .lib at all; you have to know that ahead of time (via prototypes in header files, for example) in order to call them correctly.

For functions linked with the C++ binary interface, the calling convention and arguments are encoded in the exported name of the function (also called "name mangling"). DUMPBIN /SYMBOLS will show you both the "mangled" function name as well as the decoded set of parameters.

Override devise registrations controller

Very simple methods Just go to the terminal and the type following

rails g devise:controllers users //This will create devise controllers in controllers/users folder

Next to use custom views

rails g devise:views users //This will create devise views in views/users folder

now in your route.rb file

devise_for :users, controllers: {
           :sessions => "users/sessions",
           :registrations => "users/registrations" }

You can add other controllers too. This will make devise to use controllers in users folder and views in users folder.

Now you can customize your views as your desire and add your logic to controllers in controllers/users folder. Enjoy !

Convert JavaScript string in dot notation into an object reference

recent note: While I'm flattered that this answer has gotten many upvotes, I am also somewhat horrified. If one needs to convert dot-notation strings like "x.a.b.c" into references, it could (maybe) be a sign that there is something very wrong going on (unless maybe you're performing some strange deserialization).

That is to say, novices who find their way to this answer must ask themselves the question "why am I doing this?"

It is of course generally fine to do this if your use case is small and you will not run into performance issues, AND you won't need to build upon your abstraction to make it more complicated later. In fact, if this will reduce code complexity and keep things simple, you should probably go ahead and do what OP is asking for. However, if that's not the case, consider if any of these apply:

case 1: As the primary method of working with your data (e.g. as your app's default form of passing objects around and dereferencing them). Like asking "how can I look up a function or variable name from a string".

  • This is bad programming practice (unnecessary metaprogramming specifically, and kind of violates function side-effect-free coding style, and will have performance hits). Novices who find themselves in this case, should instead consider working with array representations, e.g. ['x','a','b','c'], or even something more direct/simple/straightforward if possible: like not losing track of the references themselves in the first place (most ideal if it's only client-side or only server-side), etc. (A pre-existing unique id would be inelegant to add, but could be used if the spec otherwise requires its existence regardless.)

case 2: Working with serialized data, or data that will be displayed to the user. Like using a date as a string "1999-12-30" rather than a Date object (which can cause timezone bugs or added serialization complexity if not careful). Or you know what you're doing.

  • This is maybe fine. Be careful that there are no dot strings "." in your sanitized input fragments.

If you find yourself using this answer all the time and converting back and forth between string and array, you may be in the bad case, and should consider an alternative.

Here's an elegant one-liner that's 10x shorter than the other solutions:

function index(obj,i) {return obj[i]}
'a.b.etc'.split('.').reduce(index, obj)

[edit] Or in ECMAScript 6:

'a.b.etc'.split('.').reduce((o,i)=>o[i], obj)

(Not that I think eval always bad like others suggest it is (though it usually is), nevertheless those people will be pleased that this method doesn't use eval. The above will find obj.a.b.etc given obj and the string "a.b.etc".)

In response to those who still are afraid of using reduce despite it being in the ECMA-262 standard (5th edition), here is a two-line recursive implementation:

function multiIndex(obj,is) {  // obj,['1','2','3'] -> ((obj['1'])['2'])['3']
    return is.length ? multiIndex(obj[is[0]],is.slice(1)) : obj
}
function pathIndex(obj,is) {   // obj,'1.2.3' -> multiIndex(obj,['1','2','3'])
    return multiIndex(obj,is.split('.'))
}
pathIndex('a.b.etc')

Depending on the optimizations the JS compiler is doing, you may want to make sure any nested functions are not re-defined on every call via the usual methods (placing them in a closure, object, or global namespace).

edit:

To answer an interesting question in the comments:

how would you turn this into a setter as well? Not only returning the values by path, but also setting them if a new value is sent into the function? – Swader Jun 28 at 21:42

(sidenote: sadly can't return an object with a Setter, as that would violate the calling convention; commenter seems to instead be referring to a general setter-style function with side-effects like index(obj,"a.b.etc", value) doing obj.a.b.etc = value.)

The reduce style is not really suitable to that, but we can modify the recursive implementation:

function index(obj,is, value) {
    if (typeof is == 'string')
        return index(obj,is.split('.'), value);
    else if (is.length==1 && value!==undefined)
        return obj[is[0]] = value;
    else if (is.length==0)
        return obj;
    else
        return index(obj[is[0]],is.slice(1), value);
}

Demo:

> obj = {a:{b:{etc:5}}}

> index(obj,'a.b.etc')
5
> index(obj,['a','b','etc'])   #works with both strings and lists
5

> index(obj,'a.b.etc', 123)    #setter-mode - third argument (possibly poor form)
123

> index(obj,'a.b.etc')
123

...though personally I'd recommend making a separate function setIndex(...). I would like to end on a side-note that the original poser of the question could (should?) be working with arrays of indices (which they can get from .split), rather than strings; though there's usually nothing wrong with a convenience function.


A commenter asked:

what about arrays? something like "a.b[4].c.d[1][2][3]" ? –AlexS

Javascript is a very weird language; in general objects can only have strings as their property keys, so for example if x was a generic object like x={}, then x[1] would become x["1"]... you read that right... yup...

Javascript Arrays (which are themselves instances of Object) specifically encourage integer keys, even though you could do something like x=[]; x["puppy"]=5;.

But in general (and there are exceptions), x["somestring"]===x.somestring (when it's allowed; you can't do x.123).

(Keep in mind that whatever JS compiler you're using might choose, maybe, to compile these down to saner representations if it can prove it would not violate the spec.)

So the answer to your question would depend on whether you're assuming those objects only accept integers (due to a restriction in your problem domain), or not. Let's assume not. Then a valid expression is a concatenation of a base identifier plus some .identifiers plus some ["stringindex"]s

This would then be equivalent to a["b"][4]["c"]["d"][1][2][3], though we should probably also support a.b["c\"validjsstringliteral"][3]. You'd have to check the ecmascript grammar section on string literals to see how to parse a valid string literal. Technically you'd also want to check (unlike in my first answer) that a is a valid javascript identifier.

A simple answer to your question though, if your strings don't contain commas or brackets, would be just be to match length 1+ sequences of characters not in the set , or [ or ]:

> "abc[4].c.def[1][2][\"gh\"]".match(/[^\]\[.]+/g)
// ^^^ ^  ^ ^^^ ^  ^   ^^^^^
["abc", "4", "c", "def", "1", "2", ""gh""]

If your strings don't contain escape characters or " characters, and because IdentifierNames are a sublanguage of StringLiterals (I think???) you could first convert your dots to []:

> var R=[], demoString="abc[4].c.def[1][2][\"gh\"]";
> for(var match,matcher=/^([^\.\[]+)|\.([^\.\[]+)|\["([^"]+)"\]|\[(\d+)\]/g; 
      match=matcher.exec(demoString); ) {
  R.push(Array.from(match).slice(1).filter(x=>x!==undefined)[0]);
  // extremely bad code because js regexes are weird, don't use this
}
> R

["abc", "4", "c", "def", "1", "2", "gh"]

Of course, always be careful and never trust your data. Some bad ways to do this that might work for some use cases also include:

// hackish/wrongish; preprocess your string into "a.b.4.c.d.1.2.3", e.g.: 
> yourstring.replace(/]/g,"").replace(/\[/g,".").split(".")
"a.b.4.c.d.1.2.3"  //use code from before

Special 2018 edit:

Let's go full-circle and do the most inefficient, horribly-overmetaprogrammed solution we can come up with... in the interest of syntactical purityhamfistery. With ES6 Proxy objects!... Let's also define some properties which (imho are fine and wonderful but) may break improperly-written libraries. You should perhaps be wary of using this if you care about performance, sanity (yours or others'), your job, etc.

// [1,2,3][-1]==3 (or just use .slice(-1)[0])
if (![1][-1])
    Object.defineProperty(Array.prototype, -1, {get() {return this[this.length-1]}}); //credit to caub

// WARNING: THIS XTREME™ RADICAL METHOD IS VERY INEFFICIENT,
// ESPECIALLY IF INDEXING INTO MULTIPLE OBJECTS,
// because you are constantly creating wrapper objects on-the-fly and,
// even worse, going through Proxy i.e. runtime ~reflection, which prevents
// compiler optimization

// Proxy handler to override obj[*]/obj.* and obj[*]=...
var hyperIndexProxyHandler = {
    get: function(obj,key, proxy) {
        return key.split('.').reduce((o,i)=>o[i], obj);
    },
    set: function(obj,key,value, proxy) {
        var keys = key.split('.');
        var beforeLast = keys.slice(0,-1).reduce((o,i)=>o[i], obj);
        beforeLast[keys[-1]] = value;
    },
    has: function(obj,key) {
        //etc
    }
};
function hyperIndexOf(target) {
    return new Proxy(target, hyperIndexProxyHandler);
}

Demo:

var obj = {a:{b:{c:1, d:2}}};
console.log("obj is:", JSON.stringify(obj));

var objHyper = hyperIndexOf(obj);
console.log("(proxy override get) objHyper['a.b.c'] is:", objHyper['a.b.c']);
objHyper['a.b.c'] = 3;
console.log("(proxy override set) objHyper['a.b.c']=3, now obj is:", JSON.stringify(obj));

console.log("(behind the scenes) objHyper is:", objHyper);

if (!({}).H)
    Object.defineProperties(Object.prototype, {
        H: {
            get: function() {
                return hyperIndexOf(this); // TODO:cache as a non-enumerable property for efficiency?
            }
        }
    });

console.log("(shortcut) obj.H['a.b.c']=4");
obj.H['a.b.c'] = 4;
console.log("(shortcut) obj.H['a.b.c'] is obj['a']['b']['c'] is", obj.H['a.b.c']);

Output:

obj is: {"a":{"b":{"c":1,"d":2}}}

(proxy override get) objHyper['a.b.c'] is: 1

(proxy override set) objHyper['a.b.c']=3, now obj is: {"a":{"b":{"c":3,"d":2}}}

(behind the scenes) objHyper is: Proxy {a: {…}}

(shortcut) obj.H['a.b.c']=4

(shortcut) obj.H['a.b.c'] is obj['a']['b']['c'] is: 4

inefficient idea: You can modify the above to dispatch based on the input argument; either use the .match(/[^\]\[.]+/g) method to support obj['keys'].like[3]['this'], or if instanceof Array, then just accept an Array as input like keys = ['a','b','c']; obj.H[keys].


Per suggestion that maybe you want to handle undefined indices in a 'softer' NaN-style manner (e.g. index({a:{b:{c:...}}}, 'a.x.c') return undefined rather than uncaught TypeError)...:

1) This makes sense from the perspective of "we should return undefined rather than throw an error" in the 1-dimensional index situation ({})['e.g.']==undefined, so "we should return undefined rather than throw an error" in the N-dimensional situation.

2) This does not make sense from the perspective that we are doing x['a']['x']['c'], which would fail with a TypeError in the above example.

That said, you'd make this work by replacing your reducing function with either:

(o,i)=>o===undefined?undefined:o[i], or (o,i)=>(o||{})[i].

(You can make this more efficient by using a for loop and breaking/returning whenever the subresult you'd next index into is undefined, or using a try-catch if you expect such failures to be sufficiently rare.)

Get filename in batch for loop

The answer by @AKX works on the command line, but not within a batch file. Within a batch file, you need an extra %, like this:

@echo off
for /R TutorialSteps %%F in (*.py) do echo %%~nF

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Float a div in top right corner without overlapping sibling header

Get rid from your <Button> wrap div using display:block and float:left in both <Button> and <h1> and specifying their width with a position:relative to your Section. This approach has the advantage of not needing another div only to position your <Button>

html

<section>  
    <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>     
    <button>button</button>
</section>

? css

section {
    position: relative;
    width: 50%;
    border: 1px solid;
    float:left;
}
h1 {
    display: block;
    width:70%;
    float:left;
}
button
{
    position:relative;
    top:0;
    left:0;
    float:left;
}

?

How can I send a file document to the printer and have it print?

System.Diagnostics.Process.Start can be used to print a document. Set UseShellExecute to True and set the Verb to "print".

Is there a standardized method to swap two variables in Python?

That is the standard way to swap two variables, yes.

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

I use VS 2017. By default SQL Server Instance name is (LocalDB)\MSSQLLocalDB. However, downgrading the compatibility level of the database to 110 as in @user3390927's answer, I could attach the database file in VS, choosing Server Name as "localhost\SQLExpress".

AngularJs ReferenceError: angular is not defined

You should put the include angular line first, before including any other js file

How to handle-escape both single and double quotes in an SQL-Update statement

Depending on what language you are programming in, you can use a function to replace double quotes with two double quotes.

For example in PHP that would be:

str_replace('"', '""', $string);

If you are trying to do that using SQL only, maybe REPLACE() is what you are looking for.

So your query would look something like this:

"UPDATE Table SET columnname = '" & REPLACE(@wstring, '"', '""') & "' where ... blah ... blah "

How to declare a global variable in JavaScript

The best way is to use closures, because the window object gets very, very cluttered with properties.

HTML

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="init.js"></script>
    <script type="text/javascript">
      MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
    </script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello !</h1>
  </body>
</html>

init.js (based on this answer)

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // Private

    return {
        init : function(Args) {
            _args = Args;
            // Some other initialising
        },
        helloWorld : function(i) {
            return _args[i];
        }
    };
}());

script.js

// Here you can use the values defined in the HTML content as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);

alert(a);

Here's the plnkr. Hope it help !

Auto-fit TextView for Android

Below is avalancha TextView with added functionality for custom Font.

Usage:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:foo="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="match_parent" >

                <de.meinprospekt.androidhd.view.AutoFitText
                android:layout_width="wrap_content"
                android:layout_height="10dp"
                android:text="Small Text"
                android:textColor="#FFFFFF"
                android:textSize="100sp"
                foo:customFont="fonts/Roboto-Light.ttf" />

</FrameLayout>

Don't forget to add: xmlns:foo="http://schemas.android.com/apk/res-auto". Font should be in assets firectory

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.TextView;
import de.meinprospekt.androidhd.R;
import de.meinprospekt.androidhd.adapter.BrochuresHorizontalAdapter;
import de.meinprospekt.androidhd.util.LOG;

/**
 * https://stackoverflow.com/a/16174468/2075875 This class builds a new android Widget named AutoFitText which can be used instead of a TextView to
 * have the text font size in it automatically fit to match the screen width. Credits go largely to Dunni, gjpc, gregm and speedplane from
 * Stackoverflow, method has been (style-) optimized and rewritten to match android coding standards and our MBC. This version upgrades the original
 * "AutoFitTextView" to now also be adaptable to height and to accept the different TextView types (Button, TextClock etc.)
 * 
 * @author pheuschk
 * @createDate: 18.04.2013
 * 
 * combined with: https://stackoverflow.com/a/7197867/2075875
 */
@SuppressWarnings("unused")
public class AutoFitText extends TextView {

    private static final String TAG = AutoFitText.class.getSimpleName();

    /** Global min and max for text size. Remember: values are in pixels! */
    private final int MIN_TEXT_SIZE = 10;
    private final int MAX_TEXT_SIZE = 400;

    /** Flag for singleLine */
    private boolean mSingleLine = false;

    /**
     * A dummy {@link TextView} to test the text size without actually showing anything to the user
     */
    private TextView mTestView;

    /**
     * A dummy {@link Paint} to test the text size without actually showing anything to the user
     */
    private Paint mTestPaint;

    /**
     * Scaling factor for fonts. It's a method of calculating independently (!) from the actual density of the screen that is used so users have the
     * same experience on different devices. We will use DisplayMetrics in the Constructor to get the value of the factor and then calculate SP from
     * pixel values
     */
    private float mScaledDensityFactor;

    /**
     * Defines how close we want to be to the factual size of the Text-field. Lower values mean higher precision but also exponentially higher
     * computing cost (more loop runs)
     */
    private final float mThreshold = 0.5f;

    /**
     * Constructor for call without attributes --> invoke constructor with AttributeSet null
     * 
     * @param context
     */
    public AutoFitText(Context context) {
        this(context, null);
    }

    public AutoFitText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

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

    private void init(Context context, AttributeSet attrs) {
        //TextViewPlus part https://stackoverflow.com/a/7197867/2075875
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AutoFitText);
        String customFont = a.getString(R.styleable.AutoFitText_customFont);
        setCustomFont(context, customFont);
        a.recycle();

        // AutoFitText part
        mScaledDensityFactor = context.getResources().getDisplayMetrics().scaledDensity;
        mTestView = new TextView(context);

        mTestPaint = new Paint();
        mTestPaint.set(this.getPaint());

        this.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // make an initial call to onSizeChanged to make sure that refitText is triggered
                onSizeChanged(AutoFitText.this.getWidth(), AutoFitText.this.getHeight(), 0, 0);
                // Remove the LayoutListener immediately so we don't run into an infinite loop
                //AutoFitText.this.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                removeOnGlobalLayoutListener(AutoFitText.this, this);
            }
        });
    }

    public boolean setCustomFont(Context ctx, String asset) {
        Typeface tf = null;
        try {
        tf = Typeface.createFromAsset(ctx.getAssets(), asset);  
        } catch (Exception e) {
            LOG.e(TAG, "Could not get typeface: "+e.getMessage());
            return false;
        }

        setTypeface(tf);  
        return true;
    }

    @SuppressLint("NewApi")
    public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){
        if (Build.VERSION.SDK_INT < 16) {
            v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
        } else {
            v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
        }
    }

    /**
     * Main method of this widget. Resizes the font so the specified text fits in the text box assuming the text box has the specified width. This is
     * done via a dummy text view that is refit until it matches the real target width and height up to a certain threshold factor
     * 
     * @param targetFieldWidth The width that the TextView currently has and wants filled
     * @param targetFieldHeight The width that the TextView currently has and wants filled
     */
    private void refitText(String text, int targetFieldWidth, int targetFieldHeight) {

        // Variables need to be visible outside the loops for later use. Remember size is in pixels
        float lowerTextSize = MIN_TEXT_SIZE;
        float upperTextSize = MAX_TEXT_SIZE;

        // Force the text to wrap. In principle this is not necessary since the dummy TextView
        // already does this for us but in rare cases adding this line can prevent flickering
        this.setMaxWidth(targetFieldWidth);

        // Padding should not be an issue since we never define it programmatically in this app
        // but just to to be sure we cut it off here
        targetFieldWidth = targetFieldWidth - this.getPaddingLeft() - this.getPaddingRight();
        targetFieldHeight = targetFieldHeight - this.getPaddingTop() - this.getPaddingBottom();

        // Initialize the dummy with some params (that are largely ignored anyway, but this is
        // mandatory to not get a NullPointerException)
        mTestView.setLayoutParams(new LayoutParams(targetFieldWidth, targetFieldHeight));

        // maxWidth is crucial! Otherwise the text would never line wrap but blow up the width
        mTestView.setMaxWidth(targetFieldWidth);

        if (mSingleLine) {
            // the user requested a single line. This is very easy to do since we primarily need to
            // respect the width, don't have to break, don't have to measure...

            /*************************** Converging algorithm 1 ***********************************/
            for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) {

                // Go to the mean value...
                testSize = (upperTextSize + lowerTextSize) / 2;

                mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor);
                mTestView.setText(text);
                mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

                if (mTestView.getMeasuredWidth() >= targetFieldWidth) {
                    upperTextSize = testSize; // Font is too big, decrease upperSize
                } else {
                    lowerTextSize = testSize; // Font is too small, increase lowerSize
                }
            }
            /**************************************************************************************/

            // In rare cases with very little letters and width > height we have vertical overlap!
            mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

            if (mTestView.getMeasuredHeight() > targetFieldHeight) {
                upperTextSize = lowerTextSize;
                lowerTextSize = MIN_TEXT_SIZE;

                /*************************** Converging algorithm 1.5 *****************************/
                for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) {

                    // Go to the mean value...
                    testSize = (upperTextSize + lowerTextSize) / 2;

                    mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor);
                    mTestView.setText(text);
                    mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

                    if (mTestView.getMeasuredHeight() >= targetFieldHeight) {
                        upperTextSize = testSize; // Font is too big, decrease upperSize
                    } else {
                        lowerTextSize = testSize; // Font is too small, increase lowerSize
                    }
                }
                /**********************************************************************************/
            }
        } else {

            /*********************** Converging algorithm 2 ***************************************/
            // Upper and lower size converge over time. As soon as they're close enough the loop
            // stops
            // TODO probe the algorithm for cost (ATM possibly O(n^2)) and optimize if possible
            for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) {

                // Go to the mean value...
                testSize = (upperTextSize + lowerTextSize) / 2;

                // ... inflate the dummy TextView by setting a scaled textSize and the text...
                mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor);
                mTestView.setText(text);

                // ... call measure to find the current values that the text WANTS to occupy
                mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
                int tempHeight = mTestView.getMeasuredHeight();
                // int tempWidth = mTestView.getMeasuredWidth();

                // LOG.debug("Measured: " + tempWidth + "x" + tempHeight);
                // LOG.debug("TextSize: " + testSize / mScaledDensityFactor);

                // ... decide whether those values are appropriate.
                if (tempHeight >= targetFieldHeight) {
                    upperTextSize = testSize; // Font is too big, decrease upperSize
                } else {
                    lowerTextSize = testSize; // Font is too small, increase lowerSize
                }
            }
            /**************************************************************************************/

            // It is possible that a single word is wider than the box. The Android system would
            // wrap this for us. But if you want to decide fo yourself where exactly to break or to
            // add a hyphen or something than you're going to want to implement something like this:
            mTestPaint.setTextSize(lowerTextSize);
            List<String> words = new ArrayList<String>();

            for (String s : text.split(" ")) {
                Log.i("tag", "Word: " + s);
                words.add(s);
            }
            for (String word : words) {
                if (mTestPaint.measureText(word) >= targetFieldWidth) {
                    List<String> pieces = new ArrayList<String>();
                    // pieces = breakWord(word, mTestPaint.measureText(word), targetFieldWidth);

                    // Add code to handle the pieces here...
                }
            }
        }

        /**
         * We are now at most the value of threshold away from the actual size. To rather undershoot than overshoot use the lower value. To match
         * different screens convert to SP first. See {@link http://developer.android.com/guide/topics/resources/more-resources.html#Dimension} for
         * more details
         */
        this.setTextSize(TypedValue.COMPLEX_UNIT_SP, lowerTextSize / mScaledDensityFactor);
        return;
    }

    /**
     * This method receives a call upon a change in text content of the TextView. Unfortunately it is also called - among others - upon text size
     * change which means that we MUST NEVER CALL {@link #refitText(String)} from this method! Doing so would result in an endless loop that would
     * ultimately result in a stack overflow and termination of the application
     * 
     * So for the time being this method does absolutely nothing. If you want to notify the view of a changed text call {@link #setText(CharSequence)}
     */
    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        // Super implementation is also intentionally empty so for now we do absolutely nothing here
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
        if (width != oldWidth && height != oldHeight) {
            refitText(this.getText().toString(), width, height);
        }
    }

    /**
     * This method is guaranteed to be called by {@link TextView#setText(CharSequence)} immediately. Therefore we can safely add our modifications
     * here and then have the parent class resume its work. So if text has changed you should always call {@link TextView#setText(CharSequence)} or
     * {@link TextView#setText(CharSequence, BufferType)} if you know whether the {@link BufferType} is normal, editable or spannable. Note: the
     * method will default to {@link BufferType#NORMAL} if you don't pass an argument.
     */
    @Override
    public void setText(CharSequence text, BufferType type) {

        int targetFieldWidth = this.getWidth();
        int targetFieldHeight = this.getHeight();

        if (targetFieldWidth <= 0 || targetFieldHeight <= 0 || text.equals("")) {
            // Log.v("tag", "Some values are empty, AutoFitText was not able to construct properly");
        } else {
            refitText(text.toString(), targetFieldWidth, targetFieldHeight);
        }
        super.setText(text, type);
    }

    /**
     * TODO add sensibility for {@link #setMaxLines(int)} invocations
     */
    @Override
    public void setMaxLines(int maxLines) {
        // TODO Implement support for this. This could be relatively easy. The idea would probably
        // be to manipulate the targetHeight in the refitText-method and then have the algorithm do
        // its job business as usual. Nonetheless, remember the height will have to be lowered
        // dynamically as the font size shrinks so it won't be a walk in the park still
        if (maxLines == 1) {
            this.setSingleLine(true);
        } else {
            throw new UnsupportedOperationException("MaxLines != 1 are not implemented in AutoFitText yet, use TextView instead");
        }
    }

    @Override
    public void setSingleLine(boolean singleLine) {
        // save the requested value in an instance variable to be able to decide later
        mSingleLine = singleLine;
        super.setSingleLine(singleLine);
    }
}

known bugs: Doesn't work with Android 4.03 - fonts are invisible or very small (original avalancha doesn't work too) below is workaround for that bug: https://stackoverflow.com/a/21851239/2075875

How to use a typescript enum value in an Angular2 ngSwitch statement

My component used an object myClassObject of type MyClass, which itself was using MyEnum. This lead to the same issue described above. Solved it by doing:

export enum MyEnum {
    Option1,
    Option2,
    Option3
}
export class MyClass {
    myEnum: typeof MyEnum;
    myEnumField: MyEnum;
    someOtherField: string;
}

and then using this in the template as

<div [ngSwitch]="myClassObject.myEnumField">
  <div *ngSwitchCase="myClassObject.myEnum.Option1">
    Do something for Option1
  </div>
  <div *ngSwitchCase="myClassObject.myEnum.Option2">
    Do something for Option2
  </div>
  <div *ngSwitchCase="myClassObject.myEnum.Option3">
    Do something for Opiton3
  </div>
</div>

RegEx to parse or validate Base64 data

The answers presented so far fail to check that the Base64 string has all pad bits set to 0, as required for it to be the canonical representation of Base64 (which is important in some environments, see https://tools.ietf.org/html/rfc4648#section-3.5) and therefore, they allow aliases that are different encodings for the same binary string. This could be a security problem in some applications.

Here is the regexp that verifies that the given string is not just valid base64, but also the canonical base64 string for the binary data:

^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$

The cited RFC considers the empty string as valid (see https://tools.ietf.org/html/rfc4648#section-10) therefore the above regex also does.

The equivalent regular expression for base64url (again, refer to the above RFC) is:

^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-][AQgw]==|[A-Za-z0-9_-]{2}[AEIMQUYcgkosw048]=)?$

git: patch does not apply

WARNING: This command can remove old lost commits PERMANENTLY. Make a copy of your entire repository before attempting this.

I have found this link

I have no idea why this works but I tried many work arounds and this is the only one that worked for me. In short, run the three commands below:

git fsck --full
git reflog expire --expire=now --all
git gc --prune=now

Unpivot with column name

SELECT * FROM student

UNPIVOT(Marks FOR subjects in(Maths , Science , English));

C# Iterating through an enum? (Indexing a System.Array)

What about using a foreach loop, maybe you could work with that?

  int i = 0;
  foreach (var o in values)
  {
    print(names[i], o);
    i++;
  }

something like that perhaps?

python save image from url

Python3

import urllib.request
print('Beginning file download with urllib2...')
url = 'https://akm-img-a-in.tosshub.com/sites/btmt/images/stories/modi_instagram_660_020320092717.jpg'
urllib.request.urlretrieve(url, 'modiji.jpg')

Call fragment from fragment

I think now Fragment nesting is available just update the back computability jar

now lets dig in the problem it self .

public void onClick2(View view) {
    Fragment2 fragment2 = new Fragment2();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment1, fragment2);
    fragmentTransaction.commit();
}

I think the R.id.fragment1 belongs to a TextView which is not a good place to include child views in because its not a ViewGroup, you can remove the textView from the xml and replace it with a LinearLayout lets say and it will work , if not tell me what the error .

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:orientation="vertical" >

<LinearLayout 
    android:id="@+id/fragment1"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    />

<Button 
    android:id="@+id/btn_frag2"
    android:text="Call Fragment 2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

Update for the error in the comment

public class Fragment1 extends Fragment implements OnClickListener{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment1, container, false);
((Button) v.findViewById(R.id.btn_frag2)).setOnClickListener(this);
    return v;
}

public void onClick(View view) {
    Fragment2 fragment2 = new Fragment2();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction =        fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, fragment2);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

}

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

/* cellpadding */
th, td { padding: 5px; }

/* cellspacing */
table { border-collapse: separate; border-spacing: 5px; } /* cellspacing="5" */
table { border-collapse: collapse; border-spacing: 0; }   /* cellspacing="0" */

/* valign */
th, td { vertical-align: top; }

/* align (center) */
table { margin: 0 auto; }

sending mail from Batch file

We use blat to do this all the time in our environment. I use it as well to connect to Gmail with Stunnel. Here's the params to send a file

blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body" -attach c:\temp\file.txt

Or you can put that file in as the body

blat c:\temp\file.txt -to [email protected] -server smtp.example.com -f [email protected] -subject "subject"

Access-control-allow-origin with multiple domains

You can add this code to your asp.net webapi project

in file Global.asax

    protected void Application_BeginRequest()
{
    string origin = Request.Headers.Get("Origin");
    if (Request.HttpMethod == "OPTIONS")
    {
        Response.AddHeader("Access-Control-Allow-Origin", origin);
        Response.AddHeader("Access-Control-Allow-Headers", "*");
        Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
        Response.StatusCode = 200;
        Response.End();
    }
    else
    {
        Response.AddHeader("Access-Control-Allow-Origin", origin);
        Response.AddHeader("Access-Control-Allow-Headers", "*");
        Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
    }
}

How to import a SQL Server .bak file into MySQL?

The .BAK files from SQL server are in Microsoft Tape Format (MTF) ref: http://www.fpns.net/willy/msbackup.htm

The bak file will probably contain the LDF and MDF files that SQL server uses to store the database.

You will need to use SQL server to extract these. SQL Server Express is free and will do the job.

So, install SQL Server Express edition, and open the SQL Server Powershell. There execute sqlcmd -S <COMPUTERNAME>\SQLExpress (whilst logged in as administrator)

then issue the following command.

restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak';
GO

This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file.

RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak'
WITH 
   MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', 
   MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf';
GO

At this point you have extracted the database - then install Microsoft's "Sql Web Data Administrator". together with this export tool and you will have an SQL script that contains the database.

html select only one checkbox in a group

Radio buttons are ideal. You just need a third "neither" option that is select by default.

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

Zero => Everything Okay

Positive => Something I expected could potentially go wrong went wrong (bad command-line, can't find file, could not connect to server)

Negative => Something I didn't expect at all went wrong (system error - unanticipated exception - externally forced termination e.g. kill -9)

(values greater than 128 are actually negative, if you regard them as 8-bit signed binary, or twos complement)

There's a load of good standard exit-codes here

SQL Delete Records within a specific Range

You can use this way because id can not be sequential in all cases.

SELECT * 
FROM  `ht_news` 
LIMIT 0 , 30

Get PHP class property by string

Here is my attempt. It has some common 'stupidity' checks built in, making sure you don't try to set or get a member which isn't available.

You could move those 'property_exists' checks to __set and __get respectively and call them directly within magic().

<?php

class Foo {
    public $Name;

    public function magic($member, $value = NULL) {
        if ($value != NULL) {
            if (!property_exists($this, $member)) {
                trigger_error('Undefined property via magic(): ' .
                    $member, E_USER_ERROR);
                return NULL;
            }
            $this->$member = $value;
        } else {
            if (!property_exists($this, $member)) {
                trigger_error('Undefined property via magic(): ' .
                    $member, E_USER_ERROR);
                return NULL;
            }
            return $this->$member;
        }
    }
};

$f = new Foo();

$f->magic("Name", "Something");
echo $f->magic("Name") , "\n";

// error
$f->magic("Fame", "Something");
echo $f->magic("Fame") , "\n";

?>

Why javascript getTime() is not a function?

dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp

You would use it like this:

var date = Date.parse(dat1);

How do I set the default value for an optional argument in Javascript?

ES6 Update - ES6 (ES2015 specification) allows for default parameters

The following will work just fine in an ES6 (ES015) environment...

function(nodeBox, str="hai")
{
  // ...
}

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

Starting from SSMS 18.2, you can now view up to 2 million characters in the grid results. Source

Allow more data to be displayed (Result to Text) and stored in cells (Result to Grid). SSMS now allows up to 2M characters for both.

I verified this with the code below.

DECLARE @S varchar(max) = 'A'

SET @S =  REPLICATE(@S,2000000) + 'B' 

SELECT @S as a

how to delete a specific row in codeigniter?

It will come in the url so you can get it by two ways. Fist one

<td><?php echo anchor('textarea/delete_row', 'DELETE', 'id="$row->id"'); ?></td>
$id = $this->input->get('id');

2nd one.

$id = $this->uri->segment(3);

But in the second method you have to count the no. of segments in the url that on which no. your id come. 2,3,4 etc. then you have to pass. then in the ();

How to automatically add user account AND password with a Bash script?

Here is a script that will do it for you .....

You can add a list of users (or just one user) if you want, all in one go and each will have a different password. As a bonus you are presented at the end of the script with a list of each users password. .... If you want you can add some user maintenance options

like:

chage -m 18 $user
chage -M 28 $user

to the script that will set the password age and so on.

=======

#!/bin/bash

# Checks if you have the right privileges
if [ "$USER" = "root" ]
then

# CHANGE THIS PARAMETERS FOR A PARTICULAR USE
PERS_HOME="/home/"
PERS_SH="/bin/bash"

   # Checks if there is an argument
   [ $# -eq 0 ] && { echo >&2 ERROR: You may enter as an argument a text file containing users, one per line. ; exit 1; }
   # checks if there a regular file
   [ -f "$1" ] || { echo >&2 ERROR: The input file does not exists. ; exit 1; }
   TMPIN=$(mktemp)
   # Remove blank lines and delete duplicates 
   sed '/^$/d' "$1"| sort -g | uniq > "$TMPIN"

   NOW=$(date +"%Y-%m-%d-%X")
   LOGFILE="AMU-log-$NOW.log"

   for user in $(more "$TMPIN"); do
      # Checks if the user already exists.
      cut -d: -f1 /etc/passwd | grep "$user" > /dev/null
      OUT=$?
      if [ $OUT -eq 0 ];then
         echo >&2 "ERROR: User account: \"$user\" already exists."
         echo >&2 "ERROR: User account: \"$user\" already exists." >> "$LOGFILE"
      else
         # Create a new user
         /usr/sbin/useradd -d "$PERS_HOME""$user" -s "$PERS_SH" -m "$user"
         # passwdgen must be installed
         pass=$(passwdgen -paq --length 8)
         echo $pass | passwd --stdin $user
         # save user and password in a file
         echo -e $user"\t"$pass >> "$LOGFILE"
         echo "The user \"$user\" has been created and has the password: $pass"
      fi
   done
   rm -f "$TMPIN"
   exit 0
else
   echo >&2 "ERROR: You must be a root user to execute this script."
   exit 1
fi

===========

Hope this helps.

Cheers, Carel

datetime to string with series in python pandas

There is a pandas function that can be applied to DateTime index in pandas data frame.

date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list

the element inside the list:

u'1910-11-02'

You might need to replace the 'u'.

There might be some additional arguments that I should put into the previous functions.

Remove table row after clicking table row delete button

As @gaurang171 mentioned, we can use .closest() which will return the first ancestor, or the closest to our delete button, and use .remove() to remove it.

This is how we can implement it using jQuery click event instead of using JavaScript onclick.

HTML:

<table id="myTable">
<tr>
  <th width="30%" style="color:red;">ID</th>
  <th width="25%" style="color:red;">Name</th>
  <th width="25%" style="color:red;">Age</th>
  <th width="1%"></th>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-001</td>
  <td width="25%" style="color:red;">Ben</td>
  <td width="25%" style="color:red;">25</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-002</td>
  <td width="25%" style="color:red;">Anderson</td>
  <td width="25%" style="color:red;">47</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-003</td>
  <td width="25%" style="color:red;">Rocky</td>
  <td width="25%" style="color:red;">32</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-004</td>
  <td width="25%" style="color:red;">Lee</td>
  <td width="25%" style="color:red;">15</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>
                            

jQuery

 $(document).ready(function(){
     $("#myTable").on('click','.btnDelete',function(){
         $(this).closest('tr').remove();
      });
  });

Try in JSFiddle: click here.

How to have css3 animation to loop forever

I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.

Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div is restored, forcing the animations to restart.

All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head> section of your page:

<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>

BTW, the closing </head> in your code is misplaced: it must be before the starting <body>.

Android statusbar icons color

if you have API level smaller than 23 than you must use it this way. it worked for me declare this under v21/style.

<item name="colorPrimaryDark" tools:targetApi="23">@color/colorPrimary</item>
        <item name="android:windowLightStatusBar" tools:targetApi="23">true</item>

Amazon AWS Filezilla transfer permission denied

In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.

Conditionally Remove Dataframe Rows with R

Subset is your safest and easiest answer.

subset(dataframe, A==B & E!=0)

Real data example with mtcars

subset(mtcars, cyl==6 & am!=0)

Send and receive messages through NSNotificationCenter in Objective-C?

if you're using NSNotificationCenter for updating your view, don't forget to send it from the main thread by calling dispatch_async:

dispatch_async(dispatch_get_main_queue(),^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"my_notification" object:nil];
});

Windows command prompt log to a file

You can redirect the output of a cmd prompt to a file using > or >> to append to a file.

i.e.

echo Hello World >C:\output.txt
echo Hello again! >>C:\output.txt

or

mybatchfile.bat >C:\output.txt

Note that using > will automatically overwrite the file if it already exists.

You also have the option of redirecting stdin, stdout and stderr.

See here for a complete list of options.

How do I make a new line in swift

You can do this

textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"

The output will be

Name: output of string1 Phone Number: output of string2

Replacing NULL with 0 in a SQL server query

UPDATE TableName SET ColumnName= ISNULL(ColumnName, 0 ) WHERE Id = 10

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

refering to Deepak Vishwakarma's answer, I tried with that and was facing same problem with the url-problem. I installed maven-3.6.3 and inside .m2 folder I found a

settings.xml.bak

file and from that copied that mirror link and just changed url what @Deepak did. It worked like charm! Mirror link I got from that .bak file

http://local.maven.repo:9081/nexus/content/groups/public

Then executed :

mvn clean 
mvn clean install

How to Get enum item name from its value

No, you have no way to get the "name" from the value in C++ because all the symbols are discarded during compilation.

You may need this way X Macros

Angular 4 setting selected option in Dropdown

If you want to select a value as default, in your form builder give it a value :

this.myForm = this.FB.group({
    mySelect: [this.options[0].key, [/* Validators here */]]
});

Now in your HTML :

<form [formGroup]="myForm">
    <select [formControlName]="mySelect">
        <option *ngFor="let opt of options" [value]="opt.key">ANY TEXT YOU WANT HERE</option>
    </select>
</form>

What my code does is giving your select a value, that is equal to the first value of your options list. This is how you select an option as default in Angular, selected is useless.

How to get height of Keyboard?

// Step 1 :- Register NotificationCenter

ViewDidLoad() {

   self.yourtextfield.becomefirstresponder()

   // Register your Notification, To know When Key Board Appears.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

   // Register your Notification, To know When Key Board Hides.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

// Step 2 :- These Methods will be called Automatically when Keyboard appears Or Hides

    func keyboardWillShow(notification:NSNotification) {
        let userInfo:NSDictionary = notification.userInfo! as NSDictionary
        let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
        tblViewListData.frame.size.height = fltTblHeight-keyboardHeight
    }

    func keyboardWillHide(notification:NSNotification) {
        tblViewListData.frame.size.height = fltTblHeight
    }

Using stored procedure output parameters in C#

I slightly modified your stored procedure (to use SCOPE_IDENTITY) and it looks like this:

CREATE PROCEDURE usp_InsertContract
    @ContractNumber varchar(7),
    @NewId int OUTPUT
AS
BEGIN
    INSERT INTO [dbo].[Contracts] (ContractNumber)
    VALUES (@ContractNumber)

    SELECT @NewId = SCOPE_IDENTITY()
END

I tried this and it works just fine (with that modified stored procedure):

// define connection and command, in using blocks to ensure disposal
using(SqlConnection conn = new SqlConnection(pvConnectionString ))
using(SqlCommand cmd = new SqlCommand("dbo.usp_InsertContract", conn))
{
    cmd.CommandType = CommandType.StoredProcedure;

    // set up the parameters
    cmd.Parameters.Add("@ContractNumber", SqlDbType.VarChar, 7);
    cmd.Parameters.Add("@NewId", SqlDbType.Int).Direction = ParameterDirection.Output;

    // set parameter values
    cmd.Parameters["@ContractNumber"].Value = contractNumber;

    // open connection and execute stored procedure
    conn.Open();
    cmd.ExecuteNonQuery();

    // read output value from @NewId
    int contractID = Convert.ToInt32(cmd.Parameters["@NewId"].Value);
    conn.Close();
}

Does this work in your environment, too? I can't say why your original code won't work - but when I do this here, VS2010 and SQL Server 2008 R2, it just works flawlessly....

If you don't get back a value - then I suspect your table Contracts might not really have a column with the IDENTITY property on it.

DataSet panel (Report Data) in SSRS designer is gone

With a .rdl, .rdlc or similar file selected, you can either:

  • Click View -> Report Data or...
  • Use the keyboard shortcut CTRL + ALT + D

Example

How do I open a new window using jQuery?

It's not really something you need jQuery to do. There is a very simple plain old javascript method for doing this:

window.open('http://www.google.com','GoogleWindow', 'width=800, height=600');

That's it.

The first arg is the url, the second is the name of the window, this should be specified because IE will throw a fit about trying to use window.opener later if there was no window name specified (just a little FYI), and the last two params are width/height.

EDIT: Full specification can be found in the link mmmshuddup provided.

Write HTML string in JSON

You should escape the characters like double quotes in the html string by adding "\"

eg: <h2 class=\"fg-white\">

Is it possible to have different Git configuration for different projects?

I am doing this for my email in the following way:

git config --global alias.hobbyprofile 'config user.email "[email protected]"'

Then when I clone a new work project, I have only to run git hobbyprofile and it will be configured to use that email.

What is the maximum number of characters that nvarchar(MAX) will hold?

Max. capacity is 2 gigabytes of space - so you're looking at just over 1 billion 2-byte characters that will fit into a NVARCHAR(MAX) field.

Using the other answer's more detailed numbers, you should be able to store

(2 ^ 31 - 1 - 2) / 2 = 1'073'741'822 double-byte characters

1 billion, 73 million, 741 thousand and 822 characters to be precise

in your NVARCHAR(MAX) column (unfortunately, that last half character is wasted...)

Update: as @MartinMulder pointed out: any variable length character column also has a 2 byte overhead for storing the actual length - so I needed to subtract two more bytes from the 2 ^ 31 - 1 length I had previously stipulated - thus you can store 1 Unicode character less than I had claimed before.

change Oracle user account status from EXPIRE(GRACE) to OPEN

set long 9999999
set lin 400
select DBMS_METADATA.GET_DDL('USER','YOUR_USER_NAME') from dual;

This will output something like this:

SQL> select DBMS_METADATA.GET_DDL('USER','WILIAM') from dual;

DBMS_METADATA.GET_DDL('USER','WILIAM')
--------------------------------------------------------------------------------

   CREATE USER "WILIAM" IDENTIFIED BY VALUES 'S:6680C1468F5F3B36B726CE7620F
FD9657F0E0E49AE56AAACE847BA368CEB;120F24A4C2554B4F'
      DEFAULT TABLESPACE "USER"
      TEMPORARY TABLESPACE "TEMP"
      PASSWORD EXPIRE

Just use the first piece of that with alter user instead:

ALTER USER "WILIAM" IDENTIFIED BY VALUES 'S:6680C1468F5F3B36B726CE7620F
FD9657F0E0E49AE56AAACE847BA368CEB;120F24A4C2554B4F';

This will put the account back in to OPEN status without changing the password (as long as you cut and paste correctly the hash value from the output of DBMS_METADATA.GET_DDL) and you don't even need to know what the password is.

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

eval command in Bash and its typical uses

I originally intentionally never learned how to use eval, because most people will recommend to stay away from it like the plague. However I recently discovered a use case that made me facepalm for not recognizing it sooner.

If you have cron jobs that you want to run interactively to test, you might view the contents of the file with cat, and copy and paste the cron job to run it. Unfortunately, this involves touching the mouse, which is a sin in my book.

Lets say you have a cron job at /etc/cron.d/repeatme with the contents:

*/10 * * * * root program arg1 arg2

You cant execute this as a script with all the junk in front of it, but we can use cut to get rid of all the junk, wrap it in a subshell, and execute the string with eval

eval $( cut -d ' ' -f 6- /etc/cron.d/repeatme)

The cut command only prints out the 6th field of the file, delimited by spaces. Eval then executes that command.

I used a cron job here as an example, but the concept is to format text from stdout, and then evaluate that text.

The use of eval in this case is not insecure, because we know exactly what we will be evaluating before hand.

How to capture UIView to UIImage without loss of quality on retina display

Here's a Swift 4 UIView extension based on the answer from @Dima.

extension UIView {
   func snapshotImage() -> UIImage? {
       UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
       drawHierarchy(in: bounds, afterScreenUpdates: false)
       let image = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()
       return image
   }
}

Entity Framework is Too Slow. What are my options?

I have found the answer by @Slauma here very useful for speeding things up. I used the same sort of pattern for both inserts and updates - and performance rocketed.

How do I copy an entire directory of files into an existing directory using Python?

The previous solution has some issue that src may overwrite dst without any notification or exception.

I add a predict_error method to predict errors before copy.copytree mainly base on Cyrille Pontvieux's version.

Using predict_error to predict all errors at first is best, unless you like to see exception raised one by another when execute copytree until fix all error.

def predict_error(src, dst):  
    if os.path.exists(dst):
        src_isdir = os.path.isdir(src)
        dst_isdir = os.path.isdir(dst)
        if src_isdir and dst_isdir:
            pass
        elif src_isdir and not dst_isdir:
            yield {dst:'src is dir but dst is file.'}
        elif not src_isdir and dst_isdir:
            yield {dst:'src is file but dst is dir.'}
        else:
            yield {dst:'already exists a file with same name in dst'}

    if os.path.isdir(src):
        for item in os.listdir(src):
            s = os.path.join(src, item)
            d = os.path.join(dst, item)
            for e in predict_error(s, d):
                yield e


def copytree(src, dst, symlinks=False, ignore=None, overwrite=False):
    '''
    would overwrite if src and dst are both file
    but would not use folder overwrite file, or viceverse
    '''
    if not overwrite:
        errors = list(predict_error(src, dst))
        if errors:
            raise Exception('copy would overwrite some file, error detail:%s' % errors)

    if not os.path.exists(dst):
        os.makedirs(dst)
        shutil.copystat(src, dst)
    lst = os.listdir(src)
    if ignore:
        excl = ignore(src, lst)
        lst = [x for x in lst if x not in excl]
    for item in lst:
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if symlinks and os.path.islink(s):
            if os.path.lexists(d):
                os.remove(d)
            os.symlink(os.readlink(s), d)
            try:
                st = os.lstat(s)
                mode = stat.S_IMODE(st.st_mode)
                os.lchmod(d, mode)
            except:
                pass  # lchmod not available
        elif os.path.isdir(s):
            copytree(s, d, symlinks, ignore)
        else:
            if not overwrite:
                if os.path.exists(d):
                    continue
            shutil.copy2(s, d)

Get folder name from full file path

Based on previous answers (but fixed)

using static System.IO.Path;

var dir = GetFileName(path?.TrimEnd(DirectorySeparatorChar, AltDirectorySeparatorChar));

Explanation of GetFileName from .NET source:

Returns the name and extension parts of the given path. The resulting string contains the characters of path that follow the last backslash ("\"), slash ("/"), or colon (":") character in path. The resulting string is the entire path if path contains no backslash after removing trailing slashes, slash, or colon characters. The resulting string is null if path is null.

Creating a thumbnail from an uploaded image

You Can Use The Simplest Method

<?php
function make_thumb($src, $dest, $desired_width) {

    /* read the source image */
    $source_image = imagecreatefromjpeg($src);
    $width = imagesx($source_image);
    $height = imagesy($source_image);

    /* find the "desired height" of this thumbnail, relative to the desired width  */
    $desired_height = floor($height * ($desired_width / $width));

    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

    /* copy source image at a resized size */
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

    /* create the physical thumbnail image to its destination */
    imagejpeg($virtual_image, $dest);
}

$src="1494684586337H.jpg";
$dest="new.jpg";
$desired_width="200";
make_thumb($src, $dest, $desired_width);
?>

How do you kill all current connections to a SQL Server 2005 database?

I've always used:


ALTER DATABASE DB_NAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
GO 
SP_RENAMEDB 'DB_NAME','DB_NAME_NEW'
Go 
ALTER DATABASE DB_NAME_NEW  SET MULTI_USER -- set back to multi user 
GO 

How to check if input file is empty in jQuery

To check whether the input file is empty or not by using the file length property, index should be specified like the following:

var vidFileLength = $("#videoUploadFile")[0].files.length;
if(vidFileLength === 0){
    alert("No file selected.");
}

How do you check "if not null" with Eloquent?

If you want to search deleted record (Soft Deleted Record), do't user Eloquent Model Query. Instead use Db::table query e.g Instead of using Below:

$stu = Student::where('rollNum', '=', $rollNum . '-' . $nursery)->first();

Use:

$stu = DB::table('students')->where('rollNum', '=', $newRollNo)->first();

ansible : how to pass multiple commands

If a value in YAML begins with a curly brace ({), the YAML parser assumes that it is a dictionary. So, for cases like this where there is a (Jinja2) variable in the value, one of the following two strategies needs to be adopted to avoiding confusing the YAML parser:

Quote the whole command:

- command: "{{ item }} chdir=/src/package/"
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install    

or change the order of the arguments:

- command: chdir=/src/package/ {{ item }}
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install

Thanks for @RamondelaFuente alternative suggestion.

SQL is null and = null

I think that equality is something that can be absolutely determined. The trouble with null is that it's inherently unknown. Null combined with any other value is null - unknown. Asking SQL "Is my value equal to null?" would be unknown every single time, even if the input is null. I think the implementation of IS NULL makes it clear.

How To: Best way to draw table in console app (C#)

In case if this helps someone, this is a simple class I wrote for my need. You can change it easily to fit your needs.

using System.Collections.Generic;
using System.Linq;

namespace Utilities
{
    public class TablePrinter
    {
        private readonly string[] titles;
        private readonly List<int> lengths;
        private readonly List<string[]> rows = new List<string[]>();

        public TablePrinter(params string[] titles)
        {
            this.titles = titles;
            lengths = titles.Select(t => t.Length).ToList();
        }

        public void AddRow(params object[] row)
        {
            if (row.Length != titles.Length)
            {
                throw new System.Exception($"Added row length [{row.Length}] is not equal to title row length [{titles.Length}]");
            }
            rows.Add(row.Select(o => o.ToString()).ToArray());
            for (int i = 0; i < titles.Length; i++)
            {
                if (rows.Last()[i].Length > lengths[i])
                {
                    lengths[i] = rows.Last()[i].Length;
                }
            }
        }

        public void Print()
        {
            lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
            System.Console.WriteLine("+");

            string line = "";
            for (int i = 0; i < titles.Length; i++)
            {
                line += "| " + titles[i].PadRight(lengths[i]) + ' ';
            }
            System.Console.WriteLine(line + "|");

            lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
            System.Console.WriteLine("+");

            foreach (var row in rows)
            {
                line = "";
                for (int i = 0; i < row.Length; i++)
                {
                    if (int.TryParse(row[i], out int n))
                    {
                        line += "| " + row[i].PadLeft(lengths[i]) + ' ';  // numbers are padded to the left
                    }
                    else
                    {
                        line += "| " + row[i].PadRight(lengths[i]) + ' ';
                    }
                }
                System.Console.WriteLine(line + "|");
            }

            lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
            System.Console.WriteLine("+");
        }
    }
}

Sample usage:

var t = new TablePrinter("id", "Column A", "Column B");
t.AddRow(1, "Val A1", "Val B1");
t.AddRow(2, "Val A2", "Val B2");
t.AddRow(100, "Val A100", "Val B100");
t.Print();

Output:

+-----+----------+----------+
| id  | Column A | Column B |
+-----+----------+----------+
|   1 | Val A1   | Val B1   |
|   2 | Val A2   | Val B2   |
| 100 | Val A100 | Val B100 |
+-----+----------+----------+

How to embed a SWF file in an HTML page?

I use http://wiltgen.net/objecty/, it helps to embed media content and avoid the IE "click to activate" problem.

Get width height of remote image from url

Get image size with jQuery

function getMeta(url){
    $("<img/>",{
        load : function(){
            alert(this.width+' '+this.height);
        },
        src  : url
    });
}

Get image size with JavaScript

function getMeta(url){   
    var img = new Image();
    img.onload = function(){
        alert( this.width+' '+ this.height );
    };
    img.src = url;
}

Get image size with JavaScript (modern browsers, IE9+ )

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

Use the above simply as: getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

How does Task<int> become an int?

Does an implicit conversion occur between Task<> and int?

Nope. This is just part of how async/await works.

Any method declared as async has to have a return type of:

  • void (avoid if possible)
  • Task (no result beyond notification of completion/failure)
  • Task<T> (for a logical result of type T in an async manner)

The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length - you can't make the method just return int, as the actual method will return when it hits the first await expression which hasn't already completed. So instead, it returns a Task<int> which will complete when the async method itself completes.

Note that await does the opposite - it unwraps a Task<T> to a T value, which is how this line works:

string urlContents = await getStringTask;

... but of course it unwraps it asynchronously, whereas just using Result would block until the task had completed. (await can unwrap other types which implement the awaitable pattern, but Task<T> is the one you're likely to use most often.)

This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:

public async Task<int> AccessTheWebAndDoubleAsync()
{
    var task = AccessTheWebAsync();
    int result = await task;
    return result * 2;
}

(Or simply return await AccessTheWebAsync() * 2; of course.)

Looping from 1 to infinity in Python

def to_infinity():
    index = 0
    while True:
        yield index
        index += 1

for i in to_infinity():
    if i > 10:
        break

Can you change a path without reloading the controller in AngularJS?

Answers above, including the GitHub one, had some issues for my scenario and also back button or direct url change from browser was reloading the controller, which I did not like. I finally went with the following approach:

1. Define a property in route definitions, called 'noReload' for those routes where you don't want the controller to reload on route change.

.when('/:param1/:param2?/:param3?', {
    templateUrl: 'home.html',
    controller: 'HomeController',
    controllerAs: 'vm',
    noReload: true
})

2. In the run function of your module, put the logic that checks for those routes. It will prevent reload only if noReload is true and previous route controller is the same.

fooRun.$inject = ['$rootScope', '$route', '$routeParams'];

function fooRun($rootScope, $route, $routeParams) {
    $rootScope.$on('$routeChangeStart', function (event, nextRoute, lastRoute) {
        if (lastRoute && nextRoute.noReload 
         && lastRoute.controller === nextRoute.controller) {
            var un = $rootScope.$on('$locationChangeSuccess', function () {
                un();
                // Broadcast routeUpdate if params changed. Also update
                // $routeParams accordingly
                if (!angular.equals($route.current.params, lastRoute.params)) {
                    lastRoute.params = nextRoute.params;
                    angular.copy(lastRoute.params, $routeParams);
                    $rootScope.$broadcast('$routeUpdate', lastRoute);
                }
                // Prevent reload of controller by setting current
                // route to the previous one.
                $route.current = lastRoute;
            });
        }
    });
}

3. Finally, in the controller, listen to $routeUpdate event so you can do whatever you need to do when route parameters change.

HomeController.$inject = ['$scope', '$routeParams'];

function HomeController($scope, $routeParams) {
    //(...)

    $scope.$on("$routeUpdate", function handler(route) {
        // Do whatever you need to do with new $routeParams
        // You can also access the route from the parameter passed
        // to the event
    });

    //(...)
}

Keep in mind that with this approach, you don't change things in the controller and then update the path accordingly. It's the other way around. You first change the path, then listen to $routeUpdate event to change things in the controller when route parameters change.

This keeps things simple and consistent as you can use the same logic both when you simply change path (but without expensive $http requests if you like) and when you completely reload the browser.

Xcode error "Could not find Developer Disk Image"

This error occurs when the version of Xcode predates that of the device.

For example, attempting to run a build on a device running iOS 9.3 in Xcode 7.2 results in this error; Could not find Developer Disk Image.

Why an error message that actually describes what the hell is going on can't be provided is beyond me (Apple, I'm looking at you ).

Update to the latest version of Xcode through the App Store or via direct download to guarantee interoperability with connected iOS hardware.

printing all contents of array in C#

I upvoted the extension method answer by Matthew Watson, but if you're migrating/visiting coming from Python, you may find such a method useful:

class Utils
{
    static void dump<T>(IEnumerable<T> list, string glue="\n")
    {
        Console.WriteLine(string.Join(glue, list.Select(x => x.ToString())));
    }
}

-> this will print any collection using the separator provided. It's quite limited (nested collections?).

For a script (i.e. a C# console application which only contains Program.cs, and most things happen in Program.Main) - this may be just fine.

Simple Android RecyclerView example

implementation androidx.recyclerview:recyclerview:.... It is advised to update to the androidx libraries which are here:

https://developer.android.com/jetpack/androidx/releases/recyclerview

The layout file Widget XML tag then must be updated to: androidx.recyclerview.widget.RecyclerView

python pandas remove duplicate columns

Fast and easy way to drop the duplicated columns by their values:

df = df.T.drop_duplicates().T

More info: Pandas DataFrame drop_duplicates manual .

MIT vs GPL license

You are correct that the GPL is more restrictive than the MIT license.

You cannot include GPL code in a MIT licensed product. If you distribute a combined work that combines GPL and MIT code (except in some particular situations, e.g. 'mere aggregation'), that distribution must be compliant with the GPL.

You can include MIT licensed code in a GPL product. The whole combined work must be distributed in a way compliant with the GPL. If you have made changes to the MIT parts of the code, you would be required to publish the source for those changes if you distribute an application that contains GPL and MIT code.

If you are the copyright owner of the GPL code, you can of course choose to release that code under the MIT license instead - in that case it's your code and you can publish it under as many licenses as you want.

How do I replace text inside a div element?


function showPanel(fieldName) {
  var fieldNameElement = document.getElementById("field_name");
  while(fieldNameElement.childNodes.length >= 1) {
    fieldNameElement.removeChild(fieldNameElement.firstChild);
  }
  fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName));
}

The advantages of doing it this way:

  1. It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML
  2. fieldName might contain HTML, which could be an attempted XSS attack. If we know it's just text, we should be creating a text node, instead of having the browser parse it for HTML

If I were going to use a javascript library, I'd use jQuery, and do this:


  $("div#field_name").text(fieldName);

Note that @AnthonyWJones' comment is correct: "field_name" isn't a particularly descriptive id or variable name.

@synthesize vs @dynamic, what are the differences?

@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass or will be provided at runtime).

Uses for @dynamic are e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet.

@dynamic also can be used to delegate the responsibility of implementing the accessors. If you implement the accessors yourself within the class then you normally do not use @dynamic.

Super class:

@property (nonatomic, retain) NSButton *someButton;
...
@synthesize someButton;

Subclass:

@property (nonatomic, retain) IBOutlet NSButton *someButton;
...
@dynamic someButton;

Why are #ifndef and #define used in C++ header files?

Those are called #include guards.

Once the header is included, it checks if a unique value (in this case HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page.

When the code is included again, the first ifndef fails, resulting in a blank file.

That prevents double declaration of any identifiers such as types, enums and static variables.

Combine two pandas Data Frames (join on a common column)

You can use merge to combine two dataframes into one:

import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')

where on specifies field name that exists in both dataframes to join on, and how defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y'). if you wanted to do something like star_restaurant_id and star_restaurant_review, you can do:

 pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))

The parameters are explained in detail in this link.

Angularjs: input[text] ngChange fires while the value is changing

This is about recent additions to AngularJS, to serve as future answer (also for another question).

Angular newer versions (now in 1.3 beta), AngularJS natively supports this option, using ngModelOptions, like

ng-model-options="{ updateOn: 'default blur', debounce: { default: 500, blur: 0 } }"

NgModelOptions docs

Example:

<input type="text" name="username"
       ng-model="user.name"
       ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0} }" />

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

String replacement in Objective-C

NSString objects are immutable (they can't be changed), but there is a mutable subclass, NSMutableString, that gives you several methods for replacing characters within a string. It's probably your best bet.

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

Checking for an empty field with MySQL

This will work but there is still the possibility of a null record being returned. Though you may be setting the email address to a string of length zero when you insert the record, you may still want to handle the case of a NULL email address getting into the system somehow.

     $aUsers=$this->readToArray('
     SELECT `userID` 
     FROM `users` 
     WHERE `userID` 
     IN(SELECT `userID`
               FROM `users_indvSettings`
               WHERE `indvSettingID`=5 AND `optionID`='.$time.')
     AND `email` != "" AND `email` IS NOT NULL
     ');

How do I activate a specific workbook and a specific sheet?

The code that worked for me is:

ThisWorkbook.Sheets("sheetName").Activate

Read file from resources folder in Spring Boot

if you have for example config folder under Resources folder I tried this Class working perfectly hope be useful

File file = ResourceUtils.getFile("classpath:config/sample.txt")

//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);

Turning Sonar off for certain code

This is a FAQ. You can put //NOSONAR on the line triggering the warning. I prefer using the FindBugs mechanism though, which consists in adding the @SuppressFBWarnings annotation:

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
    value = "NAME_OF_THE_FINDBUGS_RULE_TO_IGNORE",
    justification = "Why you choose to ignore it")

Serializing a list to JSON

If you're doing this in the context of a asp.Net Core API action, the conversion to Json is done implicitly.

[HttpGet]
public ActionResult Get()
{
    return Ok(TheList);
}

Removing Conda environment

if you are in base:

(base) HP-Compaq-Elite-8300-CMT:~$ 

remove env_name by:

conda env remove -n env_name

if you are already in env_name environment :

(env_name) HP-Compaq-Elite-8300-CMT:~$ 

deactivate then remove by :

conda deactivate
conda env remove -n env_name

libxml install error using pip

I am using Ubuntu 14.04 and this solves the issue for me

sudo apt-get build-dep python3-lxml
sudo apt-get install libxml2-dev libxslt-dev python-dev

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

Same here with

dependencies {
    compile 'org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0'
}

packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE'
}

I lost like 2 days for that weird error... Why is this still happening in gradle 1.0.0 ? That is very disturbing for newbies... Anyway, thanks for that info i thought it was on my code :)

How to pass a value from one jsp to another jsp page?

Use sessions

On your search.jsp

Put your scard in sessions using session.setAttribute("scard","scard")

//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.

And in your next page you retrieve it using session.getAttribute("scard")

UPDATE

<input type="text" value="<%=session.getAttribute("scard")%>"/>

HTML5 Video autoplay on iPhone

iOs 10+ allow video autoplay inline. but you have to turn off "Low power mode" on your iPhone.

echo that outputs to stderr

If you don't mind logging the message also to syslog, the not_so_ugly way is:

logger -s $msg

The -s option means: "Output the message to standard error as well as to the system log."

Why am I getting "IndentationError: expected an indented block"?

in python intended block mean there is every thing must be written in manner in my case I written it this way

 def btnClick(numbers):
 global operator
 operator = operator + str(numbers)
 text_input.set(operator)

Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code

def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)

How to align the checkbox and label in same line in html?

Just place a div around the input and label...

    <li>
      <div>
        <input id="checkid"  type="checkbox" value="test" />
      </div>
      <div>
        <label  style="word-wrap:break-word">testdata</label>
      </div>
    </li>

Python Pandas Counting the Occurrences of a Specific value

Try this:

(df[education]=='9th').sum()

Difference between .on('click') vs .click()

Here you will get list of diffrent ways of applying the click event. You can select accordingly as suaitable or if your click is not working just try an alternative out of these.

$('.clickHere').click(function(){ 
     // this is flat click. this event will be attatched 
     //to element if element is available in 
     //dom at the time when JS loaded. 

  // do your stuff
});

$('.clickHere').on('click', function(){ 
    // same as first one

    // do your stuff
})

$(document).on('click', '.clickHere', function(){
          // this is diffrent type 
          //  of click. The click will be registered on document when JS 
          //  loaded and will delegate to the '.clickHere ' element. This is 
          //  called event delegation 
   // do your stuff
});

$('body').on('click', '.clickHere', function(){
   // This is same as 3rd 
   // point. Here we used body instead of document/

   // do your stuff
});

$('.clickHere').off().on('click', function(){ // 
    // deregister event listener if any and register the event again. This 
    // prevents the duplicate event resistration on same element. 
    // do your stuff
})

How to pass a user / password in ansible command

I used the command

ansible -i inventory example -m ping -u <your_user_name> --ask-pass

And it will ask for your password.

For anyone who gets the error:

to use the 'ssh' connection type with passwords, you must install the sshpass program

On MacOS, you can follow below instructions to install sshpass:

  1. Download the Source Code
  2. Extract it and cd into the directory
  3. ./configure
  4. sudo make install

Installing specific package versions with pip

Sometimes, the previously installed version is cached.

~$ pip install pillow==5.2.0

It returns the followings:
Requirement already satisfied: pillow==5.2.0 in /home/ubuntu/anaconda3/lib/python3.6/site-packages (5.2.0)

We can use --no-cache-dir together with -I to overwrite this

~$ pip install --no-cache-dir -I pillow==5.2.0

How to launch a Google Chrome Tab with specific URL using C#

As a simplification to chrfin's response, since Chrome should be on the run path if installed, you could just call:

Process.Start("chrome.exe", "http://www.YourUrl.com");

This seem to work as expected for me, opening a new tab if Chrome is already open.

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

Android notification is not showing

You were missing the small icon. I did the same mistake and the above step resolved it.

As per the official documentation: A Notification object must contain the following:

  1. A small icon, set by setSmallIcon()

  2. A title, set by setContentTitle()

  3. Detail text, set by setContentText()

  4. On Android 8.0 (API level 26) and higher, a valid notification channel ID, set by setChannelId() or provided in the NotificationCompat.Builder constructor when creating a channel.

See http://developer.android.com/guide/topics/ui/notifiers/notifications.html

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

Testing if value is a function

I'm replacing a submit button with an anchor link. Since calling form.submit() does not activate onsubmit's, I'm finding it, and eval()ing it myself. But I'd like to check if the function exists before just eval()ing what's there. – gms8994

<script type="text/javascript">
function onsubmitHandler() {
    alert('running onsubmit handler');
    return true;
}
function testOnsubmitAndSubmit(f) {
    if (typeof f.onsubmit === 'function') {
        // onsubmit is executable, test the return value
        if (f.onsubmit()) {
            // onsubmit returns true, submit the form
            f.submit();
        }
    }
}
</script>

<form name="theForm" onsubmit="return onsubmitHandler();">
<a href="#" onclick="
    testOnsubmitAndSubmit(document.forms['theForm']);
    return false;
"></a>
</form>

EDIT : missing parameter f in function testOnsubmitAndSubmit

The above should work regardless of whether you assign the onsubmit HTML attribute or assign it in JavaScript:

document.forms['theForm'].onsubmit = onsubmitHandler;

What is the meaning of polyfills in HTML5?

First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.

The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "

Source and example of polyfill here:

http://www.programmerinterview.com/index.php/html5/html5-polyfill/

A html space is showing as %2520 instead of %20

Try this?

encodeURIComponent('space word').replace(/%20/g,'+')

Get the number of rows in a HTML table

In the DOM, a tr element is (implicitly or explicitly) a child of tbody, thead, or tfoot, not a child of table (hence the 0 you got). So a general answer is:

var count = $('#gvPerformanceResult > * > tr').length;

This includes the rows of the table but excludes rows of any inner table.

Change color of Back button in navigation bar

Swift 4.2

Change complete app theme

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        UINavigationBar.appearance().tintColor = .white

        return true
    }

Change specific controller

let navController = UINavigationController.init(rootViewController: yourViewController) 
navController.navigationBar.tintColor = .red

present(navController, animated: true, completion: nil)

Write to text file without overwriting in Java

try this one

_x000D_
_x000D_
public void writeFile(String arg1,String arg2) {_x000D_
  try {_x000D_
   if (!dir.exists()) {_x000D_
_x000D_
    if (dir.mkdirs()) {_x000D_
_x000D_
     Toast.makeText(getBaseContext(), "Directory created",_x000D_
       Toast.LENGTH_SHORT).show();_x000D_
    } else {_x000D_
     Toast.makeText(getBaseContext(),_x000D_
       "Error writng file " + filename, Toast.LENGTH_LONG)_x000D_
       .show();_x000D_
    }_x000D_
   }_x000D_
_x000D_
   else {_x000D_
_x000D_
    File file = new File(dir, filename);_x000D_
    if (!file.exists()) {_x000D_
     file.createNewFile();_x000D_
    }_x000D_
    _x000D_
    FileWriter fileWritter = new FileWriter(file, true);_x000D_
    BufferedWriter bufferWritter = new BufferedWriter(fileWritter);_x000D_
    bufferWritter.write(arg1 + "\n");_x000D_
    bufferWritter.close();_x000D_
_x000D_
            } catch (Exception e) {_x000D_
   e.printStackTrace();_x000D_
   Toast.makeText(getBaseContext(),_x000D_
     "Error writng file " + e.toString(), Toast.LENGTH_LONG)_x000D_
     .show();_x000D_
  }_x000D_
_x000D_
 }
_x000D_
_x000D_
_x000D_

Xcopy Command excluding files and folders

It is same as above answers, but is simple in steps

c:\SRC\folder1

c:\SRC\folder2

c:\SRC\folder3

c:\SRC\folder4

to copy all above folders to c:\DST\ except folder1 and folder2.

Step1: create a file c:\list.txt with below content, one folder name per one line

folder1\

folder2\

Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt

Find the files existing in one directory but not in the other

The accepted answer will also list the files that exist in both directories, but have different content. To list ONLY the files that exist in dir1 you can use:

diff -r dir1 dir2 | grep 'Only in' | grep dir1 | awk '{print $4}' > difference1.txt

Explanation:

  • diff -r dir1 dir2 : compare
  • grep 'Only in': get lines that contain 'Only in'
  • grep dir1 : get lines that contain dir

How to check a string for specific characters?

Quick comparison of timings in response to the post by Abbafei:

import timeit

def func1():
    phrase = 'Lucky Dog'
    return any(i in 'LD' for i in phrase)

def func2():
    phrase = 'Lucky Dog'
    if ('L' in phrase) or ('D' in phrase):
        return True
    else:
        return False

if __name__ == '__main__': 
    func1_time = timeit.timeit(func1, number=100000)
    func2_time = timeit.timeit(func2, number=100000)
    print('Func1 Time: {0}\nFunc2 Time: {1}'.format(func1_time, func2_time))

Output:

Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371

So the code is more compact with any, but faster with the conditional.


EDIT : TL;DR -- For long strings, if-then is still much faster than any!

I decided to compare the timing for a long random string based on some of the valid points raised in the comments:

# Tested in Python 2.7.14

import timeit
from string import ascii_letters
from random import choice

def create_random_string(length=1000):
    random_list = [choice(ascii_letters) for x in range(length)]
    return ''.join(random_list)

def function_using_any(phrase):
    return any(i in 'LD' for i in phrase)

def function_using_if_then(phrase):
    if ('L' in phrase) or ('D' in phrase):
        return True
    else:
        return False

if __name__ == '__main__':
    random_string = create_random_string(length=2000)
    func1_time = timeit.timeit(stmt="function_using_any(random_string)",
                               setup="from __main__ import function_using_any, random_string",
                               number=200000)
    func2_time = timeit.timeit(stmt="function_using_if_then(random_string)",
                               setup="from __main__ import function_using_if_then, random_string",
                               number=200000)
    print('Time for function using any: {0}\nTime for function using if-then: {1}'.format(func1_time, func2_time))

Output:

Time for function using any: 0.1342546
Time for function using if-then: 0.0201827

If-then is almost an order of magnitude faster than any!

removing html element styles via javascript

you can just do:

element.removeAttribute("style")

How to force a line break in a long word in a DIV?

I was just Googling the same issue, and posted my final solution HERE. It's relevant to this question too.

You can do this easily with a div by giving it the style word-wrap: break-word (and you may need to set its width, too).

div {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
    width: 100%;
}

However, for tables, you also need to apply: table-layout: fixed. This means the columns widths are no longer fluid, but are defined based on the widths of the columns in the first row only (or via specified widths). Read more here.

Sample code:

table {
    table-layout: fixed;
    width: 100%;
}

table td {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
}

How to insert the current timestamp into MySQL database using a PHP insert query

Forgot to put the variable in the sql statement without quotations.

 $update_query = 
      "UPDATE db.tablename SET insert_time=NOW() WHERE username='" .$somename."'";

Is mongodb running?

I find:

ps -ax | grep mongo

To be a lot more consistent. The value returned can be used to detect how many instances of mongod there are running

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

Difference between $(this) and event.target?

http://api.jquery.com/on/ states:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.)

To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

If we have

<input type="button" class="btn" value ="btn1">
<input type="button" class="btn" value ="btn2">
<input type="button" class="btn" value ="btn3">

<div id="outer">
    <input type="button"  value ="OuterB" id ="OuterB">
    <div id="inner">
        <input type="button" class="btn" value ="InnerB" id ="InnerB">
    </div>
</div>

Check the below output:

<script>
    $(function(){
        $(".btn").on("click",function(event){
            console.log($(this));
            console.log($(event.currentTarget));
            console.log($(event.target));
        });


        $("#outer").on("click",function(event){
            console.log($(this));
            console.log($(event.currentTarget));
            console.log($(event.target));
        })
    })
</script>

Note that I use $ to wrap the dom element in order to create a jQuery object, which is how we always do.

You would find that for the first case, this ,event.currentTarget,event.target are all referenced to the same element.

While in the second case, when the event delegate to some wrapped element are triggered, event.target would be referenced to the triggered element, while this and event.currentTarget are referenced to where the event is delivered.

For this and event.currentTarget, they are exactly the same thing according to http://api.jquery.com/event.currenttarget/

What is reflection and why is it useful?

Example:

Take for example a remote application which gives your application an object which you obtain using their API Methods . Now based on the object you might need to perform some sort of computation .

The provider guarantees that object can be of 3 types and we need to perform computation based on what type of object .

So we might implement in 3 classes each containing a different logic .Obviously the object information is available in runtime so you cannot statically code to perform computation hence reflection is used to instantiate the object of the class that you require to perform the computation based on the object received from the provider .

What are these attributes: `aria-labelledby` and `aria-hidden`

HTML5 ARIA attribute is what you're looking for. It can be used in your code even without bootstrap.

Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications (especially those developed with Ajax and JavaScript) more accessible to people with disabilities.

To be precise for your question, here is what your attributes are called as ARIA attribute states and model

aria-labelledby: Identifies the element (or elements) that labels the current element.

aria-hidden (state): Indicates that the element and all of its descendants are not visible or perceivable to any user as implemented by the author.

Start/Stop and Restart Jenkins service on Windows

To Start Jenkins through Command Line

  1. Run CMD with admin

  2. You can run following commands

    "net start servicename" to start

    "net restart servicename" to restart

    "net stop servicename" to stop service

for more reference https://www.windows-commandline.com/start-stop-service-command-line/

Why is php not running?

One big gotcha is that PHP is disabled in user home directories by default, so if you are testing from ~/public_html it doesn't work. Check /etc/apache2/mods-enabled/php5.conf

# Running PHP scripts in user directories is disabled by default
# 
# To re-enable PHP in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.
#<IfModule mod_userdir.c>
#    <Directory /home/*/public_html>
#        php_admin_flag engine Off
#    </Directory>
#</IfModule>

Other than that installing in Ubuntu is real easy, as all the stuff you used to have to put in httpd.conf is done automatically.

Read a javascript cookie by name

Here is an example implementation, which would make this process seamless (Borrowed from AngularJs)

var CookieReader = (function(){
var lastCookies = {};
var lastCookieString = '';

function safeGetCookie() {
    try {
        return document.cookie || '';
    } catch (e) {
        return '';
    }
}

function safeDecodeURIComponent(str) {
    try {
        return decodeURIComponent(str);
    } catch (e) {
        return str;
    }
}

function isUndefined(value) {
    return typeof value === 'undefined';
}

return function () {
    var cookieArray, cookie, i, index, name;
    var currentCookieString = safeGetCookie();

    if (currentCookieString !== lastCookieString) {
        lastCookieString = currentCookieString;
        cookieArray = lastCookieString.split('; ');
        lastCookies = {};

        for (i = 0; i < cookieArray.length; i++) {
            cookie = cookieArray[i];
            index = cookie.indexOf('=');
            if (index > 0) { //ignore nameless cookies
                name = safeDecodeURIComponent(cookie.substring(0, index));

                if (isUndefined(lastCookies[name])) {
                    lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
                }
            }
        }
    }
    return lastCookies;
};
})();

How to display a confirmation dialog when clicking an <a> link?

This method is slightly different than either of the above answers if you attach your event handler using addEventListener (or attachEvent).

function myClickHandler(evt) {
  var allowLink = confirm('Continue with link?');
  if (!allowLink) {
    evt.returnValue = false; //for older Internet Explorer
    if (evt.preventDefault) {
      evt.preventDefault();
    }
    return false;
  }
}

You can attach this handler with either:

document.getElementById('mylinkid').addEventListener('click', myClickHandler, false);

Or for older versions of internet explorer:

document.getElementById('mylinkid').attachEvent('onclick', myClickHandler);

How to create an empty R vector to add new items

To create an empty vector use:

vec <- c();

Please note, I am not making any assumptions about the type of vector you require, e.g. numeric.

Once the vector has been created you can add elements to it as follows:

For example, to add the numeric value 1:

vec <- c(vec, 1);

or, to add a string value "a"

vec <- c(vec, "a");

How to reformat JSON in Notepad++?

I use 32-bit Notepad++ version 7.5.6. I have found that 32-bit JSToolNpp 1.20.0 does a great job.
The direct link is:
https://sourceforge.net/projects/jsminnpp/files/Uni/JSToolNPP.1.2006.0.uni.32.zip/download
which is redirected from https://sourceforge.net/projects/jsminnpp/.
VirusTotal link:
https://www.virustotal.com/gui/file/008ee0ce889dfd9e96b975cebe6faafe28bc350352e951f3dec97e8e5bec5a07

JSON-Viewer works fine too, but cannot sort the JSON data.

In Visual Basic how do you create a block comment

There is no block comment in VB.NET.

You need to use a ' in front of every line you want to comment out.

In Visual Studio you can use the keyboard shortcuts that will comment/uncomment the selected lines for you:

Ctrl + K, C to comment

Ctrl + K, U to uncomment

REST API error code 500 handling

Generally speaking, 5xx response codes indicate non-programmatic failures, such as a database connection failure, or some other system/library dependency failure. In many cases, it is expected that the client can re-submit the same request in the future and expect it to be successful.

Yes, some web-frameworks will respond with 5xx codes, but those are typically the result of defects in the code and the framework is too abstract to know what happened, so it defaults to this type of response; that example, however, doesn't mean that we should be in the habit of returning 5xx codes as the result of programmatic behavior that is unrelated to out of process systems. There are many, well defined response codes that are more suitable than the 5xx codes. Being unable to parse/validate a given input is not a 5xx response because the code can accommodate a more suitable response that won't leave the client thinking that they can resubmit the same request, when in fact, they can not.

To be clear, if the error encountered by the server was due to CLIENT input, then this is clearly a CLIENT error and should be handled with a 4xx response code. The expectation is that the client will correct the error in their request and resubmit.

It is completely acceptable, however, to catch any out of process errors and interpret them as a 5xx response, but be aware that you should also include further information in the response to indicate exactly what failed; and even better if you can include SLA times to address.

I don't think it's a good practice to interpret, "an unexpected error" as a 5xx error because bugs happen.

It is a common alert monitor to begin alerting on 5xx types of errors because these typically indicate failed systems, rather than failed code. So, code accordingly!

LINQ: Select an object and change some properties without creating a new object

If you want to update items with a Where clause, using a .Where(...) will truncate your results if you do:

mylist = mylist.Where(n => n.Id == ID).Select(n => { n.Property = ""; return n; }).ToList();

You can do updates to specific item(s) in the list like so:

mylist = mylist.Select(n => { if (n.Id == ID) { n.Property = ""; } return n; }).ToList();

Always return item even if you don't make any changes. This way it will be kept in the list.