Programs & Examples On #Wcf extensions

0

DataGridView AutoFit and Fill

This is what I have done in order to get the column "first_name" fill the space when all the columns cannot do it.

When the grid go to small the column "first_name" gets almost invisible (very thin) so I can set the DataGridViewAutoSizeColumnMode to AllCells as the others visible columns. For performance issues it´s important to set them to None before data binding it and set back to AllCell in the DataBindingComplete event handler of the grid. Hope it helps!

private void dataGridView1_Resize(object sender, EventArgs e)
    {
        int ColumnsWidth = 0;
        foreach(DataGridViewColumn col in dataGridView1.Columns)
        {
            if (col.Visible) ColumnsWidth += col.Width;
        }

        if (ColumnsWidth <dataGridView1.Width)
        {
            dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
        else if (dataGridView1.Columns["first_name"].Width < 10) dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    }

Converting an object to a string

setobjToString:function(obj){
        var me =this;
        obj=obj[0];
        var tabjson=[];
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                if (obj[p] instanceof Array){
                    tabjson.push('"'+p +'"'+ ':' + me.setobjToString(obj[p]));
                }else{
                    tabjson.push('"'+p +'"'+':"'+obj[p]+'"');
                }
            }
        }  tabjson.push()
        return '{'+tabjson.join(',')+'}';
    }

How to sort List<Integer>?

You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.

Sorting a list in ascending order can be performed as default operation on this way:

Collections.sort(list);

Sorting a list in descending order can be performed on this way:

Collections.reverse(list);

According to these facts, your solution has to be written like this:

public class tes 
{
    public static void main(String args[])
    {
        List<Integer> lList = new ArrayList<Integer>();
        lList.add(4);
        lList.add(1);
        lList.add(7);
        lList.add(2);
        lList.add(9);
        lList.add(1);
        lList.add(5);

        Collections.sort(lList);
        for(int i=0; i<lList.size();i++ )
        {
            System.out.println(lList.get(i));
        }
     }
}

More about Collections you can read here.

How to find MAC address of an Android device programmatically

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress(); 

Also, add below permission in your manifest file

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Please refer to Android 6.0 Changes.

To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.

java: HashMap<String, int> not working

You can use reference type in generic arguments, not primitive type. So here you should use

Map<String, Integer> myMap = new HashMap<String, Integer>();

and store value as

myMap.put("abc", 5);

Bash foreach loop

If they all have the same extension (for example .jpg), you can use this:

for picture in  *.jpg ; do
    echo "the next file is $picture"
done

(This solution also works if the filename has spaces)

How do I get a computer's name and IP address using VB.NET?

Label12.Text = "My ID : " + System.Net.Dns.GetHostByName(Net.Dns.GetHostName()).AddressList(0).ToString()

use this code, without any variable

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

Google map V3 Set Center to specific Marker

This should do the trick!

google.maps.event.trigger(map, "resize");
map.panTo(marker.getPosition());
map.setZoom(14);

You will need to have your maps global

How to access /storage/emulated/0/

if you are using Android device monitor and android emulator : I have accessed following way: Data/Media/0/ enter image description here

How to set connection timeout with OkHttp

For Retrofit 2.0.0-beta1 or beta2, the code goes as follows:

OkHttpClient client = new OkHttpClient();

client.setConnectTimeout(30, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://api.yourapp.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

Another situation is to check that the Primary Key is the same name as with your classes where the only difference is that your primary key has an 'ID' appended to it or to specify [Key] on primary keys that are not related to how the class is named.

converting Java bitmap to byte array

Try this to convert String-Bitmap or Bitmap-String

/**
 * @param bitmap
 * @return converting bitmap and return a string
 */
public static String BitMapToString(Bitmap bitmap){
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte [] b=baos.toByteArray();
    String temp=Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}

/**
 * @param encodedString
 * @return bitmap (from given string)
 */
public static Bitmap StringToBitMap(String encodedString){
    try{
        byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
        Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return bitmap;
    }catch(Exception e){
        e.getMessage();
        return null;
    }
}

Merge two rows in SQL

There are a few ways depending on some data rules that you have not included, but here is one way using what you gave.

SELECT
    t1.Field1,
    t2.Field2
FROM Table1 t1
    LEFT JOIN Table1 t2 ON t1.FK = t2.FK AND t2.Field1 IS NULL

Another way:

SELECT
    t1.Field1,
    (SELECT Field2 FROM Table2 t2 WHERE t2.FK = t1.FK AND Field1 IS NULL) AS Field2
FROM Table1 t1

Change the column label? e.g.: change column "A" to column "Name"

If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok

Jenkins restrict view of jobs per user

Try going to "Manage Jenkins"->"Manage Users" go to the specific user, edit his/her configuration "My Views section" default view.

Are static methods inherited in Java?

Static members are universal members. They can be accessed from anywhere.

How to add an object to an array

Put anything into an array using Array.push().

var a=[], b={};
a.push(b);    
// a[0] === b;

Extra information on Arrays

Add more than one item at a time

var x = ['a'];
x.push('b', 'c');
// x = ['a', 'b', 'c']

Add items to the beginning of an array

var x = ['c', 'd'];
x.unshift('a', 'b');
// x = ['a', 'b', 'c', 'd']

Add the contents of one array to another

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f']  (remains unchanged)

Create a new array from the contents of two arrays

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c']  (remains unchanged)
// y = ['d', 'e', 'f']  (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']

What is the right way to write my script 'src' url for a local development environment?

This is an old post but...

You can reference the working directory (the folder the .html file is located in) with ./, and the directory above that with ../

Example directory structure:

/html/public/
- index.html
- script2.js
- js/
   - script.js

To load script.js from inside index.html:

<script type="text/javascript" src="./js/script.js">

This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.

You could also specify ../ to go one directory above the working directory, to load things from there. But that is unusual.

Select element by exact match of its content

No, there's no jQuery (or CSS) selector that does that.

You can readily use filter:

$("p").filter(function() {
    return $(this).text() === "hello";
}).css("font-weight", "bold");

It's not a selector, but it does the job. :-)

If you want to handle whitespace before or after the "hello", you might throw a $.trim in there:

return $.trim($(this).text()) === "hello";

For the premature optimizers out there, if you don't care that it doesn't match <p><span>hello</span></p> and similar, you can avoid the calls to $ and text by using innerHTML directly:

return this.innerHTML === "hello";

...but you'd have to have a lot of paragraphs for it to matter, so many that you'd probably have other issues first. :-)

Pinging an IP address using PHP and echoing the result

This works fine with hostname, reverse IP (for internal networks) and IP.

function pingAddress($ip) {
    $ping = exec("ping -n 2 $ip", $output, $status);
    if (strpos($output[2], 'unreachable') !== FALSE) {
        return '<span style="color:#f00;">OFFLINE</span>';
    } else {
        return '<span style="color:green;">ONLINE</span>';
    }
}

echo pingAddress($ip);

Using ORDER BY and GROUP BY together

Why make it so complicated? This worked.

SELECT m_id,v_id,MAX(TIMESTAMP) AS TIME
 FROM table_name 
 GROUP BY m_id

How do you deploy Angular apps?

I use with forever:

  1. Build your Angular application with angular-cli to dist folder ng build --prod --output-path ./dist
  2. Create server.js file in your Angular application path:

    const express = require('express');
    const path = require('path');
    
    const app = express();
    
    app.use(express.static(__dirname + '/dist'));
    
    app.get('/*', function(req,res) {
        res.sendFile(path.join(__dirname + '/dist/index.html'));
    });
    app.listen(80);
    
  3. Start forever forever start server.js

That's all! your application should be running!

How do I use typedef and typedef enum in C?

typedef defines a new data type. So you can have:

typedef char* my_string;
typedef struct{
  int member1;
  int member2;
} my_struct;

So now you can declare variables with these new data types

my_string s;
my_struct x;

s = "welcome";
x.member1 = 10;

For enum, things are a bit different - consider the following examples:

enum Ranks {FIRST, SECOND};
int main()
{
   int data = 20;
   if (data == FIRST)
   {
      //do something
   }
}

using typedef enum creates an alias for a type:

typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
   Order data = (Order)20;  // Must cast to defined type to prevent error

   if (data == FIRST)
   {
      //do something
   }
}

How to name and retrieve a stash by name in git?

Stashes are not meant to be permanent things like you want. You'd probably be better served using tags on commits. Construct the thing you want to stash. Make a commit out of it. Create a tag for that commit. Then roll back your branch to HEAD^. Now when you want to reapply that stash you can use git cherry-pick -n tagname (-n is --no-commit).

Is either GET or POST more secure than the other?

This isn't security related but... browsers doesn't cache POST requests.

Export to CSV using MVC, C# and jQuery

Respect to Biff, here's a few tweaks that let me use the method to bounce CSV from jQuery/Post against the server and come back as a CSV prompt to the user.

    [Themed(false)]
    public FileContentResult DownloadCSV()
    {

        var csvStringData = new StreamReader(Request.InputStream).ReadToEnd();

        csvStringData = Uri.UnescapeDataString(csvStringData.Replace("mydata=", ""));

        return File(new System.Text.UTF8Encoding().GetBytes(csvStringData), "text/csv", "report.csv");
    }

You'll need the unescape line if you are hitting this from a form with code like the following,

    var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val(data);
    $('#downloadForm').append($(input));
    $("#downloadForm").submit();

How can I remove a key and its value from an associative array?

You may need two or more loops depending on your array:

$arr[$key1][$key2][$key3]=$value1; // ....etc

foreach ($arr as $key1 => $values) {
  foreach ($key1 as $key2 => $value) {
  unset($arr[$key1][$key2]);
  }
}

What is the Simplest Way to Reverse an ArrayList?

Just in case we are using Java 8, then we can make use of Stream. The ArrayList is random access list and we can get a stream of elements in reverse order and then collect it into a new ArrayList.

public static void main(String[] args) {
        ArrayList<String> someDummyList = getDummyList();
        System.out.println(someDummyList);
        int size = someDummyList.size() - 1;
        ArrayList<String> someDummyListRev = IntStream.rangeClosed(0,size).mapToObj(i->someDummyList.get(size-i)).collect(Collectors.toCollection(ArrayList::new));
        System.out.println(someDummyListRev);
    }

    private static ArrayList<String> getDummyList() {
        ArrayList dummyList = new ArrayList();
        //Add elements to ArrayList object
        dummyList.add("A");
        dummyList.add("B");
        dummyList.add("C");
        dummyList.add("D");
        return dummyList;
    }

The above approach is not suitable for LinkedList as that is not random-access. We can also make use of instanceof to check as well.

The module was expected to contain an assembly manifest

In my case, I was using InstallUtil.exe which was causing an error. To install the .Net Core service in window best way to use sc command.

More information here Exe installation throwing error The module was expected to contain an assembly manifest .Net Core

Convert an integer to a byte array

What's wrong with converting it to a string?

[]byte(fmt.Sprintf("%d", myint))

Why not use Double or Float to represent currency?

Many of the answers posted to this question discuss IEEE and the standards surrounding floating-point arithmetic.

