Programs & Examples On #Scroll position

Maintain/Save/Restore scroll position when returning to a ListView

Parcelable state;

@Override
public void onPause() {    
    // Save ListView state @ onPause
    Log.d(TAG, "saving listview state");
    state = listView.onSaveInstanceState();
    super.onPause();
}
...

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    // Set new items
    listView.setAdapter(adapter);
    ...
    // Restore previous state (including selected item index and scroll position)
    if(state != null) {
        Log.d(TAG, "trying to restore listview state");
        listView.onRestoreInstanceState(state);
    }
}

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

How can I make a div not larger than its contents?

You could use display: flex for parent element

#parentElement {
   display: flex;
   flex-direction: column;
   align-items: flex-start;
 }

How to replace NaNs by preceding values in pandas DataFrame?

You can use pandas.DataFrame.fillna with the method='ffill' option. 'ffill' stands for 'forward fill' and will propagate last valid observation forward. The alternative is 'bfill' which works the same way, but backwards.

import pandas as pd

df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
df = df.fillna(method='ffill')

print(df)
#   0  1  2
#0  1  2  3
#1  4  2  3
#2  4  2  9

There is also a direct synonym function for this, pandas.DataFrame.ffill, to make things simpler.

Getting Date or Time only from a DateTime Object

var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;

Use multiple custom fonts using @font-face?

If you are having a problem with the font working I have also had this in the past and the issue I found was down to the font-family: name. This had to match what font name was actually given.

The easiest way I found to find this out was to install the font and see what display name is given.

For example, I was using Gill Sans on one project, but the actual font was called Gill Sans MT. Spacing and capitlisation was also important to get right.

Hope that helps.

Create list of object from another using Java 8 Streams

What you are possibly looking for is map(). You can "convert" the objects in a stream to another by mapping this way:

...
 .map(userMeal -> new UserMealExceed(...))
...

Case Function Equivalent in Excel

Without reference to the original problem (which I suspect is long since solved), I very recently discovered a neat trick that makes the Choose function work exactly like a select case statement without any need to modify data. There's only one catch: only one of your choose conditions can be true at any one time.

The syntax is as follows:

CHOOSE( 
    (1 * (CONDITION_1)) + (2 * (CONDITION_2)) + ... + (N * (CONDITION_N)),
    RESULT_1, RESULT_2, ... , RESULT_N
)

On the assumption that only one of the conditions 1 to N will be true, everything else is 0, meaning the numeric value will correspond to the appropriate result.

If you are not 100% certain that all conditions are mutually exclusive, you might prefer something like:

CHOOSE(
    (1 * TEST1) + (2 * TEST2) + (4 * TEST3) + (8 * TEST4) ... (2^N * TESTN)
    OUT1, OUT2, , OUT3, , , , OUT4 , , <LOTS OF COMMAS> , OUT5
)

That said, if Excel has an upper limit on the number of arguments a function can take, you'd hit it pretty quickly.

Honestly, can't believe it's taken me years to work it out, but I haven't seen it before, so figured I'd leave it here to help others.

EDIT: Per comment below from @aTrusty: Silly numbers of commas can be eliminated (and as a result, the choose statement would work for up to 254 cases) by using a formula of the following form:

CHOOSE(
    1 + LOG(1 + (2*TEST1) + (4*TEST2) + (8*TEST3) + (16*TEST4),2), 
    OTHERWISE, RESULT1, RESULT2, RESULT3, RESULT4
)

Note the second argument to the LOG clause, which puts it in base 2 and makes the whole thing work.

Edit: Per David's answer, there's now an actual switch statement if you're lucky enough to be working on office 2016. Aside from difficulty in reading, this also means you get the efficiency of switch, not just the behaviour!

Default SecurityProtocol in .NET 4.5

According to Transport Layer Security (TLS) best practices with the .NET Framework: To ensure .NET Framework applications remain secure, the TLS version should not be hardcoded. Instead set the registry keys: SystemDefaultTlsVersions and SchUseStrongCrypto:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\.NETFramework\v2.0.50727]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

ORA-01031: insufficient privileges happens when the object exists in the schema but do not have any access to that object.

ORA-00942: table or view does not exist happens when the object does not exist in the current schema. If the object exists in another schema, you need to access it using .. Still you can get insufficient privileges error if the owner has not given access to the calling schema.

How do I convert between ISO-8859-1 and UTF-8 in Java?

Here is a function to convert UNICODE (ISO_8859_1) to UTF-8

public static String String_ISO_8859_1To_UTF_8(String strISO_8859_1) {
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strISO_8859_1.length(); i++) {
  final char ch = strISO_8859_1.charAt(i);
  if (ch <= 127) 
  {
      stringBuilder.append(ch);
  }
  else 
  {
      stringBuilder.append(String.format("%02x", (int)ch));
  }
}
String s = stringBuilder.toString();
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
    data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                         + Character.digit(s.charAt(i+1), 16));
}
String strUTF_8 =new String(data, StandardCharsets.UTF_8);
return strUTF_8;
}

TEST

String strA_ISO_8859_1_i = new String("??????".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

System.out.println("ISO_8859_1 strA est = "+ strA_ISO_8859_1_i + "\n String_ISO_8859_1To_UTF_8 = " + String_ISO_8859_1To_UTF_8(strA_ISO_8859_1_i));

RESULT

ISO_8859_1 strA est = اÙغÙا٠String_ISO_8859_1To_UTF_8 = ??????

exception in thread 'main' java.lang.NoClassDefFoundError:

Exception in thread "main" java.lang.NoClassDefFoundError  

One of the places java tries to find your .class file is your current directory. So if your .class file is in C:\java, you should change your current directory to that.

To change your directory, type the following command at the prompt and press Enter:

cd c:\java  

This . tells java that your classpath is your local directory.

Executing your program using this command should correct the problem:
java -classpath . HelloWorld  

Use superscripts in R axis labels

It works the same way for axes: parse(text='70^o*N') will raise the o as a superscript (the *N is to make sure the N doesn't get raised too).

labelsX=parse(text=paste(abs(seq(-100, -50, 10)), "^o ", "*W", sep=""))
labelsY=parse(text=paste(seq(50,100,10), "^o ", "*N", sep=""))
plot(-100:-50, 50:100, type="n", xlab="", ylab="", axes=FALSE)
axis(1, seq(-100, -50, 10), labels=labelsX)
axis(2, seq(50, 100, 10), labels=labelsY)
box()

Clear contents of cells in VBA using column reference

For anyone like me who came across this and needs a solution that doesn't clear headers, here is the one liner that works for me:

ActiveSheet.Range("A3:A" & Range("A3").End(xlDown).Row).ClearContents

Starts on the third row - change to your liking.

Find the files that have been changed in last 24 hours

On GNU-compatible systems (i.e. Linux):

find . -mtime 0 -printf '%T+\t%s\t%p\n' 2>/dev/null | sort -r | more

This will list files and directories that have been modified in the last 24 hours (-mtime 0). It will list them with the last modified time in a format that is both sortable and human-readable (%T+), followed by the file size (%s), followed by the full filename (%p), each separated by tabs (\t).

2>/dev/null throws away any stderr output, so that error messages don't muddy the waters; sort -r sorts the results by most recently modified first; and | more lists one page of results at a time.

Android: Expand/collapse animation

This is a snippet that I used to resize the width of a view (LinearLayout) with animation.

The code is supposed to do expand or shrink according the target size. If you want a fill_parent width, you will have to pass the parent .getMeasuredWidth as target width while setting the flag to true.

Hope it helps some of you.

public class WidthResizeAnimation extends Animation {
int targetWidth;
int originaltWidth;
View view;
boolean expand;
int newWidth = 0;
boolean fillParent;

public WidthResizeAnimation(View view, int targetWidth, boolean fillParent) {
    this.view = view;
    this.originaltWidth = this.view.getMeasuredWidth();
    this.targetWidth = targetWidth;
    newWidth = originaltWidth;
    if (originaltWidth > targetWidth) {
        expand = false;
    } else {
        expand = true;
    }
    this.fillParent = fillParent;
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
    if (expand && newWidth < targetWidth) {
        newWidth = (int) (newWidth + (targetWidth - newWidth) * interpolatedTime);
    }

    if (!expand && newWidth > targetWidth) {
        newWidth = (int) (newWidth - (newWidth - targetWidth) * interpolatedTime);
    }
    if (fillParent && interpolatedTime == 1.0) {
        view.getLayoutParams().width = -1;

    } else {
        view.getLayoutParams().width = newWidth;
    }
    view.requestLayout();
}

@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
    super.initialize(width, height, parentWidth, parentHeight);
}

@Override
public boolean willChangeBounds() {
    return true;
}

}

insert vertical divider line between two nested divs, not full height

Try this. I set the blue box to float right, gave left and right a fixed height, and added a white border on the right of the left div. Also added rounded corners to more match your example (These won't work in ie 8 or less). I also took out the position: relative. You don't need it. Block level elements are set to position relative by default.

See it here: http://jsfiddle.net/ZSgLJ/

#left {
  float: left;
  width: 44%;
  margin: 0;
  padding: 0;
  border-right: 1px solid white;
  height:400px;
}

#right {
  position: relative;
  float: right;
  width: 49%;
  margin: 0;
  padding: 0;
  height:400px;
}

#blue_box {
  background-color:blue;
  border-radius: 10px;
  -moz-border-radius:10px;
  -webkit-border-radius: 10px;
  width: 45%;
  min-width: 400px;
  max-width: 600px;
  padding: 2%;
  float: right;
}

How do I check in python if an element of a list is empty?

Suppose

letter= ['a','','b','c']

for i in range(len(letter)):
    if letter[i] =='':
        print(str(i) + ' is empty')

output- 1 is emtpy

So we can see index 1 is empty.

What does Ruby have that Python doesn't, and vice versa?

More about Ruby's blocks

It has being suggested that Ruby's blocks may be "substituted" by Python's context managers. In fact, blocks allow more than Python's context managers can do.

The receiving method of a block could execute the block within the context of some object, thus allowing the block to call methods otherwise unreacheable. Python's generators can't do that either.

A simple example may help:

class Proxy
   attr_accesor :target

   def method &block
      # Ruby 1.9 or in Rails 2.3
      target.instance_exec &block  
   end
end

class C
   private
   def hello
     puts "hello"
   end
end

p = Proxy.new
c = C.new
p.target = c
p.method { hello }

In this example the method call within the block { hello } has it true meaning in the context of the target object c.

This example is for illustrative purposes, only. Real working code that uses this kind of execute in the context of another object is not uncommon. The monitoring tool Godm for instance, uses it.

How to Parse JSON Array with Gson

[
      {
           id : '1',
           title: 'sample title',
           ....
      },
      {
           id : '2',
           title: 'sample title',
           ....
     },
      ...
 ]

Check Easy code for this output

 Gson gson=new GsonBuilder().create();
                List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));

Android: Proper Way to use onBackPressed() with Toast

This is the best way, because if user not back more than two seconds then reset backpressed value.

declare one global variable.

 private boolean backPressToExit = false;

Override onBackPressed Method.

@Override
public void onBackPressed() {

    if (backPressToExit) {
        super.onBackPressed();
        return;
    }
    this.backPressToExit = true;
    Snackbar.make(findViewById(R.id.yourview), getString(R.string.exit_msg), Snackbar.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            backPressToExit = false;
        }
    }, 2000);
}

Angular: Can't find Promise, Map, Set and Iterator

I noticed these problems showing up after upgrading from Angular 5 to Angular 6. I was able to fix this by doing the following in VS2017:

  • Ensure the TypeScript SDK was installed (via the Visual Studio Installer) for my particular version of TypeScript, 2.9
  • Ensure that the Module System project property is set to match that in my tsconfig.json: ES2015. This is often automatically in sync if the tsconfig file is in the root of the project. However, since I was using the VS Angular template, it places these files in a "ClientApp" subfolder, and the Module System project property was not set.

VS2017 Project Properties

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "lib": [
      "es2017",
      "dom"
    ],
    "module": "es2015",
    "baseUrl": "./"
  }
}

Difference between $.ajax() and $.get() and $.load()

Both are used to send some data and receive some response using that data.

GET: Get information stored in the server. (i.e. search, tweet, person information). If you want to send information then get request send request using process.php?name=subroto So it basically sends information through url. Url cannot handle more than 2036 char. So for blog post can you remember it is not possible?

POST: Post do same thing as GET. User registration, User login, Big data send, Blog Post. If you need to send secure information then use post or for big data as it not go through url.

AJAX: $.get() and $.post() contain features that are subsets of $.ajax(). It has more configuration.

$.get () method, which is a kind of shorthand for $.ajax(). When using $.get (), instead of passing in an object, you pass in arguments. At minimum, you’ll need the first two arguments, which are the URL of the file you want to retrieve (eg. test.txt) and a success callback.

Why doesn't JavaScript have a last method?

Another option, especially if you're already using UnderscoreJS, would be:

_.last([1, 2, 3, 4]); // Will return 4

Difference between Convert.ToString() and .ToString()

