Programs & Examples On #Sharepoint listtemplate

selenium get current url after loading a page

Page 2 is in a new tab/window ? If it's this, use the code bellow :

try {

    String winHandleBefore = driver.getWindowHandle();

    for(String winHandle : driver.getWindowHandles()){
        driver.switchTo().window(winHandle);
        String act = driver.getCurrentUrl();
    }
    }catch(Exception e){
   System.out.println("fail");
    }

Subset data to contain only columns whose names match a condition

This worked for me:

df[,names(df) %in% colnames(df)[grepl(str,colnames(df))]]

How to format numbers?

                function formatThousands(n,dp,f) {
                    // dp - decimal places
                    // f - format >> 'us', 'eu'
                    if (n == 0) {
                        if(f == 'eu') {
                            return "0," + "0".repeat(dp);   
                        }
                        return "0." + "0".repeat(dp);
                    }

                    /* round to 2 decimal places */
                    //n = Math.round( n * 100 ) / 100;
                    var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
                    while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
                    var a = s.substr(0, i + 3) + r + (d ? '.' + Math.round((d+1) * Math.pow(10,dp)).toString().substr(1,dp) : '');
                    /* change format from 20,000.00 to 20.000,00 */
                    if (f == 'eu') {
                        var b = a.toString().replace(".", "#");
                        b = b.replace(",", ".");
                        return b.replace("#", ",");
                    }                   
                    return a;
                }

How to return a part of an array in Ruby?

I like ranges for this:

def first_half(list)
  list[0...(list.length / 2)]
end

def last_half(list)
  list[(list.length / 2)..list.length]
end

However, be very careful about whether the endpoint is included in your range. This becomes critical on an odd-length list where you need to choose where you're going to break the middle. Otherwise you'll end up double-counting the middle element.

The above example will consistently put the middle element in the last half.

how to convert a string to a bool

If you want to test if a string is a valid Boolean without any thrown exceptions you can try this :

    string stringToBool1 = "true";
    string stringToBool2 = "1";
    bool value1;
    if(bool.TryParse(stringToBool1, out value1))
    {
        MessageBox.Show(stringToBool1 + " is Boolean");
    }
    else
    {
        MessageBox.Show(stringToBool1 + " is not Boolean");
    }

outputis Boolean and the output for stringToBool2 is : 'is not Boolean'

Calculate summary statistics of columns in dataframe

describe may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once

In [43]:

df.describe()

Out[43]:

       shopper_num is_martian  number_of_items  count_pineapples
count      14.0000         14        14.000000                14
mean        7.5000          0         3.357143                 0
std         4.1833          0         6.452276                 0
min         1.0000      False         0.000000                 0
25%         4.2500          0         0.000000                 0
50%         7.5000          0         0.000000                 0
75%        10.7500          0         3.500000                 0
max        14.0000      False        22.000000                 0

[8 rows x 4 columns]

Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data

As you prefer you can transpose the result if you prefer:

In [47]:

df.describe().transpose()

Out[47]:

                 count      mean       std    min   25%  50%    75%    max
shopper_num         14       7.5    4.1833      1  4.25  7.5  10.75     14
is_martian          14         0         0  False     0    0      0  False
number_of_items     14  3.357143  6.452276      0     0    0    3.5     22
count_pineapples    14         0         0      0     0    0      0      0

[4 rows x 8 columns]

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

This might be a bit like beating a dead horse here.. but, my currently implemented solution on DIY modals via vanilla JS:

On modal show:

if (document.body.style.position !== 'fixed') {
    document.body.style.top = -window.scrollY + 'px';
    document.body.style.position = 'fixed';
}

On modal hide:

document.body.style.position = '';
window.scrollTo(0, -parseInt(document.body.style.top, 10));
document.body.style.top = '';

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

How to move text up using CSS when nothing is working

footerText {
    line-height: 20px;
}

you don't need to start playing with position or even layout of other elements... use this simple solution

Stop Chrome Caching My JS Files

You can click the settings icon on top right corner ... | More Tools | Developer Tools | Network | Disable cache (while DevTools is open)

For windows, this is F12 or CTRL + SHIFT + I while on mac CMD + SHIFT + I opens up DevTools.

New path for Chrome Update Sept 2018:

Click settings icon on the top right corner ... | Settings | Preferences | Developer Tools | Network | Disable cache (while DevTools is open)

How to send value attribute from radio button in PHP

When you select a radio button and click on a submit button, you need to handle the submission of any selected values in your php code using $_POST[]
For example:
if your radio button is:

<input type="radio" name="rdb" value="male"/>

then in your php code you need to use:

$rdb_value = $_POST['rdb'];

How do I get the current time only in JavaScript

Assign to variables and display it.

time = new Date();

var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds() 

document.getElementById("time").value = hh + ":" + mm + ":" + ss;

Use jQuery to navigate away from page

Other answers rightly point out that there is no need to use jQuery in order to navigate to another URL; that's why there's no jQuery function which does so!

If you're asking how to click a link via jQuery then assuming you have markup which looks like:

<a id="my-link" href="/relative/path.html">Click Me!</a>

You could click() it by executing:

$('#my-link').click();

Including external jar-files in a new jar-file build with Ant

I'm using NetBeans and needed a solution for this also. After googleling around and starting from Christopher's answer i managed to build a script that helps you easily do this in NetBeans. I'm putting the instructions here in case someone else will need them.

What you have to do is download one-jar. You can use the link from here: http://one-jar.sourceforge.net/index.php?page=getting-started&file=ant Extract the jar archive and look for one-jar\dist folder that contains one-jar-ant-task-.jar, one-jar-ant-task.xml and one-jar-boot-.jar. Extract them or copy them to a path that we will add to the script below, as the value of the property one-jar.dist.dir.

Just copy the following script at the end of your build.xml script (from your NetBeans project), just before /project tag, replace the value for one-jar.dist.dir with the correct path and run one-jar target.

For those of you that are unfamiliar with running targets, this tutorial might help: http://www.oracle.com/technetwork/articles/javase/index-139904.html . It also shows you how to place sources into one jar, but they are exploded, not compressed into jars.

<property name="one-jar.dist.dir" value="path\to\one-jar-ant"/>
<import file="${one-jar.dist.dir}/one-jar-ant-task.xml" optional="true" />

<target name="one-jar" depends="jar">
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<property name="src.dir"          value="src"/>
<property name="bin.dir"          value="bin"/>
<property name="build.dir"        value="build"/>
<property name="dist.dir"         value="dist"/>
<property name="external.lib.dir" value="${dist.dir}/lib"/>
<property name="classes.dir"      value="${build.dir}/classes"/>
<property name="jar.target.dir"   value="${build.dir}/jars"/>
<property name="final.jar"        value="${dist.dir}/${ant.project.name}.jar"/>
<property name="main.class"       value="${main.class}"/>

<path id="project.classpath">
    <fileset dir="${external.lib.dir}">
        <include name="*.jar"/>
    </fileset>
</path>

<mkdir dir="${bin.dir}"/>
<!-- <mkdir dir="${build.dir}"/> -->
<!-- <mkdir dir="${classes.dir}"/> -->
<mkdir dir="${jar.target.dir}"/>
<copy includeemptydirs="false" todir="${classes.dir}">
    <fileset dir="${src.dir}">
        <exclude name="**/*.launch"/>
        <exclude name="**/*.java"/>
    </fileset>
</copy>

<!-- <echo message="${ant.project.name}: ${ant.file}"/> -->
<javac debug="true" debuglevel="${debuglevel}" destdir="${classes.dir}" source="${source}" target="${target}">
    <src path="${src.dir}"/>
    <classpath refid="project.classpath"/>   
</javac>

<delete file="${final.jar}" />
<one-jar destfile="${final.jar}" onejarmainclass="${main.class}">
    <main>
        <fileset dir="${classes.dir}"/>
    </main>
    <lib>
        <fileset dir="${external.lib.dir}" />
    </lib>
</one-jar>

<delete dir="${jar.target.dir}"/>
<delete dir="${bin.dir}"/>
<delete dir="${external.lib.dir}"/>

</target>

Best of luck and don't forget to vote up if it helped you.

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

How to write some data to excel file(.xlsx)

Hope here is the exact what we are looking for.

private void button2_Click(object sender, RoutedEventArgs e)
{
    UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}

private void UpdateExcel(string sheetName, int row, int col, string data)
{
    Microsoft.Office.Interop.Excel.Application oXL = null;
    Microsoft.Office.Interop.Excel._Workbook oWB = null;
    Microsoft.Office.Interop.Excel._Worksheet oSheet = null;

    try
    {
        oXL = new Microsoft.Office.Interop.Excel.Application();
        oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
        oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];

        oSheet.Cells[row, col] = data;

        oWB.Save();

        MessageBox.Show("Done!");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        if (oWB != null)
        oWB.Close();
    }
}

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Using ExcelDataReader to read Excel data starting from a particular cell

Very easy with ExcelReaderFactory 3.1 and up:

using (var openFileDialog1 = new OpenFileDialog { Filter = "Excel Workbook|*.xls;*.xlsx;*.xlsm", ValidateNames = true })
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        var fs = File.Open(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
        var reader = ExcelReaderFactory.CreateBinaryReader(fs);
        var dataSet = reader.AsDataSet(new ExcelDataSetConfiguration
        {
            ConfigureDataTable = _ => new ExcelDataTableConfiguration
            {
                UseHeaderRow = true // Use first row is ColumnName here :D
            }
        });
        if (dataSet.Tables.Count > 0)
        {
            var dtData = dataSet.Tables[0];
            // Do Something
        }
    }
}

What does this GCC error "... relocation truncated to fit..." mean?

I ran into this problem while building a program that requires a huge amount of stack space (over 2 GiB). The solution was to add the flag -mcmodel=medium, which is supported by both GCC and Intel compilers.

Run a single test method with maven

Running a set of methods in a Single Test Class With version 2.7.3, you can run only n tests in a single Test Class.

NOTE : it's supported for junit 4.x and TestNG.

You must use the following syntax

mvn -Dtest=TestCircle#mytest test

You can use patterns too

mvn -Dtest=TestCircle#test* test

As of surefire 2.12.1, you can select multiple methods (JUnit4X only at this time, patches welcome)

mvn -Dtest=TestCircle#testOne+testTwo test

Check this link about single tests

How to merge multiple dicts with same key or different key?

This function merges two dicts even if the keys in the two dictionaries are different:

def combine_dict(d1, d2):
    combined = {}
    for k in set(d1.keys()) | set(d2.keys()):
        combined[k] = tuple(d[k] for d in [d1, d2] if k in d)
    return combined

Example:

d1 = {
    'a': 1,
    'b': 2,
}
d2` = {
    'b': 'boat',
    'c': 'car',
}
combine_dict(d1, d2)
# Returns: {
#    'a': (1,),
#    'b': (2, 'boat'),
#    'c': ('car',)
# }

Double border with different color

Use of pseudo-element as suggested by Terry has one PRO and one CON:

  1. PRO - great cross-browser compatibility because pseudo-element are supported also on older IE.
  2. CON - it requires to create an extra (even if generated) element, that infact is defined pseudo-element.

Anyway is a great solution.


OTHER SOLUTIONS:

If you can accept compatibility since IE9 (IE8 does not have support for this), you can achieve desired result in other two possible ways:

  1. using outline property combined with border and a single inset box-shadow
  2. using two box-shadow combined with border.

Here a jsFiddle with Terry's modified code that shows, side by side, these other possible solutions. Main specific properties for each one are the following (others are shared in .double-border class):

.left
{
  outline: 4px solid #fff;
  box-shadow:inset 0 0 0 4px #fff;
}

.right
{
  box-shadow:0 0 0 4px #fff, inset 0 0 0 4px #fff;
}

LESS code:

You asked for possible advantages about using a pre-processor like LESS. I this specific case, utility is not so great, but anyway you could optimize something, declaring colors and border/ouline/shadow with @variable.

Here an example of my CSS code, declared in LESS (changing colors and border-width becomes very quick):

@double-border-size:4px;
@inset-border-color:#fff;
@content-color:#ccc;

.double-border 
{
  background-color: @content-color;
  border: @double-border-size solid @content-color;
  padding: 2em;
  width: 16em;
  height: 16em;
  float:left;
  margin-right:20px;
  text-align:center;
}

.left
{
  outline: @double-border-size solid @inset-border-color;
  box-shadow:inset 0 0 0 @double-border-size @inset-border-color;
}

.right
{
  box-shadow:0 0 0 @double-border-size @inset-border-color, inset 0 0 0 @double-border-size @inset-border-color;
}

Eloquent - where not equal to

Or like this:

Code::whereNotIn('to_be_used_by_user_id', [2])->get();

Share data between html pages

I know this is an old post, but figured I'd share my two cents. @Neji is correct in that you can use sessionStorage.getItem('label'), and sessionStorage.setItem('label', 'value') (although he had the setItem parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:

var val = sessionStorage.myValue

in place of getItem and

sessionStorage.myValue = 'value'

in place of setItem.

Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:

sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object

The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject all you get is [object Object], which doesn't help you too much.

Nested JSON: How to add (push) new items to an object?

You can achieve this using Lodash _.assign function.

library[title] = _.assign({}, {'foregrounds': foregrounds }, {'backgrounds': backgrounds });

_x000D_
_x000D_
// This is my JSON object generated from a database_x000D_
var library = {_x000D_
  "Gold Rush": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["1.jpg", "", "2.jpg"]_x000D_
  },_x000D_
  "California": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["3.jpg", "4.jpg", "5.jpg"]_x000D_
  }_x000D_
}_x000D_
_x000D_
// These will be dynamically generated vars from editor_x000D_
var title = "Gold Rush";_x000D_
var foregrounds = ["Howdy", "Slide 2"];_x000D_
var backgrounds = ["1.jpg", ""];_x000D_
_x000D_
function save() {_x000D_
_x000D_
  // If title already exists, modify item_x000D_
  if (library[title]) {_x000D_
_x000D_
    // override one Object with the values of another (lodash)_x000D_
    library[title] = _.assign({}, {_x000D_
      'foregrounds': foregrounds_x000D_
    }, {_x000D_
      'backgrounds': backgrounds_x000D_
    });_x000D_
    console.log(library[title]);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    // console.log('Changes Saved to <b>' + title + '</b>');_x000D_
  }_x000D_
_x000D_
  // If title does not exist, add new item_x000D_
  else {_x000D_
    // Format it for the JSON object_x000D_
    var item = ('"' + title + '" : {"foregrounds" : ' + foregrounds + ',"backgrounds" : ' + backgrounds + '}');_x000D_
_x000D_
    // THE PROBLEM SEEMS TO BE HERE??_x000D_
    // Error: "Result of expression 'library.push' [undefined] is not a function"_x000D_
    library.push(item);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    console.log('Added: <b>' + title + '</b>');_x000D_
  }_x000D_
}_x000D_
_x000D_
save();
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

What is lexical scope?

A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.

This concept is heavily used in closures in JavaScript.

Let's say we have the below code.

var x = 2;
var add = function() {
    var y = 1;
    return x + y;
};

Now, when you call add() --> this will print 3.

So, the add() function is accessing the global variable x which is defined before method function add. This is called due to lexical scoping in JavaScript.

Height equal to dynamic width (CSS fluid layout)

Using jQuery you can achieve this by doing

var cw = $('.child').width();
$('.child').css({'height':cw+'px'});

Check working example at http://jsfiddle.net/n6DAu/1/

Renaming part of a filename

All of these answers are simple and good. However, I always like to add an interactive mode to these scripts so that I can find false positives.

if [[ -n $inInteractiveMode ]]
then
  echo -e -n "$oldFileName => $newFileName\nDo you want to do this change? [Y/n]: "
  read run

  [[ -z $run || "$run" == "y" || "$run" == "Y" ]] && mv "$oldFileName" "$newFileName"
fi

Or make interactive mode the default and add a force flag (-f | --force) for automated scripts or if you're feeling daring. And this doesn't slow you down too much: the default response is "yes, I do want to rename" so you can just hit the enter key at each prompt (because of the ``-z $run\ test.

How to check if IsNumeric

You could write an extension method:

public static class Extension
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

Transition color fade on hover?

What do you want to fade? The background or color attribute?

Currently you're changing the background color, but telling it to transition the color property. You can use all to transition all properties.

.clicker { 
    -moz-transition: all .2s ease-in;
    -o-transition: all .2s ease-in;
    -webkit-transition: all .2s ease-in;
    transition: all .2s ease-in;
    background: #f5f5f5; 
    padding: 20px;
}

.clicker:hover { 
    background: #eee;
}

Otherwise just use transition: background .2s ease-in.

Select a date from date picker using Selenium webdriver

I tried this code, it may work for you also:

            DateFormat dateFormat2 = new SimpleDateFormat("dd"); 
            Date date2 = new Date();

            String today = dateFormat2.format(date2); 

            //find the calendar
            WebElement dateWidget = driver.findElement(By.id("dp-calendar"));  
            List<WebElement> columns=dateWidget.findElements(By.tagName("td"));  

            //comparing the text of cell with today's date and clicking it.
            for (WebElement cell : columns)
            {
               if (cell.getText().equals(today))
               {
                  cell.click();
                  break;
               }
            }

Verify object attribute value with mockito

One more possibility, if you don't want to use ArgumentCaptor (for example, because you're also using stubbing), is to use Hamcrest Matchers in combination with Mockito.

import org.mockito.Mockito
import org.hamcrest.Matchers
...

Mockito.verify(mockedObject).someMethodOnMockedObject(MockitoHamcrest.argThat(
    Matchers.<SomeObjectAsArgument>hasProperty("propertyName", desiredValue)));

Git submodule update

To address the --rebase vs. --merge option:

Let's say you have super repository A and submodule B and want to do some work in submodule B. You've done your homework and know that after calling

git submodule update

you are in a HEAD-less state, so any commits you do at this point are hard to get back to. So, you've started work on a new branch in submodule B

cd B
git checkout -b bestIdeaForBEver
<do work>

Meanwhile, someone else in project A has decided that the latest and greatest version of B is really what A deserves. You, out of habit, merge the most recent changes down and update your submodules.

<in A>
git merge develop
git submodule update

Oh noes! You're back in a headless state again, probably because B is now pointing to the SHA associated with B's new tip, or some other commit. If only you had:

git merge develop
git submodule update --rebase

Fast-forwarded bestIdeaForBEver to b798edfdsf1191f8b140ea325685c4da19a9d437.
Submodule path 'B': rebased into 'b798ecsdf71191f8b140ea325685c4da19a9d437'

Now that best idea ever for B has been rebased onto the new commit, and more importantly, you are still on your development branch for B, not in a headless state!

(The --merge will merge changes from beforeUpdateSHA to afterUpdateSHA into your working branch, as opposed to rebasing your changes onto afterUpdateSHA.)

How to get ERD diagram for an existing database?

postgresql_autodoc is a cli for doing this. Doesnt do cardinality, but none of the above mentioned GUI tools do as well.

Check if registry key exists using VBScript

The accepted answer is too long, other answers didn't work for me. I'm gonna leave this for future purpose.

Dim sKey, bFound
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\SecurityHealth"

with CreateObject("WScript.Shell")
  on error resume next            ' turn off error trapping
    sValue = .regread(sKey)       ' read attempt
    bFound = (err.number = 0)     ' test for success
  on error goto 0                 ' restore error trapping
end with

If bFound Then
  MsgBox = "Registry Key Exist."
Else
  MsgBox = "Nope, it doesn't exist."
End If

Here's the list of the Registry Tree, choose your own base on your current task.

HKCR = HKEY_CLASSES_ROOT
HKCU = HKEY_CURRENT_USER
HKLM = HKEY_LOCAL_MACHINE
HKUS = HKEY_USERS
HKCC = HKEY_CURRENT_CONFIG

How to get the selected date value while using Bootstrap Datepicker?

If you wan't the date in full text string format you can do it like this:

$('#your-datepicker').data().datepicker.viewDate

Different between parseInt() and valueOf() in java?

  • valueOf - converts to Wrapper class
  • parseInt - converts to primitive type

Integer.parseInt accept only String and return primitive integer type (int).

   public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

Iteger.valueOf accept int and String. If value is String, valueOf convert it to the the simple int using parseInt and return new Integer if input is less than -128 or greater than 127. If input is in range (-128 - 127) it always return the Integer objects from an internal IntegerCache. Integer class maintains an inner static IntegerCache class which acts as the cache and holds integer objects from -128 to 127 and that’s why when we try to get integer object for 127 (for example) we always get the same object.

Iteger.valueOf(200) will give new Integer from 200. It's like new Integer(200) Iteger.valueOf(127) is the same as Integer = 127;

If you wont to convert String to the Integer use Iteger.valueOf.

If you wont to convert String to the simple int use Integer.parseInt. It works faster.

  public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

  public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
  }

  private static class IntegerCache {
      static final int low = -128;
      static final int high;
      static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
  }

And comparing Integer.valueOf(127) == Integer.valueOf(127) return true

Integer a = 127; // Compiler converts this line to Integer a = Integer.valueOf(127);
Integer b = 127; // Compiler converts this line to Integer b = Integer.valueOf(127);
a == b; // return true 

Because it takes the Integer objects with the same references from the cache.

But Integer.valueOf(128) == Integer.valueOf(128) is false, because 128 is out of IntegerCache range and it return new Integer, so objects will have different references.

What does the regex \S mean in JavaScript?

/\S/.test(string) returns true if and only if there's a non-space character in string. Tab and newline count as spaces.

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

Run C++ in command prompt - Windows

have MinGW compiler bin directory added to path.

use mingw32-g++ -s -c source_file_name.cpp -o output_file_name.o to compile

then mingw32-g++ -o executable_file_name.exe output_file_name.o to build exe

finally, you run with executable_file_name.exe

Separation of business logic and data access in django

In Django, MVC structure is as Chris Pratt said, different from classical MVC model used in other frameworks, I think the main reason for doing this is avoiding a too strict application structure, like happens in others MVC frameworks like CakePHP.

In Django, MVC was implemented in the following way:

View layer is splitted in two. The views should be used only to manage HTTP requests, they are called and respond to them. Views communicate with the rest of your application (forms, modelforms, custom classes, of in simple cases directly with models). To create the interface we use Templates. Templates are string-like to Django, it maps a context into them, and this context was communicated to the view by the application (when view asks).

Model layer gives encapsulation, abstraction, validation, intelligence and makes your data object-oriented (they say someday DBMS will also). This doesn't means that you should make huge models.py files (in fact a very good advice is to split your models in different files, put them into a folder called 'models', make an '__init__.py' file into this folder where you import all your models and finally use the attribute 'app_label' of models.Model class). Model should abstract you from operating with data, it will make your application simpler. You should also, if required, create external classes, like "tools" for your models.You can also use heritage in models, setting the 'abstract' attribute of your model's Meta class to 'True'.

Where is the rest? Well, small web applications generally are a sort of an interface to data, in some small program cases using views to query or insert data would be enough. More common cases will use Forms or ModelForms, which are actually "controllers". This is not other than a practical solution to a common problem, and a very fast one. It's what a website use to do.

If Forms are not enogh for you, then you should create your own classes to do the magic, a very good example of this is admin application: you can read ModelAmin code, this actually works as a controller. There is not a standard structure, I suggest you to examine existing Django apps, it depends on each case. This is what Django developers intended, you can add xml parser class, an API connector class, add Celery for performing tasks, twisted for a reactor-based application, use only the ORM, make a web service, modify the admin application and more... It's your responsability to make good quality code, respect MVC philosophy or not, make it module based and creating your own abstraction layers. It's very flexible.

My advice: read as much code as you can, there are lots of django applications around, but don't take them so seriously. Each case is different, patterns and theory helps, but not always, this is an imprecise cience, django just provide you good tools that you can use to aliviate some pains (like admin interface, web form validation, i18n, observer pattern implementation, all the previously mentioned and others), but good designs come from experienced designers.

PS.: use 'User' class from auth application (from standard django), you can make for example user profiles, or at least read its code, it will be useful for your case.

Determining complexity for recursive functions (Big O notation)

We can prove it mathematically which is something I was missing in the above answers.

It can dramatically help you understand how to calculate any method. I recommend reading it from top to bottom to fully understand how to do it:

  1. T(n) = T(n-1) + 1 It means that the time it takes for the method to finish is equal to the same method but with n-1 which is T(n-1) and we now add + 1 because it's the time it takes for the general operations to be completed (except T(n-1)). Now, we are going to find T(n-1) as follow: T(n-1) = T(n-1-1) + 1. It looks like we can now form a function that can give us some sort of repetition so we can fully understand. We will place the right side of T(n-1) = ... instead of T(n-1) inside the method T(n) = ... which will give us: T(n) = T(n-1-1) + 1 + 1 which is T(n) = T(n-2) + 2 or in other words we need to find our missing k: T(n) = T(n-k) + k. The next step is to take n-k and claim that n-k = 1 because at the end of the recursion it will take exactly O(1) when n<=0. From this simple equation we now know that k = n - 1. Let's place k in our final method: T(n) = T(n-k) + k which will give us: T(n) = 1 + n - 1 which is exactly n or O(n).
  2. Is the same as 1. You can test it your self and see that you get O(n).
  3. T(n) = T(n/5) + 1 as before, the time for this method to finish equals to the time the same method but with n/5 which is why it is bounded to T(n/5). Let's find T(n/5) like in 1: T(n/5) = T(n/5/5) + 1 which is T(n/5) = T(n/5^2) + 1. Let's place T(n/5) inside T(n) for the final calculation: T(n) = T(n/5^k) + k. Again as before, n/5^k = 1 which is n = 5^k which is exactly as asking what in power of 5, will give us n, the answer is log5n = k (log of base 5). Let's place our findings in T(n) = T(n/5^k) + k as follow: T(n) = 1 + logn which is O(logn)
  4. T(n) = 2T(n-1) + 1 what we have here is basically the same as before but this time we are invoking the method recursively 2 times thus we multiple it by 2. Let's find T(n-1) = 2T(n-1-1) + 1 which is T(n-1) = 2T(n-2) + 1. Our next place as before, let's place our finding: T(n) = 2(2T(n-2)) + 1 + 1 which is T(n) = 2^2T(n-2) + 2 that gives us T(n) = 2^kT(n-k) + k. Let's find k by claiming that n-k = 1 which is k = n - 1. Let's place k as follow: T(n) = 2^(n-1) + n - 1 which is roughly O(2^n)
  5. T(n) = T(n-5) + n + 1 It's almost the same as 4 but now we add n because we have one for loop. Let's find T(n-5) = T(n-5-5) + n + 1 which is T(n-5) = T(n - 2*5) + n + 1. Let's place it: T(n) = T(n-2*5) + n + n + 1 + 1) which is T(n) = T(n-2*5) + 2n + 2) and for the k: T(n) = T(n-k*5) + kn + k) again: n-5k = 1 which is n = 5k + 1 that is roughly n = k. This will give us: T(n) = T(0) + n^2 + n which is roughly O(n^2).

I now recommend reading the rest of the answers which now, will give you a better perspective. Good luck winning those big O's :)

What is the significance of #pragma marks? Why do we need #pragma marks?

In simple word we can say that #pragma mark - is used for categorizing methods, so you can find your methods easily. It is very useful for long projects.

Inserting values into a SQL Server database using ado.net via C#

As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.

Also: I would recommend to separate the click event handler from the actual code to insert the data.

So I would rewrite your code to be something like

In your web page's code-behind file (yourpage.aspx.cs)

private void button1_Click(object sender, EventArgs e)
{
      string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";

      InsertData(connectionString,
                 textBox1.Text.Trim(),  -- first name
                 textBox2.Text.Trim(),  -- last name
                 textBox3.Text.Trim(),  -- user name
                 textBox4.Text.Trim(),  -- password
                 Convert.ToInt32(comboBox1.Text),  -- age
                 comboBox2.Text.Trim(), -- gender
                 textBox7.Text.Trim() );  -- contact
}

In some other code (e.g. a databaselayer.cs):

private void InsertData(string connectionString, string firstName, string lastname, string username, string password
                        int Age, string gender, string contact)
{
    // define INSERT query with parameters
    string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " + 
                   "VALUES (@FirstName, @Lastname, @Username, @Password, @Age, @Gender, @Contact) ";

    // create connection and command
    using(SqlConnection cn = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(query, cn))
    {
        // define parameters and their values
        cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstName;
        cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = lastName;
        cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = userName;
        cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = password;
        cmd.Parameters.Add("@Age", SqlDbType.Int).Value = age;
        cmd.Parameters.Add("@Gender", SqlDbType.VarChar, 50).Value = gender;
        cmd.Parameters.Add("@Contact", SqlDbType.VarChar, 50).Value = contact;

        // open connection, execute INSERT, close connection
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }
}

Code like this:

  • is not vulnerable to SQL injection attacks
  • performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
  • separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)

Adding placeholder text to textbox

Wouldn't that just be something like this:

Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";

myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
myTxtbx.LostFocus += LostFocus.EventHandle(AddText);

public void RemoveText(object sender, EventArgs e)
{
    if (myTxtbx.Text == "Enter text here...") 
    {
     myTxtbx.Text = "";
    }
}

public void AddText(object sender, EventArgs e)
{
    if (string.IsNullOrWhiteSpace(myTxtbx.Text))
        myTxtbx.Text = "Enter text here...";
}

Thats just pseudocode but the concept is there.

How do I see active SQL Server connections?

MS's query explaining the use of the KILL command is quite useful providing connection's information:

SELECT conn.session_id, host_name, program_name,
    nt_domain, login_name, connect_time, last_request_end_time 
FROM sys.dm_exec_sessions AS sess
JOIN sys.dm_exec_connections AS conn
   ON sess.session_id = conn.session_id;

The most efficient way to implement an integer based power function pow(int, int)

Just as a follow up to comments on the efficiency of exponentiation by squaring.

The advantage of that approach is that it runs in log(n) time. For example, if you were going to calculate something huge, such as x^1048575 (2^20 - 1), you only have to go thru the loop 20 times, not 1 million+ using the naive approach.

Also, in terms of code complexity, it is simpler than trying to find the most optimal sequence of multiplications, a la Pramod's suggestion.

Edit:

I guess I should clarify before someone tags me for the potential for overflow. This approach assumes that you have some sort of hugeint library.

How do I replace part of a string in PHP?

You can try

$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);

var_dump($string);

Output

this_is_th

Path of assets in CSS files in Symfony 2

The cssrewrite filter is not compatible with the @bundle notation for now. So you have two choices:

  • Reference the CSS files in the web folder (after: console assets:install --symlink web)

    {% stylesheets '/bundles/myCompany/css/*." filter="cssrewrite" %}
    
  • Use the cssembed filter to embed images in the CSS like this.

    {% stylesheets '@MyCompanyMyBundle/Resources/assets/css/*.css' filter="cssembed" %}
    

Find a string between 2 known values

To get Single/Multiple values without regular expression

// For Single
var value = inputString.Split("<tag1>", '</tag1>')[1];

// For Multiple
var values = inputString.Split("<tag1>", '</tag1>').Where((_, index) => index % 2 != 0);

New lines (\r\n) are not working in email body

This worked for me.

$message  = nl2br("
===============================\r\n
www.domain.com \r\n
===============================\r\n
From: ".$from."\r\n
To: ".$to."\r\n
Subject: ".$subject."\r\n
Message: ".$_POST['form-message']);

Get PostGIS version

PostGIS_Lib_Version(); - returns the version number of the PostGIS library.

http://postgis.refractions.net/docs/PostGIS_Lib_Version.html

Read a XML (from a string) and get some fields - Problems reading XML

I used the System.Xml.Linq.XElement for the purpose. Just check code below for reading the value of first child node of the xml(not the root node).

        string textXml = "<xmlroot><firstchild>value of first child</firstchild>........</xmlroot>";
        XElement xmlroot = XElement.Parse(textXml);
        string firstNodeContent = ((System.Xml.Linq.XElement)(xmlroot.FirstNode)).Value;

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

Android studio, gradle and NDK

To expand on what Naxos said (Thanks Naxos for sending me in the right direction!), I learned quite a bit from the recently released NDK examples and posted an answer in a similar question here.

How to configure NDK with Android Gradle plugin 0.7

This post has full details on linking prebuilt native libraries into your app for the various architectures as well as information on how to add NDK support directly to the build.gradle script. For the most part, you shouldn't need to do the work around zip and copy anymore.

Get the current script file name

alex's answer is correct but you could also do this without regular expressions like so:

str_replace(".php", "", basename($_SERVER["SCRIPT_NAME"]));

Python memory usage of numpy arrays

You can use array.nbytes for numpy arrays, for example:

>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192

Add a space (" ") after an element using :after

element::after { 
    display: block;
    content: " ";
}

This worked for me.

Check if a string is a valid Windows directory (folder) path

Call Path.GetFullPath; it will throw exceptions if the path is invalid.

To disallow relative paths (such as Word), call Path.IsPathRooted.

How do I keep two side-by-side divs the same height?

The Fiddle

HTML

<div class="container">

    <div class="left-column">

    </div>

    <div class="right-column">
        <h1>Hello Kitty!</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium cum accusamus ab nostrum sit laborum eligendi, totam nam aperiam harum officia commodi tempora dolorum. Incidunt earum explicabo deleniti architecto illo!</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium cum accusamus ab nostrum sit laborum eligendi, totam nam aperiam harum officia commodi tempora dolorum. Incidunt earum explicabo deleniti architecto illo!</p>
    </div>

</div>

CSS

.container {
    float: left;
    width: 100%;
    background-color: black;
    position: relative;
    left: 0;
}

.container:before,
.container:after {
    content: " ";
    display: table;
}

.container:after {
    clear: both;
}

.left-column {
    float: left;
    width: 30%;
    height: 100%;
    position: absolute;
    background: wheat;
}

.right-column {
    float: right;
    width: 70%;
    position: relative;
    padding: 0;
    margin: 0;
    background: rebeccapurple;            
}

Sort a single String in Java

str.chars().boxed().map(Character::toString).sorted().collect(Collectors.joining())

or

s.chars().mapToObj(Character::toString).sorted().collect(Collectors.joining())

or

Arrays.stream(str.split("")).sorted().collect(Collectors.joining())

Java Package Does Not Exist Error

Are they in the right subdirectories?

If you put /usr/share/stuff on the class path, files defined with package org.name should be in /usr/share/stuff/org/name.

EDIT: If you don't already know this, you should probably read this: http://download.oracle.com/javase/1.5.0/docs/tooldocs/windows/classpath.html#Understanding

EDIT 2: Sorry, I hadn't realised you were talking of Java source files in /usr/share/stuff. Not only they need to be in the appropriate sub-directory, but you need to compile them. The .java files don't need to be on the classpath, but on the source path. (The generated .class files need to be on the classpath.)

You might get away with compiling them if they're not under the right directory structure, but they should be, or it will generate warnings at least. The generated class files will be in the right subdirectories (wherever you've specified -d if you have).

You should use something like javac -sourcepath .:/usr/share/stuff test.java, assuming you've put the .java files that were under /usr/share/stuff under /usr/share/stuff/org/name (or whatever is appropriate according to their package names).

How do I retrieve my MySQL username and password?

An improvement to the most useful answer here:

1] No need to restart the mysql server
2] Security concern for a MySQL server connected to a network

There is no need to restart the MySQL server.

use FLUSH PRIVILEGES; after the update mysql.user statement for password change.

The FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.

The --skip-grant-options enables anyone to connect without a password and with all privileges. Because this is insecure, you might want to

use --skip-grant-tables in conjunction with --skip-networking to prevent remote clients from connecting.

from: reference: resetting-permissions-generic

How to configure Git post commit hook

As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:

#!/usr/bin/python

import sys
from subprocess import call

if __name__ == '__main__':
    for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')
        if ref == 'refs/heads/master':
            print "=============================================="
            print "Pushing to master. Triggering jenkins.        "
            print "=============================================="
            sys.stdout.flush()
            call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])

In this case I trigger jenkins jobs only when pushing to master and not other branches.

Doing a cleanup action just before Node.js exits

This catches every exit event I can find that can be handled. Seems quite reliable and clean so far.

[`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`].forEach((eventType) => {
  process.on(eventType, cleanUpServer.bind(null, eventType));
})

Setting values of input fields with Angular 6

You should use the following:

       <td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>

You will need to add the FormsModule to your app.module in the inputs section as follows:

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  ..

The use of the brackets around the ngModel are as follows:

  • The [] show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.

  • The () show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.

  • The [()] are both (e.g. a two way binding)

See here for more information: https://angular.io/guide/template-syntax

I would also suggest replacing id="priceInput-{{orderLine.id}}" with something like this [id]="getElementId(orderLine)" where getElementId(orderLine) returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1 in one place and priceInput-1 in another. (if you still need to access the input by it's Id somewhere else)

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

Could not locate Gemfile

I had the same problem and got it solved by using a different directory.

bash-4.2$ bundle install
Could not locate Gemfile
bash-4.2$ pwd
/home/amit/redmine/redmine-2.2.2-0/apps/redmine
bash-4.2$ cd htdocs/
bash-4.2$ ls
app  config db   extra  Gemfile   lib  plugins  Rakefile     script  tmp
bin  config.ru  doc  files  Gemfile.lock  log  public   README.rdoc  test    vendor
bash-4.2$ cd plugins/
bash-4.2$ bundle install
Using rake (0.9.2.2) 
Using i18n (0.6.0) 
Using multi_json (1.3.6) 
Using activesupport (3.2.11) 
Using builder (3.0.0) 
Using activemodel (3.2.11) 
Using erubis (2.7.0) 
Using journey (1.0.4) 
Using rack (1.4.1) 
Using rack-cache (1.2) 
Using rack-test (0.6.1) 
Using hike (1.2.1) 
Using tilt (1.3.3) 
Using sprockets (2.2.1) 
Using actionpack (3.2.11) 
Using mime-types (1.19) 
Using polyglot (0.3.3) 
Using treetop (1.4.10) 
Using mail (2.4.4) 
Using actionmailer (3.2.11) 
Using arel (3.0.2) 
Using tzinfo (0.3.33) 
Using activerecord (3.2.11) 
Using activeresource (3.2.11) 
Using coderay (1.0.6) 
Using rack-ssl (1.3.2) 
Using json (1.7.5) 
Using rdoc (3.12) 
Using thor (0.15.4) 
Using railties (3.2.11) 
Using jquery-rails (2.0.3) 
Using mysql2 (0.3.11) 
Using net-ldap (0.3.1) 
Using ruby-openid (2.1.8) 
Using rack-openid (1.3.1) 
Using bundler (1.2.3) 
Using rails (3.2.11) 
Using rmagick (2.13.1) 
Your bundle i

TypeError: ObjectId('') is not JSON serializable

For those who need to return the data thru Jsonify with Flask:

cursor = db.collection.find()
data = []
for doc in cursor:
    doc['_id'] = str(doc['_id']) # This does the trick!
    data.append(doc)
return jsonify(data)

Android Gradle Could not reserve enough space for object heap

in gradle.properties, you can even delete

org.gradle.jvmargs=-Xmx1536m

such lines or comment them out. Let android studio decide for it. When I ran into this same problem, none of above solutions worked for me. Commenting out this line in gradle.properties helped in solving that error.

long long int vs. long int vs. int64_t in C++

You don't need to go to 64-bit to see something like this. Consider int32_t on common 32-bit platforms. It might be typedef'ed as int or as a long, but obviously only one of the two at a time. int and long are of course distinct types.

It's not hard to see that there is no workaround which makes int == int32_t == long on 32-bit systems. For the same reason, there's no way to make long == int64_t == long long on 64-bit systems.

If you could, the possible consequences would be rather painful for code that overloaded foo(int), foo(long) and foo(long long) - suddenly they'd have two definitions for the same overload?!

The correct solution is that your template code usually should not be relying on a precise type, but on the properties of that type. The whole same_type logic could still be OK for specific cases:

long foo(long x);
std::tr1::disable_if(same_type(int64_t, long), int64_t)::type foo(int64_t);

I.e., the overload foo(int64_t) is not defined when it's exactly the same as foo(long).

[edit] With C++11, we now have a standard way to write this:

long foo(long x);
std::enable_if<!std::is_same<int64_t, long>::value, int64_t>::type foo(int64_t);

[edit] Or C++20

long foo(long x);
int64_t foo(int64_t) requires (!std::is_same_v<int64_t, long>);

How to download/upload files from/to SharePoint 2013 using CSOM?

Though this is an old post and have many answers, but here I have my version of code to upload the file to sharepoint 2013 using CSOM(c#)

I hope if you are working with downloading and uploading files then you know how to create Clientcontext object and Web object

/* Assuming you have created ClientContext object and Web object*/
string listTitle = "List title where you want your file to upload";
string filePath = "your file physical path";
List oList = web.Lists.GetByTitle(listTitle);
clientContext.Load(oList.RootFolder);//to load the folder where you will upload the file
FileCreationInformation fileInfo = new FileCreationInformation();

fileInfo.Overwrite = true;
fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
fileInfo.Url = fileName;

File fileToUpload = fileCollection.Add(fileInfo);
clientContext.ExecuteQuery();

fileToUpload.CheckIn("your checkin comment", CheckinType.MajorCheckIn);
if (oList.EnableMinorVersions)
{
    fileToUpload.Publish("your publish comment");
    clientContext.ExecuteQuery();
}
if (oList.EnableModeration)
{
     fileToUpload.Approve("your approve comment"); 
}
clientContext.ExecuteQuery();

And here is the code for download

List oList = web.Lists.GetByTitle("ListNameWhereFileExist");
clientContext.Load(oList);
clientContext.Load(oList.RootFolder);
clientContext.Load(oList.RootFolder.Files);
clientContext.ExecuteQuery();
FileCollection fileCollection = oList.RootFolder.Files;
File SP_file = fileCollection.GetByUrl("fileNameToDownloadWithExtension");
clientContext.Load(SP_file);
clientContext.ExecuteQuery();                
var Local_stream = System.IO.File.Open("c:/testing/" + SP_file.Name, System.IO.FileMode.CreateNew);
var fileInformation = File.OpenBinaryDirect(clientContext, SP_file.ServerRelativeUrl);
var Sp_Stream = fileInformation.Stream;
Sp_Stream.CopyTo(Local_stream);

Still there are different ways I believe that can be used to upload and download.

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

Since version 5, Qt uses a platform abstraction system (QPA) to abstract from the underlying platform.

The implementation for each platform is provided by plugins. For X11 it is the XCB plugin. See Qt for X11 requirements for more information about the dependencies.

Convert a SQL query result table to an HTML table for email

Here is one way to do it from an article titled "Format query output into an HTML table - the easy way [archive]". You would need to substitute the details of your own query for the ones in this example, which gets a list of tables and a row count.

declare @body varchar(max)

set @body = cast( (
select td = dbtable + '</td><td>' + cast( entities as varchar(30) ) + '</td><td>' + cast( rows as varchar(30) )
from (
      select dbtable  = object_name( object_id ),
             entities = count( distinct name ),
             rows     = count( * )
      from sys.columns
      group by object_name( object_id )
      ) as d
for xml path( 'tr' ), type ) as varchar(max) )

set @body = '<table cellpadding="2" cellspacing="2" border="1">'
          + '<tr><th>Database Table</th><th>Entity Count</th><th>Total Rows</th></tr>'
          + replace( replace( @body, '&lt;', '<' ), '&gt;', '>' )
          + '</table>'

print @body

Once you have @body, you can then use whatever email mechanism you want.

What is the size of an enum in C?

Taken from the current C Standard (C99): http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

6.7.2.2 Enumeration specifiers
[...]
Constraints
The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.
[...]
Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

Not that compilers are any good at following the standard, but essentially: If your enum holds anything else than an int, you're in deep "unsupported behavior that may come back biting you in a year or two" territory.

Update: The latest publicly available draft of the C Standard (C11): http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1570.pdf contains the same clauses. Hence, this answer still holds for C11.

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

Undefined behavior and sequence points

I am guessing there is a fundamental reason for the change, it isn't merely cosmetic to make the old interpretation clearer: that reason is concurrency. Unspecified order of elaboration is merely selection of one of several possible serial orderings, this is quite different to before and after orderings, because if there is no specified ordering, concurrent evaluation is possible: not so with the old rules. For example in:

f (a,b)

previously either a then b, or, b then a. Now, a and b can be evaluated with instructions interleaved or even on different cores.

How to store and retrieve a dictionary with redis

If you want to store a python dict in redis, it is better to store it as json string.

import redis

r = redis.StrictRedis(host='localhost', port=6379, db=0)
mydict = { 'var1' : 5, 'var2' : 9, 'var3': [1, 5, 9] }
rval = json.dumps(mydict)
r.set('key1', rval)

While retrieving de-serialize it using json.loads

data = r.get('key1')
result = json.loads(data)
arr = result['var3']

What about types (eg.bytes) that are not serialized by json functions ?

You can write encoder/decoder functions for types that cannot be serialized by json functions. eg. writing base64/ascii encoder/decoder function for byte array.

SQL Server : export query as a .txt file

You can use bcp utility.

To copy the result set from a Transact-SQL statement to a data file, use the queryout option. The following example copies the result of a query into the Contacts.txt data file. The example assumes that you are using Windows Authentication and have a trusted connection to the server instance on which you are running the bcp command. At the Windows command prompt, enter:

bcp "<your query here>" queryout Contacts.txt -c -T

You can use BCP by directly calling as operating sytstem command in SQL Agent job.

error: command 'gcc' failed with exit status 1 on CentOS

Is gcc installed?

sudo yum install gcc

Python handling socket.error: [Errno 104] Connection reset by peer

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)

So you can't do anything about it, it is the issue of the server.

But you could use try .. except block to handle that exception:

from socket import error as SocketError
import errno

try:
    response = urllib2.urlopen(request).read()
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        raise # Not error we are looking for
    pass # Handle error here.

Best way to clear a PHP array's values

Like Zack said in the comments below you are able to simply re-instantiate it using

$foo = array(); // $foo is still here

If you want something more powerful use unset since it also will clear $foo from the symbol table, if you need the array later on just instantiate it again.

unset($foo); // $foo is gone
$foo = array(); // $foo is here again

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

What is the curl error 52 "empty reply from server"?

Another common reason for an empty reply is timeout. Check all the hops from where the cron job is running from to your PHP/target server. There's probably a device/server/nginx/LB/proxy somewhere along the line that terminates the request earlier than you expected, resulting in an empty response.

How to downgrade php from 5.5 to 5.3

It is possible! Yes

In many cases, you might want to use XAMPP with a different PHP version than the one that comes preinstalled. You might do this to get the benefits of a newer version of PHP, or to reproduce bugs using an earlier version of PHP.

To use a different version of PHP with XAMPP, follow these steps:

  1. Download a binary build of the PHP version that you wish to use from the PHP website, and extract the contents of the compressed archive file to your XAMPP installation directory (usually, C:\xampp). Ensure that you give it a different directory name to avoid overwriting the existing PHP version. For example, in this tutorial, we’ll call the new directory C:\xampp\php5-6-0. NOTE : Ensure that the PHP build you download matches the Apache build (VC9 or VC11) in your XAMPP platform.

  2. Within the new directory, rename the php.ini-development file to php.ini. If you prefer to use production settings, you could instead rename the php.ini-production file to php.ini.

  3. Edit the httpd-xampp.conf file in the apache\conf\extra\ subdirectory of your XAMPP installation directory. Within this file, search for all instances of the old PHP directory path and replace them with the path to the new PHP directory created in Step 1. In particular, be sure to change the lines

    LoadFile "/xampp/php/php5ts.dll"
    LoadFile "/xampp/php/libpq.dll"
    LoadModule php5_module "/xampp/php/php5apache2_4.dll"

to

    LoadFile "/xampp/php5-6-0/php5ts.dll"
    LoadFile "/xampp/php5-6-0/libpq.dll"
    LoadModule php5_module "/xampp/php5-6-0/php5apache2_4.dll"

NOTE : Remember to adjust the file and directory paths above to reflect valid paths on your system.

  1. Restart your Apache server through the XAMPP control panel for your changes to take effect. The new version of PHP should now be active. To verify this, browse to the URL http://localhost/xampp/phpinfo.php, which displays the output of the phpinfo() command, and check the version number at the top of the page.

Is there a “not in” operator in JavaScript for checking object properties?

It seems wrong to me to set up an if/else statement just to use the else portion...

Just negate your condition, and you'll get the else logic inside the if:

if (!(id in tutorTimes)) { ... }

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

SELECT employee_number,
       MAX(MAX(course_completion_date)) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

And as Teradata allows re-using an alias this also works:

SELECT employee_number,
       MAX(max_date) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

add class with JavaScript

In your snippet, button is an instance of NodeList, to which you can't attach an event listener directly, nor can you change the elements' className properties directly.
Your best bet is to delegate the event:

document.body.addEventListener('mouseover',function(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
    {
        target.className += ' active';//set class
    }
},false);

Of course, my guess is that the active class needs to be removed once the mouseout event fires, you might consider using a second delegator for that, but you could just aswell attach an event handler to the one element that has the active class:

document.body.addEventListener('mouseover',function(e)
{
    e = e || window.event;
    var oldSrc, target = e.target || e.srcElement;
    if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
    {
        target.className += ' active';//set class
        oldSrc = target.getAttribute('src');
        target.setAttribute('src', 'images/arrows/top_o.png');
        target.onmouseout = function()
        {
            target.onmouseout = null;//remove this event handler, we don't need it anymore
            target.className = target.className.replace(/\bactive\b/,'').trim();
            target.setAttribute('src', oldSrc);
        };
    }
},false);

There is some room for improvements, with this code, but I'm not going to have all the fun here ;-).

Check the fiddle here

Switch tabs using Selenium WebDriver with Java

Simple Answer which worked for me:

for (String handle1 : driver1.getWindowHandles()) {
        System.out.println(handle1); 
        driver1.switchTo().window(handle1);     
}

Will using 'var' affect performance?

I always use the word var in web articles or guides writings.

The width of the text editor of online article is small.

If I write this:

SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName coolClass = new SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName();

You will see that above rendered pre code text is too long and flows out of the box, it gets hidden. The reader needs to scroll to the right to see the complete syntax.

That's why I always use the keyword var in web article writings.

var coolClass = new SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName();

The whole rendered pre code just fit within the screen.

In practice, for declaring object, I seldom use var, I rely on intellisense to declare object faster.

Example:

SomeCoolNamespace.SomeCoolObject coolObject = new SomeCoolNamespace.SomeCoolObject();

But, for returning object from a method, I use var to write code faster.

Example:

var coolObject = GetCoolObject(param1, param2);

Detect iPad users using jQuery?

I use this:

function fnIsAppleMobile() 
{
    if (navigator && navigator.userAgent && navigator.userAgent != null) 
    {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches != null) 
             return true;
    } // End if (navigator && navigator.userAgent) 

    return false;
} // End Function fnIsAppleMobile


var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove

javascript find and remove object in array based on key value

If you are using underscore js, it is easy to remove object based on key. http://underscorejs.org. Example:

  var temp1=[{id:1,name:"safeer"},  //temp array
             {id:2,name:"jon"},
             {id:3,name:"James"},
             {id:4,name:"deepak"},
             {id:5,name:"ajmal"}];

  var id = _.pluck(temp1,'id'); //get id array from temp1
  var ids=[2,5,10];             //ids to be removed
  var bool_ids=[];
  _.each(ids,function(val){
     bool_ids[val]=true;
  });
  _.filter(temp1,function(val){
     return !bool_ids[val.id];
  });

JS regex: replace all digits in string

Use

s.replace(/\d/g, "X")

which will replace all occurrences. The g means global match and thus will not stop matching after the first occurrence.

Or to stay with your RegExp constructor:

s.replace(new RegExp("\\d", "g"), "X")

CSS: Control space between bullet and <li>

You can use the padding-left attribute on the list items (not on the list itself!).

Drag and drop elements from list into separate blocks

_x000D_
_x000D_
 function dragStart(event) {_x000D_
            event.dataTransfer.setData("Text", event.target.id);_x000D_
        }_x000D_
_x000D_
        function allowDrop(event) {_x000D_
            event.preventDefault();_x000D_
        }_x000D_
_x000D_
        function drop(event) {_x000D_
            $("#maincontainer").append("<br/><table style='border:1px solid black; font-size:20px;'><tr><th>Name</th><th>Country</th><th>Experience</th><th>Technologies</th></tr><tr><td>  Bhanu Pratap   </td><td> India </td><td>  3 years   </td><td>  Javascript,Jquery,AngularJS,ASP.NET C#, XML,HTML,CSS,Telerik,XSLT,AJAX,etc...</td></tr></table>");_x000D_
        }
_x000D_
 .droptarget {_x000D_
            float: left;_x000D_
            min-height: 100px;_x000D_
            min-width: 200px;_x000D_
            border: 1px solid black;_x000D_
            margin: 15px;_x000D_
            padding: 10px;_x000D_
            border: 1px solid #aaaaaa;_x000D_
        }_x000D_
_x000D_
        [contentEditable=true]:empty:not(:focus):before {_x000D_
            content: attr(data-text);_x000D_
        }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
<div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)">_x000D_
        <p ondragstart="dragStart(event)" draggable="true" id="dragtarget">Drag Table</p>_x000D_
    </div>_x000D_
_x000D_
    <div id="maincontainer" contenteditable=true data-text="Drop here..." class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
_x000D_
_x000D_
_x000D_

  1. this is just simple here i'm appending html table into a div at the end
  2. we can achieve this or any thing with a simple concept of calling a JavaScript function when we want (here on drop.)
  3. In this example you can drag & drop any number of tables, new table will be added below the last table exists in the div other wise it will be the first table in the div.
  4. here we can add text between tables or we can say the section where we drop tables is editable we can type text between tables. enter image description here

Thanks... :)

symfony2 : failed to write cache directory

If you face this error when you start Symfony project with docker (my Symfony version 5.1). Or errors like these:

Uncaught Exception: Failed to write file "/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainer.xml"" while reading upstream

Uncaught Warning: file_put_contents(/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainerDeprecations.log): failed to open stream: Permission denied" while reading upstream

Fix below helped me.

In Dockerfile for nginx container add line:

RUN usermod -u 1000 www-data

In Dockerfile for php-fpm container add line:

RUN usermod -u 1000 www-data

Then remove everything in directories "/var/cache", "/var/log" and rebuild docker's containers.

How to send redirect to JSP page in Servlet

Please use the below code and let me know

try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("connection done");


            PreparedStatement ps=con.prepareStatement(q);
            System.out.println(q);
            rs=ps.executeQuery();
            System.out.println("done2");
            while (rs.next()) {
               System.out.println(rs.getString(1));
               System.out.println(rs.getString(2));

            }

         response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.

        }
            catch (Exception e) {
                // TODO: handle exception
                System.out.println("Failed");
            }

myfolder/welcome.jsp is the relative path of your jsp page. So, change it as per your jsp page path.

how to kill hadoop jobs

An unhandled exception will (assuming it's repeatable like bad data as opposed to read errors from a particular data node) eventually fail the job anyway.

You can configure the maximum number of times a particular map or reduce task can fail before the entire job fails through the following properties:

  • mapred.map.max.attempts - The maximum number of attempts per map task. In other words, framework will try to execute a map task these many number of times before giving up on it.
  • mapred.reduce.max.attempts - Same as above, but for reduce tasks

If you want to fail the job out at the first failure, set this value from its default of 4 to 1.

ListView with OnItemClickListener

if list item view contains button or checkbox or imagebutton, the onitemclicklistener and onitemlongclicklistener not working due to it has own onclick listener.

set focusable as false

holder.button.setFocusable(false);

Online Internet Explorer Simulators

I just realized that there's yet another option. I've heard a lot of good things about this service: Litmus Alkaline.

"Alkaline tests your website designs across 17 different Windows browsers right from your Mac desktop in seconds. No need for virtual machines, Windows licenses, or any messing around with Windows Update."

How to export collection to CSV in MongoDB?

I could not get mongoexport to do this for me. I found that,to get an exhaustive list of all the fields, you need to loop through the entire collection once. Use this to generate the headers. Then loop through the collection again to populate these headers for each document.

I've written a script to do just this. Converting MongoDB docs to csv irrespective of schema differences between individual documents.

https://github.com/surya-shodan/mongoexportcsv

how to increase MaxReceivedMessageSize when calling a WCF from C#

Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.

Check this : Using Large Message Requests in Silverlight with WCF

<system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="TestLargeWCF.Web.MyServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <customBinding>
       <binding name="customBinding0">
         <binaryMessageEncoding />
         <!-- Start change -->
         <httpTransport maxReceivedMessageSize="2097152"
                        maxBufferSize="2097152"
                        maxBufferPoolSize="2097152"/>
         <!-- Stop change -->
       </binding>
     </customBinding>
   </bindings>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   <services>
     <service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
       <endpoint address=""
                binding="customBinding"
                bindingConfiguration="customBinding0"
                contract="TestLargeWCF.Web.MyService"/>
       <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange"/>
     </service>
   </services>
 </system.serviceModel> 

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Well as the stack trace says, you would need to set the protected mode settings to same for all zones in IE. Read the why here : http://jimevansmusic.blogspot.in/2012/08/youre-doing-it-wrong-protected-mode-and.html

and a quick how to from the same link : "In IE, from the Tools menu (or the gear icon in the toolbar in later versions), select "Internet options." Go to the Security tab. At the bottom of the dialog for each zone, you should see a check box labeled "Enable Protected Mode." Set the value of the check box to the same value, either checked or unchecked, for each zone"

Android webview launches browser when calling loadurl

If you're using webChromeClient I'll suggest you to use webChromeClient and webViewClient together. because webChromeClient does not provides shouldOverrideUrlLoading. It is okay to use both.

        webview.webViewClient = WebViewClient()
        webview.webChromeClient = Callback()

private inner class Callback : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
           
            if (newProgress == 0) {
                progressBar.visibility = View.VISIBLE
            } else if (newProgress == 100) {
                progressBar.visibility = View.GONE
            }
        }

    }

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

I've written a small, vanilla JavaScript plugin called Layout Engine, which allows you to feature detect IE 10 (and every other browser), in a simple way that cannot be faked, unlike user agent sniffing.

It adds the rendering engine name as a class on the html tag and returns a JavaScript object containing the vendor and version (where appropriate)

Check out my blog post: http://mattstow.com/layout-engine.html and get the code on GitHub: https://github.com/stowball/Layout-Engine

JFrame in full screen Java

Easiest fix ever:

for ( Window w : Window.getWindows() ) {
    GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow( w );
}

CSS Border Not Working

The height is a 100% unsure, try putting display: block; or display: inline-block;

Java: how to represent graphs?

Why not keep things simple and use an adjacency matrix or an adjacency list?

Copy files without overwrite

Robocopy, or "Robust File Copy", is a command-line directory replication command. It has been available as part of the Windows Resource Kit starting with Windows NT 4.0, and was introduced as a standard feature of Windows Vista, Windows 7 and Windows Server 2008.

   robocopy c:\Sourcepath c:\Destpath /E /XC /XN /XO

To elaborate (using Hydrargyrum, HailGallaxar and Andy Schmidt answers):

  • /E makes Robocopy recursively copy subdirectories, including empty ones.
  • /XC excludes existing files with the same timestamp, but different file sizes. Robocopy normally overwrites those.
  • /XN excludes existing files newer than the copy in the destination directory. Robocopy normally overwrites those.
  • /XO excludes existing files older than the copy in the destination directory. Robocopy normally overwrites those.

With the Changed, Older, and Newer classes excluded, Robocopy does exactly what the original poster wants - without needing to load a scripting environment.

References: Technet, Wikipedia
Download from: Microsoft Download Link (Link last verified on Mar 30, 2016)

Should a function have only one return statement?

I often have several statements at the start of a method to return for "easy" situations. For example, this:

public void DoStuff(Foo foo)
{
    if (foo != null)
    {
        ...
    }
}

... can be made more readable (IMHO) like this:

public void DoStuff(Foo foo)
{
    if (foo == null) return;

    ...
}

So yes, I think it's fine to have multiple "exit points" from a function/method.

How to combine multiple conditions to subset a data-frame using "OR"?

Just for the sake of completeness, we can use the operators [ and [[:

set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])

Several options

df[df[1] < 0.5 | df[2] == "g", ] 
df[df[[1]] < 0.5 | df[[2]] == "g", ] 
df[df["v1"] < 0.5 | df["v2"] == "g", ]

df$name is equivalent to df[["name", exact = FALSE]]

Using dplyr:

library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")

Using sqldf:

library(sqldf)
sqldf('SELECT *
      FROM df 
      WHERE v1 < 0.5 OR v2 = "g"')

Output for the above options:

          v1 v2
1 0.26550866  a
2 0.37212390  b
3 0.20168193  e
4 0.94467527  g
5 0.06178627  j

How to call servlet through a JSP page

You can submit your jsp page to servlet. For this use <form> tag.

And to redirect use:

response.sendRedirect("servleturl")

Delimiter must not be alphanumeric or backslash and preg_match

Please try with this

 $pattern = "/My name is '\(.*\)' and im fine/"; 

Saving numpy array to txt file row wise

I found that the first solution in the accepted answer to be problematic for cases where the newline character is still required. The easiest solution to the problem was doing this:

numpy.savetxt(filename, [a], delimiter='\t')

jquery animate .css

If you are needing to use CSS with the jQuery .animate() function, you can use set the duration.

$("#my_image").css({
    'left':'1000px',
    6000, ''
});

We have the duration property set to 6000.

This will set the time in thousandth of seconds: 6 seconds.

After the duration our next property "easing" changes how our CSS happens.

We have our positioning set to absolute.

There are two default ones to the absolute function: 'linear' and 'swing'.

In this example I am using linear.

It allows for it to use a even pace.

The other 'swing' allows for a exponential speed increase.

There are a bunch of really cool properties to use with animate like bounce, etc.

$(document).ready(function(){
    $("#my_image").css({
        'height': '100px',
        'width':'100px',
        'background-color':'#0000EE',
        'position':'absolute'
    });// property than value

    $("#my_image").animate({
        'left':'1000px'
    },6000, 'linear', function(){
        alert("Done Animating");
    });
});

displaying a string on the textview when clicking a button in android

This is because you DON'T associated the OnClickListener() on the button retrieve from the XML layout.

You don't need to create object because they are already created by the Android system when you inflate XML file (with the Activity.setContentLayout( int resourceLayoutId ) method).

Just retrieve them with the findViewById(...) method.

ImportError: No Module Named bs4 (BeautifulSoup)

I will advise you to uninstall the bs4 library by using this command:

pip uninstall bs4

and then install it using this command:

sudo apt-get install python3-bs4

I was facing the same problem in my Linux Ubuntu when I used the following command for installing bs4 library:

pip install bs4

How do I fix a merge conflict due to removal of a file in a branch?

I normally just run git mergetool and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.

If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:

yes d | git mergetool -- the/subdirectory

The d is provided to choose deleting each file. You can also use m to keep the modified file. Taken from the prompt you see when you run mergetool:

Use (m)odified or (d)eleted file, or (a)bort?

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

// find the first select and bind a click handler
$('#column_select').bind('click', function(){
    // retrieve the selected value
    var value = $(this).val(),
        // build a regular expression that does a head-match
        expression = new RegExp('^' + value),
        // find the second select
        $select = $('#layout_select);

    // hide all children (<option>s) of the second select,
    // check each element's value agains the regular expression built from the first select's value
    // show elements that match the expression
    $select.children().hide().filter(function(){
      return !!$(this).val().match(expression);
    }).show();
});

(this is far from perfect, but should get you there…)

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

I had a similar problem after cloning AnySoftKeyboard and opening it in Android Studio. What worked for me was deleting the AynSoftKeyboard/gradle folder and then cleaning the project via menu item Build > Clean Project.

So try deleting YourProject/gradle folder and clean the project to trigger a Gradle sync.

Hope it works for your case.

Java: Calculating the angle between two points in degrees

The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.

How to get default gateway in Mac OSX

You can try with:

route -n get default

It is not the same as GNU/Linux's route -n (or even ip route show) but is useful for checking the default route information. Also, you can check the route that packages will take to a particular host. E.g.

route -n get www.yahoo.com

The output would be similar to:

   route to: 98.137.149.56
destination: default
       mask: 128.0.0.0
    gateway: 5.5.0.1
  interface: tun0
      flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0      1500         0

IMHO netstat -nr is what you need. Even MacOSX's Network utility app(*) uses the output of netstat to show routing information. Network utility screenshot displaying routing table information

I hope this helps :)

(*) You can start Network utility with open /Applications/Utilities/Network\ Utility.app

How do I remove a key from a JavaScript object?

It's as easy as:

delete object.keyname;

or

delete object["keyname"];

mysql: get record count between two date-time

May be with:

SELECT count(*) FROM `table` 
where 
    created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 07:42:50';

or use between:

SELECT count(*) FROM `table` 
where 
    created_at between '2011-03-17 06:42:10' and '2011-03-17 07:42:50';

You can change the datetime as per your need. May be use curdate() or now() to get the desired dates.

How do I loop through or enumerate a JavaScript object?

_x000D_
_x000D_
    var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},_x000D_
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]_x000D_
for(var value in p) {_x000D_
    for (var key in value) {_x000D_
        if (p.hasOwnProperty(key)) {_x000D_
            console.log(key + " -> " + p[key]);_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Can I have two JavaScript onclick events in one element?

This one works:

<input type="button" value="test" onclick="alert('hey'); alert('ho');" />

And this one too:

function Hey()
{
    alert('hey');
}

function Ho()
{
    alert('ho');
}

.

<input type="button" value="test" onclick="Hey(); Ho();" />

So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.

How to create an Oracle sequence starting with max value from a table?

use dynamic sql

BEGIN
            DECLARE
            maxId NUMBER;
              BEGIN
              SELECT MAX(id)+1
              INTO maxId
              FROM table_name;          
              execute immediate('CREATE SEQUENCE sequane_name MINVALUE '||maxId||' START WITH '||maxId||' INCREMENT BY 1 NOCACHE NOCYCLE');
              END;
END;

C++ -- expected primary-expression before ' '

You don't need "string" in your call to wordLengthFunction().

int wordLength = wordLengthFunction(string word);

should be

int wordLength = wordLengthFunction(word);

How do you change the server header returned by nginx?

I know the post is kinda old, but I have found a solution easy that works on Debian based distribution without compiling nginx from source.

First install nginx-extras package

sudo apt install nginx-extras

Then load the nginx http headers more module by editing nginx.conf and adding the following line inside the server block

load_module modules/ngx_http_headers_more_filter_module.so;

Once it's done you'll have access to both more_set_headers and more_clear_headers directives.

SQL Server Case Statement when IS NULL

Take a look at the ISNULL function. It helps you replace NULL values for other values. http://msdn.microsoft.com/en-us/library/ms184325.aspx

How to generate .angular-cli.json file in Angular Cli?

In Angular 6, .angular-cli.json has been replaced with angular.json

For Angular < 6:

Create a new file with name '.angular-cli.json' and add this file in your main directory.

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "my-app"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

Hyphen, underscore, or camelCase as word delimiter in URIs?

here's the best of both worlds.

I also "like" underscores, besides all your positive points about them, there is also a certain old-school style to them.

So what I do is use underscores and simply add a small rewrite rule to your Apache's .htaccess file to re-write all underscores to hyphens.

https://yoast.com/apache-rewrite-dash-underscore/

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

By mid-2016 the Chromium engine (v53) supports just 3 emphasis styles:

Plain text, bold, and super-bold...

 <div style="font:normal 400 14px Arial;">Testing</div>

 <div style="font:normal 700 14px Arial;">Testing</div>

 <div style="font:normal 800 14px Arial;">Testing</div>

Error loading the SDK when Eclipse starts

Feel tired deleting the android-wear related packages each time upgrading the sdk?

Try to make some changes to devices.xml as following, you can edit the files by hand, or use some batching tools like repl.

repl is written by me, add this line to sources.list and install:

echo 'http://deb.bodz.net/ unstable/' >>/etc/apt/sources.list
alias sagu='sudo apt-get update'
alias sagi='sudo apt-get install'
sagu
sagi repl

Then, remove those <d:skin> lines and replace ###dpi to hdpi or whatever.

repl -r --filter=devices.xml --mode=regexp -- '<d:skin>.*</d:skin>' '' .
repl -r --filter=devices.xml -- '280dpi' 'hdpi' .
repl -r --filter=devices.xml -- '360dpi' 'xhdpi' .

Check a radio button with javascript

If you want to set the "1234" button, you need to use its "id":

document.getElementById("_1234").checked = true;

When you're using the browser API ("getElementById"), you don't use selector syntax; you just pass the actual "id" value you're looking for. You use selector syntax with jQuery or .querySelector() and .querySelectorAll().

How do I Search/Find and Replace in a standard string?

In C++11, you can do this as a one-liner with a call to regex_replace:

#include <string>
#include <regex>

using std::string;

string do_replace( string const & in, string const & from, string const & to )
{
  return std::regex_replace( in, std::regex(from), to );
}

string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;

output:

Removeallspaces

How to Insert Double or Single Quotes

Easier steps:

  1. Highlight the cells you want to add the quotes.
  2. Go to Format–>Cells–>Custom
  3. Copy/Paste the following into the Type field: \"@\" or \'@\'
  4. Done!

Filter Linq EXCEPT on properties

I use an extension method for Except, that allows you to compare Apples with Oranges as long as they both have something common that can be used to compare them, like an Id or Key.

public static class ExtensionMethods
{
    public static IEnumerable<TA> Except<TA, TB, TK>(
        this IEnumerable<TA> a,
        IEnumerable<TB> b,
        Func<TA, TK> selectKeyA,
        Func<TB, TK> selectKeyB, 
        IEqualityComparer<TK> comparer = null)
    {
        return a.Where(aItem => !b.Select(bItem => selectKeyB(bItem)).Contains(selectKeyA(aItem), comparer));
    }
}

then use it something like this:

var filteredApps = unfilteredApps.Except(excludedAppIds, a => a.Id, b => b);

the extension is very similar to ColinE 's answer, it's just packaged up into a neat extension that can be reused without to much mental overhead.

Error when deploying an artifact in Nexus

I had this exact problem today and the problem was that the version I was trying to release:perform was already in the Nexus repo.

In my case this was likely due to a network disconnect during an earlier invocation of release:perform. Even though I lost my connection, it appears the release succeeded.

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

For me, using Image(fit: BoxFit.fill ...) worked when in a bounded container.

Split value from one field to two

It seems that existing responses are over complicated or not a strict answer to the particular question.

I think, the simple answer is the following query:

SELECT
    SUBSTRING_INDEX(`membername`, ' ', 1) AS `memberfirst`,
    SUBSTRING_INDEX(`membername`, ' ', -1) AS `memberlast`
;

I think it is not necessary to deal with more-than-two-word names in this particular situation. If you want to do it properly, splitting can be very hard or even impossible in some cases:

  • Johann Sebastian Bach
  • Johann Wolfgang von Goethe
  • Edgar Allan Poe
  • Jakob Ludwig Felix Mendelssohn-Bartholdy
  • Petofi Sándor
  • ?? ?

In a properly designed database, human names should be stored both in parts and in whole. This is not always possible, of course.

Styling multi-line conditions in 'if' statements?

All respondents that also provide multi-conditionals for the if statement is just as ugly as the problem presented. You don't solve this problem by doing the same thing..

Even the PEP 0008 answer is repulsive.

Here is a far more readable approach

condition = random.randint(0, 100) # to demonstrate
anti_conditions = [42, 67, 12]
if condition not in anti_conditions:
    pass

Want me to eat my words? Convince me you need multi-conditionals and I'll literally print this and eat it for your amusement.

Does PHP have threading?

I have a PHP threading class that's been running flawlessly in a production environment for over two years now.

EDIT: This is now available as a composer library and as part of my MVC framework, Hazaar MVC.

See: https://git.hazaarlabs.com/hazaar/hazaar-thread

Wait some seconds without blocking UI execution

I think what you are after is Task.Delay. This doesn't block the thread like Sleep does and it means you can do this using a single thread using the async programming model.

async Task PutTaskDelay()
{
    await Task.Delay(5000);
} 

private async void btnTaskDelay_Click(object sender, EventArgs e)
{
    await PutTaskDelay();
    MessageBox.Show("I am back");
}

How to use multiple databases in Laravel

In Laravel 5.1, you specify the connection:

$users = DB::connection('foo')->select(...);

Default, Laravel uses the default connection. It is simple, isn't it?

Read more here: http://laravel.com/docs/5.1/database#accessing-connections

How to read a list of files from a folder using PHP?

There is a glob. In this webpage there are good article how to list files in very simple way:

How to read a list of files from a folder using PHP

Implement division with bit-wise operator

For integers:

public class Division {

    public static void main(String[] args) {
        System.out.println("Division: " + divide(100, 9));
    }

    public static int divide(int num, int divisor) {
        int sign = 1;
        if((num > 0 && divisor < 0) || (num < 0 && divisor > 0))
            sign = -1;

        return divide(Math.abs(num), Math.abs(divisor), Math.abs(divisor)) * sign;
    }

    public static int divide(int num, int divisor, int sum) {
        if (sum > num) {
            return 0;
        }

        return 1 + divide(num, divisor, sum + divisor);
    }
}

R: invalid multibyte string

If you want an R solution, here's a small convenience function I sometimes use to find where the offending (multiByte) character is lurking. Note that it is the next character to what gets printed. This works because print will work fine, but substr throws an error when multibyte characters are present.

find_offending_character <- function(x, maxStringLength=256){  
  print(x)
  for (c in 1:maxStringLength){
    offendingChar <- substr(x,c,c)
    #print(offendingChar) #uncomment if you want the indiv characters printed
    #the next character is the offending multibyte Character
  }    
}

string_vector <- c("test", "Se\x96ora", "works fine")

lapply(string_vector, find_offending_character)

I fix that character and run this again. Hope that helps someone who encounters the invalid multibyte string error.

How to install a specific JDK on Mac OS X?

JDK is the Java Development Kit (used to develop Java software).

JRE is the Java Runtime Environment (used to run any .jar file 'Java software').

The JDK contains a JRE inside it.

On Windows when you update Java, it updates the JRE automatically.

On Mac you do not have a JRE separated you have it, but inside the JDK, so when you update Java it will update your JRE which is inside your JDK; it doesn't install an JDK for you. You need to get it from somewhere else.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.

in_array() and multidimensional array

This will work too.

function in_array_r($item , $array){
    return preg_match('/"'.preg_quote($item, '/').'"/i' , json_encode($array));
}

Usage:

if(in_array_r($item , $array)){
    // found!
}

Getting Keyboard Input

In java we can read input values in 6 ways:

  1. Scanner Class
  2. BufferedReader
  3. Console class
  4. Command line
  5. AWT, String, GUI
  6. System properties
  1. Scanner class: present in java.util.*; package and it has many methods, based your input types you can utilize those methods. a. nextInt() b. nextLong() c. nextFloat() d. nextDouble() e. next() f. nextLine(); etc...
import java.util.Scanner;
public class MyClass {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a :");
        int a = sc.nextInt();
        System.out.println("Enter b :");
        int b = sc.nextInt();
        
        int c = a + b;
        System.out.println("Result: "+c);
    }
}
  1. BufferedReader class: present in java.io.*; package & it has many method, to read the value from the keyboard use "readLine()" : this method reading one line at a time.
import java.io.BufferedReader;
import java.io.*;
public class MyClass {
    public static void main(String args[]) throws IOException {
       BufferedReader br = new BufferedReader(new BufferedReader(new InputStreamReader(System.in)));
        System.out.println("Enter a :");
        int a = Integer.parseInt(br.readLine());
        System.out.println("Enter b :");
        int b = Integer.parseInt(br.readLine());
        
        int c = a + b;
        System.out.println("Result: "+c);
    }
}

Shell script to send email

sendmail works for me on the mac (10.6.8)

echo "Hello" | sendmail -f [email protected] [email protected]

Set EditText cursor color

There is a new way to change cursor color in latest Appcompact v21
Just change colorAccent in style like this:

 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette-->

    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">#088FC9</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">#088FC9</item>

    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <!-- THIS IS WHAT YOU'RE LOOKING FOR -->
    <item name="colorAccent">#0091BC</item> 
</style>

Then apply this style on your app theme or activities.

Update: this way only works on API 21+
Update 2: I'm not sure the minimum android version that it can work.
Tested by android version:

2.3.7 - didn't work
4.4.4 - worked
5.0 - worked
5.1 - worked

How to make a back-to-top button using CSS and HTML only?

<a href="#">Start of page</a>

"The link has the href value of "#", which by definition means the start of the current document. Thus there is no need to worry about the correct way of setting up the destination anchor..."

Source

Stopping Excel Macro executution when pressing Esc won't work

My laptop did not have Break nor Scr Lock, so I somehow managed to make it work by pressing Ctrl + Function + Right Shift (to activate 'pause').

multiple conditions for JavaScript .includes() method

Extending String native prototype:

if (!String.prototype.contains) {
    Object.defineProperty(String.prototype, 'contains', {
        value(patterns) {
            if (!Array.isArray(patterns)) {
                return false;
            }

            let value = 0;
            for (let i = 0; i < patterns.length; i++) {
                const pattern = patterns[i];
                value = value + this.includes(pattern);
            }
            return (value === 1);
        }
    });
}

Allowing you to do things like:

console.log('Hi, hope you like this option'.toLowerCase().contains(["hello", "hi", "howdy"])); // True

VBA copy cells value and format

Instead of setting the value directly you can try using copy/paste, so instead of:

Worksheets(2).Cells(a, 15) = Worksheets(1).Cells(i, 3).Value

Try this:

Worksheets(1).Cells(i, 3).Copy
Worksheets(2).Cells(a, 15).PasteSpecial Paste:=xlPasteFormats
Worksheets(2).Cells(a, 15).PasteSpecial Paste:=xlPasteValues

To just set the font to bold you can keep your existing assignment and add this:

If Worksheets(1).Cells(i, 3).Font.Bold = True Then
  Worksheets(2).Cells(a, 15).Font.Bold = True
End If

"Input string was not in a correct format."

You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.

Reading file using relative path in python project

I was thundered when the following code worked.

import os

for file in os.listdir("../FutureBookList"):
    if file.endswith(".adoc"):
        filename, file_extension = os.path.splitext(file)
        print(filename)
        print(file_extension)
        continue
    else:
        continue

So, I checked the documentation and it says:

Changed in version 3.6: Accepts a path-like object.

path-like object:

An object representing a file system path. A path-like object is either a str or...

I did a little more digging and the following also works:

with open("../FutureBookList/file.txt") as file:
   data = file.read()

Leave menu bar fixed on top when scrolled

you may want to add:

 $(window).trigger('scroll') 

to trigger the scroll event when you reload an already scrolled page. Otherwise you might get your menu out of position.

$(document).ready(function(){
        $(window).trigger('scroll');
        $(window).bind('scroll', function () {
            var pixels = 600; //number of pixels before modifying styles
            if ($(window).scrollTop() > pixels) {
                $('header').addClass('fixed');
            } else {
                $('header').removeClass('fixed');
            }
        }); 
}); 

unable to remove file that really exists - fatal: pathspec ... did not match any files

Your file .idea/workspace.xml is not under git version control. You have either not added it yet (check git status/Untracked files) or ignored it (using .gitignore or .git/info/exclude files)

You can verify it using following git command, that lists all ignored files:

git ls-files --others -i --exclude-standard

ls command: how can I get a recursive full-path listing, one line per file?

tar cf - $PWD|tar tvf -             

This is slow but works recursively and prints both directories and files. You can pipe it with awk/grep if you just want the file names without all the other info/directories:

tar cf - $PWD|tar tvf -|awk '{print $6}'|grep -v "/$"          

TypeError: Converting circular structure to JSON in nodejs

JSON doesn't accept circular objects - objects which reference themselves. JSON.stringify() will throw an error if it comes across one of these.

The request (req) object is circular by nature - Node does that.

In this case, because you just need to log it to the console, you can use the console's native stringifying and avoid using JSON:

console.log("Request data:");
console.log(req);

how to change directory using Windows command line

cd has a parameter /d, which will change drive and path with one command:

cd /d d:\temp

( see cd /?)

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

In my case, this was caused by custom manifest entries added by the maven-jar-plugin.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <archive>
            <index>true</index>
            <manifest>
                <addClasspath>true</addClasspath>
            </manifest>
            <manifestEntries>
                <git>${buildNumber}</git>
                <build-time>${timestamp}</build-time>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

Removing the following entries fixed the problem

<index>true</index>
<manifest>
    <addClasspath>true</addClasspath>
</manifest>

Random word generator- Python

There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines(), eg) for use.

Disable double-tap "zoom" option in browser on touch devices

Using CSS touch-events: none Completly takes out all the touch events. Just leaving this here in case someone also has this problems, took me 2 hours to find this solution and it's only one line of css. https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

 sudo nano /etc/nginx/nginx.conf

Add these variables to nginx.conf file:

http {  
  # .....
  proxy_connect_timeout       600;
  proxy_send_timeout          600;
  proxy_read_timeout          600;
  send_timeout                600;
}

And then restart:

service nginx reload

Does "git fetch --tags" include "git fetch"?

I'm going to answer this myself.

I've determined that there is a difference. "git fetch --tags" might bring in all the tags, but it doesn't bring in any new commits!

Turns out one has to do this to be totally "up to date", i.e. replicated a "git pull" without the merge:

$ git fetch --tags
$ git fetch

This is a shame, because it's twice as slow. If only "git fetch" had an option to do what it normally does and bring in all the tags.

How to extract a substring using regex

as in javascript:

mydata.match(/'([^']+)'/)[1]

the actual regexp is: /'([^']+)'/

if you use the non greedy modifier (as per another post) it's like this:

mydata.match(/'(.*?)'/)[1]

it is cleaner.

how to enable sqlite3 for php?

sudo apt-get install php5-cli php5-dev make

sudo apt-get install libsqlite3-0 libsqlite3-dev

sudo apt-get install php5-sqlite3

sudo apt-get remove php5-sqlite3

cd ~

wget http://pecl.php.net/get/sqlite3-0.6.tgz

tar -zxf sqlite3-0.6.tgz

cd sqlite3-0.6/

sudo phpize

sudo ./configure

That worked for me.

Read file-contents into a string in C++

The most efficient is to create a buffer of the correct size and then read the file into the buffer.

#include <fstream>
#include <vector>

int main()
{
    std::ifstream       file("Plop");
    if (file)
    {
        /*
         * Get the size of the file
         */
        file.seekg(0,std::ios::end);
        std::streampos          length = file.tellg();
        file.seekg(0,std::ios::beg);

        /*
         * Use a vector as the buffer.
         * It is exception safe and will be tidied up correctly.
         * This constructor creates a buffer of the correct length.
         * Because char is a POD data type it is not initialized.
         *
         * Then read the whole file into the buffer.
         */
        std::vector<char>       buffer(length);
        file.read(&buffer[0],length);
    }
}

C++, copy set to vector

std::copy cannot be used to insert into an empty container. To do that, you need to use an insert_iterator like so:

std::set<double> input;
input.insert(5);
input.insert(6);

std::vector<double> output;
std::copy(input.begin(), input.end(), inserter(output, output.begin())); 

Easy way to print Perl array? (with a little formatting)

For inspection/debugging check the Data::Printer module. It is meant to do one thing and one thing only:

display Perl variables and objects on screen, properly formatted (to be inspected by a human)

Example usage:

use Data::Printer;  
p @array;  # no need to pass references

The code above might output something like this (with colors!):

   [
       [0] "a",
       [1] "b",
       [2] undef,
       [3] "c",
   ]

jQuery Multiple ID selectors

Try this:

$("#upload_link,#upload_link2,#upload_link3").each(function(){
    $(this).upload({
        //whateveryouwant
    });
});

How can I uninstall an application using PowerShell?

Use:

function remove-HSsoftware{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,
ValuefromPipeline = $true,
HelpMessage="IdentifyingNumber can be retrieved with `"get-wmiobject -class win32_product`"")]
[ValidatePattern('{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}}')]
[string[]]$ids,
[parameter(Mandatory=$false,
            ValuefromPipeline=$true,
            ValueFromPipelineByPropertyName=$true,
            HelpMessage="Computer name or IP adress to query via WMI")]