Coming from a non-computer science background (physics and engineering), I tend to look at problems from a different perspective. For me, the reason why I wouldn't use a double or float in a mathematical calculation is that I would lose too much information.

What are the alternatives? There are many (and many more of which I am not aware!).

BigDecimal in Java is native to the Java language. Apfloat is another arbitrary-precision library for Java.

The decimal data type in C# is Microsoft's .NET alternative for 28 significant figures.

SciPy (Scientific Python) can probably also handle financial calculations (I haven't tried, but I suspect so).

The GNU Multiple Precision Library (GMP) and the GNU MFPR Library are two free and open-source resources for C and C++.

There are also numerical precision libraries for JavaScript(!) and I think PHP which can handle financial calculations.

There are also proprietary (particularly, I think, for Fortran) and open-source solutions as well for many computer languages.

I'm not a computer scientist by training. However, I tend to lean towards either BigDecimal in Java or decimal in C#. I haven't tried the other solutions I've listed, but they are probably very good as well.

For me, I like BigDecimal because of the methods it supports. C#'s decimal is very nice, but I haven't had the chance to work with it as much as I'd like. I do scientific calculations of interest to me in my spare time, and BigDecimal seems to work very well because I can set the precision of my floating point numbers. The disadvantage to BigDecimal? It can be slow at times, especially if you're using the divide method.

You might, for speed, look into the free and proprietary libraries in C, C++, and Fortran.

Python Matplotlib Y-Axis ticks on Right Side of Plot

Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:

import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()

It will show this:

enter image description here

How do AX, AH, AL map onto EAX?

| 0000 0001 0010 0011 0100 0101 0110 0111 | ------> EAX

|                     0100 0101 0110 0111 | ------> AX

|                               0110 0111 | ------> AL

|                     0100 0101           | ------> AH

How to log as much information as possible for a Java Exception?

You can also use Apache's ExceptionUtils.

Example:

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;


public class Test {

    static Logger logger = Logger.getLogger(Test.class);

    public static void main(String[] args) {

        try{
            String[] avengers = null;
            System.out.println("Size: "+avengers.length);
        } catch (NullPointerException e){
            logger.info(ExceptionUtils.getFullStackTrace(e));
        }
    }

}

Console output:

java.lang.NullPointerException
    at com.aimlessfist.avengers.ironman.Test.main(Test.java:11)

Start / Stop a Windows Service from a non-Administrator user account

  1. Login as an administrator.
  2. Download subinacl.exe from Microsoft:
    http://www.microsoft.com/en-us/download/details.aspx?id=23510
  3. Grant permissions to the regular user account to manage the BST services.
    (subinacl.exe is in C:\Program Files (x86)\Windows Resource Kits\Tools\).
  4. cd C:\Program Files (x86)\Windows Resource Kits\Tools\
    subinacl /SERVICE \\MachineName\bst /GRANT=domainname.com\username=F or
    subinacl /SERVICE \\MachineName\bst /GRANT=username=F
  5. Logout and log back in as the user. They should now be able to launch the BST service.

Get access to parent control from user control - C#

Not Ideal, but try this...

Change the usercontrol to Component class (In the code editor), build the solution and remove all the code with errors (Related to usercontrols but not available in components so the debugger complains about it)

Change the usercontrol back to usercontrol class...

Now it recognises the name and parent property but shows the component as non-visual as it is no longer designable.

How to include a sub-view in Blade templates?

EDIT: Below was the preferred solution in 2014. Nowadays you should use @include, as mentioned in the other answer.


In Laravel views the dot is used as folder separator. So for example I have this code

return View::make('auth.details', array('id' => $id));

which points to app/views/auth/details.blade.php

And to include a view inside a view you do like this:

file: layout.blade.php

<html>
  <html stuff>
  @yield('content')
</html>

file: hello.blade.php

@extends('layout')

@section('content')
  <html stuff>
@stop

Unable to use Intellij with a generated sources folder

I wanted to update at the comment earlier made by DaShaun, but as it is my first time commenting, application didn't allow me.

Nonetheless, I am using eclipse and after I added the below mention code snippet to my pom.xml as suggested by Dashun and I ran the mvn clean package to generate the avro source files, but I was still getting compilation error in the workspace.

I right clicked on project_name -> maven -> update project and updated the project, which added the target/generated-sources as a source folder to my eclipse project.

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.4</version>
    <executions>
        <execution>
            <id>test</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>${basedir}/target/generated-sources</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

Python, Pandas : write content of DataFrame into text File

I used a slightly modified version:

with open(file_name, 'w', encoding = 'utf-8') as f:
    for rec_index, rec in df.iterrows():
        f.write(rec['<field>'] + '\n')

I had to write the contents of a dataframe field (that was delimited) as a text file.

In C - check if a char exists in a char array

use strchr function when dealing with C strings.

const char * strchr ( const char * str, int character );

Here is an example of what you want to do.

/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char invalids[] = ".@<>#";
  char * pch;
  pch=strchr(invalids,'s');//is s an invalid character?
  if (pch!=NULL)
  {
    printf ("Invalid character");
  }
  else 
  {
     printf("Valid character");
  } 
  return 0;
}

Use memchr when dealing with memory blocks (as not null terminated arrays)

const void * memchr ( const void * ptr, int value, size_t num );

/* memchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char * pch;
  char invalids[] = "@<>#";
  pch = (char*) memchr (invalids, 'p', strlen(invalids));
  if (pch!=NULL)
    printf (p is an invalid character);
  else
    printf ("p valid character.\n");
  return 0;
}

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

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

How to add a class with React.js?

you can also use pure js to accomplish this like the old ways with jquery

try this if you want a simple way

 document.getElementById("myID").classList.add("show-example");

How to test code dependent on environment variables using JUnit?

Decouple the Java code from the Environment variable providing a more abstract variable reader that you realize with an EnvironmentVariableReader your code to test reads from.

Then in your test you can give an different implementation of the variable reader that provides your test values.

Dependency injection can help in this.

Force browser to refresh css, javascript, etc

If you want to be sure that these files are properly refreshed by Chrome for all users, then you need to have must-revalidate in the Cache-Control header. This will make Chrome re-check files to see if they need to be re-fetched.

Recommend the following response header:

Cache-Control: must-validate

This tells Chrome to check with the server, and see if there is a newer file. If there is a newer file, it will receive it in the response. If not, it will receive a 304 response, and the assurance that the one in the cache is up to date.

If you do NOT set this header, then in the absence of any other setting that invalidates the file, Chrome will never check with the server to see if there is a newer version.

Here is a blog post that discusses the issue further.

Programmatically generate video or animated GIF in Python?

from PIL import Image
import glob  #use it if you want to read all of the certain file type in the directory
imgs=[]
for i in range(596,691): 
    imgs.append("snap"+str(i)+'.png')
    print("scanned the image identified with",i)  

starting and ending value+1 of the index that identifies different file names

imgs = glob.glob("*.png") #do this if you want to read all files ending with .png

my files were: snap596.png, snap597.png ...... snap690.png

frames = []
for i in imgs:
    new_frame = Image.open(i)
    frames.append(new_frame)

Save into a GIF file that loops forever

frames[0].save('fire3_PIL.gif', format='GIF',
    append_images=frames[1:],
    save_all=True,
    duration=300, loop=0)

I found flickering issue with imageio and this method fixed it.

Apache and Node.js on the Same Server

This question belongs more on Server Fault but FWIW I'd say running Apache in front of Node.js is not a good approach in most cases.

Apache's ProxyPass is awesome for lots of things (like exposing Tomcat based services as part of a site) and if your Node.js app is just doing a specific, small role or is an internal tool that's only likely to have a limited number of users then it might be easier just to use it so you can get it working and move on, but that doesn't sound like the case here.

If you want to take advantage of the performance and scale you'll get from using Node.js - and especially if you want to use something that involves maintaining a persistent connection like web sockets - you are better off running both Apache and your Node.js on other ports (e.g. Apache on localhost:8080, Node.js on localhost:3000) and then running something like nginx, Varnish or HA proxy in front - and routing traffic that way.

With something like varnish or nginx you can route traffic based on path and/or host. They both use much less system resources and is much more scalable that using Apache to do the same thing.

Global variables in header file

You should not define global variables in header files. You can declare them as extern in header file and define them in a .c source file.

(Note: In C, int i; is a tentative definition, it allocates storage for the variable (= is a definition) if there is no other definition found for that variable in the translation unit.)

Android XXHDPI resources

According to the post linked in the G+ resource:

The gorgeous screen on the Nexus 10 falls into the XHDPI density bucket. On tablets, Launcher uses icons from one density bucket up [0] to render them slightly larger. To ensure that your launcher icon (arguably your apps most important asset) is crisp you need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.

So it looks like the xxhdpi is set for 480dpi. According to that, tablets use the assets from one dpi bucket higher than the one they're in for the launcher. The Nexus 10 being in bucket xhdpi will pull the launcher icon from the xxhdpi.

Source

Also, was not aware that tablets take resources from the asset bucket above their level. Noted.

Django - Reverse for '' not found. '' is not a valid view function or pattern name

Fix urlpatterns in urls.py file

For example, my app name is "simulator",

My URL pattern for login and logout looks like

urlpatterns = [
    ...
    ...
    url(r'^login/$', simulator.views.login_view, name="login"),
    url(r'^logout/$', simulator.views.logout_view, name="logout"),
    ...
    ...

]

JQuery - Storing ajax response into global variable

Ran into this too. Lots of answers, yet, only one simple correct one which I'm going to provide. The key is to make your $.ajax call..sync!

$.ajax({  
    async: false, ...

How to get local server host and port in Spring Boot?

One solution mentioned in a reply by @M. Deinum is one that I've used in a number of Akka apps:

object Localhost {

  /**
   * @return String for the local hostname
   */
  def hostname(): String = InetAddress.getLocalHost.getHostName

  /**
   * @return String for the host IP address
   */
  def ip(): String = InetAddress.getLocalHost.getHostAddress

}

I've used this method when building a callback URL for Oozie REST so that Oozie could callback to my REST service and it's worked like a charm

Create a view with ORDER BY clause

I'm not sure what you think this ORDER BY is accomplishing? Even if you do put ORDER BY in the view in a legal way (e.g. by adding a TOP clause), if you just select from the view, e.g. SELECT * FROM dbo.TopUsersTest; without an ORDER BY clause, SQL Server is free to return the rows in the most efficient way, which won't necessarily match the order you expect. This is because ORDER BY is overloaded, in that it tries to serve two purposes: to sort the results and to dictate which rows to include in TOP. In this case, TOP always wins (though depending on the index chosen to scan the data, you might observe that your order is working as expected - but this is just a coincidence).

In order to accomplish what you want, you need to add your ORDER BY clause to the queries that pull data from the view, not to the code of the view itself.

So your view code should just be:

CREATE VIEW [dbo].[TopUsersTest] 
AS 
  SELECT 
    u.[DisplayName], SUM(a.AnswerMark) AS Marks
  FROM
    dbo.Users_Questions AS uq
    INNER JOIN [dbo].[Users] AS u
      ON u.[UserID] = us.[UserID] 
    INNER JOIN [dbo].[Answers] AS a
      ON a.[AnswerID] = uq.[AnswerID]
    GROUP BY u.[DisplayName];