In addition to other answers about handling null values, Convert.ToString tries to use IFormattable and IConvertible interfaces before calling base Object.ToString.

Example:

class FormattableType : IFormattable
{
    private double value = 0.42;

    public string ToString(string format, IFormatProvider formatProvider)
    {
        if (formatProvider == null)
        {
            // ... using some IOC-containers
            // ... or using CultureInfo.CurrentCulture / Thread.CurrentThread.CurrentCulture
            formatProvider = CultureInfo.InvariantCulture;
        }

        // ... doing things with format
        return value.ToString(formatProvider);
    }

    public override string ToString()
    {
        return value.ToString();
    }
}

Result:

Convert.ToString(new FormattableType()); // 0.42
new FormattableType().ToString();        // 0,42

Query to get all rows from previous month

SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)

Convert a Pandas DataFrame to a dictionary

The to_dict() method sets the column names as dictionary keys so you'll need to reshape your DataFrame slightly. Setting the 'ID' column as the index and then transposing the DataFrame is one way to achieve this.

to_dict() also accepts an 'orient' argument which you'll need in order to output a list of values for each column. Otherwise, a dictionary of the form {index: value} will be returned for each column.

These steps can be done with the following line:

>>> df.set_index('ID').T.to_dict('list')
{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

In case a different dictionary format is needed, here are examples of the possible orient arguments. Consider the following simple DataFrame:

>>> df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
>>> df
        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125

Then the options are as follows.

dict - the default: column names are keys, values are dictionaries of index:data pairs

>>> df.to_dict('dict')
{'a': {0: 'red', 1: 'yellow', 2: 'blue'}, 
 'b': {0: 0.5, 1: 0.25, 2: 0.125}}

list - keys are column names, values are lists of column data

>>> df.to_dict('list')
{'a': ['red', 'yellow', 'blue'], 
 'b': [0.5, 0.25, 0.125]}

series - like 'list', but values are Series

>>> df.to_dict('series')
{'a': 0       red
      1    yellow
      2      blue
      Name: a, dtype: object, 

 'b': 0    0.500
      1    0.250
      2    0.125
      Name: b, dtype: float64}

split - splits columns/data/index as keys with values being column names, data values by row and index labels respectively

>>> df.to_dict('split')
{'columns': ['a', 'b'],
 'data': [['red', 0.5], ['yellow', 0.25], ['blue', 0.125]],
 'index': [0, 1, 2]}

records - each row becomes a dictionary where key is column name and value is the data in the cell

>>> df.to_dict('records')
[{'a': 'red', 'b': 0.5}, 
 {'a': 'yellow', 'b': 0.25}, 
 {'a': 'blue', 'b': 0.125}]

index - like 'records', but a dictionary of dictionaries with keys as index labels (rather than a list)

>>> df.to_dict('index')
{0: {'a': 'red', 'b': 0.5},
 1: {'a': 'yellow', 'b': 0.25},
 2: {'a': 'blue', 'b': 0.125}}

Add new field to every document in a MongoDB collection

Since MongoDB version 3.2 you can use updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})

Adding image to JFrame

There is no specialized image component provided in Swing (which is sad in my opinion). So, there are a few options:

  1. As @Reimeus said: Use a JLabel with an icon.
  2. Create in the window builder a JPanel, that will represent the location of the image. Then add your own custom image component to the JPanel using a few lines of code you will never have to change. They should look like this:

    JImageComponent ic = new JImageComponent(myImageGoesHere);
    imagePanel.add(ic);
    

    where JImageComponent is a self created class that extends JComponent that overrides the paintComponent() method to draw the image.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

The following is needed:

  • MS Online Services Assistant needs to be downloaded and installed.
  • MS Online Module for PowerShell needs to be downloaded and installed
  • Connect to Microsoft Online in PowerShell

Source: http://www.msdigest.net/2012/03/how-to-connect-to-office-365-with-powershell/

Then Follow this one if you're running a 64bits computer: I’m running a x64 OS currently (Win8 Pro).

Copy the folder MSOnline from (1) –> (2) as seen here

1) C:\Windows\System32\WindowsPowerShell\v1.0\Modules(MSOnline)

2) C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules(MSOnline)

Source: http://blog.clauskonrad.net/2013/06/powershell-and-c-cant-load-msonline.html

Hope this is better and can save some people's time

What does '?' do in C++?

This is commonly referred to as the conditional operator, and when used like this:

condition ? result_if_true : result_if_false

... if the condition evaluates to true, the expression evaluates to result_if_true, otherwise it evaluates to result_if_false.

It is syntactic sugar, and in this case, it can be replaced with

int qempty()
{ 
  if(f == r)
  {
      return 1;
  } 
  else 
  {
      return 0;
  }
}

Note: Some people refer to ?: it as "the ternary operator", because it is the only ternary operator (i.e. operator that takes three arguments) in the language they are using.

What is tail recursion?

It means that rather than needing to push the instruction pointer on the stack, you can simply jump to the top of a recursive function and continue execution. This allows for functions to recurse indefinitely without overflowing the stack.

I wrote a blog post on the subject, which has graphical examples of what the stack frames look like.

Is unsigned integer subtraction defined behavior?

When you work with unsigned types, modular arithmetic (also known as "wrap around" behavior) is taking place. To understand this modular arithmetic, just have a look at these clocks:

enter image description here

9 + 4 = 1 (13 mod 12), so to the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle is applied while working with unsigned types. If the result type is unsigned, then modular arithmetic takes place.


Now look at the following operations storing the result as an unsigned int:

unsigned int five = 5, seven = 7;
unsigned int a = five - seven;      // a = (-2 % 2^32) = 4294967294 

int one = 1, six = 6;
unsigned int b = one - six;         // b = (-5 % 2^32) = 4294967291

When you want to make sure that the result is signed, then stored it into signed variable or cast it to signed. When you want to get the difference between numbers and make sure that the modular arithmetic will not be applied, then you should consider using abs() function defined in stdlib.h:

int c = five - seven;       // c = -2
int d = abs(five - seven);  // d =  2

Be very careful, especially while writing conditions, because:

if (abs(five - seven) < seven)  // = if (2 < 7)
    // ...

if (five - seven < -1)          // = if (-2 < -1)
    // ...

if (one - six < 1)              // = if (-5 < 1)
    // ...

if ((int)(five - seven) < 1)    // = if (-2 < 1)
    // ...

but

if (five - seven < 1)   // = if ((unsigned int)-2 < 1) = if (4294967294 < 1)
    // ...

if (one - six < five)   // = if ((unsigned int)-5 < 5) = if (4294967291 < 5)
    // ...

How do you clear the SQL Server transaction log?

This technique that John recommends is not recommended as there is no guarantee that the database will attach without the log file. Change the database from full to simple, force a checkpoint and wait a few minutes. The SQL Server will clear the log, which you can then shrink using DBCC SHRINKFILE.

How to create an integer-for-loop in Ruby?

x.times do |i|
    something(i+1)
end

How to execute an SSIS package from .NET?

To add to @Craig Schwarze answer,

Here are some related MSDN links:

Loading and Running a Local Package Programmatically:

Loading and Running a Remote Package Programmatically

Capturing Events from a Running Package:

using System;
using Microsoft.SqlServer.Dts.Runtime;

namespace RunFromClientAppWithEventsCS
{
  class MyEventListener : DefaultEvents
  {
    public override bool OnError(DtsObject source, int errorCode, string subComponent, 
      string description, string helpFile, int helpContext, string idofInterfaceWithError)
    {
      // Add application-specific diagnostics here.
      Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
      return false;
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      string pkgLocation;
      Package pkg;
      Application app;
      DTSExecResult pkgResults;

      MyEventListener eventListener = new MyEventListener();

      pkgLocation =
        @"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +
        @"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";
      app = new Application();
      pkg = app.LoadPackage(pkgLocation, eventListener);
      pkgResults = pkg.Execute(null, null, eventListener, null, null);

      Console.WriteLine(pkgResults.ToString());
      Console.ReadKey();
    }
  }
}

Regex: Specify "space or start of string" and "space or end of string"

(^|\s) would match space or start of string and ($|\s) for space or end of string. Together it's:

(^|\s)stackoverflow($|\s)

How to listen to the window scroll event in a VueJS component?

this does not refresh your component I solved the problem by using Vux create a module for vuex "page"

export const state = {
    currentScrollY: 0,
};

export const getters = {
    currentScrollY: s => s.currentScrollY
};

export const actions = {
    setCurrentScrollY ({ commit }, y) {
        commit('setCurrentScrollY', {y});
    },
};

export const mutations = {
    setCurrentScrollY (s, {y}) {
       s.currentScrollY = y;
    },
};

export default {
    state,
    getters,
    actions,
    mutations,
};

in App.vue :

created() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    handleScroll () {
      this.$store.dispatch("page/setCurrentScrollY", window.scrollY);
      
    }
  },

in your component :

  computed: {
    currentScrollY() {
      return this.$store.getters["page/currentScrollY"];
    }
  },

  watch: {
    currentScrollY(val) {
      if (val > 100) {
        this.isVisibleStickyMenu = true;
      } else {
        this.isVisibleStickyMenu = false;
      }
    }
  },

and it works great.

Why is “while ( !feof (file) )” always wrong?

It's wrong because (in the absence of a read error) it enters the loop one more time than the author expects. If there is a read error, the loop never terminates.

Consider the following code:

/* WARNING: demonstration of bad coding technique!! */

#include <stdio.h>
#include <stdlib.h>

FILE *Fopen(const char *path, const char *mode);

int main(int argc, char **argv)
{
    FILE *in;
    unsigned count;

    in = argc > 1 ? Fopen(argv[1], "r") : stdin;
    count = 0;

    /* WARNING: this is a bug */
    while( !feof(in) ) {  /* This is WRONG! */
        fgetc(in);
        count++;
    }
    printf("Number of characters read: %u\n", count);
    return EXIT_SUCCESS;
}

FILE * Fopen(const char *path, const char *mode)
{
    FILE *f = fopen(path, mode);
    if( f == NULL ) {
        perror(path);
        exit(EXIT_FAILURE);
    }
    return f;
}

This program will consistently print one greater than the number of characters in the input stream (assuming no read errors). Consider the case where the input stream is empty:

$ ./a.out < /dev/null
Number of characters read: 1

In this case, feof() is called before any data has been read, so it returns false. The loop is entered, fgetc() is called (and returns EOF), and count is incremented. Then feof() is called and returns true, causing the loop to abort.

This happens in all such cases. feof() does not return true until after a read on the stream encounters the end of file. The purpose of feof() is NOT to check if the next read will reach the end of file. The purpose of feof() is to determine the status of a previous read function and distinguish between an error condition and the end of the data stream. If fread() returns 0, you must use feof/ferror to decide whether an error occurred or if all of the data was consumed. Similarly if fgetc returns EOF. feof() is only useful after fread has returned zero or fgetc has returned EOF. Before that happens, feof() will always return 0.

It is always necessary to check the return value of a read (either an fread(), or an fscanf(), or an fgetc()) before calling feof().

Even worse, consider the case where a read error occurs. In that case, fgetc() returns EOF, feof() returns false, and the loop never terminates. In all cases where while(!feof(p)) is used, there must be at least a check inside the loop for ferror(), or at the very least the while condition should be replaced with while(!feof(p) && !ferror(p)) or there is a very real possibility of an infinite loop, probably spewing all sorts of garbage as invalid data is being processed.

So, in summary, although I cannot state with certainty that there is never a situation in which it may be semantically correct to write "while(!feof(f))" (although there must be another check inside the loop with a break to avoid a infinite loop on a read error), it is the case that it is almost certainly always wrong. And even if a case ever arose where it would be correct, it is so idiomatically wrong that it would not be the right way to write the code. Anyone seeing that code should immediately hesitate and say, "that's a bug". And possibly slap the author (unless the author is your boss in which case discretion is advised.)

MVC3 EditorFor readOnly

This code is supported in MVC4 onwards