[Alias('hostname,CN,computername')]
[string[]]$computers
)
begin {}
process{
    if($computers -eq $null){
    $computers = Get-ADComputer -Filter * | Select dnshostname |%{$_.dnshostname}
    }
    foreach($computer in $computers){
        foreach($id in $ids){
            write-host "Trying to uninstall sofware with ID ", "$id", "from computer ", "$computer"
            $app = Get-WmiObject -class Win32_Product -Computername "$computer" -Filter "IdentifyingNumber = '$id'"
            $app | Remove-WmiObject

        }
    }
}
end{}}
 remove-hssoftware -ids "{8C299CF3-E529-414E-AKD8-68C23BA4CBE8}","{5A9C53A5-FF48-497D-AB86-1F6418B569B9}","{62092246-CFA2-4452-BEDB-62AC4BCE6C26}"

It's not fully tested, but it ran under PowerShell 4.

I've run the PS1 file as it is seen here. Letting it retrieve all the Systems from the AD and trying to uninstall multiple applications on all systems.

I've used the IdentifyingNumber to search for the Software cause of David Stetlers input.

Not tested:

  1. Not adding ids to the call of the function in the script, instead starting the script with parameter IDs
  2. Calling the script with more then 1 computer name not automatically retrieved from the function
  3. Retrieving data from the pipe
  4. Using IP addresses to connect to the system