The ORDER BY is meaningless so should not even be included.


To illustrate, using AdventureWorks2012, here is an example:

CREATE VIEW dbo.SillyView
AS
  SELECT TOP 100 PERCENT 
    SalesOrderID, OrderDate, CustomerID , AccountNumber, TotalDue
  FROM Sales.SalesOrderHeader
  ORDER BY CustomerID;
GO

SELECT SalesOrderID, OrderDate, CustomerID, AccountNumber, TotalDue
FROM dbo.SillyView;

Results:

SalesOrderID   OrderDate   CustomerID   AccountNumber   TotalDue
------------   ----------  ----------   --------------  ----------
43659          2005-07-01  29825        10-4020-000676  23153.2339
43660          2005-07-01  29672        10-4020-000117  1457.3288
43661          2005-07-01  29734        10-4020-000442  36865.8012
43662          2005-07-01  29994        10-4020-000227  32474.9324
43663          2005-07-01  29565        10-4020-000510  472.3108

And you can see from the execution plan that the TOP and ORDER BY have been absolutely ignored and optimized away by SQL Server:

enter image description here

There is no TOP operator at all, and no sort. SQL Server has optimized them away completely.

Now, if you change the view to say ORDER BY SalesID, you will then just happen to get the ordering that the view states, but only - as mentioned before - by coincidence.

But if you change your outer query to perform the ORDER BY you wanted:

SELECT SalesOrderID, OrderDate, CustomerID, AccountNumber, TotalDue
FROM dbo.SillyView
ORDER BY CustomerID;

You get the results ordered the way you want:

SalesOrderID   OrderDate   CustomerID   AccountNumber   TotalDue
------------   ----------  ----------   --------------  ----------
43793          2005-07-22  11000        10-4030-011000  3756.989
51522          2007-07-22  11000        10-4030-011000  2587.8769
57418          2007-11-04  11000        10-4030-011000  2770.2682
51493          2007-07-20  11001        10-4030-011001  2674.0227
43767          2005-07-18  11001        10-4030-011001  3729.364

And the plan still has optimized away the TOP/ORDER BY in the view, but a sort is added (at no small cost, mind you) to present the results ordered by CustomerID:

enter image description here

So, moral of the story, do not put ORDER BY in views. Put ORDER BY in the queries that reference them. And if the sorting is expensive, you might consider adding/changing an index to support it.

Counter inside xsl:for-each loop

Try inserting <xsl:number format="1. "/><xsl:value-of select="."/><xsl:text> in the place of ???.

Note the "1. " - this is the number format. More info: here

difference between css height : 100% vs height : auto

height: 100% gives the element 100% height of its parent container.

height: auto means the element height will depend upon the height of its children.

Consider these examples:

height: 100%

<div style="height: 50px">
    <div id="innerDiv" style="height: 100%">
    </div>
</div>

#innerDiv is going to have height: 50px

height: auto

<div style="height: 50px">
    <div id="innerDiv" style="height: auto">
          <div id="evenInner" style="height: 10px">
          </div>
    </div>
</div>

#innerDiv is going to have height: 10px

Xcode 6.1 Missing required architecture X86_64 in file

If you are building a universal library and need to support the Simulator (x86_64) then build the framework for all platforms by setting Build Active Architecture Only to No. enter image description here

Install a Windows service using a Windows command prompt?

Open command prompt as administrator, go to your Folder where your .exe resides. To Install Exe as service

D:\YourFolderName\YourExeName /i

To uninstall use /u.

Tried to Load Angular More Than Once

The problem could occur when $templateCacheProvider is trying to resolve a template in the templateCache or through your project directory that does not exist

Example:

templateUrl: 'views/wrongPathToTemplate'

Should be:

templateUrl: 'views/home.html'

How do I get the path of the current executed file in Python?

You have simply called:

path = os.path.abspath(os.path.dirname(sys.argv[0]))

instead of:

path = os.path.dirname(os.path.abspath(sys.argv[0]))

abspath() gives you the absolute path of sys.argv[0] (the filename your code is in) and dirname() returns the directory path without the filename.

Reading a registry key in C#

using Microsoft.Win32;

  string chkRegVC = "NO";
   private void checkReg_vcredist() {

        string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
        using (Microsoft.Win32.RegistryKey uninstallKey = Registry.LocalMachine.OpenSubKey(regKey))
        {
            if (uninstallKey != null)
            {
                string[] productKeys = uninstallKey.GetSubKeyNames();
                foreach (var keyName in productKeys)
                {

                    if (keyName == "{196BB40D-1578-3D01-B289-BEFC77A11A1E}" ||//Visual C++ 2010 Redistributable Package (x86) 
                        keyName == "{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}" ||//Visual C++ 2010 Redistributable Package (x64) 
                        keyName == "{C1A35166-4301-38E9-BA67-02823AD72A1B}" ||//Visual C++ 2010 Redistributable Package (ia64) 
                        keyName == "{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}" ||//Visual C++ 2010 SP1 Redistributable Package (x86) 
                        keyName == "{1D8E6291-B0D5-35EC-8441-6616F567A0F7}" ||//Visual C++ 2010 SP1 Redistributable Package (x64) 
                        keyName == "{88C73C1C-2DE5-3B01-AFB8-B46EF4AB41CD}"   //Visual C++ 2010 SP1 Redistributable Package (ia64) 
                        ) { chkRegVC = "OK"; break; }
                    else { chkRegVC = "NO"; }
                }
            }
        }
    }

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

Had an error with type Int, due to referencing to a local case in my enum called .Int

func foo() { switch self { case .Int(var info): // ..... some other code } }

There error was here someFuncWithInt(parameter: Int)

Fixed it with someFuncWithInt(parameter: Swift.Int)

How to convert a Collection to List?

Collections.sort( new ArrayList( coll ) );

What does -XX:MaxPermSize do?

The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).

This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :

The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.

Note that this other Oracle documentation lists the other HotSpot arguments.

Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

Is it possible to put CSS @media rules inline?

I tried to test this and it did not seem to work but I'm curious why Apple is using it. I was just on https://linkmaker.itunes.apple.com/us/ and noticed in the generated code it provides if you select the 'Large Button' radio button, they are using an inline media query.

<a href="#" 
    target="itunes_store" 
    style="
        display:inline-block;
        overflow:hidden;
        background:url(#.png) no-repeat;
        width:135px;
        height:40px;
        @media only screen{
            background-image:url(#);
        }
"></a>

note: added line-breaks for readability, original generated code is minified

NSRange from Swift Range?

Swift 4

I think, there are two ways.

1. NSRange(range, in: )

2. NSRange(location:, length: )

Sample code:

let attributedString = NSMutableAttributedString(string: "Sample Text 12345", attributes: [.font : UIFont.systemFont(ofSize: 15.0)])

// NSRange(range, in: )
if let range = attributedString.string.range(of: "Sample")  {
    attributedString.addAttribute(.foregroundColor, value: UIColor.orange, range: NSRange(range, in: attributedString.string))
}

// NSRange(location: , length: )
if let range = attributedString.string.range(of: "12345") {
    attributedString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: range.lowerBound.encodedOffset, length: range.upperBound.encodedOffset - range.lowerBound.encodedOffset))
}

Screen Shot: enter image description here

How can I check if a view is visible or not in Android?

If the image is part of the layout it might be "View.VISIBLE" but that doesn't mean it's within the confines of the visible screen. If that's what you're after; this will work:

Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (imageView.getLocalVisibleRect(scrollBounds)) {
    // imageView is within the visible window
} else {
    // imageView is not within the visible window
}

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

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

You don't need regex for this

>>> s = "Username: How are you today?"

You can use the split method to split the string on the ':' character

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

And slice out element [0] to get the first part of the string

>>> s.split(':')[0]
'Username'

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

You can change the send line to this:

c.send(b'Thank you for connecting')

The b makes it bytes instead.

How to print GETDATE() in SQL Server with milliseconds in time?

This is equivalent to new Date().getTime() in JavaScript :

Use the below statement to get the time in seconds.

SELECT  cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)

Use the below statement to get the time in milliseconds.

SELECT  cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)  * 1000

MySQL Insert query doesn't work with WHERE clause

A way to use INSERT and WHERE is

INSERT INTO MYTABLE SELECT 953,'Hello',43 WHERE 0 in (SELECT count(*) FROM MYTABLE WHERE myID=953); In this case ist like an exist-test. There is no exception if you run it two or more times...

return, return None, and no return at all?

Yes, they are all the same.

We can review the interpreted machine code to confirm that that they're all doing the exact same thing.

import dis

def f1():
  print "Hello World"
  return None

def f2():
  print "Hello World"
  return

def f3():
  print "Hello World"

dis.dis(f1)
    4   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    5   5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f2)
    9   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    10  5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f3)
    14  0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE            
        5 LOAD_CONST    0 (None)
        8 RETURN_VALUE      

Simplest way to detect a pinch

My answer is inspired by Jeffrey's answer. Where that answer gives a more abstract solution, I try to provide more concrete steps on how to potentially implement it. This is simply a guide, one that can be implemented more elegantly. For a more detailed example check out this tutorial by MDN web docs.

HTML:

<div id="zoom_here">....</div>

JS

<script>
var dist1=0;
function start(ev) {
           if (ev.targetTouches.length == 2) {//check if two fingers touched screen
               dist1 = Math.hypot( //get rough estimate of distance between two fingers
                ev.touches[0].pageX - ev.touches[1].pageX,
                ev.touches[0].pageY - ev.touches[1].pageY);                  
           }
    
    }
    function move(ev) {
           if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) {
                 // Check if the two target touches are the same ones that started
               var dist2 = Math.hypot(//get rough estimate of new distance between fingers
                ev.touches[0].pageX - ev.touches[1].pageX,
                ev.touches[0].pageY - ev.touches[1].pageY);
                //alert(dist);
                if(dist1>dist2) {//if fingers are closer now than when they first touched screen, they are pinching
                  alert('zoom out');
                }
                if(dist1<dist2) {//if fingers are further apart than when they first touched the screen, they are making the zoomin gesture
                   alert('zoom in');
                }
           }
           
    }
        document.getElementById ('zoom_here').addEventListener ('touchstart', start, false);
        document.getElementById('zoom_here').addEventListener('touchmove', move, false);
</script>

How to pass arguments to Shell Script through docker run

With Docker, the proper way to pass this sort of information is through environment variables.

So with the same Dockerfile, change the script to

#!/bin/bash
echo $FOO

After building, use the following docker command:

docker run -e FOO="hello world!" test

Is this the proper way to do boolean test in SQL?

I personally prefer using char(1) with values 'Y' and 'N' for databases that don't have a native type for boolean. Letters are more user frendly than numbers which assume that those reading it will now that 1 corresponds to true and 0 corresponds to false.

'Y' and 'N' also maps nicely when using (N)Hibernate.

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..

Both should be same ..Java version mismatched ..Check it

SSRS chart does not show all labels on Horizontal axis

Really late reply for me, but I just suffered the pain of this problem as well.