@Html.EditorFor(model => model.userName, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", @readonly = "readonly" } })

Javascript Get Element by Id and set the value

Coming across this question, no answer brought up the possibility of using .setAttribute() in addition to .value()

document.getElementById('some-input').value="1337";
document.getElementById('some-input').setAttribute("value", "1337");

Though unlikely helpful for the original questioner, this addendum actually changes the content of the value in the pages source, which in turn makes the value update form.reset()-proof.

I hope this may help others.

(Or me in half a year when I've forgotten about js quirks...)

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

The controller function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model changes coming from View the Controller is the right person to do that job.

The story about link function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view (template).

Let' start with the parameters which are passed into the link function:

function link(scope, element, attrs) {
  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is an object with the normalized attribute names and their corresponding values.

To put the link into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:

Compile phase (a sister of link, let's mention it here to get a clear picture):

In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,

Link phase:

To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.

A nice example how to use the link could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.

Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks

.directive('myCurrentTime', function($timeout, dateFilter) {

 function link(scope, element, attrs) {

 ...

 // the not MVC job must be done
 function updateTime() {
   element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
 }

 function scheduleUpdate() {
   // save the timeoutId for canceling
   timeoutId = $timeout(function() {
     updateTime(); // update DOM
     scheduleUpdate(); // schedule the next update
   }, 1000);
 }

 element.on('$destroy', function() {
   $timeout.cancel(timeoutId);
 });

 ...

How can I check for Python version in a program that uses new language features?

Put the following at the very top of your file:

import sys

if float(sys.version.split()[0][:3]) < 2.7:
    print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
    exit(1)

Then continue on with the normal Python code:

import ...
import ...
other code...

SQL keys, MUL vs PRI vs UNI

UNI: For UNIQUE:

  • It is a set of one or more columns of a table to uniquely identify the record.
  • A table can have multiple UNIQUE key.
  • It is quite like primary key to allow unique values but can accept one null value which primary key does not.

PRI: For PRIMARY:

  • It is also a set of one or more columns of a table to uniquely identify the record.
  • A table can have only one PRIMARY key.
  • It is quite like UNIQUE key to allow unique values but does not allow any null value.

MUL: For MULTIPLE:

  • It is also a set of one or more columns of a table which does not identify the record uniquely.
  • A table can have more than one MULTIPLE key.
  • It can be created in table on index or foreign key adding, it does not allow null value.
  • It allows duplicate entries in column.
  • If we do not specify MUL column type then it is quite like a normal column but can allow null entries too hence; to restrict such entries we need to specify it.
  • If we add indexes on column or add foreign key then automatically MUL key type added.

Java Try Catch Finally blocks without Catch

how does the try block work if it encounters an exception or anything throwable

The exception is thrown out of the block, just as in any other case where it's not caught.

The finally block is executed regardless of how the try block is exited -- regardless whether there are any catches at all, regardless of whether there is a matching catch.

The catch blocks and the finally are orthogonal parts of the try block. You can have either or both. With Java 7, you'll be able to have neither!

Truncating Text in PHP?

$text="abc1234567890";

// truncate to 4 chars

echo substr(str_pad($text,4),0,4);

This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)

Is there anyway to exclude artifacts inherited from a parent POM?

Don't use a parent pom

This might sound extreme, but the same way "inheritance hell" is a reason some people turn their backs on Object Oriented Programming (or prefer composition over inheritance), remove the problematic <parent> block and copy and paste whatever <dependencies> you need (if your team gives you this liberty).

The assumption that splitting of poms into a parent and child for "reuse" and "avoidance of redunancy" should be ignored and you should serve your immediate needs first (the cure is worst than the disease). Besides, redundancy has its advantages - namely independence of external changes (i.e stability).

This is easier than it sounds if you generate the effective pom (eclipse provides it but you can generate it from the command line with mvn help:effective).

Example

I want to use logback as my slf4j binding, but my parent pom includes the log4j dependency. I don't want to go and have to push the other children's dependence on log4j down into their own pom.xml files so that mine is unobstructed.

Viewing my IIS hosted site on other machines on my network

Very Late Answer but I will highlight some point as I had to deal with it years ago setting up my IIS site across network

  1. Both your machines should be connected to the same network (same wireless network is fine)
  2. Access your remote machine via IP 168.192.x.x or via http://his-pc-name (do not forget the http part)
  3. This will server the default IIS page on the remote machine (same that is served through localhost). If you want to server another site, [you have to make that default] first1.

Make sure your IIS is working fine on remote machine by checking localhost which should served the default site. Also make sure your firewall is configured to allow connection via port 80 or you can just disable firewall for the time being for testing purposes.

Convert wchar_t to char

Technically, 'char' could have the same range as either 'signed char' or 'unsigned char'. For the unsigned characters, your range is correct; theoretically, for signed characters, your condition is wrong. In practice, very few compilers will object - and the result will be the same.

Nitpick: the last && in the assert is a syntax error.

Whether the assertion is appropriate depends on whether you can afford to crash when the code gets to the customer, and what you could or should do if the assertion condition is violated but the assertion is not compiled into the code. For debug work, it seems fine, but you might want an active test after it for run-time checking too.

How to create a new figure in MATLAB?

As has already been said: figure will create a new figure for your next plots. While calling figure you can also configure it. Example:

figHandle = figure('Name', 'Name of Figure', 'OuterPosition',[1, 1, scrsz(3), scrsz(4)]);

The example sets the name for the window and the outer size of it in relation to the used screen. Here figHandle is the handle to the resulting figure and can be used later to change appearance and content. Examples:

Dot notation:

figHandle.PaperOrientation = 'portrait';
figHandle.PaperUnits = 'centimeters';

Old Style:

set(figHandle, 'PaperOrientation', 'portrait', 'PaperUnits', 'centimeters');

Using the handle with dot notation or set, options for printing are configured here.

By keeping the handles for the figures with distinc names you can interact with multiple active figures. To set a existing figure as your active, call figure(figHandle). New plots will go there now.

How to delete an app from iTunesConnect / App Store Connect

Easy.

(as of 2021)

Click your app, click App Information in the left side menu, scroll all the way down to the Additional Information section, click Remove App.

Boom. done.

How do I 'git diff' on a certain directory?

What I was looking for was this:

git diff <ref1>..<ref2> <dirname>

How to split large text file in windows?

You can use the command split for this task. For example this command entered into the command prompt

split YourLogFile.txt -b 500m

creates several files with a size of 500 MByte each. This will take several minutes for a file of your size. You can rename the output files (by default called "xaa", "xab",... and so on) to *.txt to open it in the editor of your choice.

Make sure to check the help file for the command. You can also split the log file by number of lines or change the name of your output files.

(tested on Windows 7 64 bit)

Set up adb on Mac OS X

For Mac users : Step 1: Install the Android Studio

Step2 : Open the terminal and type

cd

Step 3: Type below mentioned command changing the userName:

export PATH=“/Users/{user_name}/Library/Android/sdk/platform-tools”:$PATH

Angular ng-if not true

try this:

<div ng-if="$scope.length == 0" ? true : false></div>

and show or hide

<div ng-show="$scope.length == 0"></div>

else it will be hide

-----------------or--------------------------

if you are using $ctrl than code will be like this:

try this:

<div ng-if="$ctrl.length == 0" ? true : false></div>

and show or hide

<div ng-show="$ctrl.length == 0"></div>

else it will be hide

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Android Camera Preview Stretched

Just to make this thread more complete i am adding my version of answer:

What i wanted to achieve: The surface view shouldn't be stretched, and it should cover the whole screen, Moreover, there was only a landscape mode in my app.

Solution:

The solution is an extremely small extension to F1sher's solution:

=> First step is to integrate F1sher's solution.

=> Now, there might arise a scenario in F1sher's solution when the surface view doesn't covers the whole screen, The solution is to make the surface view greater than the screen dimensions so that it covers the whole screen, for that:

    size = getOptimalPreviewSize(mCamera.getParameters().getSupportedPreviewSizes(), screenWidth, screenHeight);

    Camera.Parameters parameters = mCamera.getParameters();
    parameters.setPreviewSize(size.width, size.height);


    mCamera.setParameters(parameters);      

    double screenRatio = (double) screenHeight / screenWidth;
    double previewRatio = (double) size.height / size.width;

    if (previewRatio > screenRatio)     /*if preview ratio is greater than screen ratio then we will have to recalculate the surface height while keeping the surface width equal to the screen width*/
    {
        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
        params1.addRule(RelativeLayout.CENTER_IN_PARENT);
        flPreview.setLayoutParams(params1);

        flPreview.setClipChildren(false);

        LayoutParams surfaceParams = new LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
        surfaceParams.gravity = Gravity.CENTER;
        mPreview.setLayoutParams(surfaceParams);        
    }
    else     /*if preview ratio is smaller than screen ratio then we will have to recalculate the surface width while keeping the surface height equal to the screen height*/
    {
        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
        params1.addRule(RelativeLayout.CENTER_IN_PARENT);
        flPreview.setLayoutParams(params1);
        flPreview.setClipChildren(false);

        LayoutParams surfaceParams = new LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
        surfaceParams.gravity = Gravity.CENTER;
        mPreview.setLayoutParams(surfaceParams);

    }       

    flPreview.addView(mPreview); 

  /*  The TopMost layout used is the RelativeLayout, flPreview is the FrameLayout in which Surface View is added, mPreview is an instance of a class which extends SurfaceView  */

Is there a java setting for disabling certificate validation?

Use cli utility keytool from java software distribution for import (and trust!) needed certificates

Sample:

  1. From cli change dir to jre\bin

  2. Check keystore (file found in jre\bin directory)
    keytool -list -keystore ..\lib\security\cacerts
    Enter keystore password: changeit

  3. Download and save all certificates chain from needed server.

  4. Add certificates (before need to remove "read-only" attribute on file "..\lib\security\cacerts") keytool -alias REPLACE_TO_ANY_UNIQ_NAME -import -keystore ..\lib\security\cacerts -file "r:\root.crt"

accidentally I found such a simple tip. Other solutions require the use of InstallCert.Java and JDK

source: http://www.java-samples.com/showtutorial.php?tutorialid=210

How to view user privileges using windows cmd?

I'd start with:

secedit /export /areas USER_RIGHTS /cfg OUTFILE.CFG

Then examine the line for the relevant privilege. However, the problem now is that the accounts are listed as SIDs, not usernames.

Add a string of text into an input field when user clicks a button

this will do it with just javascript - you can also put the function in a .js file and call it with onclick

//button
<div onclick="
   document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>

Convert JavaScript string in dot notation into an object reference

Here is my implementation

Implementation 1

Object.prototype.access = function() {
    var ele = this[arguments[0]];
    if(arguments.length === 1) return ele;
    return ele.access.apply(ele, [].slice.call(arguments, 1));
}

Implementation 2 (using array reduce instead of slice)

Object.prototype.access = function() {
    var self = this;
    return [].reduce.call(arguments,function(prev,cur) {
        return prev[cur];
    }, self);
}

Examples:

var myobj = {'a':{'b':{'c':{'d':'abcd','e':[11,22,33]}}}};

myobj.access('a','b','c'); // returns: {'d':'abcd', e:[0,1,2,3]}
myobj.a.b.access('c','d'); // returns: 'abcd'
myobj.access('a','b','c','e',0); // returns: 11

it can also handle objects inside arrays as for

var myobj2 = {'a': {'b':[{'c':'ab0c'},{'d':'ab1d'}]}}
myobj2.access('a','b','1','d'); // returns: 'ab1d'

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

You must write onActivityResult() in your FirstActivity.Java as follows

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
}

So this will call your fragment's onActivityResult()

Edit: the solution is to replace getActivity().startActivityForResult(i, 1); with startActivityForResult(i, 1);

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

Can HTTP POST be limitless?

There is no limit according to the HTTP protocol itself, but implementations will have a practical upper limit. I have sent data exceeding 4 GB using POST to Apache, but some servers did have a limit of 4 GB at the time.

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

If you (or a helpful admin) runs Set-ExecutionPolicy as administrator, the policy will be set for all users. (I would suggest "remoteSigned" rather than "unrestricted" as a safety measure.)

NB.: On a 64-bit OS you need to run Set-ExecutionPolicy for 32-bit and 64-bit PowerShell separately.

Which is the best library for XML parsing in java

If you want a DOM-like API - that is, one where the XML parser turns the document into a tree of Element and Attribute nodes - then there are at least four to choose from: DOM itself, JDOM, DOM4J, and XOM. The only possible reason to use DOM is because it's perceived as a standard and is supplied in the JDK: in all other respects, the others are all superior. My own preference, for its combination of simplicity, power, and performance, is XOM.

And of course, there are other styles of processing: low-level parser interfaces (SAX and StAX), data-object binding interfaces (JAXB), and high-level declarative languages (XSLT, XQuery, XPath). Which is best for you depends on your project requirements and your personal taste.

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

I had the same issue. I using the standard command for execution. It was calling the X64 ro run against X86 tests. I needed to specify the X86 and not the X64 version of the nunit-runner.

Android Studio - No JVM Installation found

My JAVA_HOME was pointing to c:/jre directly. So I changed it to C:/java/jre because it was confused to pick up which one to use, so I changed it to the specific one and it works for me. Note: It is better to have only one JRE install on your machine

JSON array get length

Note: if you're using(importing) org.json.simple.JSONArray, you have to use JSONArray.size() to get the data you want. But use JSONArray.length() if you're using org.json.JSONArray.

Simple way to query connected USB devices info in Python?

For linux, I wrote a script called find_port.py which you can find here: https://github.com/dhylands/usb-ser-mon/blob/master/usb_ser_mon/find_port.py

It uses pyudev to enumerate all tty devices, and can match on various attributes.

Use the --list option to show all of the know USB serial ports and their attributes. You can filter by VID, PID, serial number, or vendor name. Use --help to see the filtering options.

find_port.py prints the /dev/ttyXXX name rather than the /dev/usb/... name.

Cookies on localhost with explicit domain

There is an issue on Chromium open since 2011, that if you are explicitly setting the domain as 'localhost', you should set it as false or undefined.

CSS Progress Circle

What about that?

HTML

<div class="chart" id="graph" data-percent="88"></div>

Javascript

var el = document.getElementById('graph'); // get canvas

var options = {
    percent:  el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';

if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
        percent = Math.min(Math.max(0, percent || 1), 1);
        ctx.beginPath();
        ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
        ctx.strokeStyle = color;
        ctx.lineCap = 'round'; // butt, round or square
        ctx.lineWidth = lineWidth
        ctx.stroke();
};

drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);

and CSS

div {
    position:relative;
    margin:80px;
    width:220px; height:220px;
}
canvas {
    display: block;
    position:absolute;
    top:0;
    left:0;
}
span {
    color:#555;
    display:block;
    line-height:220px;
    text-align:center;
    width:220px;
    font-family:sans-serif;
    font-size:40px;
    font-weight:100;
    margin-left:5px;
}

http://jsfiddle.net/Aapn8/3410/

Basic code was taken from Simple PIE Chart http://rendro.github.io/easy-pie-chart/

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

How do I split a string into an array of characters?

It's as simple as:

s.split("");

The delimiter is an empty string, hence it will break up between each single character.

How to ignore SSL certificate errors in Apache HttpClient 4.0

You need to create a SSLContext with your own TrustManager and create HTTPS scheme using this context. Here is the code,

SSLContext sslContext = SSLContext.getInstance("SSL");

// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
            }

            public void checkClientTrusted(X509Certificate[] certs,
                            String authType) {
                    System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs,
                            String authType) {
                    System.out.println("checkServerTrusted =============");
            }
} }, new SecureRandom());