What it does not:

  1. It doesn't give any information if the software actually was found on any given system.
  2. It does not give any information about failure or success of the deinstallation.

I wasn't able to use uninstall(). Trying that I got an error telling me that calling a method for an expression that has a value of NULL is not possible. Instead I used Remove-WmiObject, which seems to accomplish the same.

CAUTION: Without a computer name given it removes the software from ALL systems in the Active Directory.

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

You can replace

document.getElementById(this.state.baction).addPrecent(10);

with

this.refs[this.state.baction].addPrecent(10);


  <Progressbar completed={25} ref="Progress1" id="Progress1"/>

Export data from R to Excel

writexl, without Java requirement:

# install.packages("writexl")
library(writexl)
tempfile <- write_xlsx(iris)

How to convert a GUID to a string in C#?

Guid guidId = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
string guidValue = guidId.ToString("D"); //return with hyphens

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

New self vs. new static

In addition to others' answers :

static:: will be computed using runtime information.

That means you can't use static:: in a class property because properties values :

Must be able to be evaluated at compile time and must not depend on run-time information.

class Foo {
    public $name = static::class;

}

$Foo = new Foo;
echo $Foo->name; // Fatal error

Using self::

class Foo {
    public $name = self::class;

}
$Foo = new Foo;
echo $Foo->name; // Foo