What fixed it for me (after trying the Axis label settings and intervals from those screens, none of which worked!) was select the Horizontal Axis, then when you can see all the properties find Labels, and change LabelInterval to 1.

For some reason when I set this from the pop up properties screens it either never 'stuck' or it changes a slightly different value that didn't fix my issue.

How can bcrypt have built-in salts?

I believe that phrase should have been worded as follows:

bcrypt has salts built into the generated hashes to prevent rainbow table attacks.

The bcrypt utility itself does not appear to maintain a list of salts. Rather, salts are generated randomly and appended to the output of the function so that they are remembered later on (according to the Java implementation of bcrypt). Put another way, the "hash" generated by bcrypt is not just the hash. Rather, it is the hash and the salt concatenated.

dll missing in JDBC

Set java.library.path to a directory containing this DLL which Java uses to find native libraries. Specify -D switch on the command line

java -Djava.library.path=C:\Java\native\libs YourProgram

C:\Java\native\libs should contain sqljdbc_auth.dll

Look at this SO post if you are using Eclipse or at this blog if you want to set programatically.

XSLT counting elements with a given value

Your xpath is just a little off:

count(//Property/long[text()=$parPropId])

Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId] than the text() xpath, though you could make a case for the latter on readability grounds.

What can I say, I'm a bit tired today :)

How to use GROUP_CONCAT in a CONCAT in MySQL

SELECT id, Group_concat(column) FROM (SELECT id, Concat(name, ':', Group_concat(value)) AS column FROM mytbl GROUP BY id, name) tbl GROUP BY id;

Checking if element exists with Python Selenium

a)

from selenium.common.exceptions import NoSuchElementException        
def check_exists_by_xpath(xpath):
    try:
        webdriver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True

b) use xpath - the most reliable. Moreover you can take the xpath as a standard throughout all your scripts and create functions as above mentions for universal use.

UPDATE: I wrote the initial answer over 4 years ago and at the time I thought xpath would be the best option. Now I recommend to use css selectors. I still recommend not to mix/use "by id", "by name" and etc and use one single approach instead.

How to export/import PuTTy sessions list?

The answer posted by @m0nhawk doesn't seem to work as I test on a Windows 7 machine. Instead, using the following scripts would export/import the settings of putty:

::export
@echo off
set regfile=putty.reg
pushd %~dp0

reg export HKCU\Software\SimonTatham %regfile% /y

popd

--

::import
@echo off
pushd %~dp0
set regfile=putty.reg

if exist %regfile% reg import %regfile%

popd

How to check if array is not empty?

if self.table:
    print 'It is not empty'

Is fine too

Native query with named parameter fails with "Not all named parameters have been set"

After many tries I found that you should use createNativeQuery And you can send parameters using # replacement

In my example

String UPDATE_lOGIN_TABLE_QUERY = "UPDATE OMFX.USER_LOGIN SET LOGOUT_TIME = SYSDATE WHERE LOGIN_ID = #loginId AND USER_ID = #userId";


Query query = em.createNativeQuery(logQuery);

            query.setParameter("userId", logDataDto.getUserId());
            query.setParameter("loginId", logDataDto.getLoginId());

            query.executeUpdate();

Submit form and stay on same page?

The HTTP/CGI way to do this would be for your program to return an HTTP status code of 204 (No Content).

C#: How do you edit items and subitems in a listview?

I use a hidden textbox to edit all the listview items/subitems. The only problem is that the textbox needs to disappear as soon as any event takes place outside the textbox and the listview doesn't trigger the scroll event so if you scroll the listview the textbox will still be visible. To bypass this problem I created the Scroll event with this overrided listview.

Here is my code, I constantly reuse it so it might be help for someone:

ListViewItem.ListViewSubItem SelectedLSI;
private void listView2_MouseUp(object sender, MouseEventArgs e)
{
    ListViewHitTestInfo i = listView2.HitTest(e.X, e.Y);
    SelectedLSI = i.SubItem;
    if (SelectedLSI == null)
        return;

    int border = 0;
    switch (listView2.BorderStyle)
    {
        case BorderStyle.FixedSingle:
            border = 1;
            break;
        case BorderStyle.Fixed3D:
            border = 2;
            break;
    }

    int CellWidth = SelectedLSI.Bounds.Width;
    int CellHeight = SelectedLSI.Bounds.Height;
    int CellLeft = border + listView2.Left + i.SubItem.Bounds.Left;
    int CellTop =listView2.Top + i.SubItem.Bounds.Top;
    // First Column
    if (i.SubItem == i.Item.SubItems[0])
        CellWidth = listView2.Columns[0].Width;

    TxtEdit.Location = new Point(CellLeft, CellTop);
    TxtEdit.Size = new Size(CellWidth, CellHeight);
    TxtEdit.Visible = true;
    TxtEdit.BringToFront();
    TxtEdit.Text = i.SubItem.Text;
    TxtEdit.Select();
    TxtEdit.SelectAll();
}
private void listView2_MouseDown(object sender, MouseEventArgs e)
{
    HideTextEditor();
}
private void listView2_Scroll(object sender, EventArgs e)
{
    HideTextEditor();
}
private void TxtEdit_Leave(object sender, EventArgs e)
{
    HideTextEditor();
}
private void TxtEdit_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
        HideTextEditor();
}
private void HideTextEditor()
{
    TxtEdit.Visible = false;
    if (SelectedLSI != null)
        SelectedLSI.Text = TxtEdit.Text;
    SelectedLSI = null;
    TxtEdit.Text = "";
}

Get random sample from list while maintaining ordering of items?

Following code will generate a random sample of size 4:

import random

sample_size = 4
sorted_sample = [
    mylist[i] for i in sorted(random.sample(range(len(mylist)), sample_size))
]

(note: with Python 2, better use xrange instead of range)

Explanation

random.sample(range(len(mylist)), sample_size)

generates a random sample of the indices of the original list.

These indices then get sorted to preserve the ordering of elements in the original list.

Finally, the list comprehension pulls out the actual elements from the original list, given the sampled indices.

How do I timestamp every ping result?

just use sed:

ping google.com|sed -r "s/(.*)/$(date) \1/g"

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

Markdown to create pages and table of contents?

If using the Sublime Text editor, the MarkdownTOC plugin works beautifully! See:

  1. https://packagecontrol.io/packages/MarkdownTOC
  2. https://github.com/naokazuterada/MarkdownTOC

Once installed, go to Preferences --> Package Settings --> MarkdownTOC --> Settings -- User, to customize your settings. Here's the options you can choose: https://github.com/naokazuterada/MarkdownTOC#configuration.

I recommend the following:

{
  "defaults": {
    "autoanchor": true,
    "autolink": true,
    "bracket": "round",
    "levels": [1,2,3,4,5,6],
    "indent": "\t",
    "remove_image": true,
    "link_prefix": "",
    "bullets": ["-"],
    "lowercase": "only_ascii",
    "style": "ordered",
    "uri_encoding": true,
    "markdown_preview": ""
  },
  "id_replacements": [
    {
      "pattern": "\\s+",
      "replacement": "-"
    },
    {
      "pattern": "&lt;|&gt;|&amp;|&apos;|&quot;|&#60;|&#62;|&#38;|&#39;|&#34;|!|#|$|&|'|\\(|\\)|\\*|\\+|,|/|:|;|=|\\?|@|\\[|\\]|`|\"|\\.|\\\\|<|>|{|}|™|®|©|%",
      "replacement": ""
    }
  ],
  "logging": false
}

To insert a table of contents, simply click at the top of the document where you'd like to insert the table of contents, then go to Tools --> Markdown TOC --> Insert TOC.

It will insert something like this:

<!-- MarkdownTOC -->