SSLSocketFactory sf = new SSLSocketFactory(sslContext);
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);

// apache HttpClient version >4.2 should use BasicClientConnectionManager
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);

vi/vim editor, copy a block (not usual action)

You can do it as you do in vi, for example to yank lines from 3020 to the end, execute this command (write the block to a file):

:3020,$ w /tmp/yank

And to write this block in another line/file, go to the desired position and execute next command (insert file written before):

:r /tmp/yank

(Reminder: don't forget to remove file: /tmp/yank)

C++ Returning reference to local variable

This code snippet:

int& func1()
{
    int i;
    i = 1;
    return i;
}

will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because it now refers to an object that doesn't exist.

int main()
{
    int& p = func1();
    /* p is garbage */
}

The second version does work because the variable is allocated on the free store, which is not bound to the lifetime of the function call. However, you are responsible for deleteing the allocated int.

int* func2()
{
    int* p;
    p = new int;
    *p = 1;
    return p;
}

int main()
{
    int* p = func2();
    /* pointee still exists */
    delete p; // get rid of it
}

Typically you would wrap the pointer in some RAII class and/or a factory function so you don't have to delete it yourself.

In either case, you can just return the value itself (although I realize the example you provided was probably contrived):

int func3()
{
    return 1;
}

int main()
{
    int v = func3();
    // do whatever you want with the returned value
}

Note that it's perfectly fine to return big objects the same way func3() returns primitive values because just about every compiler nowadays implements some form of return value optimization:

class big_object 
{ 
public:
    big_object(/* constructor arguments */);
    ~big_object();
    big_object(const big_object& rhs);
    big_object& operator=(const big_object& rhs);
    /* public methods */
private:
    /* data members */
};

big_object func4()
{
    return big_object(/* constructor arguments */);
}

int main()
{
     // no copy is actually made, if your compiler supports RVO
    big_object o = func4();    
}

Interestingly, binding a temporary to a const reference is perfectly legal C++.

int main()
{
    // This works! The returned temporary will last as long as the reference exists
    const big_object& o = func4();    
    // This does *not* work! It's not legal C++ because reference is not const.
    // big_object& o = func4();  
}

Root password inside a Docker container

The password is 'ubuntu' for the 'ubuntu' user (at least in docker for ubuntu :14.04.03).

NB: 'ubuntu' is created after the startup of the container so, if you just do this:

 docker run -i -t --entrypoint /bin/bash  ubuntu     

You'll get the root prompt directly. From there you can force the password change of root, commit the container and optionally tag it (with -f) to ubuntu:latest like this:

root@ec384466fbbb:~# passwd
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
root@ec384466fbbb:~# exit

% docker commit ec3844
5d3c03e7d6d861ce519fe33b184cd477b8ad03247ffe19b2a57d3f0992d71bca

docker tag -f 5d3c ubuntu:latest

You must rebuild your eventual dependencies on ubuntu:latest.

How to retrieve images from MySQL database and display in an html tag

Technically, you can too put image data in an img tag, using data URIs.

<img src="data:image/jpeg;base64,<?php echo base64_encode( $image_data ); ?>" />

There are some special circumstances where this could even be useful, although in most cases you're better off serving the image through a separate script like daiscog suggests.

VBA Public Array : how to?

Try this:

Dim colHeader(12)
colHeader = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

Unfortunately the code found online was VB.NET not VBA.

When to use the JavaScript MIME type application/javascript instead of text/javascript?

application/javascript is the correct type to use but since it's not supported by IE6-8 you're going to be stuck with text/javascript. If you don't care about validity (HTML5 excluded) then just don't specify a type.

Plotting histograms from grouped data in a pandas DataFrame

I'm on a roll, just found an even simpler way to do it using the by keyword in the hist method:

df['N'].hist(by=df['Letter'])

That's a very handy little shortcut for quickly scanning your grouped data!

For future visitors, the product of this call is the following chart: enter image description here

Rename a column in MySQL

From MySQL 8.0 you could use

ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;

ALTER TABLE Syntax:

RENAME COLUMN:

  • Can change a column name but not its definition.

  • More convenient than CHANGE to rename a column without changing its definition.

DBFiddle Demo

How can I remove an element from a list, with lodash?

lodash and typescript

const clearSubTopics = _.filter(obj.subTopics, topic => (!_.isEqual(topic.subTopicId, 2)));
console.log(clearSubTopics);

Good ways to manage a changelog using git?

I let the CI server pipe the following into a file named CHANGELOG for a each new release with the date set in the release-filename:

>git log --graph --all --date=relative --pretty=format:"%x09 %ad %d %s (%aN)"

Convert java.util.Date to java.time.LocalDate

If you are using ThreeTen Backport including ThreeTenABP

    Date input = new Date(); // Imagine your Date here
    LocalDate date = DateTimeUtils.toInstant(input)
            .atZone(ZoneId.systemDefault())
            .toLocalDate();

If you are using the backport of JSR 310, either you haven’t got a Date.toInstant() method or it won’t give you the org.threeten.bp.Instant that you need for you further conversion. Instead you need to use the DateTimeUtils class that comes as part of the backport. The remainder of the conversion is the same, so so is the explanation.

How do I make Git ignore file mode (chmod) changes?

If you want to set this option for all of your repos, use the --global option.

git config --global core.filemode false

If this does not work you are probably using a newer version of git so try the --add option.

git config --add --global core.filemode false

If you run it without the --global option and your working directory is not a repo, you'll get

error: could not lock config file .git/config: No such file or directory

Presenting modal in iOS 13 fullscreen

If you are using a UINavigationController and embed a ViewController as a root view controller, then also you would rise up with same issue. Use following code to overcome.

let vc = UIViewController()
let navController = UINavigationController(rootViewController: vc)
navController.modalPresentationStyle = .fullScreen

To find first N prime numbers in python

def isPrime(y):
  i=2
  while i < y:
    if y%i == 0 :
      return 0
      exit()
    i=i+1
  return 1

x= raw_input('Enter the position 1st,2nd,..nth prime number you are looking for?: ')
z=int(x)
# for l in range(2,z)
count = 1
n = 2
while count <= z:
  if isPrime(n) == 1:
    if count == z:
      print n
    count +=1
  n=n+1

Convert timestamp to date in Oracle SQL

You can try the simple one

select to_date('2020-07-08T15:30:42Z','yyyy-mm-dd"T"hh24:mi:ss"Z"') from dual;

How do I get out of 'screen' without typing 'exit'?

Ctrl+a followed by k will "kill" the current screen session.

MySQL/SQL: Group by date only on a Datetime column

Cast the datetime to a date, then GROUP BY using this syntax:

SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);

Or you can GROUP BY the alias as @orlandu63 suggested:

SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;

Though I don't think it'll make any difference to performance, it is a little clearer.

How to create an AVD for Android 4.0

This site Android Create AVD shows you how to install the latest version of the Android SDK and AVD version 4 in Eclipse with video and screenshots if you're still stuck?

What does the keyword "transient" mean in Java?

Transient variables in Java are never serialized.

<embed> vs. <object>

Probably the best cross browser solution for pdf display on web pages is to use the Mozilla PDF.js project code, it can be run as a node.js service and used as follows

<iframe style="width:100%;height:500px" src="http://www.mysite.co.uk/libs/pdfjs/web/viewer.html?file="http://www.mysite.co.uk/mypdf.pdf"></iframe>

A tutorial on how to use pdf.js can be found at this ejectamenta blog article

Proper way to initialize C++ structs

That seems to me the easiest way. Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.

struct Point 
{ 
   int x, y; 
};  

int main() 
{ 
   // A valid initialization. member x gets value 0 and y 
   // gets value 1.  The order of declaration is followed. 
   struct Point p1 = {0, 1};  
}

There is good information about structs in c++ - https://www.geeksforgeeks.org/structures-in-cpp/

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

Just as an FYI - "best" questions aren't the norm at SO, but I will give you a list of options, just as a service.

OK then. These two are the ones I used:

Komodo Edit

Aptana Studio 3

and then there is always Eclipse.

*UPDATE 20 March 2013 *

Well, Sublime Text 2 is the one to heavily consider. Heavily.

What is the correct way to do a CSS Wrapper?

/******************
Fit the body to the edges of the screen
******************/    

body {
         margin:0;
         padding:0;
    }

header {
     background:black;
     width:100%;
}

.header {
     height:200px;
}

nav {
     width:100%;
     background:lightseagreen;
}

.nav {
     padding:0;
     margin:0;
}

.nav a {
     padding:10px;
     font-family:tahoma;
     font-size:12pt;
     color:white;
}

/******************
Centered wrapper, all other content divs will go inside this and will never exceed the width of 960px.
******************/

    .wrapper {
         width:960px;
         max-width:100%;
         margin:0 auto;
    }



<!-------- Start HTML ---------->

    <body>

<header>

    <div id="header" class="wrapper">

    </div>

</header>

<nav>

     <div id="nav" class="wrapper">

     </div>

</nav>



    </body>

How can I convert String to Int?

This may help you ;D

{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        float Stukprijs;
        float Aantal;
        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("In de eersre textbox staat een geldbedrag." + Environment.NewLine + "In de tweede textbox staat een aantal." + Environment.NewLine + "Bereken wat er moetworden betaald." + Environment.NewLine + "Je krijgt 15% korting over het bedrag BOVEN de 100." + Environment.NewLine + "Als de korting meer dan 10 euri is," + Environment.NewLine + "wordt de korting textbox lichtgroen");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            errorProvider2.Clear();
            if (float.TryParse(textBox1.Text, out Stukprijs))
            {
                if (float.TryParse(textBox2.Text, out Aantal))
                {
                    float Totaal = Stukprijs * Aantal;
                    string Output = Totaal.ToString();
                    textBox3.Text = Output;
                    if (Totaal >= 100)
                    {
                        float korting = Totaal - 100;
                        float korting2 = korting / 100 * 15;
                        string Output2 = korting2.ToString();
                        textBox4.Text = Output2;
                        if (korting2 >= 10)
                        {
                            textBox4.BackColor = Color.LightGreen;
                        }
                        else
                        {
                            textBox4.BackColor = SystemColors.Control;
                        }
                    }
                    else
                    {
                        textBox4.Text = "0";
                        textBox4.BackColor = SystemColors.Control;
                    }
                }
                else
                {
                    errorProvider2.SetError(textBox2, "Aantal plz!");
                }

            }
            else
            {
                errorProvider1.SetError(textBox1, "Bedrag plz!");
                if (float.TryParse(textBox2.Text, out Aantal))
                {

                }
                else
                {
                    errorProvider2.SetError(textBox2, "Aantal plz!");
                }
            }

        }

        private void BTNwissel_Click(object sender, EventArgs e)
        {
            //LL, LU, LR, LD.
            Color c = LL.BackColor;
            LL.BackColor = LU.BackColor;
            LU.BackColor = LR.BackColor;
            LR.BackColor = LD.BackColor;
            LD.BackColor = c;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("zorg dat de kleuren linksom wisselen als je op de knop drukt.");
        }
    }
}

How to deserialize xml to object

Your classes should look like this

[XmlRoot("StepList")]
public class StepList
{
    [XmlElement("Step")]
    public List<Step> Steps { get; set; }
}

public class Step
{
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("Desc")]
    public string Desc { get; set; }
}

Here is my testcode.

string testData = @"<StepList>
                        <Step>
                            <Name>Name1</Name>
                            <Desc>Desc1</Desc>
                        </Step>
                        <Step>
                            <Name>Name2</Name>
                            <Desc>Desc2</Desc>
                        </Step>
                    </StepList>";

XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
    StepList result = (StepList) serializer.Deserialize(reader);
}