Please note that the Fatal error comment in the code i made doesn't indicate where the error happened, the error happened earlier before the object was instantiated as @Grapestain mentioned in the comments

Best C++ IDE or Editor for Windows

Emacs. Xemacs works fine under Windows. For using it as an IDE, I recommend running it under Cygwin.

CSS @media print issues with background-color;

Do not set the background-color inside the print stylesheet. Just set the attribute in the normal css file and it works fine :)

Checkout this example: The Ultimate Print HTML Template with Header & Footer

Demo: The Ultimate Print HTML Template with Header & Footer Demo

java.io.FileNotFoundException: (Access is denied)

  1. check the rsp's reply
  2. check that you have permissions to read the file
  3. check whether the file is not locked by other application. It is relevant mostly if you are on windows. for example I think that you can get the exception if you are trying to read the file while it is opened in notepad

round() doesn't seem to be rounding properly

round(5.59, 1) is working fine. The problem is that 5.6 cannot be represented exactly in binary floating point.

>>> 5.6
5.5999999999999996
>>> 

As Vinko says, you can use string formatting to do rounding for display.

Python has a module for decimal arithmetic if you need that.

What "wmic bios get serialnumber" actually retrieves?

wmic bios get serialnumber     

if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)

I had to do exactly that.:):)

Single quotes vs. double quotes in Python

