Programs & Examples On #Osgi

The OSGi (Open Service Gateway Initiative) framework is a module system and service platform for the Java programming language that implements a complete and dynamic component model.

Reading my own Jar's Manifest

I have used the solution from Anthony Juckel but in the MANIFEST.MF the key have to start with uppercase.

So my MANIFEST.MF file contain a key like:

Mykey: value

Then in the activator or another class you can use the code from Anthony to read the MANIFEST.MF file and the the value that you need.

// If you have a BundleContext 
Dictionary headers = bundleContext.getBundle().getHeaders();

// If you don't have a context, and are running in 4.2 
Bundle bundle = `FrameworkUtil.getBundle(this.getClass()); 
bundle.getHeaders();

A cycle was detected in the build path of project xxx - Build Path Problem

When I've had these problems it always has been a true cycle in the dependencies expressed in Manifest.mf

So open the manifest of the project in question, on the Dependencies Tab, look at the "Required Plugins" entry. Then follow from there to the next project(s), and repeat eventually the cycle will become clear.

You can simpify this task somewhat by using the Dependency Analysis links in the bottom right corner of the Dependencies Tab, this has cycle detection and easier navigation depdendencies.

I also don't know why Maven is more tolerant,

Can I do a max(count(*)) in SQL?

Depending on which database you're using...

select yr, count(*) num from ...
order by num desc

Most of my experience is in Sybase, which uses some different syntax than other DBs. But in this case, you're naming your count column, so you can sort it, descending order. You can go a step further, and restrict your results to the first 10 rows (to find his 10 busiest years).

How to predict input image using trained model in Keras?

You can use model.predict() to predict the class of a single image as follows [doc]:

# load_model_sample.py
from keras.models import load_model
from keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os


def load_image(img_path, show=False):

    img = image.load_img(img_path, target_size=(150, 150))
    img_tensor = image.img_to_array(img)                    # (height, width, channels)
    img_tensor = np.expand_dims(img_tensor, axis=0)         # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
    img_tensor /= 255.                                      # imshow expects values in the range [0, 1]

    if show:
        plt.imshow(img_tensor[0])                           
        plt.axis('off')
        plt.show()

    return img_tensor


if __name__ == "__main__":

    # load model
    model = load_model("model_aug.h5")

    # image path
    img_path = '/media/data/dogscats/test1/3867.jpg'    # dog
    #img_path = '/media/data/dogscats/test1/19.jpg'      # cat

    # load a single image
    new_image = load_image(img_path)

    # check prediction
    pred = model.predict(new_image)

In this example, a image is loaded as a numpy array with shape (1, height, width, channels). Then, we load it into the model and predict its class, returned as a real value in the range [0, 1] (binary classification in this example).

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

ULIMIT configuration:

  1. Login by root
  2. vi security/limits.conf
  3. Make Below entry

    Ulimit configuration start for website user

    website   soft   nofile    8192
    website   hard   nofile    8192
    website   soft   nproc    4096
    website   hard   nproc    8192
    website   soft   core    unlimited
    website   hard   core    unlimited
    
  4. Make Below entry for ALL USER

    Ulimit configuration for every user

    *   soft   nofile    8192
    *   hard   nofile    8192
    *   soft   nproc    4096
    *   hard   nproc    8192
    *   soft   core    unlimited
    *   hard   core    unlimited
    
  5. After modifying the file, user need to logoff and login again to see the new values.

Tuple unpacking in for loops

Take this code as an example:

elements = ['a', 'b', 'c', 'd', 'e']
index = 0

for element in elements:
  print element, index
  index += 1

You loop over the list and store an index variable as well. enumerate() does the same thing, but more concisely:

elements = ['a', 'b', 'c', 'd', 'e']

for index, element in enumerate(elements):
  print element, index

The index, element notation is required because enumerate returns a tuple ((1, 'a'), (2, 'b'), ...) that is unpacked into two different variables.

Inline Form nested within Horizontal Form in Bootstrap 3

I had problems aligning the label to the input(s) elements so I transferred the label element inside the form-inline and form-group too...and it works..

<div class="form-group">
    <div class="col-xs-10">
        <div class="form-inline">
            <div class="form-group">
                <label for="birthday" class="col-xs-2 control-label">Birthday:</label>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="year"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="month"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="day"/>
            </div>
        </div>
    </div>
</div>

Test if a command outputs an empty string

As mentioned by tripleee in the question comments , use moreutils ifne (if input not empty).

In this case we want ifne -n which negates the test:

ls -A /tmp/empty | ifne -n command-to-run-if-empty-input

The advantage of this over many of the another answers when the output of the initial command is non-empty. ifne will start writing it to STDOUT straight away, rather than buffering the entire output then writing it later, which is important if the initial output is slowly generated or extremely long and would overflow the maximum length of a shell variable.

There are a few utils in moreutils that arguably should be in coreutils -- they're worth checking out if you spend a lot of time living in a shell.

In particular interest to the OP may be dirempty/exists tool which at the time of writing is still under consideration, and has been for some time (it could probably use a bump).

Basic Apache commands for a local Windows machine

Going back to absolute basics here. The answers on this page and a little googling have brought me to the following resolution to my issue. Steps to restart the apache service with Xampp installed:-

  1. Click the start button and type CMD (if on Windows Vista or later and Apache is installed as a service make sure this is an elevated command prompt)
  2. In the command window that appears type cd C:\xampp\apache\bin (the default installation path for Xampp)
  3. Then type httpd -k restart

I hope that this is of use to others just starting out with running a local Apache server.

Setup a Git server with msysgit on Windows

I'm using GitWebAccess for many projects for half a year now, and it's proven to be the best of what I've tried. It seems, though, that lately sources are not supported, so - don't take latest binaries/sources. Currently they're broken :(

You can build from this version or download compiled binaries which I use from here.

Auto-click button element on page load using jQuery

You would simply use jQuery like so...

<script>
jQuery(function(){
   jQuery('#modal').click();
});
</script>

Use the click function to auto-click the #modal button

How would I get everything before a : in a string Python

Just use the split function. It returns a list, so you can keep the first element:

>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'

filename and line number of Python script

Handy if used in a common file - prints file name, line number and function of the caller:

import inspect
def getLineInfo():
    print(inspect.stack()[1][1],":",inspect.stack()[1][2],":",
          inspect.stack()[1][3])

What is the format specifier for unsigned short int?

For scanf, you need to use %hu since you're passing a pointer to an unsigned short. For printf, it's impossible to pass an unsigned short due to default promotions (it will be promoted to int or unsigned int depending on whether int has at least as many value bits as unsigned short or not) so %d or %u is fine. You're free to use %hu if you prefer, though.

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

I don't know if this is good enough but I made a static ThreadHelperClass class and implemented it as following .Now I can easily set text property of various controls without much coding .

public static class ThreadHelperClass
{
    delegate void SetTextCallback(Form f, Control ctrl, string text);
    /// <summary>
    /// Set text property of various controls
    /// </summary>
    /// <param name="form">The calling form</param>
    /// <param name="ctrl"></param>
    /// <param name="text"></param>
    public static void SetText(Form form, Control ctrl, string text)
    {
        // InvokeRequired required compares the thread ID of the 
        // calling thread to the thread ID of the creating thread. 
        // If these threads are different, it returns true. 
        if (ctrl.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            form.Invoke(d, new object[] { form, ctrl, text });
        }
        else
        {
            ctrl.Text = text;
        }
    }
}

Using the code:

 private void btnTestThread_Click(object sender, EventArgs e)
 {
    Thread demoThread =
       new Thread(new ThreadStart(this.ThreadProcSafe));
            demoThread.Start();
 }

 // This method is executed on the worker thread and makes 
 // a thread-safe call on the TextBox control. 
 private void ThreadProcSafe()
 {
     ThreadHelperClass.SetText(this, textBox1, "This text was set safely.");
     ThreadHelperClass.SetText(this, textBox2, "another text was set safely.");
 }

Excel 2007 - Compare 2 columns, find matching values

VLOOKUP deosnt work for String literals

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The only thing that worked for me was creating a new application in the IIS, mapping it to exactly the same physical path, and changing only the authentication to be Anonymous.

Call Jquery function

Just add click event by jquery in $(document).ready() like :

$(document).ready(function(){

                  $('#YourControlID').click(function(){
                     if(Check your condtion)
                     {
                             $.messager.show({  
                                title:'My Title',  
                                msg:'The message content',  
                                showType:'fade',  
                                style:{  
                                    right:'',  
                                    bottom:''  
                                }  
                            });  
                     }
                 });
            });

WinForms DataGridView font size

Go to designer.cs file of the form in which you have the grid view and comment the following line: - //this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;

if you are using vs 2008 or .net framework 3.5 as it will be by default applied to alternating rows.

Python logging not outputting anything

The default logging level is warning. Since you haven't changed the level, the root logger's level is still warning. That means that it will ignore any logging with a level that is lower than warning, including debug loggings.

This is explained in the tutorial:

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

The 'info' line doesn't print anything, because the level is higher than info.

To change the level, just set it in the root logger:

'root':{'handlers':('console', 'file'), 'level':'DEBUG'}

In other words, it's not enough to define a handler with level=DEBUG, the actual logging level must also be DEBUG in order to get it to output anything.

Pycharm and sys.argv arguments

Notice that for some unknown reason, it is not possible to add command line arguments in the PyCharm Edu version. It can be only done in Professional and Community editions.

How can I remove the extension of a filename in a shell script?

As pointed out by Hawker65 in the comment of chepner answer, the most voted solution does neither take care of multiple extensions (such as filename.tar.gz), nor of dots in the rest of the path (such as this.path/with.dots/in.path.name). A possible solution is:

a=this.path/with.dots/in.path.name/filename.tar.gz
echo $(dirname $a)/$(basename $a | cut -d. -f1)

htaccess redirect all pages to single page

Add this for pages not currently on your site...

ErrorDocument 404 http://example.com/

Along with your Redirect 301 / http://www.thenewdomain.com/ that should cover all the bases...

Good luck!

Why does this iterative list-growing code give IndexError: list assignment index out of range?

One more way:

j=i[0]
for k in range(1,len(i)):
    j = numpy.vstack([j,i[k]])

In this case j will be a numpy array

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

For users with two-factor authentication, you can use bennedich's solution, but you just need to add the X-Github-OTP header for the first command. Replace CODE with the code that you get from the two-factor authentication provider. Replace USER and REPO with the username and name of the repository, as you would in his solution.

curl -u 'USER' -H "X-GitHub-OTP: CODE" -d '{"name":"REPO"}' https://api.github.com/user/repos
git remote add origin [email protected]:USER/REPO.git
git push origin master

How to kill a thread instantly in C#?

You can kill instantly doing it in that way:

private Thread _myThread = new Thread(SomeThreadMethod);

private void SomeThreadMethod()
{
   // do whatever you want
}

[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
private void KillTheThread()
{
   _myThread.Abort();
}

I always use it and works for me:)

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

Relying on column order is generally a bad idea in SQL. SQL is based on Relational theory where order is never guaranteed - by design. You should treat all your columns and rows as having no order and then change your queries to provide the correct results:

For Columns:

  • Try not to use SELECT *, but instead specify the order of columns in the select list as in: SELECT Member_ID, MemberName, MemberAddress from TableName. This will guarantee order and will ease maintenance if columns get added.

For Rows:

  • Row order in your result set is only guaranteed if you specify the ORDER BY clause.
  • If no ORDER BY clause is specified the result set may differ as the Query Plan might differ or the database pages might have changed.

Hope this helps...

Alter and Assign Object Without Side Effects

You will have the same object two times in your array, because object values are passed by reference. You have to create a new object like this

myElement.id = 244;
myElement.value = 3556;
myArray[0] = $.extend({}, myElement); //for shallow copy or
myArray[0] = $.extend(true, {}, myElement); // for deep copy

or

myArray.push({ id: 24, value: 246 });

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

how to console.log result of this ajax call?

If you want to check your URL. I suppose you are using Chrome. You can go to chrome console and URL will be displayed under "XHR finished loading:"

Convert Numeric value to Varchar

First convert the numeric value then add the 'S':

 select convert(varchar(10),StandardCost) +'S'
 from DimProduct where ProductKey = 212

jQuery ajax post file field

Try this...

<script type="text/javascript">
      $("#form_oferta").submit(function(event) 
      {
           var myData = $( form ).serialize(); 
           $.ajax({
                type: "POST", 
                contentType:attr( "enctype", "multipart/form-data" ),
                url: " URL Goes Here ",  
                data: myData,  
                success: function( data )  
                {
                     alert( data );
                }
           });
           return false;  
      });
</script>

Here the contentType is specified as multipart/form-data as we do in the form tag, this will work to upload simple file On server side you just need to write simple file upload code to handle this request with echoing message you want to show to user as a response.

Cast object to interface in TypeScript

There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:

const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;

You can check at runtime if the value is valid and if not throw an error, i.e.:

function isToDoDto(obj: any): obj is IToDoDto {
    return typeof obj.description === "string" && typeof obj.status === "boolean";
}

@Post()
addToDo(@Response() res, @Request() req) {
    if (!isToDoDto(req.body)) {
        throw new Error("invalid request");
    }

    const toDo = req.body as IToDoDto;
    this.toDoService.addToDo(toDo);
    return res.status(HttpStatus.CREATED).end();
}

Edit

As @huyz pointed out, there's no need for the type assertion because isToDoDto is a type guard, so this should be enough:

if (!isToDoDto(req.body)) {
    throw new Error("invalid request");
}

this.toDoService.addToDo(req.body);

Writing a list to a file with Python

Using numpy.savetxt is also an option:

import numpy as np

np.savetxt('list.txt', list, delimiter="\n", fmt="%s")

PHP Curl And Cookies

In working with a similar problem I created the following function after combining a lot of resources I ran into on the web, and adding my own cookie handling. Hopefully this is useful to someone else.

      function get_web_page( $url, $cookiesIn = '' ){
        $options = array(
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => true,     //return headers in addition to content
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
            CURLOPT_TIMEOUT        => 120,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
            CURLINFO_HEADER_OUT    => true,
            CURLOPT_SSL_VERIFYPEER => true,     // Validate SSL Certificates
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_COOKIE         => $cookiesIn
        );

        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $rough_content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );
        curl_close( $ch );

        $header_content = substr($rough_content, 0, $header['header_size']);
        $body_content = trim(str_replace($header_content, '', $rough_content));
        $pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m"; 
        preg_match_all($pattern, $header_content, $matches); 
        $cookiesOut = implode("; ", $matches['cookie']);

        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['headers']  = $header_content;
        $header['content'] = $body_content;
        $header['cookies'] = $cookiesOut;
    return $header;
}

Installing Tomcat 7 as Service on Windows Server 2008

To Start Tomcat7 Service :

  • Open cmd, go to bin directory within "Apache Tomcat 7" folder. You will see some this like C:\..\bin>

  • Enter above command to start the service: C:\..\bin>service.bat install. The service will get started now.

  • Enter above command to start tomcat7w monitory service. If you have issue with starting the tomcat7 service then remove the service with command : C:\..\bin>tomcat7 //DS//Tomcat7

  • Now the service will no longer exist. Try the install command again, now the service will get installed and started: C:\..\bin>tomcat7w \\MS\tomcat7w

  • You will see the tomcat 7 icon in the system tray. Now, the tomcat7 service and tomcat7w will start automatically when the windows get start.

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

Your description is a little bit strange because the GlassFish server can even start if port 1527 is occupied, because the Java Derby database is a separate java process. So one option could be to just ignore the message in case that the real GlassFish server is indeed starting correctly (NetBeans displays the output for the GlassFish server and the Derby server in different tabs).

Nevertheless you can try to disable starting the registered Derby server for your GlassFish instance.

Make sure that the Derby server is shut down, it can even still run if you have closed NetBeans. If you are not sure kill every java process via the task manager and restart NetBeans.

Right-click your GlassFish instance in the Services tab and choose Properties.

disable derby server start

If instead the real problem is that either port 8080 or 443 (if you activated the HTTPS listener) is in use (which would really prevent GlassFish from starting), you have to find out which application is using this port (maybe Tomcat or something similar) and shut it down.

The error message

'Could not start GlassFish Server 4.1: HTTP or HTTPS listener port is occupied while server is not running'

just points a little bit more in this direction...

JSON parsing using Gson for Java

Simplest thing usually is to create matching Object hierarchy, like so:

public class Wrapper {
   public Data data;
}
static class Data {
   public Translation[] translations;
}
static class Translation {
   public String translatedText;
}

and then bind using GSON, traverse object hierarchy via fields. Adding getters and setters is pointless for basic data containers.

So something like:

Wrapper value = GSON.fromJSON(jsonString, Wrapper.class);
String text = value.data.translations[0].translatedText;

How do I use CMake?

Cmake from Windows terminal:

mkdir build
cd build/
cmake ..
cmake --build . --config Release
./Release/main.exe

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

If you're using IntelliJ & Mac just go to Project structure -> SDK and make sure that there is Java listed but it points to sth like

/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

Rather than user home...

What are forward declarations in C++?

Why forward-declare is necessary in C++

The compiler wants to ensure you haven't made spelling mistakes or passed the wrong number of arguments to the function. So, it insists that it first sees a declaration of 'add' (or any other types, classes or functions) before it is used.

This really just allows the compiler to do a better job of validating the code, and allows it to tidy up loose ends so it can produce a neat looking object file. If you didn't have to forward declare things, the compiler would produce an object file that would have to contain information about all the possible guesses as to what the function 'add' might be. And the linker would have to contain very clever logic to try and work out which 'add' you actually intended to call, when the 'add' function may live in a different object file the linker is joining with the one that uses add to produce a dll or exe. It's possible that the linker may get the wrong add. Say you wanted to use int add(int a, float b), but accidentally forgot to write it, but the linker found an already existing int add(int a, int b) and thought that was the right one and used that instead. Your code would compile, but wouldn't be doing what you expected.

So, just to keep things explicit and avoid the guessing etc, the compiler insists you declare everything before it is used.

Difference between declaration and definition

As an aside, it's important to know the difference between a declaration and a definition. A declaration just gives enough code to show what something looks like, so for a function, this is the return type, calling convention, method name, arguments and their types. But the code for the method isn't required. For a definition, you need the declaration and then also the code for the function too.

How forward-declarations can significantly reduce build times

You can get the declaration of a function into your current .cpp or .h file by #includ'ing the header that already contains a declaration of the function. However, this can slow down your compile, especially if you #include a header into a .h instead of .cpp of your program, as everything that #includes the .h you're writing would end up #include'ing all the headers you wrote #includes for too. Suddenly, the compiler has #included pages and pages of code that it needs to compile even when you only wanted to use one or two functions. To avoid this, you can use a forward-declaration and just type the declaration of the function yourself at the top of the file. If you're only using a few functions, this can really make your compiles quicker compared to always #including the header. For really large projects, the difference could be an hour or more of compile time bought down to a few minutes.

Break cyclic references where two definitions both use each other

Additionally, forward-declarations can help you break cycles. This is where two functions both try to use each other. When this happens (and it is a perfectly valid thing to do), you may #include one header file, but that header file tries to #include the header file you're currently writing.... which then #includes the other header, which #includes the one you're writing. You're stuck in a chicken and egg situation with each header file trying to re #include the other. To solve this, you can forward-declare the parts you need in one of the files and leave the #include out of that file.

Eg:

File Car.h

#include "Wheel.h"  // Include Wheel's definition so it can be used in Car.
#include <vector>

class Car
{
    std::vector<Wheel> wheels;
};

File Wheel.h

Hmm... the declaration of Car is required here as Wheel has a pointer to a Car, but Car.h can't be included here as it would result in a compiler error. If Car.h was included, that would then try to include Wheel.h which would include Car.h which would include Wheel.h and this would go on forever, so instead the compiler raises an error. The solution is to forward declare Car instead:

class Car;     // forward declaration

class Wheel
{
    Car* car;
};

If class Wheel had methods which need to call methods of car, those methods could be defined in Wheel.cpp and Wheel.cpp is now able to include Car.h without causing a cycle.

Why does JavaScript only work after opening developer tools in IE once?

I guess this could help, adding this before any tag of javascript:

try{
  console
}catch(e){
   console={}; console.log = function(){};
}

Capturing standard out and error with Start-Process

Here's a kludgy way to get the output from another powershell process:

start-process -wait -nonewwindow powershell 'ps | Export-Clixml out.xml'; import-clixml out.xml

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

How to create an executable .exe file from a .m file

If your code is more of a data analysis routine (vs. visualization / GUI), try GNU Octave. It's free and many of its functions are compatible with MATLAB. (Not 100% but maybe 99.5%.)

Insert array into MySQL database with PHP

$columns = implode(", ",array_keys($data));
$escaped_values = array_map(array($con, 'real_escape_string'),array_values($data));
$values  = implode("', '", $escaped_values);
return $sql = "INSERT INTO `reservations`($columns) VALUES ('$values')";

This is improvement to the solution given by Shiplu Mokaddim

.NET Core vs Mono

.Net Core does not require mono in the sense of the mono framework. .Net Core is a framework that will work on multiple platforms including Linux. Reference https://dotnet.github.io/.

However the .Net core can use the mono framework. Reference https://docs.asp.net/en/1.0.0-rc1/getting-started/choosing-the-right-dotnet.html (note rc1 documentatiopn no rc2 available), however mono is not a Microsoft supported framework and would recommend using a supported framework

Now entity framework 7 is now called Entity Framework Core and is available on multiple platforms including Linux. Reference https://github.com/aspnet/EntityFramework (review the road map)

I am currently using both of these frameworks however you must understand that it is still in release candidate stage (RC2 is the current version) and over the beta & release candidates there have been massive changes that usually end up with you scratching your head.

Here is a tutorial on how to install MVC .Net Core into Linux. https://docs.asp.net/en/1.0.0-rc1/getting-started/installing-on-linux.html

Finally you have a choice of Web Servers (where I am assuming the fast cgi reference came from) to host your application on Linux. Here is a reference point for installing to a Linux enviroment. https://docs.asp.net/en/1.0.0-rc1/publishing/linuxproduction.html

I realise this post ends up being mostly links to documentation but at this point those are your best sources of information. .Net core is still relatively new in the .Net community and until its fully released I would be hesitant to use it in a product environment given the breaking changes between released version.

grep --ignore-case --only

This is a known bug on the initial 2.5.1, and has been fixed in early 2007 (Redhat 2.5.1-5) according to the bug reports. Unfortunately Apple is still using 2.5.1 even on Mac OS X 10.7.2.

You could get a newer version via Homebrew (3.0) or MacPorts (2.26) or fink (3.0-1).


Edit: Apparently it has been fixed on OS X 10.11 (or maybe earlier), even though the grep version reported is still 2.5.1.

Android get image path from drawable as string

I think you cannot get it as String but you can get it as int by get resource id:

int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());

Extracting numbers from vectors of strings

Update Since extract_numeric is deprecated, we can use parse_number from readr package.

library(readr)
parse_number(years)

Here is another option with extract_numeric

library(tidyr)
extract_numeric(years)
#[1] 20  1

How can I truncate a double to only two decimal places in Java?

      double value = 3.4555;
      String value1 =  String.format("% .3f", value) ;
      String value2 = value1.substring(0, value1.length() - 1);
      System.out.println(value2);         
      double doublevalue= Double.valueOf(value2);
      System.out.println(doublevalue);

How to know Laravel version and where is it defined?

If you want to know the specific version then you need to check composer.lock file and search For

"name": "laravel/framework",

you will find your version in next line

"version": "v5.7.9",

Add line break to 'git commit -m' from the command line

There is no need complicating the stuff. After the -m "text... the next line is gotten by pressing Enter. When Enter is pressed > appears. When you are done, just put " and press Enter:

$ git commit -m "Another way of demonstrating multicommit messages:
>
> This is a new line written
> This is another new line written
> This one is really awesome too and we can continue doing so till ..."

$ git log -1
commit 5474e383f2eda610be6211d8697ed1503400ee42 (HEAD -> test2)
Author: ************** <*********@gmail.com>
Date:   Mon Oct 9 13:30:26 2017 +0200

Another way of demonstrating multicommit messages:

This is a new line written
This is another new line written
This one is really awesome too and we can continue doing so till ...

Egit rejected non-fast-forward

  1. Go in Github an create a repo for your new code.
  2. Use the new https or ssh url in Eclise when you are doing the push to upstream;

PHP regular expression - filter number only

To remove anything that is not a number:

$output = preg_replace('/[^0-9]/', '', $input);

Explanation:

  • [0-9] matches any number between 0 and 9 inclusively.
  • ^ negates a [] pattern.
  • So, [^0-9] matches anything that is not a number, and since we're using preg_replace, they will be replaced by nothing '' (second argument of preg_replace).

How do I get the current date and time in PHP?

If you want a different timescale, please use:

$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);

date_default_timezone_set("Asia/Calcutta");
echo date("Y/m/d H:i:s");

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

How do I call a Django function on button click?

The following answer could be helpful for the first part of your question:

Django: How can I call a view function from template?

form_for but to post to a different action

I have done it like that

<%= form_for :user, url: {action: "update", params: {id: @user.id}} do |f| %>

Note the optional parameter id set to user instance id attribute.

Convert string to Python class object?

This could work:

import sys

def str_to_class(classname):
    return getattr(sys.modules[__name__], classname)

How to checkout a specific Subversion revision from the command line?

svn checkout to revision where your repository is on another server

Use svn log command to find out which revisions are available:

svn log

Which prints:

------------------------------------------------------------------------
r762 | machines | 2012-12-02 13:00:16 -0500 (Sun, 02 Dec 2012) | 2 lines

------------------------------------------------------------------------
r761 | machines | 2012-12-02 12:59:40 -0500 (Sun, 02 Dec 2012) | 2 lines

Note the number r761. Here is the command description:

svn export http://url-to-your-file@761 /tmp/filename

I used this command specifically:

svn export svn+ssh://[email protected]/home1/oct/calc/calcFeatures.m@761 calcFeatures.m

Which causes calcFeatures.m revision 761 to be checked out to the current directory.

Efficiently replace all accented characters in a string?

I can't speak to what you are trying to do specifically with the function itself, but if you don't like the regex being built every time, here are two solutions and some caveats about each.

Here is one way to do this:

function makeSortString(s) {
  if(!makeSortString.translate_re) makeSortString.translate_re = /[öäüÖÄÜ]/g;
  var translate = {
    "ä": "a", "ö": "o", "ü": "u",
    "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
  };
  return ( s.replace(makeSortString.translate_re, function(match) { 
    return translate[match]; 
  }) );
}

This will obviously make the regex a property of the function itself. The only thing you may not like about this (or you may, I guess it depends) is that the regex can now be modified outside of the function's body. So, someone could do this to modify the interally-used regex:

makeSortString.translate_re = /[a-z]/g;

So, there is that option.

One way to get a closure, and thus prevent someone from modifying the regex, would be to define this as an anonymous function assignment like this:

var makeSortString = (function() {
  var translate_re = /[öäüÖÄÜ]/g;
  return function(s) {
    var translate = {
      "ä": "a", "ö": "o", "ü": "u",
      "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
    };
    return ( s.replace(translate_re, function(match) { 
      return translate[match]; 
    }) );
  }
})();

Hopefully this is useful to you.


UPDATE: It's early and I don't know why I didn't see the obvious before, but it might also be useful to put you translate object in a closure as well:

var makeSortString = (function() {
  var translate_re = /[öäüÖÄÜ]/g;
  var translate = {
    "ä": "a", "ö": "o", "ü": "u",
    "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
  };
  return function(s) {
    return ( s.replace(translate_re, function(match) { 
      return translate[match]; 
    }) );
  }
})();

Read Session Id using Javascript

you can receive the session id by issuing the following regular expression on document.cookie:

alert(document.cookie.match(/PHPSESSID=[^;]+/));

in my example the cookie name to store session id is PHPSESSID (php server), just replace the PHPSESSID with the cookie name that holds the session id. (configurable by the web server)

http post - how to send Authorization header?

Ok. I found problem.

It was not on the Angular side. To be honest, there were no problem at all.

Reason why I was unable to perform my request succesfuly was that my server app was not properly handling OPTIONS request.

Why OPTIONS, not POST? My server app is on different host, then frontend. Because of CORS my browser was converting POST to OPTION: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/

With help of this answer: Standalone Spring OAuth2 JWT Authorization Server + CORS

I implemented proper filter on my server-side app.

Thanks to @Supamiu - the person which fingered me that I am not sending POST at all.

jQuery: how to find first visible input/select/textarea excluding buttons?

This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text selects input elements that have no specified type attribute (in which case type="text" is implied):

$('form').find(':text,textarea,select').filter(':visible:first')

Vagrant error : Failed to mount folders in Linux guest

Install the vagrant-vbguest plugin by running this command:

vagrant plugin install vagrant-vbguest

How to store token in Local or Session Storage in Angular 2?

Save to local storage

localStorage.setItem('currentUser', JSON.stringify({ token: token, name: name }));

Load from local storage

var currentUser = JSON.parse(localStorage.getItem('currentUser'));
var token = currentUser.token; // your token

For more I suggest you go through this tutorial: Angular 2 JWT Authentication Example & Tutorial

Node.js fs.readdir recursive directory search

here is the complete working code. As per your requirement. you can get all files and folders recursively.

var recur = function(dir) {
            fs.readdir(dir,function(err,list){
                list.forEach(function(file){
                    var file2 = path.resolve(dir, file);
                    fs.stat(file2,function(err,stats){
                        if(stats.isDirectory()) {
                            recur(file2);
                        }
                        else {
                            console.log(file2);
                        }
                    })
                })
            });
        };
        recur(path);

in path give your directory path in which you want to search like "c:\test"

PHP fopen() Error: failed to open stream: Permission denied

[function.fopen]: failed to open stream

If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :

allow_url_fopen = off
should bee this 
allow_url_fopen = On

And add this line below it:
allow_url_include = off
should bee this 
allow_url_include = on

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Stop absolutely positioned div from overlapping text

Put a z-indez of -1 on your absolute (or relative) positioned element.

This will pull it out of the stacking context. (I think.) Read more wonderful things about "stacking contexts" here: https://philipwalton.com/articles/what-no-one-told-you-about-z-index/

Rails: How to reference images in CSS within Rails 4

WHAT I HAVE FOUND AFTER HOURS OF MUCKING WITH THIS:

WORKS :

background-image: url(image_path('transparent_2x2.png')); 

// how to add attributes like repeat, center, fixed?

The above outputs something like: "/assets/transparent_2x2-ec47061dbe4fb88d51ae1e7f41a146db.png"

Notice the leading "/", and it's within quotes. Also note the scss extension and image_path helper in yourstylesheet.css.scss. The image is in the app/assets/images directory.

Doesn't work:

background: url(image_path('transparent_2x2.png') repeat center center fixed;

doesn't work, invalid property:

background:url(/assets/pretty_photo/default/sprite.png) 2px 1px repeat center fixed;

My last resort was going to be to put these in my public s3 bucket and load from there, but finally got something going.

How to add a right button to a UINavigationController?

You can try

self.navigationBar.topItem.rightBarButtonItem = anotherButton;

Extracting a parameter from a URL in WordPress

When passing parameters through the URL you're able to retrieve the values as GET parameters.

Use this:

$variable = $_GET['param_name'];

//Or as you have it
$ppc = $_GET['ppc'];

It is safer to check for the variable first though:

if (isset($_GET['ppc'])) {
  $ppc = $_GET['ppc'];
} else {
  //Handle the case where there is no parameter
}

Here's a bit of reading on GET/POST params you should look at: http://php.net/manual/en/reserved.variables.get.php

EDIT: I see this answer still gets a lot of traffic years after making it. Please read comments attached to this answer, especially input from @emc who details a WordPress function which accomplishes this goal securely.

How to uncommit my last commit in Git

git reset --soft HEAD^ Will keep the modified changes in your working tree.

git reset --hard HEAD^ WILL THROW AWAY THE CHANGES YOU MADE !!!

How do I convert a numpy array to (and display) an image?

this could be a possible code solution:

from skimage import io
import numpy as np
data=np.random.randn(5,2)
io.imshow(data)

/usr/bin/ld: cannot find

Add -L/opt/lib to your compiler parameters, this makes the compiler and linker search that path for libcalc.so in that folder.

How to send email via Django?

I had actually done this from Django a while back. Open up a legitimate GMail account & enter the credentials here. Here's my code -

from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

def sendmail(to, subject, text, attach=[], mtype='html'):
    ok = True
    gmail_user = settings.EMAIL_HOST_USER
    gmail_pwd  = settings.EMAIL_HOST_PASSWORD

    msg = MIMEMultipart('alternative')

    msg['From']    = gmail_user
    msg['To']      = to
    msg['Cc']      = '[email protected]'
    msg['Subject'] = subject

    msg.attach(MIMEText(text, mtype))

    for a in attach:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(attach, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(a))
        msg.attach(part)

    try:
        mailServer = smtplib.SMTP("smtp.gmail.com", 687)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmail_user, gmail_pwd)
        mailServer.sendmail(gmail_user, [to,msg['Cc']], msg.as_string())
        mailServer.close()
    except:
        ok = False
    return ok

IOCTL Linux device driver

The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

int ioctl(int fd, int request, ...)
  1. fd is file descriptor, the one returned by open;
  2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
  3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

A request code has 4 main parts

    1. A Magic number - 8 bits
    2. A sequence number - 8 bits
    3. Argument type (typically 14 bits), if any.
    4. Direction of data transfer (2 bits).  

If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

In order to generate a request code, Linux provides some predefined function-like macros.

1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM) 

and now use ioctl as

ret_val = ioctl(fd, PAUSE_PRIN);

The corresponding system call in the driver module will receive the code and pause the printer.

  1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)

further,

char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font); 

Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

Please let me know if this helps!

Why do we need to use flatMap?

People tend to over complicate things by giving the definition which says:

flatMap transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable

I swear this definition still confuses me but I am going to explain it in the simplest way which is by using an example

Our Situation: we have an observable which returns data(simple URL) that we are going to use to make an HTTP call that will return an observable containing the data we need so you can visualize the situation like this:

Observable 1
    |_
       Make Http Call Using Observable 1 Data (returns Observable_2)
            |_
               The Data We Need

so as you can see we can't reach the data we need directly so the first way to retrieve the data we can use just normal subscriptions like this:

Observable_1.subscribe((URL) => {
         Http.get(URL).subscribe((Data_We_Need) => {
                  console.log(Data_We_Need);
          });
});

this works but as you can see we have to nest subscriptions to get our data this currently does not look bad but imagine we have 10 nested subscriptions that would become unmaintainable.

so a better way to handle this is just to use the operator flatMap which will do the same thing but makes us avoid that nested subscription:

Observable_1
    .flatMap(URL => Http.get(URL))
    .subscribe(Data_We_Need => console.log(Data_We_Need));

javascript pushing element at the beginning of an array

Use .unshift() to add to the beginning of an array.

TheArray.unshift(TheNewObject);

See MDN for doc on unshift() and here for doc on other array methods.

FYI, just like there's .push() and .pop() for the end of the array, there's .shift() and .unshift() for the beginning of the array.

Wait until a process ends

Use Process.WaitForExit? Or subscribe to the Process.Exited event if you don't want to block? If that doesn't do what you want, please give us more information about your requirements.

Ignore Typescript Errors "property does not exist on value of type"

In my particular project I couldn't get it to work, and used declare var $;. Not a clean/recommended solution, it doesnt recognise the JQuery variables, but I had no errors after using that (and had to for my automatic builds to succeed).

CSS selector for a checked radio button's label

You could use a bit of jQuery:

$('input:radio').click(function(){
    $('label#' + $(this).attr('id')).toggleClass('checkedClass'); // checkedClass is defined in your CSS
});

You'd need to make sure your checked radio buttons have the correct class on page load as well.

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

Side-by-side list items as icons within a div (css)

This can be a pure CSS solution. Given:

<ul class="tileMe">
    <li>item 1<li>
    <li>item 2<li>
    <li>item 3<li>
</ul>

The CSS would be:

.tileMe li {
    display: inline;
    float: left;
}

Now, since you've changed the display mode from 'block' (implied) to 'inline', any padding, margin, width, or height styles you applied to li elements will not work. You need to nest a block-level element inside the li:

<li><a class="tile" href="home">item 1</a></li>

and add the following CSS:

.tile a {
    display: block;
    padding: 10px;
    border: 1px solid red;
    margin-right: 5px;
}

The key concept behind this solution is that you are changing the display style of the li to 'inline', and nesting a block-level element inside to achieve the consistent tiling effect.

Read HttpContent in WebApi controller

You can keep your CONTACT parameter with the following approach:

using (var stream = new MemoryStream())
{
    var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
    context.Request.InputStream.Seek(0, SeekOrigin.Begin);
    context.Request.InputStream.CopyTo(stream);
    string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}

Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.

Found as accepted answer here

How to change Hash values?

Rails-specific

In case someone only needs to call to_s method to each of the values and is not using Rails 4.2 ( which includes transform_values method link), you can do the following:

original_hash = { :a => 'a', :b => BigDecimal('23.4') }
#=> {:a=>"a", :b=>#<BigDecimal:5c03a00,'0.234E2',18(18)>}
JSON(original_hash.to_json)
#=> {"a"=>"a", "b"=>"23.4"}

Note: The use of 'json' library is required.

Note 2: This will turn keys into strings as well

Accessing a Dictionary.Keys Key through a numeric index

A dictionary may not be very intuitive for using index for reference but, you can have similar operations with an array of KeyValuePair:

ex. KeyValuePair<string, string>[] filters;

FB OpenGraph og:image not pulling images (possibly https?)

I don't know, if it's only with me but for me og:image does not work and it picks my site logo, even though facebook debugger shows the correct image.

But changing og:image to og:image:url worked for me. Hope this helps anybody else facing similar issue.

How to extract text from a PDF file?

Use pdfminer.six. Here is the the doc : https://pdfminersix.readthedocs.io/en/latest/index.html

To convert pdf to text :

    def pdf_to_text():
        from pdfminer.high_level import extract_text

        text = extract_text('test.pdf')
        print(text)

How to get an HTML element's style values in javascript?

I believe you are now able to use Window.getComputedStyle()

Documentation MDN

var style = window.getComputedStyle(element[, pseudoElt]);

Example to get width of an element:

window.getComputedStyle(document.querySelector('#mainbar')).width

Multiple conditions in WHILE loop

Your condition is wrong. myChar != 'n' || myChar != 'N' will always be true.

Use myChar != 'n' && myChar != 'N' instead

How to remove commits from a pull request

So do the following ,

Lets say your branch name is my_branch and this has the extra commits.

  1. git checkout -b my_branch_with_extra_commits (Keeping this branch saved under a different name)
  2. gitk (Opens git console)
  3. Look for the commit you want to keep. Copy the SHA of that commit to a notepad.
  4. git checkout my_branch
  5. gitk (This will open the git console )
  6. Right click on the commit you want to revert to (State before your changes) and click on "reset branch to here"
  7. Do a git pull --rebase origin branch_name_to _merge_to
  8. git cherry-pick <SHA you copied in step 3. >

Now look at the local branch commit history and make sure everything looks good.

AngularJS: How do I manually set input to $valid in controller?

to get this working for a date error I had to delete the error first before calling $setValidity for the form to be marked valid.

delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

What's "this" in JavaScript onclick?

When calling a function, the word "this" is a reference to the object that called the function.

In your example, it is a reference to the anchor element. At the other end, the function call then access member variables of the element through the parameter that was passed.

Disabling Controls in Bootstrap

<select id="message_tag">
<optgroup>
<option>
....
....
</option>
</optgroup>

here i just removed bootstrap css for only "select" element. using following css code.

#message_tag_chzn{
display: none;
}

 #message_tag{
  display: inline !important;
}

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

Modifying local variable from inside lambda

I had a slightly different problem. Instead of incrementing a local variable in the forEach, I needed to assign an object to the local variable.

I solved this by defining a private inner domain class that wraps both the list I want to iterate over (countryList) and the output I hope to get from that list (foundCountry). Then using Java 8 "forEach", I iterate over the list field, and when the object I want is found, I assign that object to the output field. So this assigns a value to a field of the local variable, not changing the local variable itself. I believe that since the local variable itself is not changed, the compiler doesn't complain. I can then use the value that I captured in the output field, outside of the list.

Domain Object:

public class Country {

    private int id;
    private String countryName;

    public Country(int id, String countryName){
        this.id = id;
        this.countryName = countryName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

Wrapper object:

private class CountryFound{
    private final List<Country> countryList;
    private Country foundCountry;
    public CountryFound(List<Country> countryList, Country foundCountry){
        this.countryList = countryList;
        this.foundCountry = foundCountry;
    }
    public List<Country> getCountryList() {
        return countryList;
    }
    public void setCountryList(List<Country> countryList) {
        this.countryList = countryList;
    }
    public Country getFoundCountry() {
        return foundCountry;
    }
    public void setFoundCountry(Country foundCountry) {
        this.foundCountry = foundCountry;
    }
}

Iterate operation:

int id = 5;
CountryFound countryFound = new CountryFound(countryList, null);
countryFound.getCountryList().forEach(c -> {
    if(c.getId() == id){
        countryFound.setFoundCountry(c);
    }
});
System.out.println("Country found: " + countryFound.getFoundCountry().getCountryName());

You could remove the wrapper class method "setCountryList()" and make the field "countryList" final, but I did not get compilation errors leaving these details as-is.

calling parent class method from child class object in java

NOTE calling parent method via super will only work on parent class, If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();

interface Vehicle {
    //Non abstract method
    public default void printVehicleTypeName() { //default keyword can be used only in interface.
        System.out.println("Vehicle");
    }
}


class FordFigo extends FordImpl implements Vehicle, Ford {
    @Override
    public void printVehicleTypeName() { 
        System.out.println("Figo");
        Vehicle.super.printVehicleTypeName();
    }
}

Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.

Angular - Use pipes in services and components

Yes, it is possible by using a simple custom pipe. Advantage of using custom pipe is if we need to update the date format in future, we can go and update a single file.

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
    name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {
    transform(value: string) {
       var datePipe = new DatePipe("en-US");
        value = datePipe.transform(value, 'MMM-dd-yyyy');
        return value;
    }
}

{{currentDate | dateFormatPipe }}

You can always use this pipe anywhere , component, services etc

For example:

export class AppComponent {
  currentDate : any;
  newDate : any;
  constructor(){
    this.currentDate = new Date().getTime();
    let dateFormatPipeFilter = new dateFormatPipe();
    this.newDate = dateFormatPipeFilter.transform(this.currentDate);
    console.log(this.newDate);
}

Don't forget to import dependencies.

import { Component } from '@angular/core';
import {dateFormatPipe} from './pipes'

Custom Pipe examples and more info

Bootstrap 4 Change Hamburger Toggler Color

You can create the toggler button with css only in a very easy way, there is no need to use any fonts in SVG or ... foramt.

Your Button:

<button 
     class="navbar-toggler collapsed" 
    data-target="#navbarsExampleDefault" 
    data-toggle="collapse">
        <span class="line"></span> 
        <span class="line"></span> 
        <span class="line"></span>
</button>

Your Button Style:

.navbar-toggler{
width: 47px;
height: 34px;
background-color: #7eb444;

}

Your horizontal line Style:

.navbar-toggler .line{
width: 100%;
float: left;
height: 2px;
background-color: #fff;
margin-bottom: 5px;

}

Demo

_x000D_
_x000D_
.navbar-toggler{_x000D_
    width: 47px;_x000D_
    height: 34px;_x000D_
    background-color: #7eb444;_x000D_
    border:none;_x000D_
}_x000D_
.navbar-toggler .line{_x000D_
    width: 100%;_x000D_
    float: left;_x000D_
    height: 2px;_x000D_
    background-color: #fff;_x000D_
    margin-bottom: 5px;_x000D_
}
_x000D_
<button class="navbar-toggler" data-target="#navbarsExampleDefault" data-toggle="collapse" aria-expanded="true" >_x000D_
        <span class="line"></span> _x000D_
        <span class="line"></span> _x000D_
        <span class="line" style="margin-bottom: 0;"></span>_x000D_
</button>
_x000D_
_x000D_
_x000D_

What's onCreate(Bundle savedInstanceState)

onCreate(Bundle savedInstanceState) gets called and savedInstanceState will be non-null if your Activity and it was terminated in a scenario(visual view) described above. Your app can then grab (catch) the data from savedInstanceState and regenerate your Activity

How can I add a class to a DOM element in JavaScript?

new_row.className = "aClassName";

Here's more information on MDN: className

Back button and refreshing previous activity

One option would be to use the onResume of your first activity.

@Override
public void onResume()
    {  // After a pause OR at startup
    super.onResume();
    //Refresh your stuff here
     }

Or you can start Activity for Result:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

In secondActivity if you want to send back data:

 Intent returnIntent = new Intent();
 returnIntent.putExtra("result",result);
 setResult(RESULT_OK,returnIntent);     
 finish();

if you don't want to return data:

Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);        
finish();

Now in your FirstActivity class write following code for onActivityResult() method

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  if (requestCode == 1) {

     if(resultCode == RESULT_OK){      
         //Update List         
     }
     if (resultCode == RESULT_CANCELED) {    
         //Do nothing?
     }
  }
}//onActivityResult

How to disable javax.swing.JButton in java?

The code is very long so I can't paste all the code.

There could be any number of reasons why your code doesn't work. Maybe you declared the button variables twice so you aren't actually changing enabling/disabling the button like you think you are. Maybe you are blocking the EDT.

You need to create a SSCCE to post on the forum.

So its up to you to isolate the problem. Start with a simple frame thas two buttons and see if your code works. Once you get that working, then try starting a Thread that simply sleeps for 10 seconds to see if it still works.

Learn how the basice work first before writing a 200 line program.

Learn how to do some basic debugging, we are not mind readers. We can't guess what silly mistake you are doing based on your verbal description of the problem.

What's the difference between SortedList and SortedDictionary?

Enough is said already on the topic, however to keep it simple, here's my take.

Sorted dictionary should be used when-

  • More inserts and delete operations are required.
  • Data in un-ordered.
  • Key access is enough and index access is not required.
  • Memory is not a bottleneck.

On the other side, Sorted List should be used when-

  • More lookups and less inserts and delete operations are required.
  • Data is already sorted (if not all, most).
  • Index access is required.
  • Memory is an overhead.

Hope this helps!!

Failed to load resource: the server responded with a status of 404 (Not Found)

Your files are not under the jsp folder that's why it is not found. You have to go back again 1 folder Try this:

     <script  src="../../Jquery/prettify.js"></script>

Javascript equivalent of php's strtotime()?

Check out this implementation of PHP's strtotime() in JavaScript!

I found that it works identically to PHP for everything that I threw at it.

Update: this function as per version 1.0.2 can't handle this case: '2007:07:20 20:52:45' (Note the : separator for year and month)

Update 2018:

This is now available as an npm module! Simply npm install locutus and then in your source:

var strtotime = require('locutus/php/datetime/strtotime');

How do you send a Firebase Notification to all devices via CURL?

For anyone wondering how to do it in cordova hybrid app:

  • go to index.js -> inside the function onDeviceReady() write :

      subscribe();
    

(It's important to write it at the top of the function!)

  • then, in the same file (index.js) find :

    function subscribe(){

     FirebasePlugin.subscribe("write_here_your_topic", function(){
    
     },function(error){
    
         logError("Failed to subscribe to topic", error);
     });
     }
    

and write your own topic here -> "write_here_your_topic"

window.location.href and window.open () methods in JavaScript

There are already answers which describes about window.location.href property and window.open() method.

I will go by Objective use:

1. To redirect the page to another

Use window.location.href. Set href property to the href of another page.

2. Open link in the new or specific window.

Use window.open(). Pass parameters as per your goal.

3. Know current address of the page

Use window.location.href. Get value of window.location.href property. You can also get specific protocol, hostname, hashstring from window.location object.

See Location Object for more information.

How can I disable a tab inside a TabControl?

in C# 7.0, there is a new feature called Pattern Matching. You can disable all tabs via Type Pattern.

foreach (Control control in Controls)
{
    // the is expression tests the variable and 
    // assigned it to a new appropriate variable type
    if (control is TabControl tabs)
    {
        tabs.Enabled = false;
    }
}

rmagick gem install "Can't find Magick-config"

Things change...maybe this will help someone else:

sudo apt-get install libmagick9-dev used to work. But with a later version of imagemagick I needed:

sudo apt-get install graphicsmagick-libmagick-dev-compat libmagickcore-dev libmagickwand-dev

jQuery: how to trigger anchor link's click event

$(":button").click(function () {                
                $("#anchor_google")[0].click();
            });
  1. First, find the button by type(using ":") if id is not given.
  2. Second,find the anchor tag by id or in some other tag like div and $("#anchor_google")[0] returns the DOM object.

When to use cla(), clf() or close() for clearing a plot in matplotlib?

There is just a caveat that I discovered today. If you have a function that is calling a plot a lot of times you better use plt.close(fig) instead of fig.clf() somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).

So the the following script will produce an empty list:

for i in range(5):
    fig = plot_figure()
    plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())

Whereas this one will produce a list with five figures on it.

for i in range(5):
    fig = plot_figure()
    fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())

From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.

If you want to try a complete script there you have:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    plt.close(fig)

print(plt.get_fignums())

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    fig.clf()

print(plt.get_fignums())

If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted

how to display full stored procedure code?

use pgAdmin or use pg_proc to get the source of your stored procedures. pgAdmin does the same.

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

How to change port for jenkins window service when 8080 is being used

  1. Go to the directory where you installed Jenkins (by default, it's under Program Files/Jenkins)
  2. Open the Jenkins.xml configuration file
  3. Search --httpPort=8080 and replace the 8080 with the new port number that you wish
  4. Restart Jenkins for changes to take effect

Monitor network activity in Android Phones

For Android Phones(Without Root):- you can use this application tPacketCapture this will capture the network trafic for your device when you enable the capture. See this url for more details about network sniffing without rooting your device.

Once you have the file which is in .pcap format you can use this file and analyze the traffic using any traffic analyzer like Wireshark.

Also see this post for further ideas on Capturing mobile phone traffic on wireshark

What is the difference between HAVING and WHERE in SQL?

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

Check out this w3schools link for more information

Syntax:

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value

A query such as this:

SELECT column_name, COUNT( column_name ) AS column_name_tally
  FROM table_name
 WHERE column_name < 3
 GROUP 
    BY column_name
HAVING COUNT( column_name ) >= 3;

...may be rewritten using a derived table (and omitting the HAVING) like this:

SELECT column_name, column_name_tally
  FROM (
        SELECT column_name, COUNT(column_name) AS column_name_tally
          FROM table_name
         WHERE column_name < 3
         GROUP 
            BY column_name
       ) pointless_range_variable_required_here
 WHERE column_name_tally >= 3;

iPhone X / 8 / 8 Plus CSS media queries

If your page is missing meta[@name="viewport"] element within its DOM, then the following could be used to detect a mobile device:

@media only screen and (width: 980px), (hover: none) { … }

If you want to avoid false-positives with desktops that just magically have their viewport set to 980px like all the mobile browsers do, then a device-width test could also be added into the mix:

@media only screen and (max-device-width: 800px) and (width: 980px), (hover: none) { … }

Per the list at https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries, the new hover property would appear to be the final new way to detect that you've got yourself a mobile device that doesn't really do proper hover; it's only been introduced in 2018 with Firefox 64 (2018), although it's been supported since 2016 with Android Chrome 50 (2016), or even since 2014 with Chrome 38 (2014):

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

Non-const and const reference binding follow different rules

These are the rules of the C++ language:

  • an expression consisting of a literal number (12) is a "rvalue"
  • it is not permitted to create a non-const reference with a rvalue: int &ri = 12; is ill-formed
  • it is permitted to create a const reference with a rvalue: in this case, an unnamed object is created by the compiler; this object will persist as long as the reference itself exist.

You have to understand that these are C++ rules. They just are.

It is easy to invent a different language, say C++', with slightly different rules. In C++', it would be permitted to create a non-const reference with a rvalue. There is nothing inconsistent or impossible here.

But it would allow some risky code where the programmer might not get what he intended, and C++ designers rightly decided to avoid that risk.

How to analyze disk usage of a Docker container

I use docker stats $(docker ps --format={{.Names}}) --no-stream to get :

  1. CPU usage,
  2. Mem usage/Total mem allocated to container (can be allocate with docker run command)
  3. Mem %
  4. Block I/O
  5. Net I/O

Installing Python 3 on RHEL

You can download a source RPMs and binary RPMs for RHEL6 / CentOS6 from here

This is a backport from the newest Fedora development source rpm to RHEL6 / CentOS6

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

Here is the plunker

New plunker with cleaner code & where both the query and search list items are case insensitive

Main idea is create a filter function to achieve this purpose.

From official doc

function: A predicate function can be used to write arbitrary filters. The function is called for each element of array. The final result is an array of those elements that the predicate returned true for.

<input ng-model="query">

<tr ng-repeat="smartphone in smartphones | filter: search "> 

$scope.search = function(item) {
    if (!$scope.query || (item.brand.toLowerCase().indexOf($scope.query) != -1) || (item.model.toLowerCase().indexOf($scope.query.toLowerCase()) != -1) ){
        return true;
    }
    return false;
};

Update

Some people might have a concern on performance in real world, which is correct.

In real world, we probably would do this kinda filter from controller.

Here is the detail post showing how to do it.

in short, we add ng-change to input for monitoring new search change

and then trigger filter function.

Swift extract regex matches

Most of the solutions above only give the full match as a result ignoring the capture groups e.g.: ^\d+\s+(\d+)

To get the capture group matches as expected you need something like (Swift4) :

public extension String {
    public func capturedGroups(withRegex pattern: String) -> [String] {
        var results = [String]()

        var regex: NSRegularExpression
        do {
            regex = try NSRegularExpression(pattern: pattern, options: [])
        } catch {
            return results
        }
        let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.count))

        guard let match = matches.first else { return results }

        let lastRangeIndex = match.numberOfRanges - 1
        guard lastRangeIndex >= 1 else { return results }

        for i in 1...lastRangeIndex {
            let capturedGroupIndex = match.range(at: i)
            let matchedString = (self as NSString).substring(with: capturedGroupIndex)
            results.append(matchedString)
        }

        return results
    }
}

How to debug a GLSL shader?

Do offline rendering to a texture and evaluate the texture's data. You can find related code by googling for "render to texture" opengl Then use glReadPixels to read the output into an array and perform assertions on it (since looking through such a huge array in the debugger is usually not really useful).

Also you might want to disable clamping to output values that are not between 0 and 1, which is only supported for floating point textures.

I personally was bothered by the problem of properly debugging shaders for a while. There does not seem to be a good way - If anyone finds a good (and not outdated/deprecated) debugger, please let me know.

Npm Please try using this command again as root/administrator

As my last resort with this error I created a fresh windows 10 virtual machine and installed the latest nodejs (v6). But there was a host of other "ERRs!" to work through.

I had to run npm cache clean --force which ironically will give you a message that reads "I sure hope you know what you are doing". That seems to have worked.

It doesn't solve the issue on my main Dev machine. I'm canning nodejs as I found over the last few years that you spend more time on fixing it rather than on actual development. I had fewer issues with node on linux ubuntu 14.04 if that's any help.

What Does This Mean in PHP -> or =>

The double arrow operator, =>, is used as an access mechanism for arrays. This means that what is on the left side of it will have a corresponding value of what is on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. The index can be associative (string based) or numeric.

$myArray = array(
    0 => 'Big',
    1 => 'Small',
    2 => 'Up',
    3 => 'Down'
);

The object operator, ->, is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.

// Create a new instance of MyObject into $obj
$obj = new MyObject();
// Set a property in the $obj object called thisProperty
$obj->thisProperty = 'Fred';
// Call a method of the $obj object named getProperty
$obj->getProperty();

What is the equivalent of bigint in C#?

Int64 maps directly to BigInt.

Source

Exec : display stdout "live"

I'd just like to add that one small issue with outputting the buffer strings from a spawned process with console.log() is that it adds newlines, which can spread your spawned process output over additional lines. If you output stdout or stderr with process.stdout.write() instead of console.log(), then you'll get the console output from the spawned process 'as is'.

I saw that solution here: Node.js: printing to console without a trailing newline?

Hope that helps someone using the solution above (which is a great one for live output, even if it is from the documentation).

What MIME type should I use for CSV?

For anyone struggling with Google API mimeType for *.csv files. I have found the list of MIME types for google api docs files (look at snipped result)

_x000D_
_x000D_
<table border="1"><thead><tr><th>Google Doc Format</th><th>Conversion Format</th><th>Corresponding MIME type</th></tr></thead><tbody><tr><td>Documents</td><td>HTML</td><td>text/html</td></tr><tr></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td></td><td>Rich text</td><td>application/rtf</td></tr><tr><td></td><td>Open Office doc</td><td>application/vnd.oasis.opendocument.text</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>MS Word document</td><td>application/vnd.openxmlformats-officedocument.wordprocessingml.document</td></tr><tr><td></td><td>EPUB</td><td>application/epub+zip</td></tr><tr><td>Spreadsheets</td><td>MS Excel</td><td>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</td></tr><tr><td></td><td>Open Office sheet</td><td>application/x-vnd.oasis.opendocument.spreadsheet</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>CSV (first sheet only)</td><td>text/csv</td></tr><tr><td></td><td>TSV (first sheet only)</td><td>text/tab-separated-values</td></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr></tr><tr><td>Drawings</td><td>JPEG</td><td>image/jpeg</td></tr><tr><td></td><td>PNG</td><td>image/png</td></tr><tr><td></td><td>SVG</td><td>image/svg+xml</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td>Presentations</td><td>MS PowerPoint</td><td>application/vnd.openxmlformats-officedocument.presentationml.presentation</td></tr><tr><td></td><td>Open Office presentation</td><td>application/vnd.oasis.opendocument.presentation</td></tr><tr></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td>Apps Scripts</td><td>JSON</td><td>application/vnd.google-apps.script+json</td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Source here: https://developers.google.com/drive/v3/web/manage-downloads#downloading_google_documents the table under: "Google Doc formats and supported export MIME types map to each other as follows"

There is also another list

_x000D_
_x000D_
<table border="1"><thead><tr><th>MIME Type</th><th>Description</th></tr></thead><tbody><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>audio</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>document</span></code></td><td>Google Docs</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drawing</span></code></td><td>Google Drawing</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>file</span></code></td><td>Google Drive file</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>folder</span></code></td><td>Google Drive folder</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>form</span></code></td><td>Google Forms</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>fusiontable</span></code></td><td>Google Fusion Tables</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>map</span></code></td><td>Google My Maps</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>photo</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>presentation</span></code></td><td>Google Slides</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>script</span></code></td><td>Google Apps Scripts</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>site</span></code></td><td>Google Sites</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>spreadsheet</span></code></td><td>Google Sheets</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>unknown</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>video</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drive-sdk</span></code></td><td>3rd party shortcut</td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Source here: https://developers.google.com/drive/v3/web/mime-types

But the first one was more helpful for my use case..

Happy coding ;)

addID in jQuery?

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

How to copy static files to build directory with Webpack?

Above suggestions are good. But to try to answer your question directly I'd suggest using cpy-cli in a script defined in your package.json.

This example expects node to somewhere on your path. Install cpy-cli as a development dependency:

npm install --save-dev cpy-cli

Then create a couple of nodejs files. One to do the copy and the other to display a checkmark and message.

copy.js

#!/usr/bin/env node

var shelljs = require('shelljs');
var addCheckMark = require('./helpers/checkmark');
var path = require('path');

var cpy = path.join(__dirname, '../node_modules/cpy-cli/cli.js');

shelljs.exec(cpy + ' /static/* /build/', addCheckMark.bind(null, callback));

function callback() {
  process.stdout.write(' Copied /static/* to the /build/ directory\n\n');
}

checkmark.js

var chalk = require('chalk');

/**
 * Adds mark check symbol
 */
function addCheckMark(callback) {
  process.stdout.write(chalk.green(' ?'));
  callback();
}

module.exports = addCheckMark;

Add the script in package.json. Assuming scripts are in <project-root>/scripts/

...
"scripts": {
  "copy": "node scripts/copy.js",
...

To run the sript:

npm run copy

How to make a hyperlink in telegram without using bots?

Try this link format: https://t.me/[YourUserName]

I was looking for such a thing, BUT with text in (like the one that WhatsApp got)

Android: Rotate image in imageview by an angle

just write this in your onactivityResult

            Bitmap yourSelectedImage= BitmapFactory.decodeFile(filePath);
            Matrix mat = new Matrix();
            mat.postRotate((270)); //degree how much you rotate i rotate 270
            Bitmap bMapRotate=Bitmap.createBitmap(yourSelectedImage, 0,0,yourSelectedImage.getWidth(),yourSelectedImage.getHeight(), mat, true);
            image.setImageBitmap(bMapRotate);
            Drawable d=new BitmapDrawable(yourSelectedImage);
            image.setBackground(d); 

Java serialization - java.io.InvalidClassException local class incompatible

The short answer here is the serial ID is computed via a hash if you don't specify it. (Static members are not inherited--they are static, there's only (1) and it belongs to the class).

http://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html

The getSerialVersionUID method returns the serialVersionUID of this class. Refer to Section 4.6, "Stream Unique Identifiers." If not specified by the class, the value returned is a hash computed from the class's name, interfaces, methods, and fields using the Secure Hash Algorithm (SHA) as defined by the National Institute of Standards.

If you alter a class or its hierarchy your hash will be different. This is a good thing. Your objects are different now that they have different members. As such, if you read it back in from its serialized form it is in fact a different object--thus the exception.

The long answer is the serialization is extremely useful, but probably shouldn't be used for persistence unless there's no other way to do it. Its a dangerous path specifically because of what you're experiencing. You should consider a database, XML, a file format and probably a JPA or other persistence structure for a pure Java project.

How to remove item from list in C#?

More simplified:

resultList.Remove(resultList.Single(x => x.Id == 2));

there is no needing to create a new var object.

What is difference between arm64 and armhf?

armhf stands for "arm hard float", and is the name given to a debian port for arm processors (armv7+) that have hardware floating point support.

On the beaglebone black, for example:

:~$ dpkg --print-architecture
armhf

Although other commands (such as uname -a or arch) will just show armv7l

:~$ cat /proc/cpuinfo 
processor       : 0
model name      : ARMv7 Processor rev 2 (v7l)
BogoMIPS        : 995.32
Features        : half thumb fastmult vfp edsp thumbee neon vfpv3 tls
...

The vfpv3 listed under Features is what refers to the floating point support.

Incidentally, armhf, if your processor supports it, basically supersedes Raspbian, which if I understand correctly was mainly a rebuild of armhf with work arounds to deal with the lack of floating point support on the original raspberry pi's. Nowdays, of course, there's a whole ecosystem build up around Raspbian, so they're probably not going to abandon it. However, this is partly why the beaglebone runs straight debian, and that's ok even if you're used to Raspbian, unless you want some of the special included non-free software such as Mathematica.

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

How to resize image (Bitmap) to a given size?

 Bitmap yourBitmap;
 Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);

or:

 resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);

Android ADB doesn't see device

Some of these answers are pretty old, so maybe it's changed in recent times, but I had similar issues and I solved it by:

  1. Loading the USB drivers for the device - Samsung S6
  2. Enable Developer tools on the phone.
  3. On the device, go to Settings - Applications - Development - Check USB Debugging
  4. Reboot O/S (Windows 7 - 64bit)
  5. Open Visual Studio

I think it was step 3 that had me stumped for a while. I'd enabled developer tools, but I didn't specifically enable the "USB Debugging" but.

How to get all selected values of a multiple select box?

suppose the multiSelect is the Multiple-Select-Element, just use its selectedOptions Property:

//show all selected options in the console:

for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
  console.log( multiSelect.selectedOptions[i].value);
}

MVC Return Partial View as JSON

Instead of RenderViewToString I prefer a approach like

return Json(new { Url = Url.Action("Evil", model) });

then you can catch the result in your javascript and do something like

success: function(data) {
    $.post(data.Url, function(partial) { 
        $('#IdOfDivToUpdate').html(partial);
    });
}

CSV API for Java

For the last enterprise application I worked on that needed to handle a notable amount of CSV -- a couple of months ago -- I used SuperCSV at sourceforge and found it simple, robust and problem-free.

How can I show the table structure in SQL Server query?

For SQL Server, if using a newer version, you can use

select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'

There are different ways to get the schema. Using ADO.NET, you can use the schema methods. Use the DbConnection's GetSchema method or the DataReader'sGetSchemaTable method.

Provided that you have a reader for the for the query, you can do something like this:

using(DbCommand cmd = ...)
using(var reader = cmd.ExecuteReader())
{
    var schema = reader.GetSchemaTable();
    foreach(DataRow row in schema.Rows)
    {
        Debug.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"])
    }
}

See this article for further details.

VSCode regex find & replace submatch math?

For beginners, the accepted answer is correct, but a little terse if you're not that familiar with either VSC or Regex.

So, in case this is your first contact with either:

To find and modify text,

  1. In the "Find" step, you can use regex with "capturing groups," e.g. I want to find (group1) and (group2), using parentheses. This would find the same text as I want to find group1 and group2, but with the difference that you can then reference group1 and group2 in the next step:

  2. In the "Replace" step, you can refer to the capturing groups via $1, $2 etc, so you could change the sentence to I found $1 and $2 having a picnic, which would output I found group1 and group2 having a picnic.

Notes:

  • Instead of just a string, anything inside or outside the () can be a regular expression.

  • $0 refers to the whole match

How to access site through IP address when website is on a shared host?

serverIPaddress/~cpanelusername will only work for cPanel. It will not work for Parallel's Panel.

As long as you have the website created on the shared, VPS or Dedicated, you should be able to always use the following in your host file, which is what your browser will use.

67.225.235.59 somerandomservice.com www.somerandomservice.com

How do you Programmatically Download a Webpage in Java

Here's some tested code using Java's URL class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.

public static void main(String[] args) {
    URL url;
    InputStream is = null;
    BufferedReader br;
    String line;

    try {
        url = new URL("http://stackoverflow.com/");
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException mue) {
         mue.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
}

std::string length() and size() member functions

Ruby's just the same, btw, offering both #length and #size as synonyms for the number of items in arrays and hashes (C++ only does it for strings).

Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

Filter

app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

Usage

<ANY ng-bind-html="value | unsafe"></ANY>

failed to open stream: HTTP wrapper does not support writeable connections

it is because of using web address, You can not use http to write data. don't use : http:// or https:// in your location for upload files or save data or somting like that. instead of of using $_SERVER["HTTP_REFERER"] use $_SERVER["DOCUMENT_ROOT"]. for example :

wrong :

move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["HTTP_REFERER"].'/uploads/images/1.jpg')

correct:

move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["DOCUMENT_ROOT"].'/uploads/images/1.jpg')

List all sequences in a Postgres db 8.1 with SQL

Here is an example how to use psql to get a list of all sequences with their last_value:

psql -U <username> -d <database> -t -c "SELECT 'SELECT ''' || c.relname || ''' as sequence_name, last_value FROM ' || c.relname || ';' FROM pg_class c WHERE (c.relkind = 'S')" | psql -U <username> -d <database> -t

Auto-loading lib files in Rails 4

Though this does not directly answer the question, but I think it is a good alternative to avoid the question altogether.

To avoid all the autoload_paths or eager_load_paths hassle, create a "lib" or a "misc" directory under "app" directory. Place codes as you would normally do in there, and Rails will load files just like how it will load (and reload) model files.

How to force a view refresh without having it trigger automatically from an observable?

I have created a JSFiddle with my bindHTML knockout binding handler here: https://jsfiddle.net/glaivier/9859uq8t/

First, save the binding handler into its own (or a common) file and include after Knockout.

If you use this switch your bindings to this:

<div data-bind="bindHTML: htmlValue"></div>

OR

<!-- ko bindHTML: htmlValue --><!-- /ko -->

How to deal with SettingWithCopyWarning in Pandas

Pandas dataframe copy warning

When you go and do something like this:

quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]

pandas.ix in this case returns a new, stand alone dataframe.

Any values you decide to change in this dataframe, will not change the original dataframe.

This is what pandas tries to warn you about.


Why .ix is a bad idea

The .ix object tries to do more than one thing, and for anyone who has read anything about clean code, this is a strong smell.

Given this dataframe:

df = pd.DataFrame({"a": [1,2,3,4], "b": [1,1,2,2]})

Two behaviors:

dfcopy = df.ix[:,["a"]]
dfcopy.a.ix[0] = 2

Behavior one: dfcopy is now a stand alone dataframe. Changing it will not change df

df.ix[0, "a"] = 3

Behavior two: This changes the original dataframe.


Use .loc instead

The pandas developers recognized that the .ix object was quite smelly[speculatively] and thus created two new objects which helps in the accession and assignment of data. (The other being .iloc)

.loc is faster, because it does not try to create a copy of the data.

.loc is meant to modify your existing dataframe inplace, which is more memory efficient.

.loc is predictable, it has one behavior.


The solution

What you are doing in your code example is loading a big file with lots of columns, then modifying it to be smaller.

The pd.read_csv function can help you out with a lot of this and also make the loading of the file a lot faster.

So instead of doing this

quote_df = pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64}
quote_df.rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True)
quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]

Do this

columns = ['STK', 'TPrice', 'TPCLOSE', 'TOpen', 'THigh', 'TLow', 'TVol', 'TAmt', 'TDate', 'TTime']
df = pd.read_csv(StringIO(str_of_all), sep=',', usecols=[0,3,2,1,4,5,8,9,30,31])
df.columns = columns

This will only read the columns you are interested in, and name them properly. No need for using the evil .ix object to do magical stuff.

Initializing default values in a struct

Yes. bar.a and bar.b are set to true, but bar.c is undefined. However, certain compilers will set it to false.

See a live example here: struct demo

According to C++ standard Section 8.5.12:

if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value

For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.

If you don't really want undefined bar.c to start with, you should also initialize it like you did for bar.a and bar.b.

Merge Two Lists in R

merged = map(names(first), ~c(first[[.x]], second[[.x]])
merged = set_names(merged, names(first))

Using purrr. Also solves the problem of your lists not being in order.

Show/Hide Multiple Divs with Jquery

Just a small side-note... If you are using this with other scripts, the $ on the last line will cause a conflict. Just replace it with jQuery and you're good.

jQuery(function(){
     jQuery('#showall').click(function(){
           jQuery('.targetDiv').show();
    });
    jQuery('.showSingle').click(function(){
          jQuery('.targetDiv').hide();
          jQuery('#div'+jQuery(this).attr('target')).show();
    });
});

http://jsfiddle.net/XwN2L/4764/

In Mongoose, how do I sort by date? (node.js)

ES6 solution with Koa.

  async recent() {
    data = await ReadSchema.find({}, { sort: 'created_at' });
    ctx.body = data;
  }

Group by in LINQ

try

persons.GroupBy(x => x.PersonId).Select(x => x)

or

to check if any person is repeating in your list try

persons.GroupBy(x => x.PersonId).Where(x => x.Count() > 1).Any(x => x)

Hibernate: flush() and commit()

session.flush() is synchronise method means to insert data in to database sequentially.if we use this method data will not store in database but it will store in cache,if any exception will rise in middle we can handle it. But commit() it will store data in database,if we are storing more amount of data then ,there may be chance to get out Of Memory Exception,As like in JDBC program in Save point topic

How do I make a burn down chart in Excel?

But why would you use excel when you could do it all online and have your boss check your dynamic link.

We are using this new tool since last week. http://www.burndown-charts.com/

What I do is I send my boss the link to my chart and he plays around with the links to see if we will be on time...

http://www.burndown-charts.com/teams/dreamteam/sprints/prototype-x

Split a List into smaller lists of N size

Serj-Tm solution is fine, also this is the generic version as extension method for lists (put it into a static class):

public static List<List<T>> Split<T>(this List<T> items, int sliceSize = 30)
{
    List<List<T>> list = new List<List<T>>();
    for (int i = 0; i < items.Count; i += sliceSize)
        list.Add(items.GetRange(i, Math.Min(sliceSize, items.Count - i)));
    return list;
} 

Looking for simple Java in-memory cache

Since this question was originally asked, Google's Guava library now includes a powerful and flexible cache. I would recommend using this.

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

Simply use the "utf-8-sig" codec:

fp = open("file.txt")
s = fp.read()
u = s.decode("utf-8-sig")

That gives you a unicode string without the BOM. You can then use

s = u.encode("utf-8")

to get a normal UTF-8 encoded string back in s. If your files are big, then you should avoid reading them all into memory. The BOM is simply three bytes at the beginning of the file, so you can use this code to strip them out of the file:

import os, sys, codecs

BUFSIZE = 4096
BOMLEN = len(codecs.BOM_UTF8)

path = sys.argv[1]
with open(path, "r+b") as fp:
    chunk = fp.read(BUFSIZE)
    if chunk.startswith(codecs.BOM_UTF8):
        i = 0
        chunk = chunk[BOMLEN:]
        while chunk:
            fp.seek(i)
            fp.write(chunk)
            i += len(chunk)
            fp.seek(BOMLEN, os.SEEK_CUR)
            chunk = fp.read(BUFSIZE)
        fp.seek(-BOMLEN, os.SEEK_CUR)
        fp.truncate()

It opens the file, reads a chunk, and writes it out to the file 3 bytes earlier than where it read it. The file is rewritten in-place. As easier solution is to write the shorter file to a new file like newtover's answer. That would be simpler, but use twice the disk space for a short period.

As for guessing the encoding, then you can just loop through the encoding from most to least specific:

def decode(s):
    for encoding in "utf-8-sig", "utf-16":
        try:
            return s.decode(encoding)
        except UnicodeDecodeError:
            continue
    return s.decode("latin-1") # will always work

An UTF-16 encoded file wont decode as UTF-8, so we try with UTF-8 first. If that fails, then we try with UTF-16. Finally, we use Latin-1 — this will always work since all 256 bytes are legal values in Latin-1. You may want to return None instead in this case since it's really a fallback and your code might want to handle this more carefully (if it can).

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

How to select Python version in PyCharm?

File -> Settings

Preferences->Project Interpreter->Python Interpreters

If it's not listed add it.

enter image description here

Remove querystring from URL

2nd Update: In attempt to provide a comprehensive answer, I am benchmarking the three methods proposed in the various answers.

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
var i;

// Testing the substring method
i = 0;
console.time('10k substring');
while (i < 10000) {
    testURL.substring(0, testURL.indexOf('?'));
    i++;
}
console.timeEnd('10k substring');

// Testing the split method
i = 0;
console.time('10k split');
while (i < 10000) {
    testURL.split('?')[0]; 
    i++;
}
console.timeEnd('10k split');

// Testing the RegEx method
i = 0;
var re = new RegExp("[^?]+");
console.time('10k regex');
while (i < 10000) {
    testURL.match(re)[0]; 
    i++;
}
console.timeEnd('10k regex');

Results in Firefox 3.5.8 on Mac OS X 10.6.2:

10k substring:  16ms
10k split:      25ms
10k regex:      44ms

Results in Chrome 5.0.307.11 on Mac OS X 10.6.2:

10k substring:  14ms
10k split:      20ms
10k regex:      15ms

Note that the substring method is inferior in functionality as it returns a blank string if the URL does not contain a querystring. The other two methods would return the full URL, as expected. However it is interesting to note that the substring method is the fastest, especially in Firefox.


1st UPDATE: Actually the split() method suggested by Robusto is a better solution that the one I suggested earlier, since it will work even when there is no querystring:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.split('?')[0];    // Returns: "/Products/List"

var testURL2 = '/Products/List';
testURL2.split('?')[0];    // Returns: "/Products/List"

Original Answer:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.substring(0, testURL.indexOf('?'));    // Returns: "/Products/List"

Programmatically navigate using React router

Simply just use this.props.history.push('/where/to/go');

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

You can use the datedif function to find out difference in days.

=DATEDIF(A1,TODAY(),"d")

Quote from excel.datedif.com

The mysterious datedif function in Microsoft Excel

The Datedif function is used to calculate interval between two dates in days, months or years.

This function is available in all versions of Excel but is not documented. It is not even listed in the "Insert Function" dialog box. Hence it must be typed manually in the formula box. Syntax

DATEDIF( start_date, end_date, interval_unit )

start_date from date end_date to date (must be after start_date) interval_unit Unit to be used for output interval Values for interval_unit

interval_unit Description

D Number of days

M Number of complete months

Y Number of complete years

YD Number of days excluding years

MD Number of days excluding months and years

YM Number of months excluding years

Errors

Error Description

#NUM! The end_date is later than (greater than) the start_date or interval_unit has an invalid value. #VALUE! end_date or start_date is invalid.

What is the purpose of global.asax in asp.net

The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application

Python: Append item to list N times

I had to go another route for an assignment but this is what I ended up with.

my_array += ([x] * repeated_times)

How to check the maximum number of allowed connections to an Oracle database?

Use gv$session for RAC, if you want get the total number of session across the cluster.

How to use font-awesome icons from node-modules

Install as npm install font-awesome --save-dev

In your development less file, you can either import the whole font awesome less using @import "node_modules/font-awesome/less/font-awesome.less", or look in that file and import just the components that you need. I think this is the minimum for basic icons:

/* adjust path as needed */
@fa_path: "../node_modules/font-awesome/less";
@import "@{fa_path}/variables.less";
@import "@{fa_path}/mixins.less";
@import "@{fa_path}/path.less";
@import "@{fa_path}/core.less";
@import "@{fa_path}/icons.less";

As a note, you still aren't going to save that many bytes by doing this. Either way, you're going to end up including between 2-3k lines of unminified CSS.

You'll also need to serve the fonts themselves from a folder called/fonts/ in your public directory. You could just copy them there with a simple gulp task, for example:

gulp.task('fonts', function() {
  return gulp.src('node_modules/font-awesome/fonts/*')
    .pipe(gulp.dest('public/fonts'))
})

Show an image preview before upload

Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).

Don't forget to validate image extension.

<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');

const handle_file_preview = (e) => {
  let files = e.target.files;
  let length = files.length;

  for(let i = 0; i < length; i++) {
      let image = document.createElement('img');
      // use the DOMstring for source
      image.src = window.URL.createObjectURL(files[i]);
      image_preview.appendChild(image);
  }
}

file_input.addEventListener('change', handle_file_preview);

Validate that a string is a positive integer

Two answers for you:

  • Based on parsing

  • Regular expression

Note that in both cases, I've interpreted "positive integer" to include 0, even though 0 is not positive. I include notes if you want to disallow 0.

Based on Parsing

If you want it to be a normalized decimal integer string over a reasonable range of values, you can do this:

function isNormalInteger(str) {
    var n = Math.floor(Number(str));
    return n !== Infinity && String(n) === str && n >= 0;
}

or if you want to allow whitespace and leading zeros:

function isNormalInteger(str) {
    str = str.trim();
    if (!str) {
        return false;
    }
    str = str.replace(/^0+/, "") || "0";
    var n = Math.floor(Number(str));
    return n !== Infinity && String(n) === str && n >= 0;
}

Live testbed (without handling leading zeros or whitespace):

_x000D_
_x000D_
function isNormalInteger(str) {_x000D_
    var n = Math.floor(Number(str));_x000D_
    return n !== Infinity && String(n) === str && n >= 0;_x000D_
}_x000D_
function gid(id) {_x000D_
    return document.getElementById(id);_x000D_
}_x000D_
function test(str, expect) {_x000D_
    var result = isNormalInteger(str);_x000D_
    console.log(_x000D_
        str + ": " +_x000D_
        (result ? "Yes" : "No") +_x000D_
        (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")_x000D_
    );_x000D_
}_x000D_
gid("btn").addEventListener(_x000D_
    "click",_x000D_
    function() {_x000D_
        test(gid("text").value);_x000D_
    },_x000D_
    false_x000D_
);_x000D_
test("1", true);_x000D_
test("1.23", false);_x000D_
test("1234567890123", true);_x000D_
test("1234567890123.1", false);_x000D_
test("0123", false); // false because we don't handle leading 0s_x000D_
test(" 123 ", false); // false because we don't handle whitespace
_x000D_
<label>_x000D_
  String:_x000D_
  <input id="text" type="text" value="">_x000D_
<label>_x000D_
<input id="btn" type="button" value="Check">
_x000D_
_x000D_
_x000D_

Live testbed (with handling for leading zeros and whitespace):

_x000D_
_x000D_
function isNormalInteger(str) {_x000D_
    str = str.trim();_x000D_
    if (!str) {_x000D_
        return false;_x000D_
    }_x000D_
    str = str.replace(/^0+/, "") || "0";_x000D_
    var n = Math.floor(Number(str));_x000D_
    return String(n) === str && n >= 0;_x000D_
}_x000D_
function gid(id) {_x000D_
    return document.getElementById(id);_x000D_
}_x000D_
function test(str, expect) {_x000D_
    var result = isNormalInteger(str);_x000D_
    console.log(_x000D_
        str + ": " +_x000D_
        (result ? "Yes" : "No") +_x000D_
        (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")_x000D_
    );_x000D_
}_x000D_
gid("btn").addEventListener(_x000D_
    "click",_x000D_
    function() {_x000D_
        test(gid("text").value);_x000D_
    },_x000D_
    false_x000D_
);_x000D_
test("1", true);_x000D_
test("1.23", false);_x000D_
test("1234567890123", true);_x000D_
test("1234567890123.1", false);_x000D_
test("0123", true);_x000D_
test(" 123 ", true);
_x000D_
<label>_x000D_
  String:_x000D_
  <input id="text" type="text" value="">_x000D_
<label>_x000D_
<input id="btn" type="button" value="Check">
_x000D_
_x000D_
_x000D_

If you want to disallow 0, just change >= 0 to > 0. (Or, in the version that allows leading zeros, remove the || "0" on the replace line.)

How that works:

  1. In the version allowing whitespace and leading zeros:

    • str = str.trim(); removes any leading and trailing whitepace.
    • if (!str) catches a blank string and returns, no point in doing the rest of the work.
    • str = str.replace(/^0+/, "") || "0"; removes all leading 0s from the string — but if that results in a blank string, restores a single 0.
  2. Number(str): Convert str to a number; the number may well have a fractional portion, or may be NaN.

  3. Math.floor: Truncate the number (chops off any fractional portion).

  4. String(...): Converts the result back into a normal decimal string. For really big numbers, this will go to scientific notation, which may break this approach. (I don't quite know where the split is, the details are in the spec, but for whole numbers I believe it's at the point you've exceeded 21 digits [by which time the number has become very imprecise, as IEEE-754 double-precision numbers only have roughtly 15 digits of precision..)

  5. ... === str: Compares that to the original string.

  6. n >= 0: Check that it's positive.

Note that this fails for the input "+1", any input in scientific notation that doesn't turn back into the same scientific notation at the String(...) stage, and for any value that the kind of number JavaScript uses (IEEE-754 double-precision binary floating point) can't accurately represent which parses as closer to a different value than the given one (which includes many integers over 9,007,199,254,740,992; for instance, 1234567890123456789 will fail). The former is an easy fix, the latter two not so much.

Regular Expression

The other approach is to test the characters of the string via a regular expression, if your goal is to just allow (say) an optional + followed by either 0 or a string in normal decimal format:

function isNormalInteger(str) {
    return /^\+?(0|[1-9]\d*)$/.test(str);
}

Live testbed:

_x000D_
_x000D_
function isNormalInteger(str) {_x000D_
    return /^\+?(0|[1-9]\d*)$/.test(str);_x000D_
}_x000D_
function gid(id) {_x000D_
    return document.getElementById(id);_x000D_
}_x000D_
function test(str, expect) {_x000D_
    var result = isNormalInteger(str);_x000D_
    console.log(_x000D_
        str + ": " +_x000D_
        (result ? "Yes" : "No") +_x000D_
        (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")_x000D_
    );_x000D_
}_x000D_
gid("btn").addEventListener(_x000D_
    "click",_x000D_
    function() {_x000D_
        test(gid("text").value);_x000D_
    },_x000D_
    false_x000D_
);_x000D_
test("1", true);_x000D_
test("1.23", false);_x000D_
test("1234567890123", true);_x000D_
test("1234567890123.1", false);_x000D_
test("0123", false); // false because we don't handle leading 0s_x000D_
test(" 123 ", false); // false because we don't handle whitespace
_x000D_
<label>_x000D_
  String:_x000D_
  <input id="text" type="text" value="">_x000D_
<label>_x000D_
<input id="btn" type="button" value="Check">
_x000D_
_x000D_
_x000D_

How that works:

  1. ^: Match start of string

  2. \+?: Allow a single, optional + (remove this if you don't want to)

  3. (?:...|...): Allow one of these two options (without creating a capture group):

    1. (0|...): Allow 0 on its own...

    2. (...|[1-9]\d*): ...or a number starting with something other than 0 and followed by any number of decimal digits.

  4. $: Match end of string.

If you want to disallow 0 (because it's not positive), the regular expression becomes just /^\+?[1-9]\d*$/ (e.g., we can lose the alternation that we needed to allow 0).

If you want to allow leading zeroes (0123, 00524), then just replace the alternation (?:0|[1-9]\d*) with \d+

function isNormalInteger(str) {
    return /^\+?\d+$/.test(str);
}

If you want to allow whitespace, add \s* just after ^ and \s* just before $.

Note for when you convert that to a number: On modern engines it would probably be fine to use +str or Number(str) to do it, but older ones might extend those in a non-standard (but formerly-allowed) way that says a leading zero means octal (base 8), e.g "010" => 8. Once you've validated the number, you can safely use parseInt(str, 10) to ensure that it's parsed as decimal (base 10). parseInt would ignore garbage at the end of the string, but we've ensured there isn't any with the regex.

Kendo grid date column not formatting

As far as I'm aware in order to format a date value you have to handle it in parameterMap,

$('#listDiv').kendoGrid({
            dataSource: {
                type: 'json',
                serverPaging: true,
                pageSize: 10,
                transport: {
                    read: {
                        url: '@Url.Action("_ListMy", "Placement")',
                        data: refreshGridParams,
                        type: 'POST'
                    },
                    parameterMap: function (options, operation) {
                        if (operation != "read") {
                            var d = new Date(options.StartDate);
                            options.StartDate = kendo.toString(new Date(d), "dd/MM/yyyy");
                            return options;
                        }
                        else { return options; }

                    }
                },
                schema: {
                    model: {
                        id: 'Id',
                        fields: {
                            Id: { type: 'number' },
                            StartDate: { type: 'date', format: 'dd/MM/yyyy' },
                            Area: { type: 'string' },
                            Length: { type: 'string' },
                            Display: { type: 'string' },
                            Status: { type: 'string' },
                            Edit: { type: 'string' }
                        }
                    },
                    data: "Data",
                    total: "Count"
                }
            },
            scrollable: false,
            columns:
                [
                    {
                        field: 'StartDate',
                        title: 'Start Date',
                        format: '{0:dd/MM/yyyy}',
                        width: 100
                    },

If you follow the above example and just renames objects like 'StartDate' then it should work (ignore 'data: refreshGridParams,')

For further details check out below link or just search for kendo grid parameterMap ans see what others have done.

http://docs.kendoui.com/api/framework/datasource#configuration-transport.parameterMap

How to convert a structure to a byte array in C#?

As the main answer is using CIFSPacket type, which is not (or no longer) available in C#, I wrote correct methods:

    static byte[] getBytes(object str)
    {
        int size = Marshal.SizeOf(str);
        byte[] arr = new byte[size];
        IntPtr ptr = Marshal.AllocHGlobal(size);

        Marshal.StructureToPtr(str, ptr, true);
        Marshal.Copy(ptr, arr, 0, size);
        Marshal.FreeHGlobal(ptr);

        return arr;
    }

    static T fromBytes<T>(byte[] arr)
    {
        T str = default(T);

        int size = Marshal.SizeOf(str);
        IntPtr ptr = Marshal.AllocHGlobal(size);

        Marshal.Copy(arr, 0, ptr, size);

        str = (T)Marshal.PtrToStructure(ptr, str.GetType());
        Marshal.FreeHGlobal(ptr);

        return str;
    }

Tested, they work.

Scikit-learn train_test_split with indices

Scikit learn plays really well with Pandas, so I suggest you use it. Here's an example:

In [1]: 
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
data = np.reshape(np.random.randn(20),(10,2)) # 10 training examples
labels = np.random.randint(2, size=10) # 10 labels

In [2]: # Giving columns in X a name
X = pd.DataFrame(data, columns=['Column_1', 'Column_2'])
y = pd.Series(labels)

In [3]:
X_train, X_test, y_train, y_test = train_test_split(X, y, 
                                                    test_size=0.2, 
                                                    random_state=0)

In [4]: X_test
Out[4]:

     Column_1    Column_2
2   -1.39       -1.86
8    0.48       -0.81
4   -0.10       -1.83

In [5]: y_test
Out[5]:

2    1
8    1
4    1
dtype: int32

You can directly call any scikit functions on DataFrame/Series and it will work.

Let's say you wanted to do a LogisticRegression, here's how you could retrieve the coefficients in a nice way:

In [6]: 
from sklearn.linear_model import LogisticRegression

model = LogisticRegression()
model = model.fit(X_train, y_train)

# Retrieve coefficients: index is the feature name (['Column_1', 'Column_2'] here)
df_coefs = pd.DataFrame(model.coef_[0], index=X.columns, columns = ['Coefficient'])
df_coefs
Out[6]:
            Coefficient
Column_1    0.076987
Column_2    -0.352463

Does Spring @Transactional attribute work on a private method?

The answer is no. Please see Spring Reference: Using @Transactional :

The @Transactional annotation may be placed before an interface definition, a method on an interface, a class definition, or a public method on a class

Getting a "This application is modifying the autolayout engine from a background thread" error?

It could be something as simple as setting a text field / label value or adding a subview inside a background thread, which may cause a field's layout to change. Make sure anything you do with the interface only happens in the main thread.

Check this link: https://forums.developer.apple.com/thread/7399

Difference between long and int data types

The guarantees the standard gives you go like this:

1 == sizeof(char) <= sizeof(short) <= sizeof (int) <= sizeof(long) <= sizeof(long long)

So it's perfectly valid for sizeof (int) and sizeof (long) to be equal, and many platforms choose to go with this approach. You will find some platforms where int is 32 bits, long is 64 bits, and long long is 128 bits, but it seems very common for sizeof (long) to be 4.

(Note that long long is recognized in C from C99 onwards, but was normally implemented as an extension in C++ prior to C++11.)

How do I install Keras and Theano in Anaconda Python on Windows?

Anaconda with Windows

  • Run anaconda prompt with administrator privilages
  • conda update conda
  • conda update --all
  • conda install mingw libpython
  • conda install theano

After conda commands it's required to accept process - Proceed ([y]/n)?

UILabel font size?

For Swift 3.1, Swift 4 and Swift 5, if you only want change the font size for a label :

let myLabel : UILabel = ...
myLabel.font = myLabel.font.withSize(25)

Select query with date condition

hey guys i think what you are looking for is this one using select command. With this you can specify a RANGE GREATER THAN(>) OR LESSER THAN(<) IN MySQL WITH THIS:::::

select* from <**TABLE NAME**> where year(**COLUMN NAME**) > **DATE** OR YEAR(COLUMN NAME )< **DATE**;

FOR EXAMPLE:

select name, BIRTH from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+------------+
| name     | BIRTH      |
+----------+------------+
| bowser   | 1979-09-11 |
| chirpy   | 1998-09-11 |
| whistler | 1999-09-09 |
+----------+------------+

FOR SIMPLE RANGE LIKE USE ONLY GREATER THAN / LESSER THAN

mysql> select COLUMN NAME from <TABLE NAME> where year(COLUMN NAME)> 1996;

FOR EXAMPLE mysql>

select name from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+
| name     |
+----------+
| bowser   |
| chirpy   |
| whistler |
+----------+
3 rows in set (0.00 sec)

List all kafka topics

Zookeeper is required for running Kafka. zookeeper is must. still if you want to see topic list without zookeeper then you need kafka monitoring tool such as Kafka Monitor Tool, kafka-manager etc.

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

If your mail server is Gmail (smtp.google.com), you will get this error when you hit the message limit. Gmail allows sending over SMTP up to only 2000 messages per 24 hours.

How to insert newline in string literal?

If you want a const string that contains Environment.NewLine in it you can do something like this:

const string stringWithNewLine =
@"first line
second line
third line";

EDIT

Since this is in a const string it is done in compile time therefore it is the compiler's interpretation of a newline. I can't seem to find a reference explaining this behavior but, I can prove it works as intended. I compiled this code on both Windows and Ubuntu (with Mono) then disassembled and these are the results:

Disassemble on Windows Disassemble on Ubuntu

As you can see, in Windows newlines are interpreted as \r\n and on Ubuntu as \n

Embed Youtube video inside an Android app

although I suggest to use youtube api or call new intent and make the system handle it (i.e. youtube app), here some code that can help you, it has a call to an hidden method because you can't pause and resume webview

import java.lang.reflect.Method;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import android.app.Activity;

@SuppressLint("SetJavaScriptEnabled")
public class MultimediaPlayer extends Activity
{
    private WebView mWebView;
    private boolean mIsPaused = false;

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

        String media_url = VIDEO_URL;

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.setWebChromeClient(new WebChromeClient());

        WebSettings ws = mWebView.getSettings();
        ws.setBuiltInZoomControls(true);
        ws.setJavaScriptEnabled(true);

        mIsPaused = true;
        resumeBrowser();
        mWebView.loadUrl(media_url);
    }

    @Override
    protected void onPause()
    {
        pauseBrowser();
        super.onPause();
    }

    @Override
    protected void onResume()
    {
        resumeBrowser();
        super.onResume();
    }

    private void pauseBrowser()
    {
        if (!mIsPaused)
        {
            // pause flash and javascript etc
            callHiddenWebViewMethod(mWebView, "onPause");
            mWebView.pauseTimers();
            mIsPaused = true;
        }
    }

    private void resumeBrowser()
    {
        if (mIsPaused)
        {
            // resume flash and javascript etc
            callHiddenWebViewMethod(mWebView, "onResume");
            mWebView.resumeTimers();
            mIsPaused = false;
        }
    }

    private void callHiddenWebViewMethod(final WebView wv, final String name)
    {
        try
        {
            final Method method = WebView.class.getMethod(name);
            method.invoke(mWebView);
        } catch (final Exception e)
        {}
    }
}

How to set css style to asp.net button?

nobody wants to go to the clutter of using a class, try this:

<asp:button Style="margin:0px" runat="server" />

Intellisense won't suggest it but it will get the job done without throwing errors, warnings, or messages. Don't forget the capital S in Style

print memory address of Python variable

id is the method you want to use: to convert it to hex:

hex(id(variable_here))

For instance:

x = 4
print hex(id(x))

Gave me:

0x9cf10c

Which is what you want, right?

(Fun fact, binding two variables to the same int may result in the same memory address being used.)
Try:

x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))

This gave me identical pairs, even for the large integers.

Dynamically Add Images React Webpack

If you are looking for a way to import all your images from the image

// Import all images in image folder
function importAll(r) {
    let images = {};
    r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
    return images;
}

const images = importAll(require.context('../images', false, /\.(gif|jpe?g|svg)$/));

Then:

<img src={images['image-01.jpg']}/>

You can find the original thread here: Dynamically import images from a directory using webpack

How to disable manual input for JQuery UI Datepicker field?

When you make the input, set it to be readonly.

<input type="text" name="datepicker" id="datepicker" readonly="readonly" />

Remove Object from Array using JavaScript

Performance

Today 2021.01.27 I perform tests on MacOs HighSierra 10.13.6 on Chrome v88, Safari v13.1.2 and Firefox v84 for chosen solutions.

Results

For all browsers:

  • fast/fastest solutions when element not exists: A and B
  • fast/fastest solutions for big arrays: C
  • fast/fastest solutions for big arrays when element exists: H
  • quite slow solutions for small arrays: F and G
  • quite slow solutions for big arrays: D, E and F

enter image description here

Details

I perform 4 tests cases:

  • small array (10 elements) and element exists - you can run it HERE
  • small array (10 elements) and element NOT exists - you can run it HERE
  • big array (milion elements) and element exists - you can run it HERE
  • big array (milion elements) and element NOT exists - you can run it HERE

Below snippet presents differences between solutions A B C D E F G H I

_x000D_
_x000D_
function A(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  if(idx>=0) arr.splice(idx, 1);
  return arr;
}


function B(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  return idx<0 ? arr : arr.slice(0,idx).concat(arr.slice(idx+1,arr.length));
}


function C(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  delete arr[idx];
  return arr;
}


function D(arr, name) {
  return arr.filter(el => el.name != name);
}


function E(arr, name) {
  let result = [];
  arr.forEach(o => o.name==name || result.push(o));
  return result;
}


function F(arr, name) {
  return _.reject(arr, el => el.name == name);
}


function G(arr, name) {
  let o = arr.find(o => o.name==name);
  return _.without(arr,o);
}


function H(arr, name) {
  $.each(arr, function(i){
      if(arr[i].name === 'Kristian') {
          arr.splice(i,1);
          return false;
      }
  });
  return arr;
}


function I(arr, name) {
  return $.grep(arr,o => o.name!=name);
}








// Test
let test1 = [   
    {name:"Kristian", lines:"2,5,10"},
    {name:"John", lines:"1,19,26,96"},  
];

let test2 = [   
    {name:"John3", lines:"1,19,26,96"},
    {name:"Kristian", lines:"2,5,10"},
    {name:"John", lines:"1,19,26,96"},
  {name:"Joh2", lines:"1,19,26,96"},
];

let test3 = [   
    {name:"John3", lines:"1,19,26,96"},
    {name:"John", lines:"1,19,26,96"},
  {name:"Joh2", lines:"1,19,26,96"},
];

console.log(`
Test1: original array from question
Test2: array with more data
Test3: array without element which we want to delete
`);

[A,B,C,D,E,F,G,H,I].forEach(f=> console.log(`
Test1 ${f.name}: ${JSON.stringify(f([...test1],"Kristian"))}
Test2 ${f.name}: ${JSON.stringify(f([...test2],"Kristian"))}
Test3 ${f.name}: ${JSON.stringify(f([...test3],"Kristian"))}
`));
_x000D_
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
  
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

How to initialize a list of strings (List<string>) with many string values

This is how you would do it.

_x000D_
_x000D_
List <string> list1 = new List <string>();
_x000D_
_x000D_
_x000D_

Do Not Forget to add

_x000D_
_x000D_
using System.Collections.Generic;
_x000D_
_x000D_
_x000D_