If you want to read a text file you should load the file into a FileStream and deserialize this.

using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open)) 
{
    StepList result = (StepList) serializer.Deserialize(fileStream);
}

ViewDidAppear is not called when opening app from background

Swift 3.0 ++ version

In your viewDidLoad, register at notification center to listen to this opened from background action

NotificationCenter.default.addObserver(self, selector:#selector(doSomething), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
        

Then add this function and perform needed action

func doSomething(){
    //...
}

Finally add this function to clean up the notification observer when your view controller is destroyed.

deinit {
    NotificationCenter.default.removeObserver(self)
}

Presenting a UIAlertController properly on an iPad using iOS 8

Just add the following code before presenting your action sheet:

if let popoverController = optionMenu.popoverPresentationController {
    popoverController.sourceView = self.view
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
    popoverController.permittedArrowDirections = []
}

MVC Calling a view from a different controller

You can move you read.aspx view to Shared folder. It is standard way in such circumstances

Regex to match words of a certain length

Length of characters to be matched.

{n,m}  n <= length <= m
{n}    length == n
{n,}   length >= n

And by default, the engine is greedy to match this pattern. For example, if the input is 123456789, \d{2,5} will match 12345 which is with length 5.

If you want the engine returns when length of 2 matched, use \d{2,5}?

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

Its complete installation nightmare, but I'll give one more hope you can avoid building opencv from source:

pip install opencv-contrib-python

ASP.NET MVC3 Razor - Html.ActionLink style

VB sample:

 @Html.ActionLink("Home", "Index", Nothing, New With {.style = "font-weight:bold;", .class = "someClass"})

Sample Css:

.someClass
{
    color: Green !important;
}

In my case, I found that I need the !important attribute to over ride the site.css a:link css class

What is the difference between a static and a non-static initialization code block

This is directly from http://www.programcreek.com/2011/10/java-class-instance-initializers/

1. Execution Order

Look at the following class, do you know which one gets executed first?

public class Foo {
 
    //instance variable initializer
    String s = "abc";
 
    //constructor
    public Foo() {
        System.out.println("constructor called");
    }
 
    //static initializer
    static {
        System.out.println("static initializer called");
    }
 
    //instance initializer
    {
        System.out.println("instance initializer called");
    }
 
    public static void main(String[] args) {
        new Foo();
        new Foo();
    }
}

Output:

static initializer called

instance initializer called

constructor called

instance initializer called

constructor called

2. How do Java instance initializer work?

The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0. This can make it more obvious to understand.

Instead of

int b = 0, you could write

int b;
b = 0;

Therefore, instance initializers and instance variable initializers are pretty much the same.

3. When are instance initializers useful?

The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:

  1. Initializer code must handle exceptions
  2. Perform calculations that can’t be expressed with an instance variable initializer.

Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.

With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)

Another case in which instance initializers are useful is anonymous inner classes, which can’t declare any constructors at all. (Will this be a good place to place a logging function?)

Thanks to Derhein.

Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are needed to execute any kinds of expressions at construction time.

Is there a difference between "throw" and "throw ex"?

Look at here: http://blog-mstechnology.blogspot.de/2010/06/throw-vs-throw-ex.html

Throw:

try 
{
    // do some operation that can fail
}
catch (Exception ex)
{
    // do some local cleanup
    throw;
}

It preserve the Stack information with Exception

This is called as "Rethrow"

If want to throw new exception,

throw new ApplicationException("operation failed!");

Throw Ex:

try
{
    // do some operation that can fail
}
catch (Exception ex)
{
    // do some local cleanup
    throw ex;
}

It Won't Send Stack information with Exception

This is called as "Breaking the Stack"

If want to throw new exception,

throw new ApplicationException("operation failed!",ex);

Graph implementation C++

The most common representations are probably these two:

Of these two the adjacency matrix is the simplest, as long as you don't mind having a (possibly huge) n * n array, where n is the number of vertices. Depending on the base type of the array, you can even store edge weights for use in e.g. shortest path discovery algorithms.

Adding 'serial' to existing column in Postgres

Look at the following commands (especially the commented block).

DROP TABLE foo;
DROP TABLE bar;

CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);

INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;

-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a;    -- 8.2 or later

SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5);  -- replace 5 by SELECT MAX result

INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');

SELECT * FROM foo;
SELECT * FROM bar;

How to list all files in a directory and its subdirectories in hadoop hdfs

don't use recursive approach (heap issues) :) use a queue

queue.add(param_dir)
while (queue is not empty){

  directory=  queue.pop
 - get items from current directory
 - if item is file add to a list (final list)
 - if item is directory => queue.push
}

that was easy, enjoy!

How to connect to Oracle 11g database remotely

You will need to run the lsnrctl utility on server A to start the listener. You would then connect from computer B using the following syntax:

sqlplus username/password@hostA:1521 /XE

The port information is optional if the default of 1521 is used.

Listener configuration documentation here. Remote connection documentation here.

Could not establish secure channel for SSL/TLS with authority '*'

Yes an Untrusted certificate can cause this. Look at the certificate path for the webservice by opening the websservice in a browser and use the browser tools to look at the certificate path. You may need to install one or more intermediate certificates onto the computer calling the webservice. In the browser you may see "Certificate errors" with an option to "Install Certificate" when you investigate further - this could be the certificate you missing.

My particular problem was a Geotrust Geotrust DV SSL CA intermediate certificate missing following an upgrade to their root server in July 2010 https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422

(2020 update deadlink preserved here: https://web.archive.org/web/20140724085537/https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422 )

Detect backspace and del on "input" event?

It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:

document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
    if (e.inputType == "deleteContentBackward") {
        // your code here
    }
});

Convert DateTime to String PHP

There are some predefined formats in date_d.php to use with format like:

define ('DATE_ATOM', "Y-m-d\TH:i:sP");
define ('DATE_COOKIE', "l, d-M-y H:i:s T");
define ('DATE_ISO8601', "Y-m-d\TH:i:sO");
define ('DATE_RFC822', "D, d M y H:i:s O");
define ('DATE_RFC850', "l, d-M-y H:i:s T");
define ('DATE_RFC1036', "D, d M y H:i:s O");
define ('DATE_RFC1123', "D, d M Y H:i:s O");
define ('DATE_RFC2822', "D, d M Y H:i:s O");
define ('DATE_RFC3339', "Y-m-d\TH:i:sP");
define ('DATE_RSS', "D, d M Y H:i:s O");
define ('DATE_W3C', "Y-m-d\TH:i:sP");

Use like this:

$date = new \DateTime();
$string = $date->format(DATE_RFC2822);

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

CSS force image resize and keep aspect ratio

I would suggest for a responsive approach the best practice would be using the Viewport units and min/max attributes as follows:

img{
  display: block;
  width: 12vw;
  height:12vw;
  max-width:100%;
  min-width:100px;
  min-height:100px;
  object-fit:contain;
}

Configure apache to listen on port other than 80

Run this command if your ufw(Uncomplicatd Firewall) is enabled . Add for Example port 8080

$ sudo ufw allow 8080/tcp

And you can check the status by running

$ sudo ufw status

For more info check : https://linuxhint.com/ubuntu_allow_port_firewall

How to check if a file exists in Go?

Let's look at few aspects first, both the function provided by os package of golang are not utilities but error checkers, what do I mean by that is they are just a wrapper to handle errors on cross platform.

So basically if os.Stat if this function doesn't give any error that means the file is existing if it does you need to check what kind of error it is, here comes the use of these two function os.IsNotExist and os.IsExist.

This can be understood as the Stat of the file throwing error because it doesn't exists or is it throwing error because it exist and there is some problem with it.

The parameter that these functions take is of type error, although you might be able to pass nil to it but it wouldn't make sense.

This also points to the fact that IsExist is not same as !IsNotExist, they are way two different things.

So now if you want to know if a given file exist in go, I would prefer the best way is:

if _, err := os.Stat(path/to/file); !os.IsNotExist(err){
   //TODO
} 

Using subprocess to run Python script on Windows

Yes subprocess.Popen(cmd, ..., shell=True) works like a charm. On Windows the .py file extension is recognized, so Python is invoked to process it (on *NIX just the usual shebang). The path environment controls whether things are seen. So the first arg to Popen is just the name of the script.

subprocess.Popen(['myscript.py', 'arg1', ...], ..., shell=True)

RegEx for validating an integer with a maximum length of 10 characters

In most languages i am aware of, the actual regex for validating should be ^[0-9]{1,10}$; otherwise the matcher will also return positive matches if the to be validated number is part of a longer string.

Get records with max value for each group of grouped SQL results

The correct solution is:

SELECT o.*
FROM `Persons` o                    # 'o' from 'oldest person in group'
  LEFT JOIN `Persons` b             # 'b' from 'bigger age'
      ON o.Group = b.Group AND o.Age < b.Age
WHERE b.Age is NULL                 # bigger age not found

How it works:

It matches each row from o with all the rows from b having the same value in column Group and a bigger value in column Age. Any row from o not having the maximum value of its group in column Age will match one or more rows from b.

The LEFT JOIN makes it match the oldest person in group (including the persons that are alone in their group) with a row full of NULLs from b ('no biggest age in the group').
Using INNER JOIN makes these rows not matching and they are ignored.

The WHERE clause keeps only the rows having NULLs in the fields extracted from b. They are the oldest persons from each group.

Further readings

This solution and many others are explained in the book SQL Antipatterns: Avoiding the Pitfalls of Database Programming

dispatch_after - GCD in Swift?

In Swift 5, use in the below:

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: closure) 

// time gap, specify unit is second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
            Singleton.shared().printDate()
        }
// default time gap is second, you can reduce it
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
          // just do it!
    }

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

for VS code and later versions Ctrl + P to open and then writing Whitespace, you can select the View: Toggle Render Whitespace

Add a new item to a dictionary in Python

default_data['item3'] = 3

Easy as py.

Another possible solution:

default_data.update({'item3': 3})

which is nice if you want to insert multiple items at once.

Allow Google Chrome to use XMLHttpRequest to load a URL from a local file

Using --disable-web-security switch is quite dangerous! Why disable security at all while you can just allow XMLHttpRequest to access files from other files using --allow-file-access-from-files switch?

Before using these commands be sure to end all running instances of Chrome.

On Windows:

chrome.exe --allow-file-access-from-files

On Mac:

open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files

Discussions of this "feature" of Chrome:

Update Top 1 record in table sql server

When TOP is used with INSERT, UPDATE, MERGE, or DELETE, the referenced rows are not arranged in any order and the ORDER BY clause can not be directly specified in these statements. If you need to use TOP to insert, delete, or modify rows in a meaningful chronological order, you must use TOP together with an ORDER BY clause that is specified in a subselect statement.

TOP cannot be used in an UPDATE and DELETE statements on partitioned views.

TOP cannot be combined with OFFSET and FETCH in the same query expression (in the same query scope). For more information, see http://technet.microsoft.com/en-us/library/ms189463.aspx

Static Classes In Java

Java has static nested classes but it sounds like you're looking for a top-level static class. Java has no way of making a top-level class static but you can simulate a static class like this:

  • Declare your class final - Prevents extension of the class since extending a static class makes no sense
  • Make the constructor private - Prevents instantiation by client code as it makes no sense to instantiate a static class
  • Make all the members and functions of the class static - Since the class cannot be instantiated no instance methods can be called or instance fields accessed
  • Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member

Simple example per suggestions from above:

public class TestMyStaticClass {
     public static void main(String []args){
        MyStaticClass.setMyStaticMember(5);
        System.out.println("Static value: " + MyStaticClass.getMyStaticMember());
        System.out.println("Value squared: " + MyStaticClass.squareMyStaticMember());
        // MyStaticClass x = new MyStaticClass(); // results in compile time error
     }
}

// A top-level Java class mimicking static class behavior
public final class MyStaticClass {
    private MyStaticClass () { // private constructor
        myStaticMember = 1;
    }
    private static int myStaticMember;
    public static void setMyStaticMember(int val) {
        myStaticMember = val;
    }
    public static int getMyStaticMember() {
        return myStaticMember;
    }
    public static int squareMyStaticMember() {
        return myStaticMember * myStaticMember;
    }
}

What good are static classes? A good use of a static class is in defining one-off, utility and/or library classes where instantiation would not make sense. A great example is the Math class that contains some mathematical constants such as PI and E and simply provides mathematical calculations. Requiring instantiation in such a case would be unnecessary and confusing. See the Math class and source code. Notice that it is final and all of its members are static. If Java allowed top-level classes to be declared static then the Math class would indeed be static.

How can I create an error 404 in PHP?

In the Drupal or Wordpress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS's 404 handler take over:

<?php
  if(condition){
    do stuff;
  } else {
    include('index.php');
  }
?>

How can an html element fill out 100% of the remaining screen height, using css only?

Have you tried something like this?

CSS:

.content {
    height: 100%;
    display: block;
}

HTML:

<div class=".content">
<!-- Content goes here -->
</div>

Templated check for the existence of a class member function?