Triple quoted comments are an interesting subtopic of this question. PEP 257 specifies triple quotes for doc strings. I did a quick check using Google Code Search and found that triple double quotes in Python are about 10x as popular as triple single quotes -- 1.3M vs 131K occurrences in the code Google indexes. So in the multi line case your code is probably going to be more familiar to people if it uses triple double quotes.

Web API optional parameters

I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.

In case anyone else needs it, in order to have optional parameters in a query string such as:

  • ~/api/products/filter?apc=AA&xpc=BB
  • ~/api/products/filter?sku=7199123

you would use:

[Route("products/filter/{apc?}/{xpc?}/{sku?}")]
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

It seems odd to have to define default values for the method parameters when these types already have a default.

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a
armv7l

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

As johnnyynnoj mentioned ng-repeat creates a new scope. I would in fact use a function to set the value. See plunker

JS:

$scope.setSelected = function(selected) {
  $scope.selected = selected;
}

HTML:

{{ selected }}

<ul>
  <li ng-class="{current: selected == 100}">
     <a href ng:click="setSelected(100)">ABC</a>
  </li>
  <li ng-class="{current: selected == 101}">
     <a href ng:click="setSelected(101)">DEF</a>
  </li>
  <li ng-class="{current: selected == $index }" 
      ng-repeat="x in [4,5,6,7]">
     <a href ng:click="setSelected($index)">A{{$index}}</a>
  </li>