1. [Helpful Links:](#helpful-links)
1. [Sublime Text Settings:](#sublime-text-settings)
1. [Packages to install](#packages-to-install)

<!-- /MarkdownTOC -->

Note the <!-- --> HTML comments it inserts for you. These are special markers that help the program know where the ToC is so that it can automatically update it for you every time you save! So, leave these intact.

To get extra fancy, add some <details> and <summary> HTML tags around it to make the ToC collapsible/expandable, like this:

<details>
<summary><b>Table of Contents</b> (click to open)</summary>
<!-- MarkdownTOC -->

1. [Helpful Links:](#helpful-links)
1. [Sublime Text Settings:](#sublime-text-settings)
1. [Packages to install](#packages-to-install)

<!-- /MarkdownTOC -->
</details>

Now, you get this super cool effect, as shown below. See it in action in my main eRCaGuy_dotfiles readme here, or in my Sublime_Text_editor readme here.

  1. Collapsed: enter image description here
  2. Expanded: enter image description here

For extra information about its usage and limitations, be sure to read my notes about the MarkdownTOC plugin in that readme too.

Object Dump JavaScript

function mydump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;

    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";

    if(typeof(arr) == 'object') {  
        for(var item in arr) {
            var value = arr[item];

            if(typeof(value) == 'object') { 
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += mydump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { 
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}

Check table exist or not before create it in Oracle

My solution is just compilation of best ideas in thread, with a little improvement. I use both dedicated procedure (@Tomasz Borowiec) to facilitate reuse, and exception handling (@Tobias Twardon) to reduce code and to get rid of redundant table name in procedure.

DECLARE

    PROCEDURE create_table_if_doesnt_exist(
        p_create_table_query VARCHAR2
    ) IS
    BEGIN
        EXECUTE IMMEDIATE p_create_table_query;
    EXCEPTION
        WHEN OTHERS THEN
        -- suppresses "name is already being used" exception
        IF SQLCODE = -955 THEN
            NULL; 
        END IF;
    END;

BEGIN
    create_table_if_doesnt_exist('
        CREATE TABLE "MY_TABLE" (
            "ID" NUMBER(19) NOT NULL PRIMARY KEY,
            "TEXT" VARCHAR2(4000),
            "MOD_TIME" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ');
END;
/

What is this CSS selector? [class*="span"]

It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid that has a class that CONTAINS span.

So would select the <strong> element in this example:

<div class="show-grid">
    <strong class="span6">Blah blah</strong>
</div>

You can also do searches for 'begins with...'

div[class^="something"] { }

which would work on something like this:-

<div class="something-else-class"></div>

and 'ends with...'

div[class$="something"] { }

which would work on

<div class="you-are-something"></div>

Good references

JavaFX How to set scene background image

I know this is an old Question

But in case you want to do it programmatically or the java way

For Image Backgrounds; you can use BackgroundImage class

BackgroundImage myBI= new BackgroundImage(new Image("my url",32,32,false,true),
        BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
          BackgroundSize.DEFAULT);
//then you set to your node
myContainer.setBackground(new Background(myBI));

For Paint or Fill Backgrounds; you can use BackgroundFill class

BackgroundFill myBF = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1),
         new Insets(0.0,0.0,0.0,0.0));// or null for the padding
//then you set to your node or container or layout
myContainer.setBackground(new Background(myBF));

Keeps your java alive && your css dead..

Is there a reason for C#'s reuse of the variable in a foreach?

In C# 5.0, this problem is fixed and you can close over loop variables and get the results you expect.

The language specification says:

8.8.4 The foreach statement

(...)

A foreach statement of the form

foreach (V v in x) embedded-statement

is then expanded to:

{
  E e = ((C)(x)).GetEnumerator();
  try {
      while (e.MoveNext()) {
          V v = (V)(T)e.Current;
          embedded-statement
      }
  }
  finally {
      … // Dispose e
  }
}

(...)

The placement of v inside the while loop is important for how it is captured by any anonymous function occurring in the embedded-statement. For example:

int[] values = { 7, 9, 13 };
Action f = null;
foreach (var value in values)
{
    if (f == null) f = () => Console.WriteLine("First value: " + value);
}
f();

If v was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value, 13, which is what the invocation of f would print. Instead, because each iteration has its own variable v, the one captured by f in the first iteration will continue to hold the value 7, which is what will be printed. (Note: earlier versions of C# declared v outside of the while loop.)

UTF-8 problems while reading CSV file with fgetcsv

The problem is that the function returns UTF-8 (it can check using mb_detect_encoding), but do not convert, and these characters takes as UTF-8. ?herefore, it's necessary to do the reverse-convert to initial encoding (Windows-1251 or CP1251) using iconv. But since by the fgetcsv returns an array, I suggest to write a custom function: [Sorry for my english]

function customfgetcsv(&$handle, $length, $separator = ';'){
    if (($buffer = fgets($handle, $length)) !== false) {
        return explode($separator, iconv("CP1251", "UTF-8", $buffer));
    }
    return false;
}

Reference member variables as class members

It's called dependency injection via constructor injection: class A gets the dependency as an argument to its constructor and saves the reference to dependent class as a private variable.

There's an interesting introduction on wikipedia.

For const-correctness I'd write:

using T = int;

class A
{
public:
  A(const T &thing) : m_thing(thing) {}
  // ...

private:
   const T &m_thing;
};

but a problem with this class is that it accepts references to temporary objects:

T t;
A a1{t};    // this is ok, but...

A a2{T()};  // ... this is BAD.

It's better to add (requires C++11 at least):

class A
{
public:
  A(const T &thing) : m_thing(thing) {}
  A(const T &&) = delete;  // prevents rvalue binding
  // ...

private:
  const T &m_thing;
};

Anyway if you change the constructor:

class A
{
public:
  A(const T *thing) : m_thing(*thing) { assert(thing); }
  // ...

private:
   const T &m_thing;
};

it's pretty much guaranteed that you won't have a pointer to a temporary.

Also, since the constructor takes a pointer, it's clearer to users of A that they need to pay attention to the lifetime of the object they pass.


Somewhat related topics are:

how to query child objects in mongodb

Assuming your "states" collection is like:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistake to query for nulls as:

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

JS. How to replace html element with another element/text, represented in string?

If you need to actually replace the td you are selecting from the DOM, then you need to first go to the parentNode, then replace the contents replace the innerHTML with a new html string representing what you want. The trick is converting the first-table-cell to a string so you can then use it in a string replace method.

I added a fiddle example: http://jsfiddle.net/vzUF4/

<table><tr><td id="first-table-cell">0</td><td>END</td></tr></table>

<script>
  var firstTableCell = document.getElementById('first-table-cell');
  var tableRow = firstTableCell.parentNode;
  // Create a separate node used to convert node into string.
  var renderingNode = document.createElement('tr');
  renderingNode.appendChild(firstTableCell.cloneNode(true));
  // Do a simple string replace on the html
  var stringVersionOfFirstTableCell = renderingNode.innerHTML;
  tableRow.innerHTML = tableRow.innerHTML.replace(stringVersionOfFirstTableCell,
    '<td>0</td><td>1</td>');
</script>

A lot of the complexity here is that you are mixing DOM methods with string methods. If DOM methods work for your application, it would be much bette to use those. You can also do this with pure DOM methods (document.createElement, removeChild, appendChild), but it takes more lines of code and your question explicitly said you wanted to use a string.

How to select the last column of dataframe

Somewhat similar to your original attempt, but more Pythonic, is to use Python's standard negative-indexing convention to count backwards from the end:

df[df.columns[-1]]

IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

You need to assign permissions for IIS_IUSRS on the local machine (but you don't have to assign for IUSR, in fact it will work even if you explicitly deny permissions).

To assign permissions, just right click on the folder and on the security tab make sure to grant the correct permissions, and if the user is not listed then click "ADD", and enter IIS_IUSRS (and make sure that under "domain" the local computer is selected, or enter in the name field YourLocalComputerName\IIS_IUSRS), and then you are good to go.

If you want you can instead of assigning permissions to the IIS_IUSRS group, you can instead assign to the app pool which should in general be "IIS APPPOOL\ app pool name".

How to stop PHP code execution?

You could try to kill the PHP process:

exec('kill -9 ' . getmypid());

Inserting created_at data with Laravel

In your User model, add the following line in the User class:

public $timestamps = true;

Now, whenever you save or update a user, Laravel will automatically update the created_at and updated_at fields.


Update:
If you want to set the created at manually you should use the date format Y-m-d H:i:s. The problem is that the format you have used is not the same as Laravel uses for the created_at field.

Update: Nov 2018 Laravel 5.6 "message": "Access level to App\\Note::$timestamps must be public", Make sure you have the proper access level as well. Laravel 5.6 is public.

If statement in aspx page

Here's a simple one written in VB for an ASPX page:

                If myVar > 1 Then
                    response.write("Greater than 1")
                else
                    response.write("Not!")
                End If

How to find and replace with regex in excel

If you want a formula to do it then:

=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)

This will do it. Change `"WORD" To the word you want.

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

Short ES6 code

const convertFrom24To12Format = (time24) => {
  const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
  const period = +sHours < 12 ? 'AM' : 'PM';
  const hours = +sHours % 12 || 12;

  return `${hours}:${minutes} ${period}`;
}
const convertFrom12To24Format = (time12) => {
  const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
  const PM = period === 'PM';
  const hours = (+sHours % 12) + (PM ? 12 : 0);

  return `${('0' + hours).slice(-2)}:${minutes}`;
}

hadoop No FileSystem for scheme: file

Took me ages to figure it out with Spark 2.0.2, but here's my bit:

val sparkBuilder = SparkSession.builder
.appName("app_name")
.master("local")
// Various Params
.getOrCreate()

val hadoopConfig: Configuration = sparkBuilder.sparkContext.hadoopConfiguration

hadoopConfig.set("fs.hdfs.impl", classOf[org.apache.hadoop.hdfs.DistributedFileSystem].getName)

hadoopConfig.set("fs.file.impl", classOf[org.apache.hadoop.fs.LocalFileSystem].getName)

And the relevant parts of my build.sbt:

scalaVersion := "2.11.8"
libraryDependencies += "org.apache.spark" %% "spark-core" % "2.0.2"

I hope this can help!

Change Primary Key

You will need to drop and re-create the primary key like this:

alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

However, if there are other tables with foreign keys that reference this primary key, then you will need to drop those first, do the above, and then re-create the foreign keys with the new column list.

An alternative syntax to drop the existing primary key (e.g. if you don't know the constraint name):

alter table my_table drop primary key;

How do you get the string length in a batch file?

You can try this code. Fast, you can also include special characters

@echo off
set "str=[string]"
echo %str% > "%tmp%\STR"
for %%P in ("%TMP%\STR") do (set /a strlen=%%~zP-3)
echo String lenght: %strlen%

Bash ignoring error for a particular command

Thanks for the simple solution here from above:

<particular_script/command> || true

The following construction could be used for additional actions/troubleshooting of script steps and additional flow control options:

if <particular_script/command>
then
   echo "<particular_script/command> is fine!"
else
   echo "<particular_script/command> failed!"
   #exit 1
fi

We can brake the further actions and exit 1 if required.

What is the difference between require and require-dev sections in composer.json?

require section This section contains the packages/dependencies which are better candidates to be installed/required in the production environment.

require-dev section: This section contains the packages/dependencies which can be used by the developer to test her code (or to experiment on her local machine and she doesn't want these packages to be installed on the production environment).

Find max and second max salary for a employee table MySQL

select 
    e.salary
        from(
           SELECT * FROM 
           Employee 
             group by salary
             order by salary desc
             limit 2
          ) e
     order by salary asc
     limit 1;

How to create a GUID / UUID

I really like how clean Broofa's answer is, but it's unfortunate that poor implementations of Math.random leave the chance for collision.

Here's a similar RFC4122 version 4 compliant solution that solves that issue by offsetting the first 13 hex numbers by a hex portion of the timestamp, and once depleted offsets by a hex portion of the microseconds since pageload. That way, even if Math.random is on the same seed, both clients would have to generate the UUID the exact same number of microseconds since pageload (if high-perfomance time is supported) AND at the exact same millisecond (or 10,000+ years later) to get the same UUID:

_x000D_
_x000D_
function generateUUID() { // Public Domain/MIT_x000D_
    var d = new Date().getTime();//Timestamp_x000D_
    var d2 = (performance && performance.now && (performance.now()*1000)) || 0;//Time in microseconds since page-load or 0 if unsupported_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
        var r = Math.random() * 16;//random number between 0 and 16_x000D_
        if(d > 0){//Use timestamp until depleted_x000D_
            r = (d + r)%16 | 0;_x000D_
            d = Math.floor(d/16);_x000D_
        } else {//Use microseconds since page-load if supported_x000D_
            r = (d2 + r)%16 | 0;_x000D_
            d2 = Math.floor(d2/16);_x000D_
        }_x000D_
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);_x000D_
    });_x000D_
}_x000D_
_x000D_
console.log(generateUUID())
_x000D_
_x000D_
_x000D_


Here's a fiddle to test.

how does unix handle full path name with space and arguments?

You can quote the entire path as in windows or you can escape the spaces like in:

/foo\ folder\ with\ space/foo.sh -help

Both ways will work!

Can inner classes access private variables?

An inner class has access to all members of the outer class, but it does not have an implicit reference to a parent class instance (unlike some weirdness with Java). So if you pass a reference to the outer class to the inner class, it can reference anything in the outer class instance.

How to use comparison and ' if not' in python?

In this particular case the clearest solution is the S.Lott answer

But in some complex logical conditions I would prefer use some boolean algebra to get a clear solution.

Using De Morgan's law ¬(A^B) = ¬Av¬B

not (u0 <= u and u < u0+step)
(not u0 <= u) or (not u < u0+step)
u0 > u or u >= u0+step

then

if u0 > u or u >= u0+step:
    pass

... in this case the «clear» solution is not more clear :P

What is a quick way to force CRLF in C# / .NET?

input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n")

This will work if the input contains only one type of line breaks - either CR, or LF, or CR+LF.

C# generic list <T> how to get the type of T?

Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

More generally, to support any IList<T>, you need to check the interfaces:

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}

Check if a class `active` exist on element with jquery

I think you want to use hasClass()

$('li.menu').hasClass('active');

What's the strangest corner case you've seen in C# or .NET?

I'm arriving a bit late to the party, but I've got three four five:

  1. If you poll InvokeRequired on a control that hasn't been loaded/shown, it will say false - and blow up in your face if you try to change it from another thread (the solution is to reference this.Handle in the creator of the control).

  2. Another one which tripped me up is that given an assembly with:

    enum MyEnum
    {
        Red,
        Blue,
    }
    

    if you calculate MyEnum.Red.ToString() in another assembly, and in between times someone has recompiled your enum to:

    enum MyEnum
    {
        Black,
        Red,
        Blue,
    }
    

    at runtime, you will get "Black".

  3. I had a shared assembly with some handy constants in. My predecessor had left a load of ugly-looking get-only properties, I thought I'd get rid of the clutter and just use public const. I was more than a little surprised when VS compiled them to their values, and not references.

  4. If you implement a new method of an interface from another assembly, but you rebuild referencing the old version of that assembly, you get a TypeLoadException (no implementation of 'NewMethod'), even though you have implemented it (see here).

  5. Dictionary<,>: "The order in which the items are returned is undefined". This is horrible, because it can bite you sometimes, but work others, and if you've just blindly assumed that Dictionary is going to play nice ("why shouldn't it? I thought, List does"), you really have to have your nose in it before you finally start to question your assumption.

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

For me, it's working with this:

BigDecimal a = new BigDecimal("9999999999.6666",precision);
BigDecimal b = new BigDecimal("21",precision);

a.divideToIntegralValue(b).setScale(2)

How can I set the initial value of Select2 when using AJAX?

For a simple and semantic solution i prefer to define the initial value in HTML, example:

<select name="myfield" data-placeholder="Select an option">
    <option value="initial-value" selected>Initial text</option>
</select>

So when i call $('select').select2({ ajax: {...}}); the initial value is initial-value and its option text is Initial text.

My current Select2 version is 4.0.3, but i think it has a great compatibility with other versions.

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

string.isNullOrWhiteSpace(text) should be used in most cases as it also includes a blank string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            var str = "";

            Console.WriteLine(string.IsNullOrWhiteSpace(str));              

        }
    }
}

It returns True!

VBA shorthand for x=x+1?

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

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

for example:

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

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

Oracle database: How to read a BLOB?

If the content is not too large, you can also use

SELECT CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) FROM <table>;

or

SELECT DUMP ( CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) ) FROM <table>;

This will show you the HEX values.

Angular2: custom pipe could not be found

see this is working for me.

ActStatus.pipe.ts First this is my pipe

import {Pipe,PipeTransform} from "@angular/core";

@Pipe({
  name:'actStatusPipe'
})
export class ActStatusPipe implements PipeTransform{
  transform(status:any):any{
    switch (status) {
      case 1:
        return "UN_PUBLISH";
      case 2:
        return "PUBLISH";
      default:
        return status
    }
  }
}

main-pipe.module.ts in pipe module, i need to declare my pipe/s and export it.

import { NgModule } from '@angular/core';
import {CommonModule} from "@angular/common";

import {ActStatusPipe} from "./ActStatusPipe.pipe"; // <---

@NgModule({
  declarations:[ActStatusPipe], // <---
  imports:[CommonModule],
  exports:[ActStatusPipe] // <---
})

export class MainPipe{}

app.module.ts user this pipe module in any module.

@NgModule({
  declarations: [...],
  imports: [..., MainPipe], // <---
  providers: [...],
  bootstrap: [AppComponent]
})

you can directly user pipe in this module. but if you feel that your pipe is used with in more than one component i suggest you to follow my approach.

  1. create pipe .
  2. create separate module and declare and export one or more pipe.
  3. user that pipe module.

How to use pipe totally depends on your project complexity and requirement. you might have just one pipe which used only once in the whole project. in that case you can directly use it without creating a pipe/s module (module approach).

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

cannot find zip-align when publishing app

Normally the zipalign.exe is close of the "Android manager"(also, "Android", "Android SDK" etc), so you can search for "Android Manager" in windows search and give a righ-click above the command and open file location. You probably are in: something\ Android\android-sdk\tools. Then is just necessary return a folder and go to Android\android-sdk\build-tools\23.0.3. The zipalign is there, you maybe be not able to use it with double-click, so you have to copy all the path of the zipalign file to use in CMD, the final code that you have to input will be something like:

C:\Users\heitor\AppData\Local\Android\android-sdk\build-tools\23.0.1\zipalign.exe -v 4 android.apk android2.apk

Adding sheets to end of workbook in Excel (normal method not working?)

mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name 

should probably be

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name 

No visible cause for "Unexpected token ILLEGAL"

Here is my reason:

before:

var path = "D:\xxx\util.s"

which \u is a escape, I figured it out by using Codepen's analyze JS.

after:

var path = "D:\\xxx\\util.s"

and the error fixed

Java: Detect duplicates in ArrayList?

If your elements are somehow Comparable (the fact that the order has any real meaning is indifferent -- it just needs to be consistent with your definition of equality), the fastest duplicate removal solution is going to sort the list ( 0(n log(n)) ) then to do a single pass and look for repeated elements (that is, equal elements that follow each other) (this is O(n)).

The overall complexity is going to be O(n log(n)), which is roughly the same as what you would get with a Set (n times long(n)), but with a much smaller constant. This is because the constant in sort/dedup results from the cost of comparing elements, whereas the cost from the set is most likely to result from a hash computation, plus one (possibly several) hash comparisons. If you are using a hash-based Set implementation, that is, because a Tree based is going to give you a O( n log²(n) ), which is even worse.

As I understand it, however, you do not need to remove duplicates, but merely test for their existence. So you should hand-code a merge or heap sort algorithm on your array, that simply exits returning true (i.e. "there is a dup") if your comparator returns 0, and otherwise completes the sort, and traverse the sorted array testing for repeats. In a merge or heap sort, indeed, when the sort is completed, you will have compared every duplicate pair unless both elements were already in their final positions (which is unlikely). Thus, a tweaked sort algorithm should yield a huge performance improvement (I would have to prove that, but I guess the tweaked algorithm should be in the O(log(n)) on uniformly random data)

How do you rebase the current branch's changes on top of changes being merged in?

You've got what rebase does backwards. git rebase master does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master on top of the current branch.

Vertical Tabs with JQuery?

I wouldn't expect vertical tabs to need different Javascript from horizontal tabs. The only thing that would be different is the CSS for presenting the tabs and content on the page. JS for tabs generally does no more than show/hide/maybe load content.

How can I convert a string to boolean in JavaScript?

I think this is much universal:

if (String(a).toLowerCase() == "true") ...

It goes:

String(true) == "true"     //returns true
String(false) == "true"    //returns false
String("true") == "true"   //returns true
String("false") == "true"  //returns false

jquery ui Dialog: cannot call methods on dialog prior to initialization

So you use this:

var theDialog = $("#divDialog").dialog(opt);
theDialog.dialog("open");

and if you open a MVC Partial View in Dialog, you can create in index a hidden button and JQUERY click event:

$("#YourButton").click(function()
{
   theDialog.dialog("open");
   OR
   theDialog.dialog("close");
});

then inside partial view html you call button trigger click like:

$("#YouButton").trigger("click")

see ya.

Oracle SQL Developer: Unable to find a JVM

If you have a 64-bit version of SQL Developer, but for some reason your default JDK is a 32-bit JDK (e.g. if you develop an Eclipse RCP application which requires a 32-bit JDK), then you have to set the value of the SetJavaHome property in the product.conf file to a 64-bit version of JDK in order to run the SQL Developer. For example:

SetJavaHome C:\Program Files\Java\jdk1.7.0_80

The product.conf file is in my case located in the following directory:

C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0

The solution described above worked in my case. The solutions of @evgenyl and @FGreg did not work in my case.

Highlight Bash/shell code in Markdown files

Bitbucket uses CodeMirror for syntax highlighting. For Bash or shell you can use sh, bash, or zsh. More information can be found at Configuring syntax highlighting for file extensions and Code mirror language modes.

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

How can I check if a string contains a character in C#?

The following should work:

var abc = "sAb";
bool exists = abc.IndexOf("ab", StringComparison.CurrentCultureIgnoreCase) > -1;

How can I get session id in php and show it?

You have uniqid function for unique id

You can add prefix to make it more unique

Source : http://pk1.php.net/uniqid

How can I add to a List's first position?

 myList.Insert(0, item);

         

Entity Framework 6 Code first Default value

Your model properties don't have to be 'auto properties' Even though that is easier. And the DefaultValue attribute is really only informative metadata The answer accepted here is one alternative to the constructor approach.

public class Track
{

    private const int DEFAULT_LENGTH = 400;
    private int _length = DEFAULT_LENGTH;
    [DefaultValue(DEFAULT_LENGTH)]
    public int LengthInMeters {
        get { return _length; }
        set { _length = value; }
    }
}

vs.

public class Track
{
    public Track()
    {
        LengthInMeters = 400;   
    }

    public int LengthInMeters { get; set; }        
}

This will only work for applications creating and consuming data using this specific class. Usually this isn't a problem if data access code is centralized. To update the value across all applications you need to configure the datasource to set a default value. Devi's answer shows how it can be done using migrations, sql, or whatever language your data source speaks.

Google Play on Android 4.0 emulator

You could download it from a Android 4.0 phone and then mount the system image rw and copy it over.

Didnt tried it before but it should work.

Uncaught TypeError: Cannot read property 'appendChild' of null

If this is happening to you in an AJAX post, you'll want to compare the values that you're sending and the values that the Controller is expecting.

In my case, I had changed a parameter in a serializable class from State to StateID, and then in an AJAX call didn't change the receiving field out 'data'

success: function (data) { MakeAddressForm.formData.StateID = data.State;

Note that the class was changed - it doesn't matter what I call it in the formData.

This created a null reference in the formData which I was trying to post back to the Controller once I'd done the update. Obviously, if someone changed the state (which was the purpose of the form) then they didn't get the error, so it made for a hard one to find.

This also through a 500 error. I'm posting this here in hopes it saves someone else the time I've wasted

How to get a product's image in Magento?

echo $_product->getImageUrl();

This method of the Product class should do the trick for you.

Throwing exceptions from constructors

#include <iostream>

class bar
{
public:
  bar()
  {
    std::cout << "bar() called" << std::endl;
  }

  ~bar()
  {
    std::cout << "~bar() called" << std::endl;

  }
};
class foo
{
public:
  foo()
    : b(new bar())
  {
    std::cout << "foo() called" << std::endl;
    throw "throw something";
  }

  ~foo()
  {
    delete b;
    std::cout << "~foo() called" << std::endl;
  }

private:
  bar *b;
};


int main(void)
{
  try {
    std::cout << "heap: new foo" << std::endl;
    foo *f = new foo();
  } catch (const char *e) {
    std::cout << "heap exception: " << e << std::endl;
  }

  try {
    std::cout << "stack: foo" << std::endl;
    foo f;
  } catch (const char *e) {
    std::cout << "stack exception: " << e << std::endl;
  }

  return 0;
}

the output:

heap: new foo
bar() called
foo() called
heap exception: throw something
stack: foo
bar() called
foo() called
stack exception: throw something

the destructors are not called, so if a exception need to be thrown in a constructor, a lot of stuff(e.g. clean up?) to do.

Formatting a field using ToText in a Crystal Reports formula field

if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
   "nd"
else
    totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')

The above logic should be what you are looking for.

How to Sign an Already Compiled Apk

Automated Process:

Use this tool (uses the new apksigner from Google):

https://github.com/patrickfav/uber-apk-signer

Disclaimer: Im the developer :)

Manual Process:

Step 1: Generate Keystore (only once)

You need to generate a keystore once and use it to sign your unsigned apk. Use the keytool provided by the JDK found in %JAVA_HOME%/bin/

keytool -genkey -v -keystore my.keystore -keyalg RSA -keysize 2048 -validity 10000 -alias app

Step 2 or 4: Zipalign

zipalign which is a tool provided by the Android SDK found in e.g. %ANDROID_HOME%/sdk/build-tools/24.0.2/ is a mandatory optimization step if you want to upload the apk to the Play Store.

zipalign -p 4 my.apk my-aligned.apk

Note: when using the old jarsigner you need to zipalign AFTER signing. When using the new apksigner method you do it BEFORE signing (confusing, I know). Invoking zipalign before apksigner works fine because apksigner preserves APK alignment and compression (unlike jarsigner).

You can verify the alignment with

zipalign -c 4 my-aligned.apk

Step 3: Sign & Verify

Using build-tools 24.0.2 and older

Use jarsigner which, like the keytool, comes with the JDK distribution found in %JAVA_HOME%/bin/ and use it like so:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my.keystore my-app.apk my_alias_name

and can be verified with

jarsigner -verify -verbose my_application.apk

Using build-tools 24.0.3 and newer

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files (See here and here for more details). Therefore, Google implemented their own apk signer called apksigner (duh!) The script file can be found in %ANDROID_HOME%/sdk/build-tools/24.0.3/ (the .jar is in the /lib subfolder). Use it like this

apksigner sign --ks my.keystore my-app.apk --ks-key-alias alias_name

and can be verified with

apksigner verify my-app.apk

The official documentation can be found here.

Open a URL in a new tab (and not a new window)

function openInNewTab(href) {
  Object.assign(document.createElement('a'), {
    target: '_blank',
    href: href,
  }).click();
}

It creates a virtual a element, gives it target="_blank" so it opens in a new tab, gives it proper url href and then clicks it.

and then you can use it like:

openInNewTab("https://google.com"); 

Important note:

openInNewTab (as well as any other solution on this page) must be called during the so-called 'trusted event' callback - eg. during click event (not necessary in callback function directly, but during click action). Otherwise opening a new page will be blocked by the browser

If you call it manually at some random moment (e.g., inside an interval or after server response) - it might be blocked by the browser (which makes sense as it'd be a security risk and might lead to poor user experience)

How can I adjust DIV width to contents

One way you can achieve this is setting display: inline-block; on the div. It is by default a block element, which will always fill the width it can fill (unless specifying width of course).

inline-block's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline elements, but there are hacks to solve this problem.

There are other options you have, you can either float it, or set position: absolute on it, but these also have other effects on layout, you need to decide which one fits your situation better.

What is the point of WORKDIR on Dockerfile?

Before applying WORKDIR. Here the WORKDIR is at the wrong place and is not used wisely.

FROM microsoft/aspnetcore:2
COPY --from=build-env /publish /publish
WORKDIR /publish
ENTRYPOINT ["dotnet", "/publish/api.dll"]

We corrected the above code to put WORKDIR at the right location and optimised the following statements by removing /Publish

FROM microsoft/aspnetcore:2
WORKDIR /publish
COPY --from=build-env /publish .
ENTRYPOINT ["dotnet", "api.dll"]

So it acts like a cd and sets the tone for the upcoming statements.

How to get the selected radio button’s value?

Edit: As said by Chips_100 you should use :

var sizes = document.theForm[field];

directly without using the test variable.


Old answer:

Shouldn't you eval like this ?

var sizes = eval(test);

I don't know how that works, but to me you're only copying a string.

How do I cast a JSON Object to a TypeScript class?

While it is not casting per se; I have found https://github.com/JohnWhiteTB/TypedJSON to be a useful alternative.

@JsonObject
class Person {
    @JsonMember
    firstName: string;

    @JsonMember
    lastName: string;

    public getFullname() {
        return this.firstName + " " + this.lastName;
    }
}
var person = TypedJSON.parse('{ "firstName": "John", "lastName": "Doe" }', Person);

person instanceof Person; // true
person.getFullname(); // "John Doe"

How many bytes in a JavaScript string?

This function will return the byte size of any UTF-8 string you pass to it.

function byteCount(s) {
    return encodeURI(s).split(/%..|./).length - 1;
}

Source

JavaScript engines are free to use UCS-2 or UTF-16 internally. Most engines that I know of use UTF-16, but whatever choice they made, it’s just an implementation detail that won’t affect the language’s characteristics.

The ECMAScript/JavaScript language itself, however, exposes characters according to UCS-2, not UTF-16.

Source

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

For a simpler pure CSS solution that works in most cases, one could remove children's pointer-events by setting them to none

.parent * {
     pointer-events: none;
}

Browser support: IE11+

how to configure lombok in eclipse luna

Just remove the 'F:\' from -javaagent

-vm E:\Program Files\Java\jdk1.7.0_60\bin

-vmargs

-Dosgi.requiredJavaVersion=1.7

-javaagent:\Tools\Java Lib\Lombok\lombok.jar

-Xbootclasspath/a:F:\Tools\Java Lib\Lombok\lombok.jar

-Xms40m

-Xmx512m

How to show two figures using matplotlib?

I had this same problem.


Did:

f1 = plt.figure(1)

# code for figure 1

# don't write 'plt.show()' here


f2 = plt.figure(2)

# code for figure 2

plt.show()


Write 'plt.show()' only once, after the last figure. Worked for me.

ActiveXObject in Firefox or Chrome (not IE!)

ActiveX is supported by Chrome.

Chrome check parameters defined in : control panel/Internet option/Security.

Nevertheless,if it's possible to define four different area with IE, Chrome only check "Internet" area.

Making TextView scrollable on Android

In kotlin for making the textview scrollable

myTextView.movementMethod= ScrollingMovementMethod()

and also add in xml this property

    android:scrollbars = "vertical"

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

Yet another solution:

I was stumped because I was including boost_regex-vc120-mt-gd-1_58.lib in my Link->Additional Dependencies property, but the link kept telling me it couldn't open libboost_regex-vc120-mt-gd-1_58.lib (note the lib prefix). I didn't specify libboost_regex-vc120-mt-gd-1_58.lib.

I was trying to use (and had built) the boost dynamic libraries (.dlls) but did not have the BOOST_ALL_DYN_LINK macro defined. Apparently there are hints in the compile to include a library, and without BOOST_ALL_DYN_LINK it looks for the static library (with the lib prefix), not the dynamic library (without a lib prefix).

Why does range(start, end) not include end?

Exclusive ranges do have some benefits:

For one thing each item in range(0,n) is a valid index for lists of length n.

Also range(0,n) has a length of n, not n+1 which an inclusive range would.

Submit form on pressing Enter with AngularJS

Angular supports this out of the box. Have you tried ngSubmit on your form element?

<form ng-submit="myFunc()" ng-controller="mycontroller">
   <input type="text" ng-model="name" />
    <br />
    <input type="text" ng-model="email" />
</form>

EDIT: Per the comment regarding the submit button, see Submitting a form by pressing enter without a submit button which gives the solution of:

<input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/>

If you don't like the hidden submit button solution, you'll need to bind a controller function to the Enter keypress or keyup event. This normally requires a custom directive, but the AngularUI library has a nice keypress solution set up already. See http://angular-ui.github.com/

After adding the angularUI lib, your code would be something like:

<form ui-keypress="{13:'myFunc($event)'}">
  ... input fields ...
</form>

or you can bind the enter keypress to each individual field.

Also, see this SO questions for creating a simple keypres directive: How can I detect onKeyUp in AngularJS?

EDIT (2014-08-28): At the time this answer was written, ng-keypress/ng-keyup/ng-keydown did not exist as native directives in AngularJS. In the comments below @darlan-alves has a pretty good solution with:

<input ng-keyup="$event.keyCode == 13 && myFunc()"... />

Search for highest key/index in an array

$keys = array_keys($arr);
$keys = rsort($keys);

print $keys[0];

should print "10"

How to delete a workspace in Eclipse?

Just delete the whole directory. This will delete all the projects but also the Eclipse cache and settings for the workspace. These are kept in the .metadata folder of an Eclipse workspace. Note that you can configure Eclipse to use project folders that are outside the workspace folder as well, so you may want to verify the location of each of the projects.

You can remove the workspace from the suggested workspaces by going into the General/Startup and Shutdown/Workspaces section of the preferences (via Preferences > General > Startup & Shudown > Workspaces > [Remove] ). Note that this does not remove the files itself. For old versions of Eclipse you will need to edit the org.eclipse.ui.ide.prefs file in the configuration/.settings directory under your installation directory (or in ~/.eclipse on Unix, IIRC).

Accessing elements of Python dictionary by index

As a bonus, I'd like to offer kind of a different solution to your issue. You seem to be dealing with nested dictionaries, which is usually tedious, especially when you have to check for existence of an inner key.

There are some interesting libraries regarding this on pypi, here is a quick search for you.

In your specific case, dict_digger seems suited.

>>> import dict_digger
>>> d = {
  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
  'Grapes':{'Arabian':'25','Indian':'20'} 
}

>>> print(dict_digger.dig(d, 'Apple','American'))
16
>>> print(dict_digger.dig(d, 'Grapes','American'))
None

Getting value from appsettings.json in .net core

I think the best option is:

  1. Create a model class as config schema

  2. Register in DI: services.Configure(Configuration.GetSection("democonfig"));

  3. Get the values as model object from DI in your controller:

    private readonly your_model myConfig;
    public DemoController(IOptions<your_model> configOps)
    {
        this.myConfig = configOps.Value;
    }
    

Print a div content using Jquery

use this library : Print.JS

with this library you can print both HTML and PDF.

<form method="post" action="#" id="printJS-form">
    ...
 </form>

 <button type="button" onclick="printJS('printJS-form', 'html')">
    Print Form
 </button>

Returning a file to View/Download in ASP.NET MVC

Darin Dimitrov's answer is correct. Just an addition:

Response.AppendHeader("Content-Disposition", cd.ToString()); may cause the browser to fail rendering the file if your response already contains a "Content-Disposition" header. In that case, you may want to use:

Response.Headers.Add("Content-Disposition", cd.ToString());

How to write an XPath query to match two attributes?

//div[@id='..' and @class='...]

should do the trick. That's selecting the div operators that have both attributes of the required value.

It's worth using one of the online XPath testbeds to try stuff out.

Access elements of parent window from iframe

I think you can just use window.parent from the iframe. window.parent returns the window object of the parent page, so you could do something like:

window.parent.document.getElementById('yourdiv');

Then do whatever you want with that div.

Reading images in python

For the better answer, you can use these lines of code. Here is the example maybe help you :

image = cv2.imread('/home/pictures/1.jpg')
plt.imshow(image)
plt.show()

In imread() you can pass the directory .so you can also use str() and + to combine dynamic directories and fixed directory like this:

path = '/home/pictures/'
for i in range(2) :
    image = cv2.imread(str(path)+'1.jpg')
    plt.imshow(image)
    plt.show()

Both are the same.

RSA Public Key format

Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser

RSA Public Key

-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----

Encrypted Private Key

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----

CRL

-----BEGIN X509 CRL-----
-----END X509 CRL-----

CRT

-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

CSR

-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----

NEW CSR

-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----

PEM

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

PKCS7

-----BEGIN PKCS7-----
-----END PKCS7-----

PRIVATE KEY

-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----

DSA KEY

-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----

Elliptic Curve

-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----

PGP Private Key

-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----

PGP Public Key

-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----

Opening Chrome From Command Line

open command prompt and type

cd\ (enter)

then type

start chrome "www.google.com"(any website you require)

pip install returning invalid syntax

You can also go into the directory where you have your pip.exe or pip3.exe located. For me it was on my D drive so here is what I did:

D:\>cd python

D:\python>cd Scripts

D:\python\Scripts>pip3.exe install tweepy

Hope it helps

2D array values C++

One alternative is to represent your 2D array as a 1D array. This can make element-wise operations more efficient. You should probably wrap it in a class that would also contain width and height.

Another alternative is to represent a 2D array as an std::vector<std::vector<int> >. This will let you use STL's algorithms for array arithmetic, and the vector will also take care of memory management for you.

How to view query error in PDO PHP

I'm using this without any additional settings:

if (!$st->execute()) {
    print_r($st->errorInfo());
}

Javascript Date: next month

You'll probably find you're setting the date to Feb 31, 2009 (if today is Jan 31) and Javascript automagically rolls that into the early part of March.

Check the day of the month, I'd expect it to be 1, 2 or 3. If it's not the same as before you added a month, roll back by one day until the month changes again.

That way, the day "last day of Jan" becomes "last day of Feb".

EDIT:

Ronald, based on your comments to other answers, you might want to steer clear of edge-case behavior such as "what happens when I try to make Feb 30" or "what happens when I try to make 2009/13/07 (yyyy/mm/dd)" (that last one might still be a problem even for my solution, so you should test it).

Instead, I would explicitly code for the possibilities. Since you don't care about the day of the month (you just want the year and month to be correct for next month), something like this should suffice:

var now = new Date();
if (now.getMonth() == 11) {
    var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
    var current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}

That gives you Jan 1 the following year for any day in December and the first day of the following month for any other day. More code, I know, but I've long since grown tired of coding tricks for efficiency, preferring readability unless there's a clear requirement to do otherwise.

How to change Elasticsearch max memory size

  • Elasticsearch will assign the entire heap specified in jvm.options via the Xms (minimum heap size) and Xmx (maximum heap size) settings.
    • -Xmx12g
    • -Xmx12g
  • Set the minimum heap size (Xms) and maximum heap size (Xmx) to be equal to each other.
  • Don’t set Xmx to above the cutoff that the JVM uses for compressed object pointers (compressed oops), the exact cutoff varies but is near 32 GB.

  • It is also possible to set the heap size via an environment variable

    • ES_JAVA_OPTS="-Xms2g -Xmx2g" ./bin/elasticsearch
    • ES_JAVA_OPTS="-Xms4000m -Xmx4000m" ./bin/elasticsearch

Creating Accordion Table with Bootstrap

In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:

.collapse-row.collapsed + tr {
     display: none;
}

'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.

Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/

How do you put an image file in a json object?

Use data URL scheme: https://en.wikipedia.org/wiki/Data_URI_scheme

In this case you use that string directly in html : <img src="data:image/png;base64,iVBOR....">

Common Header / Footer with static HTML

You can try loading them via the client-side, like this:

<!DOCTYPE html>
<html>
  <head>
    <!-- ... -->
  </head>
  <body>

    <div id="headerID"> <!-- your header --> </div>
    <div id="pageID"> <!-- your header --> </div>
    <div id="footerID"> <!-- your header --> </div>

    <script>
      $("#headerID").load("header.html");
      $("#pageID").load("page.html");
      $("#footerID").load("footer.html");
    </script>
  </body>
</html>

NOTE: the content will load from top to bottom and replace the content of the container you load it into.

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

Optional Parameters in Web Api Attribute Routing

Converting my comment into an answer to complement @Kiran Chala's answer as it seems helpful for the audiences-

When we mark a parameter as optional in the action uri using ? character then we must provide default values to the parameters in the method signature as shown below:

MyMethod(string name = "someDefaultValue", int? Id = null)

Create <div> and append <div> dynamically

var arrayDiv = new Array();
    for(var i=0; i <= 1; i++){
        arrayDiv[i] = document.createElement('div');
        arrayDiv[i].id = 'block' + i;
        arrayDiv[i].className = 'block' + i;
    }
    document.body.appendChild(arrayDiv[0].appendChild(arrayDiv[1]));

Recursive Fibonacci

int fib(int n) {
    if (n == 1 || n == 2) {
        return 1;
    } else {
        return fib(n - 1) + fib(n - 2);
    }
}

in fibonacci sequence first 2 numbers always sequels to 1 then every time the value became 1 or 2 it must return 1

How to create local notifications?

Creating local notifications are pretty easy. Just follow these steps.

  1. On viewDidLoad() function ask user for permission that your apps want to display notifications. For this we can use the following code.

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
    })
    
  2. Then you can create a button, and then in the action function you can write the following code to display a notification.

    //creating the notification content
    let content = UNMutableNotificationContent()
    
    //adding title, subtitle, body and badge
    content.title = "Hey this is Simplified iOS"
    content.subtitle = "iOS Development is fun"
    content.body = "We are learning about iOS Local Notification"
    content.badge = 1
    
    //getting the notification trigger
    //it will be called after 5 seconds
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    
    //getting the notification request
    let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
    
    //adding the notification to notification center
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    
  3. Notification will be displayed, just click on home button after tapping the notification button. As when the application is in foreground the notification is not displayed. But if you are using iPhone X. You can display notification even when the app is in foreground. For this you just need to add a delegate called UNUserNotificationCenterDelegate

For more details visit this blog post: iOS Local Notification Tutorial

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

PYTHONPATH vs. sys.path

In general I would consider setting up of an environment variable (like PYTHONPATH) to be a bad practice. While this might be fine for a one off debugging but using this as
a regular practice might not be a good idea.

Usage of environment variable leads to situations like "it works for me" when some one
else reports problems in the code base. Also one might carry the same practice with the test environment as well, leading to situations like the tests running fine for a particular developer but probably failing when some one launches the tests.

What is mod_php?

Just to add on these answers is that, mod_php is the oldest and slowest method available in HTTPD server to use PHP. It is not recommended, unless you are running old versions of Apache HTTPD and PHP. php-fpm and proxy_cgi are the preferred methods.

What does the Java assert keyword do, and when should it be used?

A real world example, from a Stack-class (from Assertion in Java Articles)

public int pop() {
   // precondition
   assert !isEmpty() : "Stack is empty";
   return stack[--num];
}

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

how about

var top = $('html').scrollTop() || $('body').scrollTop();

Nested JSON objects - do I have to use arrays for everything?

You don't need to use arrays.

JSON values can be arrays, objects, or primitives (numbers or strings).

You can write JSON like this:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

You can use it like this:

obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1]  //thing is a nested array or a 2-by-2 matrix.
                            //I'm not sure whether you intended to do that.

How to get a div to resize its height to fit container?

Another one simple method is there. You don't need to code more in CSS. Just including a java script and entering the div "id" inside the script you can get equal height of columns so that you can have the height fit to container. It works in major browsers.

Source Code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title></title>
<style type="text/css">
*   {border:0; padding:0; margin:0;}/* Set everything to "zero" */
#container {
    margin-left: auto;
    margin-right: auto;
    border: 1px solid black;
    overflow: auto;
    width: 800px;       
}
#nav {
    width: 19%;
    border: 1px solid green;
    float:left; 
}
#content {
    width: 79%;
    border: 1px solid red;
    float:right;
}
</style>

<script language="javascript">
var ddequalcolumns=new Object()
//Input IDs (id attr) of columns to equalize. Script will check if each corresponding column actually exists:
ddequalcolumns.columnswatch=["nav", "content"]

ddequalcolumns.setHeights=function(reset){
var tallest=0
var resetit=(typeof reset=="string")? true : false
for (var i=0; i<this.columnswatch.length; i++){
if (document.getElementById(this.columnswatch[i])!=null){
if (resetit)
document.getElementById(this.columnswatch[i]).style.height="auto"
if (document.getElementById(this.columnswatch[i]).offsetHeight>tallest)
tallest=document.getElementById(this.columnswatch[i]).offsetHeight
}
}
if (tallest>0){
for (var i=0; i<this.columnswatch.length; i++){
if (document.getElementById(this.columnswatch[i])!=null)
document.getElementById(this.columnswatch[i]).style.height=tallest+"px"
}
}
}

ddequalcolumns.resetHeights=function(){
this.setHeights("reset")
}

ddequalcolumns.dotask=function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
if (target.addEventListener)
target.addEventListener(tasktype, functionref, false)
else if (target.attachEvent)
target.attachEvent(tasktype, functionref)
}

ddequalcolumns.dotask(window, function(){ddequalcolumns.setHeights()}, "load")
ddequalcolumns.dotask(window, function(){if (typeof ddequalcolumns.timer!="undefined") clearTimeout(ddequalcolumns.timer); ddequalcolumns.timer=setTimeout("ddequalcolumns.resetHeights()", 200)}, "resize")


</script>

<div id=container>
    <div id=nav>
        <ul>
                <li>Menu</li>
                <li>Menu</li>
                <li>Menu</li>
                <li>Menu</li>
                <li>Menu</li>
        </ul>
    </div>
    <div id=content>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fermentum consequat ligula vitae posuere. Mauris dolor quam, consequat vel condimentum eget, aliquet sit amet sem. Nulla in lectus ac felis ultrices dignissim quis ac orci. Nam non tellus eget metus sollicitudin venenatis sit amet at dui. Quisque malesuada feugiat tellus, at semper eros mollis sed. In luctus tellus in magna condimentum sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur vel dui est. Aliquam vitae condimentum dui. Praesent vel mi at odio blandit pellentesque. Proin felis massa, vestibulum a hendrerit ut, imperdiet in nulla. Sed aliquam, dolor id congue porttitor, mauris turpis congue felis, vel luctus ligula libero in arcu. Pellentesque egestas blandit turpis ac aliquet. Sed sit amet orci non turpis feugiat euismod. In elementum tristique tortor ac semper.</p>
    </div>
</div>

</body>
</html>

You can include any no of divs in this script.

ddequalcolumns.columnswatch=["nav", "content"]

modify in the above line its enough.

Try this.

Exporting result of select statement to CSV format in DB2

According to the docs, you want to export of type del (the default delimiter looks like a comma, which is what you want). See the doc page for more information on the EXPORT command.