MSVC has the __if_exists and __if_not_exists keywords (Doc). Together with the typeof-SFINAE approach of Nicola I could create a check for GCC and MSVC like the OP looked for.

Update: Source can be found Here

How to do paging in AngularJS?

Old question but since I think my approach is a bit different and less complex I will share this and hope that someone besides me find it useful.

What I found to be an easy and small solution to pagination is to combine a directive with a filter which uses the same scope variables.

To implement this you add the filter on the array and add the directiv like this

<div class="row">
    <table class="table table-hover">
        <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
                <th>Quantity</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in items | cust_pagination:p_Size:p_Step">
                <td>{{item.Name}}</td>
                <td>{{item.Price}}</td>
                <td>{{item.Quantity}}</td>
            </tr>
        </tbody>
    </table>
    <div cust-pagination p-items="items" p-boundarylinks="true" p-size="p_Size" p-step="p_Step"></div>
</div>

p_Size and p_Step are scope variables which can be customized in the scope else the default value of the p_Size is 5 and p_Step is 1.

When a step is change in the pagination the p_Step is updated and will trigger a new filtering by cust_pagination filter. The cust_pagination filter then slices the array depending on the p_Step value like below and only return the active records selected in the pagination section

var startIndex = nStep * nPageSize;
var endIndex = startIndex + nPageSize;
var arr = items.slice(startIndex, endIndex);
return arr;

DEMO View the complete solution in this plunker

$(this).attr("id") not working