</ul>

<div  
  ng:show="selected == 100">
  100        
</div>
<div  
  ng:show="selected == 101">
  101        
</div>
<div ng-repeat="x in [4,5,6,7]" 
  ng:show="selected == $index">
  {{ $index }}        
</div>

PHP: How to get current time in hour:minute:second?

You can have both formats as an argument to the function date():

date("d-m-Y H:i:s")

Check the manual for more info : http://php.net/manual/en/function.date.php

As pointed out by @ThomasVdBerge to display minutes you need the 'i' character

VueJs get url query

Current route properties are present in this.$route, this.$router is the instance of router object which gives the configuration of the router. You can get the current route query using this.$route.query

Bootstrap 3 Slide in Menu / Navbar on Mobile

Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu

Bootstrap 3

I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/

The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..

http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook

List supported SSL/TLS versions for a specific OpenSSL build

When you run OPENSSL command using s_client this is the output. See the Cipher, if the cipher NULL it means that version of TLS is not supported.

TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : ECDHE-RSA-AES256
    Session-ID: A84600002D4945DE6
    Session-ID-ctx:
    Master-Key:  
    Start Time: 15852343333860
    Timeout   : 2343 (sec)
    Verify return code: 0 (ok)

how to change onclick event with jquery?

@Amirali

console.log(document.getElementById("SAVE_FOOTER"));
document.getElementById("SAVE_FOOTER").attribute("onclick","console.log('c')");

throws:

Uncaught TypeError: document.getElementById(...).attribute is not a function

in chrome.

Element exists and is dumped in console;

Create Directory When Writing To File In Node.js

Shameless plug alert!

You will have to check for each directory in the path structure you want and create it manually if it doesn't exist. All the tools to do so are already there in Node's fs module, but you can do all of that simply with my mkpath module: https://github.com/jrajav/mkpath