You could also write your entire function as a jQuery extension, so you could do something along the lines of `$('#element').showHideOther();

(function($) {
    $.extend($.fn, {
        showHideOther: function() {
            $.each(this, function() {
                var Id = $(this).attr('id');
                alert(Id);

                ...

                return this;
            });
        }
    });
})(jQuery);

Not that it answers your question... Just food for thought.

Merging 2 branches together in GIT

If you want to merge changes in SubBranch to MainBranch

  1. you should be on MainBranch git checkout MainBranch
  2. then run merge command git merge SubBranch

Resolving instances with ASP.NET Core DI from within ConfigureServices

If you just need to resolve one dependency for the purpose of passing it to the constructor of another dependency you are registering, you can do this.

Let's say you had a service that took in a string and an ISomeService.

public class AnotherService : IAnotherService
{
    public AnotherService(ISomeService someService, string serviceUrl)
    {
        ...
    }
}

When you go to register this inside Startup.cs, you'll need to do this:

services.AddScoped<IAnotherService>(ctx => 
      new AnotherService(ctx.GetService<ISomeService>(), "https://someservice.com/")
);

In SQL, is UPDATE always faster than DELETE+INSERT?

In your case, I believe the update will be faster.

Remember indexes!

You have defined a primary key, it will likely automatically become a clustered index (at least SQL Server does so). A cluster index means the records are physically laid on the disk according to the index. DELETE operation itself won't cause much trouble, even after one record goes away, the index stays correct. But when you INSERT a new record, the DB engine will have to put this record in the correct location which under circumstances will cause some "reshuffling" of the old records to "make place" for a new one. There where it will slow down the operation.

An index (especially clustered) works best if the values are ever increasing, so the new records just get appended to the tail. Maybe you can add an extra INT IDENTITY column to become a clustered index, this will simplify insert operations.

How to convert a String to CharSequence?

Straight answer:

String s = "Hello World!";

// String => CharSequence conversion:

CharSequence cs = s;  // String is already a CharSequence

CharSequence is an interface, and the String class implements CharSequence.

To compare two elements(string type) in XSLT?

First of all, the provided long code:

    <xsl:choose>
        <xsl:when test="OU_NAME='OU_ADDR1'">   --comparing two elements coming from XML             
            <!--remove if  adrees already contain  operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="OU_NAME"/>
            <fo:block/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:otherwise>
    </xsl:choose>

is equivalent to this, much shorter code:

<xsl:if test="not(OU_NAME='OU_ADDR1)'">
              <xsl:value-of select="OU_NAME"/>
        </xsl:if>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>

Now, to your question:

how to compare two elements coming from xml as string

In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator = and the function not() together with the operator =.

$str1 = $str2

evaluates to true() exactly when the string $str1 is equal to the string $str2.

not($str1 = $str2)

evaluates to true() exactly when the string $str1 is not equal to the string $str2.

There is also the != operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.

Now, the rules for comparing two element nodes are similar:

$el1 = $el2

evaluates to true() exactly when the string value of $el1 is equal to the string value of $el2.

not($el1 = $el2)

evaluates to true() exactly when the string value of $el1 is not equal to the string value of $el2.

However, if one of the operands of = is a node-set, then

 $ns = $str

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string $str

$ns1 = $ns2

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string value of some node from $ns2

Therefore, the expression:

OU_NAME='OU_ADDR1'

evaluates to true() only when there is at least one element child of the current node that is named OU_NAME and whose string value is the string 'OU_ADDR1'.

This is obviously not what you want!

Most probably you want:

OU_NAME=OU_ADDR1

This expression evaluates to true exactly there is at least one OU_NAME child of the current node and one OU_ADDR1 child of the current node with the same string value.

Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt, le, eq, gt, ge and the inherited from XPath 1.0 general comparison operator =.

Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

I know It's been a while since this question was asked but I just run into the same issue of inconsistency with onMouseLeave() What I did is to use onMouseOut() for the drop-list and on mouse leave for the whole menu, it is reliable and works every time I've tested it. I saw the events here in the docs: https://facebook.github.io/react/docs/events.html#mouse-events here is an example using https://www.w3schools.com/bootstrap/bootstrap_dropdowns.asp:

handleHoverOff(event){
  //do what ever, for example I use it to collapse the dropdown
  let collapsing = true;
  this.setState({dropDownCollapsed : collapsing });
}

render{
  return(
    <div class="dropdown" onMouseLeave={this.handleHoverOff.bind(this)}>
      <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
      <span class="caret"></span></button>
      <ul class="dropdown-menu" onMouseOut={this.handleHoverOff.bind(this)}>
        <li><a href="#">bla bla 1</a></li>
        <li><a href="#">bla bla 2</a></li>
        <li><a href="#">bla bla 3</a></li>
      </ul>
    </div>
  )
}

Get text of label with jquery

try document.getElementById('<%=Label1.ClientID%>').text or innerHTML OTHERWISE LOAD JQUERY SCRIPT AND put your code as it is....

How to access child's state in React?

Its 2020 and lots of you will come here looking for a similar solution but with Hooks ( They are great! ) and with latest approaches in terms of code cleanliness and syntax.

So as previous answers had stated, the best approach to this kind of problem is to hold the state outside of child component fieldEditor. You could do that in multiple ways.

The most "complex" is with global context (state) that both parent and children could access and modify. Its a great solution when components are very deep in the tree hierarchy and so its costly to send props in each level.

In this case I think its not worth it, and more simple approach will bring us the results we want, just using the powerful React.useState().

Approach with React.useState() hook, way simpler than with Class components

As said we will deal with changes and store the data of our child component fieldEditor in our parent fieldForm. To do that we will send a reference to the function that will deal and apply the changes to the fieldForm state, you could do that with:

function FieldForm({ fields }) {
  const [fieldsValues, setFieldsValues] = React.useState({});
  const handleChange = (event, fieldId) => {
    let newFields = { ...fieldsValues };
    newFields[fieldId] = event.target.value;

    setFieldsValues(newFields);
  };

  return (
    <div>
      {fields.map(field => (
        <FieldEditor
          key={field}
          id={field}
          handleChange={handleChange}
          value={fieldsValues[field]}
        />
      ))}
      <div>{JSON.stringify(fieldsValues)}</div>
    </div>
  );
}

Note that React.useState({}) will return an array with position 0 being the value specified on call (Empty object in this case), and position 1 being the reference to the function that modifies the value.

Now with the child component, FieldEditor, you don't even need to create a function with a return statement, a lean constant with an arrow function will do!

const FieldEditor = ({ id, value, handleChange }) => (
  <div className="field-editor">
    <input onChange={event => handleChange(event, id)} value={value} />
  </div>
);

Aaaaand we are done, nothing more, with just these two slime functional components we have our end goal "access" our child FieldEditor value and show it off in our parent.

You could check the accepted answer from 5 years ago and see how Hooks made React code leaner (By a lot!).

Hope my answer helps you learn and understand more about Hooks, and if you want to check a working example here it is.

How to get relative path from absolute path

If you're sure that your absolute path 2 is always relative to absolute path, just remove the first N characters from path2, where N is the length of path1.

How do I update a formula with Homebrew?

You can update all outdated packages like so:

brew install `brew outdated`

or

brew outdated | xargs brew install

or

brew upgrade

This is from the brew site..

for upgrading individual formula:

brew install formula-name && brew cleanup formula-name

What is the alternative for ~ (user's home directory) on Windows command prompt?

I just tried set ~=%userprofile% and that works too if you want to keep using the same habit

You can then use %~% instead.

ToList().ForEach in Linq

Try with this combination of Lambda expressions:

employees.ToList().ForEach(emp => 
{
    collection.AddRange(emp.Departments);
    emp.Departments.ToList().ForEach(dept => dept.SomeProperty = null);                    
});

How do I do logging in C# without using 3rd party libraries?

If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.

Div side by side without float

I am currently working on this, and i have already a number of solutions. It is nice to have a high quality site, that i can use also for my convenience. Because if you do not write these things down, you will eventually forget some parts. And i can also recommend writing some basic's down if you are starting any kind of new programming/design.

So if the float functions are causing problems there is a couple of options you can try.

One is modify the div alignment in the div tag it self like so <div class="kosher" align=left> If this does not suit you then there is another option with margin like so.

.leftdiv {
    display: inline-block;
    width: 40%;
    float: left;
}
.rightdiv {
    display: block;
    margin-right: 20px;
    margin-left: 45%;
}

Don't forget to remove the <div align=left>.

Get everything after the dash in a string in JavaScript

You can do it with built-in RegExp(pattern[, flags]) Factory Notation in js like this:

RegExp(/-(.*)/).exec("sometext-20202")[1]

in above code exec function will return an array with two elements (["-20202", "20202"]) one with hyphen(-20202) and one without hyphen(20202) , you should pick second element (index 1)

String replace method is not replacing characters

You aren't doing anything with the return value of replace. You'll need to assign the result of the method, which is the new String:

sentence = sentence.replace("and", " ");

A String is immutable in java. Methods like replace return a new String.

Your contains test is unnecessary: replace will just no-op if there aren't instances of the text to replace.

How to merge specific files from Git branches

If you only care about the conflict resolution and not about keeping the commit history, the following method should work. Say you want to merge a.py b.py from BRANCHA into BRANCHB. First, make sure any changes in BRANCHB are either committed or stashed away, and that there are no untracked files. Then:

git checkout BRANCHB
git merge BRANCHA
# 'Accept' all changes
git add .
# Clear staging area
git reset HEAD -- .
# Stash only the files you want to keep
git stash push a.py b.py
# Remove all other changes
git add .
git reset --hard
# Now, pull the changes
git stash pop

git won't recognize that there are conflicts in a.py b.py, but the merge conflict markers are there if there were in fact conflicts. Using a third-party merge tool, such as VSCode, one will be able to resolve conflicts more comfortably.

Remove ALL styling/formatting from hyperlinks

You can simply define a style for links, which would override a:hover, a:visited etc.:

a {
  color: blue;
  text-decoration: none; /* no underline */
}

You can also use the inherit value if you want to use attributes from parent styles instead:

body {
  color: blue;
}
a {
  color: inherit; /* blue colors for links too */
  text-decoration: inherit; /* no underline */
}

Why does this code using random strings print "hello world"?

Everyone here did a great job of explaining how the code works and showing how you can construct your own examples, but here's an information theoretical answer showing why we can reasonably expect a solution to exist that the brute force search will eventually find.

The 26 different lower-case letters form our alphabet S. To allow generating words of different lengths, we further add a terminator symbol ? to yield an extended alphabet S' := S ? {?}.

Let a be a symbol and X a uniformly distributed random variable over S'. The probability of obtaining that symbol, P(X = a), and its information content, I(a), are given by:

P(X = a) = 1/|S'| = 1/27

I(a) = -log2[P(X = a)] = -log2(1/27) = log2(27)

For a word ? ? S* and its ?-terminated counterpart ?' := ? · ? ? (S')*, we have

I(?) := I(?') = |?'| * log2(27) = (|?| + 1) * log2(27)

Since the Pseudorandom Number Generator (PRNG) is initialized with a 32-bit seed, we can expect most words of length up to

? = floor[32/log2(27)] - 1 = 5

to be generated by at least one seed. Even if we were to search for a 6-character word, we would still be successful about 41.06% of the time. Not too shabby.

For 7 letters we're looking at closer to 1.52%, but I hadn't realized that before giving it a try:

#include <iostream>
#include <random>
 
int main()
{
    std::mt19937 rng(631647094);
    std::uniform_int_distribution<char> dist('a', 'z' + 1);
 
    char alpha;
    while ((alpha = dist(rng)) != 'z' + 1)
    {
        std::cout << alpha;
    }
}

See the output: http://ideone.com/JRGb3l

AngularJS passing data to $http.get request

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

CONTROLLER:

public class AngularController : Controller
{
    public JsonResult GetFullName(string name, string surname)
    {
        System.Diagnostics.Debugger.Break();
        return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
    }
}

VIEW:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);

    myApp.controller('controller', function ($scope, $http) {

        $scope.GetFullName = function (employee) {

            //The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue

            $http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
            success(function (data, status, headers, config) {
                alert('Your full name is - ' + data.fullName);
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });

        }
    });

</script>

<div ng-app="app" ng-controller="controller">

    <input type="text" ng-model="name" />
    <input type="text" ng-model="surname" />
    <input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>

Java math function to convert positive int to negative and negative to positive?

No such function exists or is possible to write.

The problem is the edge case Integer.MIN_VALUE (-2,147,483,648 = 0x80000000) apply each of the three methods above and you get the same value out. This is due to the representation of integers and the maximum possible integer Integer.MAX_VALUE (-2,147,483,647 = 0x7fffffff) which is one less what -Integer.MIN_VALUE should be.

Apache won't run in xampp

There are 2 ways to solving this problem.

  1. If you want to run Apache in another port then:Replace in xampp/apache/conf/httpd.conf "ServerName localhost:80" by "ServerName localhost:81" At line 184. After that even it may not work.Then replace
#Listen 0.0.0.0:80
#Listen [::]:80
Listen 80 

by

#Listen 0.0.0.0:81
#Listen [::]:81
Listen 81

at line 45

  1. If you want to use port 80. Then follow this. In Windows 8 “World Wide Publishing Service is using this port and stopping this service will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop. If you don't find there then Then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.

If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80

enter image description here

And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.

How to apply CSS page-break to print a table with lots of rows?

this is working for me:

<td>
  <div class="avoid">
    Cell content.
  </div>
</td>
...
<style type="text/css">
  .avoid {
    page-break-inside: avoid !important;
    margin: 4px 0 4px 0;  /* to keep the page break from cutting too close to the text in the div */
  }
</style>

From this thread: avoid page break inside row of table

How to install a specific version of a ruby gem?

Linux

To install different version of ruby, check the latest version of package using apt as below:

$ apt-cache madison ruby
      ruby |    1:1.9.3 | http://ftp.uk.debian.org/debian/ wheezy/main amd64 Packages
      ruby |        4.5 | http://ftp.uk.debian.org/debian/ squeeze/main amd64 Packages

Then install it:

$ sudo apt-get install ruby=1:1.9.3

To check what's the current version, run:

$ gem --version # Check for the current user.
$ sudo gem --version # Check globally.

If the version is still old, you may try to switch the version to new by using ruby version manager (rvm) by:

rvm 1.9.3

Note: You may prefix it by sudo if rvm was installed globally. Or run /usr/local/rvm/scripts/rvm if your command rvm is not in your global PATH. If rvm installation process failed, see the troubleshooting section.


Troubleshooting:

  • If you still have the old version, you may try to install rvm (ruby version manager) via:

    sudo apt-get install curl # Install curl first
    curl -sSL https://get.rvm.io | bash -s stable --ruby # Install only for the user.
    #or:# curl -sSL https://get.rvm.io | sudo bash -s stable --ruby # Install globally. 
    

    then if installed locally (only for current user), load rvm via:

    source /usr/local/rvm/scripts/rvm; rvm 1.9.3
    

    if globally (for all users), then:

    sudo bash -c "source /usr/local/rvm/scripts/rvm; rvm 1.9.3"
    
  • if you still having problem with the new ruby version, try to install it by rvm via:

    source /usr/local/rvm/scripts/rvm && rvm install ruby-1.9.3 # Locally.
    sudo bash -c "source /usr/local/rvm/scripts/rvm && rvm install ruby-1.9.3" # Globally.
    
  • if you'd like to install some gems globally and you have rvm already installed, you may try:

    rvmsudo gem install [gemname]
    

    instead of:

      gem install [gemname] # or:
      sudo gem install [gemname]
    

Note: It's prefered to NOT use sudo to work with RVM gems. When you do sudo you are running commands as root, another user in another shell and hence all of the setup that RVM has done for you is ignored while the command runs under sudo (such things as GEM_HOME, etc...). So to reiterate, as soon as you 'sudo' you are running as the root system user which will clear out your environment as well as any files it creates are not able to be modified by your user and will result in strange things happening.

What is the difference between 'E', 'T', and '?' for Java generics?

compiler will make a capture for each wildcard (e.g., question mark in List) when it makes up a function like:

foo(List<?> list) {
    list.put(list.get()) // ERROR: capture and Object are not identical type.
}

However a generic type like V would be ok and making it a generic method:

<V>void foo(List<V> list) {
    list.put(list.get())
}

How to convert a PIL Image into a numpy array?

I am using Pillow 4.1.1 (the successor of PIL) in Python 3.5. The conversion between Pillow and numpy is straightforward.

from PIL import Image
import numpy as np
im = Image.open('1.jpg')
im2arr = np.array(im) # im2arr.shape: height x width x channel
arr2im = Image.fromarray(im2arr)

One thing that needs noticing is that Pillow-style im is column-major while numpy-style im2arr is row-major. However, the function Image.fromarray already takes this into consideration. That is, arr2im.size == im.size and arr2im.mode == im.mode in the above example.

We should take care of the HxWxC data format when processing the transformed numpy arrays, e.g. do the transform im2arr = np.rollaxis(im2arr, 2, 0) or im2arr = np.transpose(im2arr, (2, 0, 1)) into CxHxW format.

How to use __doPostBack()

Old question, but I'd like to add something: when calling doPostBack() you can use the server handler method for the action.

For an example:

__doPostBack('<%= btn.UniqueID%>', 'my args');

Will fire, on server:

protected void btn_Click(object sender, EventArgs e)

I didn't find a better way to get the argument, so I'm still using Request["__EVENTARGUMENT"].

How do I set a variable to the output of a command in Bash?

If you want to do it with multiline/multiple command/s then you can do this:

output=$( bash <<EOF
# Multiline/multiple command/s
EOF
)

Or:

output=$(
# Multiline/multiple command/s
)

Example:

#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"

Output:

first
second
third

Using heredoc, you can simplify things pretty easily by breaking down your long single line code into a multiline one. Another example:

output="$( ssh -p $port $user@$domain <<EOF
# Breakdown your long ssh command into multiline here.
EOF
)"

pdftk compression option

Trying to compress a PDF I made with 400ppi tiffs, mostly 8-bit, a few 24-bit, with PackBits compression, using tiff2pdf compressed with Zip/Deflate. One problem I had with every one of these methods: none of the above methods preserved the bookmarks TOC that I painstakingly manually created in Acrobat Pro X. Not even the recommended ebook setting for gs. Sure, I could just open a copy of the original with the TOC intact and do a Replace pages but unfortunately, none of these methods did a satisfactory job to begin with. Either they reduced the size so much that the quality was unacceptably pixellated, or they didn't reduce the size at all and in one case actually increased it despite quality loss.

pdftk compress:

no change in size
bookmarks TOC are gone

gs screen:

takes a ridiculously long time and 100% CPU
errors:
    sfopen: gs_parse_file_name failed.                                 ? 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->10.2MB hideously pixellated
bookmarks TOC are gone

gs printer:

takes a ridiculously long time and 100% CPU
no errors
74.8MB-->66.1MB
light blue background on pages 1-4
bookmarks TOC are gone

gs ebook:

errors:
    sfopen: gs_parse_file_name failed.
      ./base/gsicc_manage.c:1050: gsicc_open_search(): Could not find default_rgb.ic 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->32.2MB
badly pixellated
bookmarks TOC are gone

qpdf --linearize:

very fast, a few seconds
no size change
bookmarks TOC are gone

pdf2ps:

took very long time
output_pdf2ps.ps 74.8MB-->331.6MB

ps2pdf:

pretty fast
74.8MB-->79MB
very slightly degraded with sl. bluish background
bookmarks TOC are gone

How can I scan barcodes on iOS?

The problem with iPhone camera is that the first models (of which there are tons in use) have a fixed-focus camera that cannot take picture in-focus for distances under 2ft. The images are blurry and distorted and if taken from greater distance there is not enough detail/information from the barcode.

A few companies have developed iPhone apps that can accomodate for that by using advanced de-blurring technologies. Those applications you can find on Apple app store: pic2shop, RedLaser and ShopSavvy. All of the companies have announced that they have also SDKs available - some for free or very preferential terms, check that one out.

SQL Query with Join, Count and Where

You have to use GROUP BY so you will have multiple records returned,

SELECT  COUNT(*) TotalCount, 
        b.category_id, 
        b.category_name 
FROM    table1 a
        INNER JOIN table2 b
            ON a.category_id = b.category_id 
WHERE   a.colour <> 'red'
GROUP   BY b.category_id, b.category_name

MVC Form not able to post List of objects

Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId, planCompareViewModel[1].PlanId to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model) use for loop and render names with indexes.

How to get index of object by its property in JavaScript?

Why don't you use a small work-around?

Create a new array with names as indexes. after that all searches will use indexes. So, only one loop. After that you don't need to loop through all elements!

var Data = [
    {id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
    ]
var searchArr = []
Data.forEach(function(one){
  searchArr[one.name]=one;
})
console.log(searchArr['Nick'])

http://jsbin.com/xibala/1/edit

live example.

Plot a legend outside of the plotting area in base graphics?

I like to do it like this:

par(oma=c(0, 0, 0, 5))
plot(1:3, rnorm(3), pch=1, lty=1, type="o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch=2, lty=2, type="o")
legend(par('usr')[2], par('usr')[4], bty='n', xpd=NA,
       c("group A", "group B"), pch=c(1, 2), lty=c(1,2))

enter image description here

The only tweaking required is in setting the right margin to be wide enough to accommodate the legend.

However, this can also be automated:

dev.off() # to reset the graphics pars to defaults
par(mar=c(par('mar')[1:3], 0)) # optional, removes extraneous right inner margin space
plot.new()
l <- legend(0, 0, bty='n', c("group A", "group B"), 
            plot=FALSE, pch=c(1, 2), lty=c(1, 2))
# calculate right margin width in ndc
w <- grconvertX(l$rect$w, to='ndc') - grconvertX(0, to='ndc')
par(omd=c(0, 1-w, 0, 1))
plot(1:3, rnorm(3), pch=1, lty=1, type="o", ylim=c(-2, 2))
lines(1:3, rnorm(3), pch=2, lty=2, type="o")
legend(par('usr')[2], par('usr')[4], bty='n', xpd=NA,
       c("group A", "group B"), pch=c(1, 2), lty=c(1, 2))

enter image description here

How to measure time elapsed on Javascript?

var seconds = 0;
setInterval(function () {
  seconds++;
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

How do I use the new computeIfAbsent function?

Another example. When building a complex map of maps, the computeIfAbsent() method is a replacement for map's get() method. Through chaining of computeIfAbsent() calls together, missing containers are constructed on-the-fly by provided lambda expressions:

  // Stores regional movie ratings
  Map<String, Map<Integer, Set<String>>> regionalMovieRatings = new TreeMap<>();

  // This will throw NullPointerException!
  regionalMovieRatings.get("New York").get(5).add("Boyhood");

  // This will work
  regionalMovieRatings
    .computeIfAbsent("New York", region -> new TreeMap<>())
    .computeIfAbsent(5, rating -> new TreeSet<>())
    .add("Boyhood");

How to randomize (or permute) a dataframe rowwise and columnwise?

Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations

How to determine the current language of a wordpress page when using polylang?

Simple:

if(pll_current_language() == 'en'){
   //do your work here
}

The view or its master was not found or no view engine supports the searched locations

I got this error because I renamed my View (and POST action).

Finally I found that I forgot to rename BOTH GET and POST actions to new name.

Solution : Rename both GET and POST actions to match the View name.

How do I get the current timezone name in Postgres 9.3?

This may or may not help you address your problem, OP, but to get the timezone of the current server relative to UTC (UT1, technically), do:

SELECT EXTRACT(TIMEZONE FROM now())/3600.0;

The above works by extracting the UT1-relative offset in minutes, and then converting it to hours using the factor of 3600 secs/hour.

Example:

SET SESSION timezone TO 'Asia/Kabul';
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
-- output: 4.5 (as of the writing of this post)

(docs).

How can I check file size in Python?

The other answers work for real files, but if you need something that works for "file-like objects", try this:

# f is a file-like object. 
f.seek(0, os.SEEK_END)
size = f.tell()

It works for real files and StringIO's, in my limited testing. (Python 2.7.3.) The "file-like object" API isn't really a rigorous interface, of course, but the API documentation suggests that file-like objects should support seek() and tell().

Edit

Another difference between this and os.stat() is that you can stat() a file even if you don't have permission to read it. Obviously the seek/tell approach won't work unless you have read permission.

Edit 2

At Jonathon's suggestion, here's a paranoid version. (The version above leaves the file pointer at the end of the file, so if you were to try to read from the file, you'd get zero bytes back!)

# f is a file-like object. 
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)

What is setup.py?

setup.py is a Python file like any other. It can take any name, except by convention it is named setup.py so that there is not a different procedure with each script.

Most frequently setup.py is used to install a Python module but server other purposes:

Modules:

Perhaps this is most famous usage of setup.py is in modules. Although they can be installed using pip, old Python versions did not include pip by default and they needed to be installed separately.

If you wanted to install a module but did not want to install pip, just about the only alternative was to install the module from setup.py file. This could be achieved via python setup.py install. This would install the Python module to the root dictionary (without pip, easy_install ect).

This method is often used when pip will fail. For example if the correct Python version of the desired package is not available via pipperhaps because it is no longer maintained, , downloading the source and running python setup.py install would perform the same thing, except in the case of compiled binaries are required, (but will disregard the Python version -unless an error is returned).

Another use of setup.py is to install a package from source. If a module is still under development the wheel files will not be available and the only way to install is to install from the source directly.

Building Python extensions:

When a module has been built it can be converted into module ready for distribution using a distutils setup script. Once built these can be installed using the command above.

A setup script is easy to build and once the file has been properly configured and can be compiled by running python setup.py build (see link for all commands).

Once again it is named setup.py for ease of use and by convention, but can take any name.

Cython:

Another famous use of setup.py files include compiled extensions. These require a setup script with user defined values. They allow fast (but once compiled are platform dependant) execution. Here is a simple example from the documentation:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    name = 'Hello world app',
    ext_modules = cythonize("hello.pyx"),
)

This can be compiled via python setup.py build

Cx_Freeze:

Another module requiring a setup script is cx_Freeze. This converts Python script to executables. This allows many commands such as descriptions, names, icons, packages to include, exclude ect and once run will produce a distributable application. An example from the documentation:

import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]} 

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "guifoo",
        version = "0.1",
        description = "My GUI application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("guifoo.py", base=base)])

This can be compiled via python setup.py build.

So what is a setup.py file?

Quite simply it is a script that builds or configures something in the Python environment.

A package when distributed should contain only one setup script but it is not uncommon to combine several together into a single setup script. Notice this often involves distutils but not always (as I showed in my last example). The thing to remember it just configures Python package/script in some way.

It takes the name so the same command can always be used when building or installing.

Enter export password to generate a P12 certificate

I know this thread has been idle for a while, but I just wanted to add my two cents to supplement jariq's comment...

Per manual, you don't necessary want to use -password option.

Let's say mykey.key has a password and your want to protect iphone-dev.p12 with another password, this is what you'd use:

pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -passin pass:password_for_mykey -passout pass:password_for_iphone_dev

Have fun scripting!!

What is the difference between 'java', 'javaw', and 'javaws'?

java.exe is associated with the console, whereas javaw.exe doesn't have any such association. So, when java.exe is run, it automatically opens a command prompt window where output and error streams are shown.

ASP.NET MVC get textbox input value

Try This.

View:

@using (Html.BeginForm("Login", "Accounts", FormMethod.Post)) 
{
   <input type="text" name="IP" id="IP" />
   <input type="text" name="Name" id="Name" />

   <input type="submit" value="Login" />
}

Controller:

[HttpPost]
public ActionResult Login(string IP, string Name)
{
    string s1=IP;//
    string s2=Name;//
}

If you can use model class

[HttpPost]
public ActionResult Login(ModelClassName obj)
{
    string s1=obj.IP;//
    string s2=obj.Name;//
}

How can I get a list of repositories 'apt-get' is checking?

As far as I know, you can't ask apt for what their current sources are. However, you can do what you want using shell tools.

Getting a list of repositories:

grep -h ^deb /etc/apt/sources.list /etc/apt/sources.list.d/* >> current.repos.list

Applying the list:

apt-add-repository << current.repos.list

Regarding getting the repository from a package (installed or available), this will do the trick:

apt-cache policy package_name | grep -m1 http | awk '{ print $2 " " $3 }'

However, that will show you the repository of the latest version available of that package, and you may have more repositories for the same package with older versions. Remove all the grep/awk stuff if you want to see the full list.

how to calculate percentage in python

I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"

Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...

I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.

#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

Here you can test the code and experiment with it.

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

How can I make a multipart/form-data POST request using Java?

We use HttpClient 4.x to make multipart file post.

UPDATE: As of HttpClient 4.3, some classes have been deprecated. Here is the code with new API:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

// This attaches the file to the POST:
File f = new File("[/path/to/upload]");
builder.addBinaryBody(
    "file",
    new FileInputStream(f),
    ContentType.APPLICATION_OCTET_STREAM,
    f.getName()
);

HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();

Below is the original snippet of code with deprecated HttpClient 4.0 API:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

Closing WebSocket correctly (HTML5, Javascript)

As mentioned by theoobe, some browsers do not close the websockets automatically. Don't try to handle any "close browser window" events client-side. There is currently no reliable way to do it, if you consider support of major desktop AND mobile browsers (e.g. onbeforeunload will not work in Mobile Safari). I had good experience with handling this problem server-side. E.g. if you use Java EE, take a look at javax.websocket.Endpoint, depending on the browser either the OnClose method or the OnError method will be called if you close/reload the browser window.

Calling another different view from the controller using ASP.NET MVC 4

You can directly return a different view like:

return View("NameOfView", Model);

Or you can make a partial view and can return like:

return PartialView("PartialViewName", Model);

Regular expression to get a string between two strings in Javascript

I find regex to be tedious and time consuming given the syntax. Since you are already using javascript it is easier to do the following without regex:

const text = 'My cow always gives milk'
const start = `cow`;
const end = `milk`;
const middleText = text.split(start)[1].split(end)[0]
console.log(middleText) // prints "always gives"

How to create a listbox in HTML without allowing multiple selection?

For Asp.Net MVC

@Html.ListBox("parameterName", ViewBag.ParameterValueList as MultiSelectList, 
 new { 
 @class = "chosen-select form-control"
 }) 

or

  @Html.ListBoxFor(model => model.parameterName,
  ViewBag.ParameterValueList as MultiSelectList,
   new{
       data_placeholder = "Select Options ",
       @class = "chosen-select form-control"
   })

Howto: Clean a mysql InnoDB storage engine?

Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.

Keep in mind that /var/lib/mysql/ibdata1 is the busiest file in the InnoDB infrastructure. It normally houses six types of information:

InnoDB Architecture

InnoDB Architecture

Many people create multiple ibdata files hoping for better disk-space management and performance, however that belief is mistaken.

Can I run OPTIMIZE TABLE ?

Unfortunately, running OPTIMIZE TABLE against an InnoDB table stored in the shared table-space file ibdata1 does two things:

  • Makes the table’s data and indexes contiguous inside ibdata1
  • Makes ibdata1 grow because the contiguous data and index pages are appended to ibdata1

You can however, segregate Table Data and Table Indexes from ibdata1 and manage them independently.

Can I run OPTIMIZE TABLE with innodb_file_per_table ?

Suppose you were to add innodb_file_per_table to /etc/my.cnf (my.ini). Can you then just run OPTIMIZE TABLE on all the InnoDB Tables?

Good News : When you run OPTIMIZE TABLE with innodb_file_per_table enabled, this will produce a .ibd file for that table. For example, if you have table mydb.mytable witha datadir of /var/lib/mysql, it will produce the following:

  • /var/lib/mysql/mydb/mytable.frm
  • /var/lib/mysql/mydb/mytable.ibd

The .ibd will contain the Data Pages and Index Pages for that table. Great.

Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable from living in ibdata. The data dictionary entry for every table, including mydb.mytable, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1 AT THIS POINT !!! Please note that ibdata1 has not shrunk at all.

InnoDB Infrastructure Cleanup

To shrink ibdata1 once and for all you must do the following:

  1. Dump (e.g., with mysqldump) all databases into a .sql text file (SQLData.sql is used below)

  2. Drop all databases (except for mysql and information_schema) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:

    mkdir /var/lib/mysql_grants
    cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
    chown -R mysql:mysql /var/lib/mysql_grants
    
  3. Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0; (This will completely flush all remaining transactional changes from ib_logfile0 and ib_logfile1)

  4. Shutdown MySQL

  5. Add the following lines to /etc/my.cnf (or my.ini on Windows)

    [mysqld]
    innodb_file_per_table
    innodb_flush_method=O_DIRECT
    innodb_log_file_size=1G
    innodb_buffer_pool_size=4G
    

    (Sidenote: Whatever your set for innodb_buffer_pool_size, make sure innodb_log_file_size is 25% of innodb_buffer_pool_size.

    Also: innodb_flush_method=O_DIRECT is not available on Windows)

  6. Delete ibdata* and ib_logfile*, Optionally, you can remove all folders in /var/lib/mysql, except /var/lib/mysql/mysql.

  7. Start MySQL (This will recreate ibdata1 [10MB by default] and ib_logfile0 and ib_logfile1 at 1G each).

  8. Import SQLData.sql

Now, ibdata1 will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1. ibdata1 will no longer contain InnoDB data and indexes for other tables.

For example, suppose you have an InnoDB table named mydb.mytable. If you look in /var/lib/mysql/mydb, you will see two files representing the table:

  • mytable.frm (Storage Engine Header)
  • mytable.ibd (Table Data and Indexes)

With the innodb_file_per_table option in /etc/my.cnf, you can run OPTIMIZE TABLE mydb.mytable and the file /var/lib/mysql/mydb/mytable.ibd will actually shrink.

I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1 file down to only 500MB!

Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.

CAVEAT

At Step 6, if mysql cannot restart because of the mysql schema begin dropped, look back at Step 2. You made the physical copy of the mysql schema. You can restore it as follows:

mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql

Go back to Step 6 and continue

UPDATE 2013-06-04 11:13 EDT

With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.

Back on July 03, 2006, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.

I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.

Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.

Java: Finding the highest value in an array

You can use a function that accepts a array and finds the max value in it. i made it generic so it could also accept other data types

public static <T extends Comparable<T>> T findMax(T[] array){       
    T max = array[0];
    for(T data: array){
        if(data.compareTo(max)>0)
            max =data;                
    }
    return max;
}

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

If the list of conditions is not known at compile time and is instead built at run time, you don't have to worry about whether you have one or more than one condition. You can generate them all like:

and <condition>

and concatenate them all together. With the 1=1 at the start, the initial and has something to associate with.

I've never seen this used for any kind of injection protection, as you say it doesn't seem like it would help much. I have seen it used as an implementation convenience. The SQL query engine will end up ignoring the 1=1 so it should have no performance impact.

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

I encountered a similar problem when I was trying to connect my Django application to PostgreSQL database.

I wrote my Dockerfile with instructions to setup the Django project followed by instructions to install PostgreSQL and run Django server in my docker-compose.yml.

I defined two services in my docker-compose-yml.

services:
  postgres:
    image: "postgres:latest"
    environment:
      - POSTGRES_DB=abc
      - POSTGRES_USER=abc
      - POSTGRES_PASSWORD=abc
    volumes:
      - pg_data:/var/lib/postgresql/data/
  django:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8004
    volumes:
      - .:/app
    ports:
      - 8004:8004
    depends_on:
      - postgres 

Unfortunately whenever I used to run docker-compose up then same err. used to pop up.

And this is how my database was defined in Django settings.py.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'abc',
        'USER': 'abc',
        'PASSWORD': 'abc',
        'HOST': '127.0.0.1',
        'PORT': '5432',
        'OPTIONS': {
            'client_encoding': 'UTF8',
        },
    }
} 

So, In the end I made use of docker-compose networking which means if I change the host of my database to postgres which is defined as a service in docker-compose.yml will do the wonders.

So, Replacing 'HOST': '127.0.0.1' => 'HOST': 'postgres' did wonders for me.

After replacement this is how your Database config in settings.py will look like.

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'abc',
            'USER': 'abc',
            'PASSWORD': 'abc',
            'HOST': 'postgres',
            'PORT': '5432',
            'OPTIONS': {
                'client_encoding': 'UTF8',
            },
        }
    } 

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

SSSSSS is microseconds. Let us say the time is 10:30:22 (Seconds 22) and 10:30:22.1 would be 22 seconds and 1/10 of a second . Extending the same logic , 10:32.22.000132 would be 22 seconds and 132/1,000,000 of a second, which is nothing but microseconds.

Error when using scp command "bash: scp: command not found"

Make sure the scp command is available on both sides - both on the client and on the server.

If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:

    yum -y install openssh-clients

If you work with Debian or Ubuntu and clones, install this package:

    apt-get install openssh-client

Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found or similar although you have it locally. This already confused thousands of people, I guess :)

How can I read user input from the console?

Sometime in the future .NET4.6

//for Double
double inputValues = double.Parse(Console.ReadLine());

//for Int
int inputValues = int.Parse(Console.ReadLine());

How do I remove packages installed with Python's easy_install?

try

$ easy_install -m [PACKAGE]

then

$ rm -rf .../python2.X/site-packages/[PACKAGE].egg

XPath selecting a node with some attribute value equals to some other node's attribute value

I think this is what you want:

/grand/parent/child[@id="#grand"]