Programs & Examples On #Level of detail

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;

In C#, how to check if a TCP port is available?

You don't have to know what ports are open on your local machine to connect to some remote TCP service (unless you want to use a specific local port, but usually that is not the case).

Every TCP/IP connection is identified by 4 values: remote IP, remote port number, local IP, local port number, but you only need to know remote IP and remote port number to establish a connection.

When you create tcp connection using

TcpClient c;
c = new TcpClient(remote_ip, remote_port);

Your system will automatically assign one of many free local port numbers to your connection. You don't need to do anything. You might also want to check if a remote port is open. but there is no better way to do that than just trying to connect to it.

What does the "+" (plus sign) CSS selector mean?

The + selector targets the one element after. On a similar note, the ~ selector targets all the elements after. Here's a diagram, if you're confused:

enter image description here

How can I convert spaces to tabs in Vim or Linux?

Using Vim to expand all leading spaces (wider than 'tabstop'), you were right to use retab but first ensure 'expandtab' is reset (:verbose set ts? et? is your friend). retab takes a range, so I usually specify % to mean "the whole file".

:set tabstop=2      " To match the sample file
:set noexpandtab    " Use tabs, not spaces
:%retab!            " Retabulate the whole file

Before doing anything like this (particularly with Python files!), I usually set 'list', so that I can see the whitespace and change.

I have the following mapping in my .vimrc for this:

nnoremap    <F2> :<C-U>setlocal lcs=tab:>-,trail:-,eol:$ list! list? <CR>

Is it possible to change the content HTML5 alert messages?

Yes:

<input required title="Enter something OR ELSE." /> 

The title attribute will be used to notify the user of a problem.

Saving images in Python at a very high quality

If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image:

plt.savefig('destination_path.eps', format='eps')

I have found that EPS files work best and the dpi parameter is what really makes them look good in a document.

To specify the orientation of the figure before saving, simply call the following before the plt.savefig call, but after creating the plot (assuming you have plotted using an axes with the name ax):

ax.view_init(elev=elevation_angle, azim=azimuthal_angle)

Where elevation_angle is a number (in degrees) specifying the polar angle (down from vertical z axis) and the azimuthal_angle specifies the azimuthal angle (around the z axis).

I find that it is easiest to determine these values by first plotting the image and then rotating it and watching the current values of the angles appear towards the bottom of the window just below the actual plot. Keep in mind that the x, y, z, positions appear by default, but they are replaced with the two angles when you start to click+drag+rotate the image.

Visual Studio Code compile on save

Instead of building a single file and bind Ctrl+S to trigger that build I would recommend to start tsc in watch mode using the following tasks.json file:

{
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "args": ["-w", "-p", "."],
    "showOutput": "silent",
    "isWatching": true,
    "problemMatcher": "$tsc-watch"
}

This will once build the whole project and then rebuild the files that get saved independent of how they get saved (Ctrl+S, auto save, ...)

AngularJS - Find Element with attribute

You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)

If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.

So, for this HTML:

<div ng-controller='MyCtrl'>
    <div>
        <div name='foo' class='myElementClass'>this one</div>
    </div>
</div>

This AngularJS code should work:

angular.module('MyClient').controller('MyCtrl', [
    '$scope',
    '$element',
    '$log',
    function ($scope, $element, $log) {

        // Find the element by its class attribute, within your controller's scope
        var myElements = $element.find('.myElementClass');

        // myElements is now an array of jQuery DOM elements

        if (myElements.length == 0) {
            // Not found. Are you sure you've included the full jQuery?
        } else {
            // There should only be one, and it will be element 0
            $log.debug(myElements[0].name); // "foo"
        }

    }
]);

init-param and context-param

<init-param> will be used if you want to initialize some parameter for a particular servlet. When request come to servlet first its init method will be called then doGet/doPost whereas if you want to initialize some variable for whole application you will need to use <context-param> . Every servlet will have access to the context variable.

c++ Read from .csv file

a csv-file is just like any other file a stream of characters. the getline reads from the file up to a delimiter however in your case the delimiter for the last item is not ' ' as you assume

getline(file, genero, ' ') ; 

it is newline \n

so change that line to

getline(file, genero); // \n is default delimiter

HTML iframe - disable scroll

It seems to work using

html, body { overflow: hidden; }

inside the IFrame

edit: Of course this is only working, if you have access to the Iframe's content (which I have in my case)

What is the difference between a generative and a discriminative algorithm?

My two cents: Discriminative approaches highlight differences Generative approaches do not focus on differences; they try to build a model that is representative of the class. There is an overlap between the two. Ideally both approaches should be used: one will be useful to find similarities and the other will be useful to find dis-similarities.

How to right-align and justify-align in Markdown?

I used

<p align='right'>Farhan Khan</p>

and it worked for me on Google Colaboratory. Funnily enough it does not work anywhere else?

How to mock private method for testing using PowerMock?

I don't see a problem here. With the following code using the Mockito API, I managed to do just that :

public class CodeWithPrivateMethod {

    public void meaningfulPublicApi() {
        if (doTheGamble("Whatever", 1 << 3)) {
            throw new RuntimeException("boom");
        }
    }

    private boolean doTheGamble(String whatever, int binary) {
        Random random = new Random(System.nanoTime());
        boolean gamble = random.nextBoolean();
        return gamble;
    }
}

And here's the JUnit test :

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());

        when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))
                .withArguments(anyString(), anyInt())
                .thenReturn(true);

        spy.meaningfulPublicApi();
    }
}

How do I merge a git tag onto a branch

Remember before you merge you need to update the tag, it's quite different from branches (git pull origin tag_name won't update your local tags). Thus, you need the following command:

git fetch --tags origin

Then you can perform git merge tag_name to merge the tag onto a branch.

Python: convert string to byte array

encode function can help you here, encode returns an encoded version of the string

In [44]: str = "ABCD"

In [45]: [elem.encode("hex") for elem in str]
Out[45]: ['41', '42', '43', '44']

or you can use array module

In [49]: import array

In [50]: print array.array('B', "ABCD")
array('B', [65, 66, 67, 68])

Unknown column in 'field list' error on MySQL Update query

A query like this will also cause the error:

SELECT table1.id FROM table2

Where the table is specified in column select and not included in the from clause.

How to sort an array of objects in Java?

Java 8


Using lambda expressions

Arrays.sort(myTypes, (a,b) -> a.name.compareTo(b.name));

Test.java

public class Test {

    public static void main(String[] args) {

        MyType[] myTypes = {
                new MyType("John", 2, "author1", "publisher1"),
                new MyType("Marry", 298, "author2", "publisher2"),
                new MyType("David", 3, "author3", "publisher3"),
        };

        System.out.println("--- before");
        System.out.println(Arrays.asList(myTypes));
        Arrays.sort(myTypes, (a, b) -> a.name.compareTo(b.name));
        System.out.println("--- after");
        System.out.println(Arrays.asList(myTypes));

    }

}

MyType.java

public class MyType {

    public String name;
    public int id;
    public String author;
    public String publisher;

    public MyType(String name, int id, String author, String publisher) {
        this.name = name;
        this.id = id;
        this.author = author;
        this.publisher = publisher;
    }

    @Override
    public String toString() {
        return "MyType{" +
                "name=" + name + '\'' +
                ", id=" + id +
                ", author='" + author + '\'' +
                ", publisher='" + publisher + '\'' +
                '}' + System.getProperty("line.separator");
    }
}

Output:

--- before
[MyType{name=John', id=2, author='author1', publisher='publisher1'}
, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}
, MyType{name=David', id=3, author='author3', publisher='publisher3'}
]
--- after
[MyType{name=David', id=3, author='author3', publisher='publisher3'}
, MyType{name=John', id=2, author='author1', publisher='publisher1'}
, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}
]

Using method references

Arrays.sort(myTypes, MyType::compareThem);

where compareThem has to be added in MyType.java:

public static int compareThem(MyType a, MyType b) {
    return a.name.compareTo(b.name);
}

.ps1 cannot be loaded because the execution of scripts is disabled on this system

There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.

Look in your Windows directory for System32 and SysWOW64.

Repeat these steps for each directory:

  1. Navigate to WindowsPowerShell\v1.0 and launch powershell.exe
  2. Check the current setting for ExecutionPolicy:

    Get-ExecutionPolicy -List

  3. Set the ExecutionPolicy for the level and scope you want, for example:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.

You can read a lot more here: Running Windows PowerShell Scripts

Reading a text file using OpenFileDialog in windows forms

for this approach, you will need to add system.IO to your references by adding the next line of code below the other references near the top of the c# file(where the other using ****.** stand).

using System.IO;

this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))

both should be quite easy to understand and use.


    string pathToFile = "";//to save the location of the selected object
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Title = "Open Text File";
        theDialog.Filter = "TXT files|*.txt";
        theDialog.InitialDirectory = @"C:\";
        if (theDialog.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show(theDialog.FileName.ToString());
            pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object

        }

        if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
        {
            //method1
            string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
            string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();

            //method2
            string text = "";
            using(StreamReader sr =new StreamReader(pathToFile))
            {
                text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
            }
        }
    }

To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.


to add the data to your class you can use the constructor to add the data like:

  public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
        {
            EmployeeNum = EMPLOYEENUM;
            Name = NAME;
            Address = ADRESS;
            Wage = WAGE;
            Hours = HOURS;
        }

or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).

DataRow: Select cell value by a given column name

On top of what Jimmy said, you can also make the select generic by using Convert.ChangeType along with the necessary null checks:

public T GetColumnValue<T>(DataRow row, string columnName)
  {
        T value = default(T);
        if (row.Table.Columns.Contains(columnName) && row[columnName] != null && !String.IsNullOrWhiteSpace(row[columnName].ToString()))
        {
            value = (T)Convert.ChangeType(row[columnName].ToString(), typeof(T));
        }

        return value;
  }

How to implement HorizontalScrollView like Gallery?

Try this code:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="100dip"
tools:context=".MainActivity" >
<HorizontalScrollView
    android:id="@+id/hsv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:fillViewport="true"
    android:measureAllChildren="false"
    android:scrollbars="none" >
    <LinearLayout
        android:id="@+id/innerLay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >
        <LinearLayout
            android:id="@+id/asthma_action_plan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/action_plan" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/controlled_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/controlled" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/as_needed_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/as_needed" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/rescue_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/rescue" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/your_symptoms"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/symptoms" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/your_triggers"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/triggers" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/wheeze_rate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/wheeze_rate" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/peak_flow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/peak_flow" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>
</HorizontalScrollView>
<TextView
    android:layout_width="fill_parent"
    android:layout_height="0.2dp"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/hsv"
    android:background="@drawable/ln" />
<LinearLayout
    android:id="@+id/prev"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:paddingLeft="5dip"
    android:paddingRight="5dip"
    android:descendantFocusability="blocksDescendants" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/prev_arrow" />
</LinearLayout>
<LinearLayout
    android:id="@+id/next"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:paddingLeft="5dip"
    android:paddingRight="5dip"
    android:descendantFocusability="blocksDescendants" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/next_arrow" />
</LinearLayout>
</RelativeLayout>

grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:src="@drawable/ic_launcher" />
</LinearLayout>

MainActivity.java

import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {

LinearLayout asthmaActionPlan, controlledMedication, asNeededMedication,
        rescueMedication, yourSymtoms, yourTriggers, wheezeRate, peakFlow;
LayoutParams params;
LinearLayout next, prev;
int viewWidth;
GestureDetector gestureDetector = null;
HorizontalScrollView horizontalScrollView;
ArrayList<LinearLayout> layouts;
int parentLeft, parentRight;
int mWidth;
int currPosition, prevPosition;

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

    prev = (LinearLayout) findViewById(R.id.prev);
    next = (LinearLayout) findViewById(R.id.next);
    horizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv);
    gestureDetector = new GestureDetector(new MyGestureDetector());
    asthmaActionPlan = (LinearLayout) findViewById(R.id.asthma_action_plan);
    controlledMedication = (LinearLayout) findViewById(R.id.controlled_medication);
    asNeededMedication = (LinearLayout) findViewById(R.id.as_needed_medication);
    rescueMedication = (LinearLayout) findViewById(R.id.rescue_medication);
    yourSymtoms = (LinearLayout) findViewById(R.id.your_symptoms);
    yourTriggers = (LinearLayout) findViewById(R.id.your_triggers);
    wheezeRate = (LinearLayout) findViewById(R.id.wheeze_rate);
    peakFlow = (LinearLayout) findViewById(R.id.peak_flow);

    Display display = getWindowManager().getDefaultDisplay();
    mWidth = display.getWidth(); // deprecated
    viewWidth = mWidth / 3;
    layouts = new ArrayList<LinearLayout>();
    params = new LayoutParams(viewWidth, LayoutParams.WRAP_CONTENT);

    asthmaActionPlan.setLayoutParams(params);
    controlledMedication.setLayoutParams(params);
    asNeededMedication.setLayoutParams(params);
    rescueMedication.setLayoutParams(params);
    yourSymtoms.setLayoutParams(params);
    yourTriggers.setLayoutParams(params);
    wheezeRate.setLayoutParams(params);
    peakFlow.setLayoutParams(params);

    layouts.add(asthmaActionPlan);
    layouts.add(controlledMedication);
    layouts.add(asNeededMedication);
    layouts.add(rescueMedication);
    layouts.add(yourSymtoms);
    layouts.add(yourTriggers);
    layouts.add(wheezeRate);
    layouts.add(peakFlow);

    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    horizontalScrollView.smoothScrollTo(
                            (int) horizontalScrollView.getScrollX()
                                    + viewWidth,
                            (int) horizontalScrollView.getScrollY());
                }
            }, 100L);
        }
    });

    prev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    horizontalScrollView.smoothScrollTo(
                            (int) horizontalScrollView.getScrollX()
                                    - viewWidth,
                            (int) horizontalScrollView.getScrollY());
                }
            }, 100L);
        }
    });

    horizontalScrollView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            }
            return false;
        }
    });
}

class MyGestureDetector extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        if (e1.getX() < e2.getX()) {
            currPosition = getVisibleViews("left");
        } else {
            currPosition = getVisibleViews("right");
        }

        horizontalScrollView.smoothScrollTo(layouts.get(currPosition)
                .getLeft(), 0);
        return true;
    }
}

public int getVisibleViews(String direction) {
    Rect hitRect = new Rect();
    int position = 0;
    int rightCounter = 0;
    for (int i = 0; i < layouts.size(); i++) {
        if (layouts.get(i).getLocalVisibleRect(hitRect)) {
            if (direction.equals("left")) {
                position = i;
                break;
            } else if (direction.equals("right")) {
                rightCounter++;
                position = i;
                if (rightCounter == 2)
                    break;
            }
        }
    }
    return position;
}
}

Let me know if any issue enjoy...

How to redirect from one URL to another URL?

location.href = "Pagename.html";

Tomcat Server Error - Port 8080 already in use

I would suggest to end java.exe or javaw.exe process from task manager and try again. This will not end the entire eclipse application but will free the port.

Show diff between commits

  1. gitk --all
  2. Select the first commit
  3. Right click on the other, then diff selected → this

How to write to a file in Scala?

A simple answer:

import java.io.File
import java.io.PrintWriter

def writeToFile(p: String, s: String): Unit = {
    val pw = new PrintWriter(new File(p))
    try pw.write(s) finally pw.close()
  }

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

When to use <span> instead <p>?

tag is a block-level element but tag is inline element.Normally we use span tag to style inside block elements.but you don't need to use span tag to inline style.you have to do is; convert block element to inline element using "display: inline"

Javascript: Setting location.href versus location

Just to clarify, you can't do location.split('#'), location is an object, not a string. But you can do location.href.split('#'); because location.href is a string.

How to hide columns in HTML table?

you can also use:

<td style="visibility:hidden;">
or
<td style="visibility:collapse;">

The difference between them that "hidden" hides the cell but it holds the space but with "collapse" the space is not held like display:none. This is significant when hidding a whole column or row.

How do I terminate a thread in C++11?

Tips of using OS-dependent function to terminate C++ thread:

  1. std::thread::native_handle() only can get the thread’s valid native handle type before calling join() or detach(). After that, native_handle() returns 0 - pthread_cancel() will coredump.

  2. To effectively call native thread termination function(e.g. pthread_cancel()), you need to save the native handle before calling std::thread::join() or std::thread::detach(). So that your native terminator always has a valid native handle to use.

More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .

How can I get the concatenation of two lists in Python without modifying either one?

Just to let you know:

When you write list1 + list2, you are calling the __add__ method of list1, which returns a new list. in this way you can also deal with myobject + list1 by adding the __add__ method to your personal class.

how to refresh Select2 dropdown menu after ajax loading different content?

Got the same problem in 11 11 19, so sorry for possible necroposting. The only what helped was next solution:

var drop = $('#product_1');   // get our element, **must be unique**;
var settings = drop.attr('data-krajee-select2');  pick krajee attrs of our elem;
var drop_id = drop.attr('id');  // take id 
settings = window[settings];  // take previous settings from window;
drop.select2(settings);  // initialize select2 element with it;
$('.kv-plugin-loading').remove(); // remove loading animation;

It's, maybe, not so good, nice and precise solution, and maybe I still did not clearly understood, how it works and why, but this was the only, what keeps my select2 dropdowns, gotten by ajax, alive. Hope, this solution will be usefull or may push you in right decision in problem fixing

How to perform a for-each loop over all the files under a specified path?

Use command substitution instead of quotes to execute find instead of passing the command as a string:

for line in $(find . -iname '*.txt'); do 
     echo $line
     ls -l $line; 
done

JavaScript override methods

Since this is a top hit on Google, I'd like to give an updated answer.

Using ES6 classes makes inheritance and method overriding a lot easier:

'use strict';

class A {
    speak() {
        console.log("I'm A");
    }
}

class B extends A {
    speak() {
        super.speak();

        console.log("I'm B");
    }
}

var a = new A();
a.speak();
// Output:
// I'm A

var b = new B();
b.speak();
// Output:
// I'm A
// I'm B

The super keyword refers to the parent class when used in the inheriting class. Also, all methods on the parent class are bound to the instance of the child, so you don't have to write super.method.apply(this);.

As for compatibility: the ES6 compatibility table shows only the most recent versions of the major players support classes (mostly). V8 browsers have had them since January of this year (Chrome and Opera), and Firefox, using the SpiderMonkey JS engine, will see classes next month with their official Firefox 45 release. On the mobile side, Android still does not support this feature, while iOS 9, release five months ago, has partial support.

Fortunately, there is Babel, a JS library for re-compiling Harmony code into ES5 code. Classes, and a lot of other cool features in ES6 can make your Javascript code a lot more readable and maintainable.

Apache default VirtualHost

I found the answer: I remembered that Apache uses the first block if no other matching block is found, so I've added a block without a serveralias at the top of the blocks:

NameVirtualHost *

<VirtualHost *>
    DocumentRoot /defaultdir/
</VirtualHost>

<VirtualHost *>
    ServerAdmin [email protected]
    DocumentRoot /someOtherDir/
    ServerAlias ip.of.the.server
</VirtualHost>

<VirtualHost *>
    ServerAdmin [email protected]
    DocumentRoot /someroot/
    ServerAlias domain.com *.domain.com
</VirtualHost>

How to change collation of database, table, column?

I was surprised to learn, and so I had to come back here and report, that the excellent and well maintained Interconnect/it SAFE SEARCH AND REPLACE ON DATABASE script has some options for converting tables to utf8 / unicode, and even to convert to innodb. It's a script commonly used to migrate a database driven website (Wordpress, Drupal, Joomla, etc) from one domain to another.

interconnect script buttons

Bootstrap full responsive navbar with logo or brand name text

If you want to achieve this (you can resize the window to see how it will look for mobile version), all you have to do is to have 2 logo images (1 for desktop and one for mobile) and display them depending of the enviroment using visible-xs and hidden-xs classes.

So i used something like this:

<img class="hidden-xs" src="http://placehold.it/150x50&text=Logo" alt="">
<img class="visible-xs" src="http://placehold.it/120x40&text=Logo" alt=""> 

And ofcourse, i styled the mobile logo using:

@media (max-width: 767px) { 
    .navbar-brand {
        padding: 0;        
    }

    .navbar-brand img {
        margin-top: 5px;
        margin-left: 5px;
    }
}

You can see all the code here. In case you need a text on mobile version insted of the logo, it's not a big deal. Just replace the logo with a <h1 class="visible-xs">AppName</h3> and change the style inside the media query like this:

@media (max-width: 767px) { 
    .navbar-brand {
        padding: 0;        
    }

    .navbar-brand h1{
        //here add your style depending of the position you want the text to be placed
    }
} 

EDIT:

You need this conditions to make it work:

.navbar-toggle {
   margin: 23px 0; 
}

.navbar-nav, .navbar-nav li, .navbar-nav li a {
  height: 80px;
  line-height: 80px;
}

.navbar-nav li a {
  padding-top: 0;
  padding-bottom:0;
}

Convert pandas.Series from dtype object to float, and errors to nans

In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]: 
0     1
1     2
2     3
3     4
4   NaN
dtype: float64

iOS 6 apps - how to deal with iPhone 5 screen size?

I have just finished updating and sending an iOS 6.0 version of one of my Apps to the store. This version is backwards compatible with iOS 5.0, thus I kept the shouldAutorotateToInterfaceOrientation: method and added the new ones as listed below.

I had to do the following:

Autorotation is changing in iOS 6. In iOS 6, the shouldAutorotateToInterfaceOrientation: method of UIViewController is deprecated. In its place, you should use the supportedInterfaceOrientationsForWindow: and shouldAutorotate methods. Thus, I added these new methods (and kept the old for iOS 5 compatibility):

- (BOOL)shouldAutorotate {
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAllButUpsideDown;    
}
  • Used the view controller’s viewWillLayoutSubviews method and adjust the layout using the view’s bounds rectangle.
  • Modal view controllers: The willRotateToInterfaceOrientation:duration:,
    willAnimateRotationToInterfaceOrientation:duration:, and
    didRotateFromInterfaceOrientation: methods are no longer called on any view controller that makes a full-screen presentation over
    itself
    —for example, presentViewController:animated:completion:.
  • Then I fixed the autolayout for views that needed it.
  • Copied images from the simulator for startup view and views for the iTunes store into PhotoShop and exported them as png files.
  • The name of the default image is: [email protected] and the size is 640×1136. It´s also allowed to supply 640×1096 for the same portrait mode (Statusbar removed). Similar sizes may also be supplied in landscape mode if your app only allows landscape orientation on the iPhone.
  • I have dropped backward compatibility for iOS 4. The main reason for that is because support for armv6 code has been dropped. Thus, all devices that I am able to support now (running armv7) can be upgraded to iOS 5.
  • I am also generation armv7s code to support the iPhone 5 and thus can not use any third party frameworks (as Admob etc.) until they are updated.

That was all but just remember to test the autorotation in iOS 5 and iOS 6 because of the changes in rotation.

Bootstrap col-md-offset-* not working

check this bootply

this is wrong because bootstrap using margin-left:**%

.jumbotron h2:first-child {
   margin: 120px 0 0;
}

How to Sort Date in descending order From Arraylist Date in android?

Easier alternative to above answers

  1. If Object(Model Class/POJO) contains the date in String datatype.

    private void sortArray(ArrayList<myObject> arraylist) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //your own date format
    if (reports != null) {
        Collections.sort(arraylist, new Comparator<myObject>() {
            @Override
            public int compare(myObject o1, myObject o2) {
                try {
                    return simpleDateFormat.parse(o2.getCreated_at()).compareTo(simpleDateFormat.parse(o1.getCreated_at()));
                } catch (ParseException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }
    
  2. If Object(Model Class/POJO) contains date in Date datatype

    private void sortArray(ArrayList<myObject> arrayList) {
    if (arrayList != null) {
        Collections.sort(arrayList, new Comparator<myObject>() {
            @Override
            public int compare(myObject o1, myObject o2) {
                return o2.getCreated_at().compareTo(o1.getCreated_at()); }
        });
    } }
    

The above code is for sorting the array in descending order of date, swap o1 and o2 for ascending order.

os.walk without digging into directories below

for path, dirs, files in os.walk('.'):
    print path, dirs, files
    del dirs[:] # go only one level deep

npm check and update package if needed

npm outdated will identify packages that should be updated, and npm update <package name> can be used to update each package. But prior to [email protected], npm update <package name> will not update the versions in your package.json which is an issue.

The best workflow is to:

  1. Identify out of date packages
  2. Update the versions in your package.json
  3. Run npm update to install the latest versions of each package

Check out npm-check-updates to help with this workflow.

  • Install npm-check-updates
  • Run npm-check-updates to list what packages are out of date (basically the same thing as running npm outdated)
  • Run npm-check-updates -u to update all the versions in your package.json (this is the magic sauce)
  • Run npm update as usual to install the new versions of your packages based on the updated package.json

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

Putting an if-elif-else statement on one line?

You can use nested ternary if statements.

# if-else ternary construct
country_code = 'USA'
is_USA = True if country_code == 'USA' else False
print('is_USA:', is_USA)

# if-elif-else ternary construct
# Create function to avoid repeating code.
def get_age_category_name(age):
    age_category_name = 'Young' if age <= 40 else ('Middle Aged' if age > 40 and age <= 65 else 'Senior')
    return age_category_name

print(get_age_category_name(25))
print(get_age_category_name(50))
print(get_age_category_name(75))

How to set environment variable for everyone under my linux system?

man 8 pam_env

man 5 pam_env.conf

If all login services use PAM, and all login services have session required pam_env.so in their respective /etc/pam.d/* configuration files, then all login sessions will have some environment variables set as specified in pam_env's configuration file.

On most modern Linux distributions, this is all there by default -- just add your desired global environment variables to /etc/security/pam_env.conf.

This works regardless of the user's shell, and works for graphical logins too (if xdm/kdm/gdm/entrance/… is set up like this).

Most common C# bitwise operations on enums

@Drew

Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:

[Flags]
public enum TestFlags
{
    One = 1,
    Two = 2,
    Three = 4,
    Four = 8,
    Five = 16,
    Six = 32,
    Seven = 64,
    Eight = 128,
    Nine = 256,
    Ten = 512
}


class Program
{
    static void Main(string[] args)
    {
        TestFlags f = TestFlags.Five; /* or any other enum */
        bool result = false;

        Stopwatch s = Stopwatch.StartNew();
        for (int i = 0; i < 10000000; i++)
        {
            result |= f.HasFlag(TestFlags.Three);
        }
        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*

        s.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            result |= (f & TestFlags.Three) != 0;
        }
        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*        

        Console.ReadLine();
    }
}

Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.

curl posting with header application/x-www-form-urlencoded

 $curl = curl_init();
 curl_setopt_array($curl, array(
            CURLOPT_URL => "http://example.com",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "value1=111&value2=222",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded"
            ),
        ));
 $response = curl_exec($curl);
 $err = curl_error($curl);

 curl_close($curl);

 if (!$err)
 {
      var_dump($response);
 }

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:

$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session 

or

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

ASP.NET MVC: What is the purpose of @section?

A good example is Javascript. You want this to be at the bottom of the page that is rendered in the browser because this is best practice.

How would you do this from a View based on a Layout/Masterpage where you can only access the middle of the page?

You do this by declaring a Scripts section at the bottom of the Layout page. Then you can add content, in this case Javascript includes (I hope!), from your View page to the bottom of your layout page.

Finding rows that don't contain numeric data in Oracle

enter image description hereI tray order by with problematic column and i find rows with column.

SELECT 
 D.UNIT_CODE,
         D.CUATM,
         D.CAPITOL,
          D.RIND,
          D.COL1  AS COL1


FROM
  VW_DATA_ALL_GC  D
  
  WHERE
  
   (D.PERIOADA IN (:pPERIOADA))  AND   
   (D.FORM = 62) 
   AND D.COL1 IS NOT NULL
 --  AND REGEXP_LIKE (D.COL1, '\[\[:alpha:\]\]')
 
-- AND REGEXP_LIKE(D.COL1, '\[\[:digit:\]\]')
 
 --AND REGEXP_LIKE(TO_CHAR(D.COL1), '\[^0-9\]+')
 
 
   GROUP BY 
    D.UNIT_CODE,
         D.CUATM,
         D.CAPITOL,
          D.RIND ,
          D.COL1  
         
         
        ORDER BY 
        D.COL1

How to read/process command line arguments?

The canonical solution in the standard library is argparse (docs):

Here is an example:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
                    help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
                    action="store_false", dest="verbose", default=True,
                    help="don't print status messages to stdout")

args = parser.parse_args()

argparse supports (among other things):

  • Multiple options in any order.
  • Short and long options.
  • Default values.
  • Generation of a usage help message.

string in namespace std does not name a type

You need to add:

#include <string>

In your header file.

Can local storage ever be considered secure?

Well, the basic premise here is: no, it is not secure yet.

Basically, you can't run crypto in JavaScript: JavaScript Crypto Considered Harmful.

The problem is that you can't reliably get the crypto code into the browser, and even if you could, JS isn't designed to let you run it securely. So until browsers have a cryptographic container (which Encrypted Media Extensions provide, but are being rallied against for their DRM purposes), it will not be possible to do securely.

As far as a "Better way", there isn't one right now. Your only alternative is to store the data in plain text, and hope for the best. Or don't store the information at all. Either way.

Either that, or if you need that sort of security, and you need local storage, create a custom application...

Length of string in bash

UTF-8 string length

In addition to fedorqui's correct answer, I would like to show the difference between string length and byte length:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
LANG=$oLang LC_ALL=$oLcAll
printf "%s is %d char len, but %d bytes len.\n" "${myvar}" $chrlen $bytlen

will render:

Généralités is 11 char len, but 14 bytes len.

you could even have a look at stored chars:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
printf -v myreal "%q" "$myvar"
LANG=$oLang LC_ALL=$oLcAll
printf "%s has %d chars, %d bytes: (%s).\n" "${myvar}" $chrlen $bytlen "$myreal"

will answer:

Généralités has 11 chars, 14 bytes: ($'G\303\251n\303\251ralit\303\251s').

Nota: According to Isabell Cowan's comment, I've added setting to $LC_ALL along with $LANG.

Length of an argument

Argument work same as regular variables

strLen() {
    local bytlen sreal oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    printf -v sreal %q "$1"
    LANG=$oLang LC_ALL=$oLcAll
    printf "String '%s' is %d bytes, but %d chars len: %s.\n" "$1" $bytlen ${#1} "$sreal"
}

will work as

strLen théorème
String 'théorème' is 10 bytes, but 8 chars len: $'th\303\251or\303\250me'

Useful printf correction tool:

If you:

for string in Généralités Language Théorème Février  "Left: ?" "Yin Yang ?";do
    printf " - %-14s is %2d char length\n" "'$string'"  ${#string}
done

 - 'Généralités' is 11 char length
 - 'Language'     is  8 char length
 - 'Théorème'   is  8 char length
 - 'Février'     is  7 char length
 - 'Left: ?'    is  7 char length
 - 'Yin Yang ?' is 10 char length

Not really pretty... For this, there is a little function:

strU8DiffLen () { 
    local bytlen oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    LANG=$oLang LC_ALL=$oLcAll
    return $(( bytlen - ${#1} ))
}

Then now:

for string in Généralités Language Théorème Février  "Left: ?" "Yin Yang ?";do
    strU8DiffLen "$string"
    printf " - %-$((14+$?))s is %2d chars length, but uses %2d bytes\n" \
        "'$string'" ${#string} $((${#string}+$?))
  done 

 - 'Généralités'  is 11 chars length, but uses 14 bytes
 - 'Language'     is  8 chars length, but uses  8 bytes
 - 'Théorème'     is  8 chars length, but uses 10 bytes
 - 'Février'      is  7 chars length, but uses  8 bytes
 - 'Left: ?'      is  7 chars length, but uses  9 bytes
 - 'Yin Yang ?'   is 10 chars length, but uses 12 bytes

Unfortunely, this is not perfect!

But there left some strange UTF-8 behaviour, like double-spaced chars, zero spaced chars, reverse deplacement and other that could not be as simple...

Have a look at diffU8test.sh or diffU8test.sh.txt for more limitations.

Deleting specific rows from DataTable

I'm seeing various bits and pieces of the right answer here, but let me bring it all together and explain a couple of things.

First of all, AcceptChanges should only be used to mark the entire transaction on a table as being validated and committed. Which means if you are using the DataTable as a DataSource for binding to, for example, an SQL server, then calling AcceptChanges manually will guarantee that that the changes never get saved to the SQL server.

What makes this issue more confusing is that there are actually two cases in which the exception is thrown and we have to prevent both of them.

1. Modifying an IEnumerable's Collection

We can't add or remove an index to the collection being enumerated because doing so may affect the enumerator's internal indexing. There are two ways to get around this: either do your own indexing in a for loop, or use a separate collection (that is not modified) for the enumeration.

2. Attempting to Read a Deleted Entry

Since DataTables are transactional collections, entries can be marked for deletion but still appear in the enumeration. Which means that if you ask a deleted entry for the column "name" then it will throw an exception. Which means we must check to see whether dr.RowState != DataRowState.Deleted before querying a column.

Putting it all together

We could get messy and do all of that manually, or we can let the DataTable do all the work for us and make the statement look and at more like an SQL call by doing the following:

string name = "Joe";
foreach(DataRow dr in dtPerson.Select($"name='{name}'"))
    dr.Delete();

By calling DataTable's Select function, our query automatically avoids already deleted entries in the DataTable. And since the Select function returns an array of matches, the collection we are enumerating over is not modified when we call dr.Delete(). I've also spiced up the Select expression with string interpolation to allow for variable selection without making the code noisy.

download a file from Spring boot rest service

using Apache IO could be another option for copy the Stream

@RequestMapping(path = "/file/{fileId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> downloadFile(@PathVariable(value="fileId") String fileId,HttpServletResponse response) throws Exception {

    InputStream yourInputStream = ...
    IOUtils.copy(yourInputStream, response.getOutputStream());
    response.flushBuffer();
    return ResponseEntity.ok().build();
}

maven dependency

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>

MySQL - How to parse a string value to DATETIME format inside an INSERT statement?

Use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert:

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
  (STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))

How to get the last character of a string in a shell?

That's one of the reasons why you need to quote your variables:

echo "${str:$i:1}"

Otherwise, bash expands the variable and in this case does globbing before printing out. It is also better to quote the parameter to the script (in case you have a matching filename):

sh lash_ch.sh 'abcde*'

Also see the order of expansions in the bash reference manual. Variables are expanded before the filename expansion.

To get the last character you should just use -1 as the index since the negative indices count from the end of the string:

echo "${str: -1}"

The space after the colon (:) is REQUIRED.

This approach will not work without the space.

How to tell CRAN to install package dependencies automatically?

On your own system, try

install.packages("foo", dependencies=...)

with the dependencies= argument is documented as

dependencies: logical indicating to also install uninstalled packages
      which these packages depend on/link to/import/suggest (and so
      on recursively).  Not used if ‘repos = NULL’.  Can also be a
      character vector, a subset of ‘c("Depends", "Imports",
      "LinkingTo", "Suggests", "Enhances")’.

      Only supported if ‘lib’ is of length one (or missing), so it
      is unambiguous where to install the dependent packages.  If
      this is not the case it is ignored, with a warning.

      The default, ‘NA’, means ‘c("Depends", "Imports",
      "LinkingTo")’.

      ‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
      "Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
      ‘c("Depends", "Imports", "LinkingTo")’ for added
      dependencies: this installs all the packages needed to run
      ‘pkgs’, their examples, tests and vignettes (if the package
      author specified them correctly).

so you probably want a value TRUE.

In your package, list what is needed in Depends:, see the Writing R Extensions manual which is pretty clear on this.

PHP 7 RC3: How to install missing MySQL PDO

I'll start with the answer then context NOTE this fix was logged above, I'm just re-stating it for anyone googling.

  1. Download the source code of php 7 and extract it.
  2. open your terminal
  3. swim to the ext/pdo_mysql directory
  4. use commands:

    phpize

    ./configure

    make

    make install (as root)

  5. enable extension=mysqli.so in your php.ini file

This is logged as an answer from here (please upvote it if it helped you too): https://stackoverflow.com/a/39277373/3912517

Context: I'm trying to add LimeSurvey to the standard WordPress Docker. The single point holding me back is "PHP PDO driver library" which is "None found"

php -i | grep PDO                                                                                  
PHP Warning:  PHP Startup: Unable to load dynamic library 'pdo_odbc' (tried: /usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc (/usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc: cannot open shared object file: No such file or directory), /usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc.so (/usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHP Warning:  Module 'mysqli' already loaded in Unknown on line 0
PDO
PDO support => enabled
PDO drivers => sqlite
PDO Driver for SQLite 3.x => enabled

Ubuntu 16 (Ubuntu 7.3.0)

apt-get install php7.0-mysql

Result:

Package 'php7.0-mysql' has no installation candidate

Get instructions saying all I have to do is run this:

add-apt-repository -y ppa:ondrej/apache2

But then I get this:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 223: ordinal not in range(128)

So I try and force some type of UTF: LC_ALL=C.UTF-8 add-apt-repository -y ppa:ondrej/apache2 and I get this: no valid OpenPGP data found.

Follow some other instructions to run this: apt-get update and I get this: Err:14 http://ppa.launchpad.net/ondrej/apache2/ubuntu cosmic/main amd64 Packages 404 Not Found Err:15 http://ppa.launchpad.net/ondrej/php/ubuntu cosmic/main amd64 Packages 404 Not Found and - I think because of that - I then get:

The repository 'http://ppa.launchpad.net/ondrej/apache2/ubuntu cosmic Release' does not have a Release file.

By this stage, I'm still getting this on apt-get update:

Package 'php7.0-mysql' has no installation candidate.

I start trying to add in php libraries, got Unicode issues, tried to get around that and.... you get the idea... whack-a-mole. I gave up and looked to see if I could compile it and I found the answer I started with.

You might be wondering why I wrote so much? So that anyone googling can find this solution (including me!).

Can you set a border opacity in CSS?

Other answers deal with the technical aspect of the border-opacity issue, while I'd like to present a hack(pure CSS and HTML only). Basically create a container div, having a border div and then the content div.

<div class="container">
  <div class="border-box"></div>
  <div class="content-box"></div>
</div>

And then the CSS:(set content border to none, take care of positioning such that border thickness is accounted for)

.container {
  width: 20vw;
  height: 20vw;
  position: relative;
}
.border-box {
  width: 100%;
  height: 100%;
  border: 5px solid black;
  position: absolute;
  opacity: 0.5;
}
.content-box {
  width: 100%;
  height: 100%;
  border: none;
  background: green;
  top: 5px;
  left: 5px;
  position: absolute;
}

How to Query Database Name in Oracle SQL Developer?

Edit: Whoops, didn't check your question tags before answering.

Check that you can actually connect to DB (have the driver placed? tested the conn when creating it?).

If so, try runnung those queries with F5

how do I change text in a label with swift?

swift solution

yourlabel.text = yourvariable

or self is use for when you are in async {brackets} or in some Extension

DispatchQueue.main.async{
    self.yourlabel.text = "typestring"
}

css h1 - only as wide as the text

You can use the inline-block value for display, however in this case you will loose the block feature of h1 i.e. the siblings will be displayed inline with h1 if they are inline elements(in which case you can use a line-break
).

display:inline-block; 

Http post and get request in angular 6

For reading full response in Angular you should add the observe option:

{ observe: 'response' }
    return this.http.get(`${environment.serverUrl}/api/posts/${postId}/comments/?page=${page}&size=${size}`, { observe: 'response' });

How to create XML file with specific structure in Java

public static void main(String[] args) {

try {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("CONFIGURATION");
    doc.appendChild(rootElement);
    Element browser = doc.createElement("BROWSER");
    browser.appendChild(doc.createTextNode("chrome"));
    rootElement.appendChild(browser);
    Element base = doc.createElement("BASE");
    base.appendChild(doc.createTextNode("http:fut"));
    rootElement.appendChild(base);
    Element employee = doc.createElement("EMPLOYEE");
    rootElement.appendChild(employee);
    Element empName = doc.createElement("EMP_NAME");
    empName.appendChild(doc.createTextNode("Anhorn, Irene"));
    employee.appendChild(empName);
    Element actDate = doc.createElement("ACT_DATE");
    actDate.appendChild(doc.createTextNode("20131201"));
    employee.appendChild(actDate);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("/Users/myXml/ScoreDetail.xml"));
    transformer.transform(source, result);
    System.out.println("File saved!");
  } catch (ParserConfigurationException pce) {
    pce.printStackTrace();
  } catch (TransformerException tfe) {
    tfe.printStackTrace();}}

The values in you XML is Hard coded.

How do you switch pages in Xamarin.Forms?

In Xamarin we have page called NavigationPage. It holds stack of ContentPages. NavigationPage has method like PushAsync()and PopAsync(). PushAsync add a page at the top of the stack, at that time that page page will become the currently active page. PopAsync() method remove the page from the top of the stack.

In App.Xaml.Cs we can set like.

MainPage = new NavigationPage( new YourPage());

await Navigation.PushAsync(new newPage()); this method will add newPage at the top of the stack. At this time nePage will be currently active page.

java : convert float to String and String to float

String str = "1234.56";
float num = 0.0f;

int digits = str.length()- str.indexOf('.') - 1;

float factor = 1f;

for(int i=0;i<digits;i++) factor /= 10;

for(int i=str.length()-1;i>=0;i--){

    if(str.charAt(i) == '.'){
        factor = 1;
        System.out.println("Reset, value="+num);
        continue;
    }

    num += (str.charAt(i) - '0') * factor;
    factor *= 10;
}

System.out.println(num);

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

How to get hex color value rather than RGB value?

Function that returns background color of an element in hex.

function getBgColorHex(elem){
    var color = elem.css('background-color')
    var hex;
    if(color.indexOf('#')>-1){
        //for IE
        hex = color;
    } else {
        var rgb = color.match(/\d+/g);
        hex = '#'+ ('0' + parseInt(rgb[0], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2);
    }
    return hex;
}

usage example:

$('#div1').click(function(){
   alert(getBgColorHex($(this));
}

jsfiddle

Creating a segue programmatically

A couple of problems, actually:

First, in that project you uploaded for us, the segue does not bear the "segue1" identifier:

no identifier

You should fill in that identifier if you haven't already.

Second, as you're pushing from table view to table view, you're calling initWithNibName to create a view controller. You really want to use instantiateViewControllerWithIdentifier.

Java 8 Lambda filter by Lists

Predicate<Client> hasSameNameAsOneUser = 
    c -> users.stream().anyMatch(u -> u.getName().equals(c.getName()));

return clients.stream()
              .filter(hasSameNameAsOneUser)
              .collect(Collectors.toList());

But this is quite inefficient, because it's O(m * n). You'd better create a Set of acceptable names:

Set<String> acceptableNames = 
    users.stream()
         .map(User::getName)
         .collect(Collectors.toSet());

return clients.stream()
              .filter(c -> acceptableNames.contains(c.getName()))
              .collect(Collectors.toList());

Also note that it's not strictly equivalent to the code you have (if it compiled), which adds the same client twice to the list if several users have the same name as the client.

Delete all Duplicate Rows except for One in MySQL?

Editor warning: This solution is computationally inefficient and may bring down your connection for a large table.

NB - You need to do this first on a test copy of your table!

When I did it, I found that unless I also included AND n1.id <> n2.id, it deleted every row in the table.

  1. If you want to keep the row with the lowest id value:

    DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
    
  2. If you want to keep the row with the highest id value:

    DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
    

I used this method in MySQL 5.1

Not sure about other versions.


Update: Since people Googling for removing duplicates end up here
Although the OP's question is about DELETE, please be advised that using INSERT and DISTINCT is much faster. For a database with 8 million rows, the below query took 13 minutes, while using DELETE, it took more than 2 hours and yet didn't complete.

INSERT INTO tempTableName(cellId,attributeId,entityRowId,value)
    SELECT DISTINCT cellId,attributeId,entityRowId,value
    FROM tableName;

how do I set height of container DIV to 100% of window height?

I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
 html {height: 50%; border: solid red 3px; }_x000D_
 body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
 div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
 _x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
 <div id="container">_x000D_
  <p>&lt;html&gt; is red</p>_x000D_
  <p>&lt;body&gt; is green</p>_x000D_
  <p>&lt;div&gt; is blue</p>_x000D_
 </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.

About CSS units: w3schools: CSS units

A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."

Android, getting resource ID from string?

In your res/layout/my_image_layout.xml

<LinearLayout ...>
    <ImageView
        android:id="@+id/row_0_col_7"
      ...>
    </ImageView>
</LinearLayout>

To grab that ImageView by its @+id value, inside your java code do this:

String row = "0";
String column= "7";
String tileID = "row_" + (row) + "_col_" + (column);
ImageView image = (ImageView) activity.findViewById(activity.getResources()
                .getIdentifier(tileID, "id", activity.getPackageName()));

/*Bottom code changes that ImageView to a different image. "blank" (R.mipmap.blank) is the name of an image I have in my drawable folder. */
image.setImageResource(R.mipmap.blank);  

Is it wrong to place the <script> tag after the </body> tag?

As Andy said the document will be not valid, but nevertheless the script will still be interpreted. See the snippet from WebKit for example:

void HTMLParser::processCloseTag(Token* t)
{
    // Support for really broken html.
    // we never close the body tag, since some stupid web pages close it before 
    // the actual end of the doc.
    // let's rely on the end() call to close things.
    if (t->tagName == htmlTag || t->tagName == bodyTag 
                              || t->tagName == commentAtom)
        return;
    ...

Inheriting from a template class in c++

Are you just trying to derive from Area<int>? In which case you do this:

class Rectangle : public Area<int>
{
    // ...
};

EDIT: Following the clarification, it seems you're actually trying to make Rectangle a template as well, in which case the following should work:

template <typename T>
class Rectangle : public Area<T>
{
    // ...
};

mingw-w64 threads: posix vs win32

GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.

I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.

To summarize:

  • posix: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.
  • win32: No C++11 multithreading features.

Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

I think making UIEdgeInsets -35 0 0 0 is tedious. In my case, I implemented tableView: heightForHeaderInSection: method and it has a potential to return 0.

When I changed 0 to 0.1f, the problem just went away.

How to pass parameter to a promise function

You can use .bind() to pass the param(this) to the function.

var someFunction =function(resolve, reject) {
  /* get username, password*/
  var username=this.username;
  var password=this.password;
  if ( /* everything turned out fine */ ) {
    resolve("Stuff worked!");
  } else {
    reject(Error("It broke"));
  }
}
var promise=new Promise(someFunction.bind({username:"your username",password:"your password"}));

Mocking python function based on input arguments

Just to show another way of doing it:

def mock_isdir(path):
    return path in ['/var/log', '/var/log/apache2', '/var/log/tomcat']

with mock.patch('os.path.isdir') as os_path_isdir:
    os_path_isdir.side_effect = mock_isdir

What is CDATA in HTML?

CDATA is Obsolete.

Note that CDATA sections should not be used within HTML; they only work in XML.

So do not use it in HTML 5.

https://developer.mozilla.org/en-US/docs/Web/API/CDATASection#Specifications

Screenshot from MDN

"Cannot GET /" with Connect on Node.js

This code should work:

var connect = require("connect");

var app = connect.createServer().use(connect.static(__dirname + '/public'));

app.listen(8180);

Also in connect 2.0 .createServer() method deprecated. Use connect() instead.

var connect = require("connect");

var app = connect().use(connect.static(__dirname + '/public'));

app.listen(8180);

Python Graph Library

I'm having the most luck with pydot. Some of the others are hard to install and configure on different platforms like Win 7.

http://code.google.com/p/pydot/

How can I get client information such as OS and browser

You cannot reliably get this information. The basis of several answers provided here is to examine the User-Agent header of the HTTP request. However, there is no way to know if the information in the User-Agent header is truthful. The client sending the request can write anything in that header. So its content can be spoofed, or not sent at all.

File URL "Not allowed to load local resource" in the Internet Browser

For people do not like to modify chrome's security options, we can simply start a python http server from directory which contains your local file:

python -m SimpleHTTPServer

and for python 3:

python3 -m http.server

Now you can reach any local file directly from your js code or externally with http://127.0.0.1:8000/some_file.txt

bootstrap datepicker setDate format dd/mm/yyyy

You can use this code for bootstrap datepicker:

HTML Code:

<p>Date: <input type="text" id="datepicker" class="datepicker"></p>

Javascript:

$( ".datepicker" ).datepicker({
   format: 'yyyy-mm-dd'
});

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

Somewhat convoluted, but:

Select * from myTable m
join (SELECT a.COLUMN_VALUE || b.COLUMN_VALUE status
FROM   (TABLE(Sys.Dbms_Debug_Vc2coll('Done', 'Finished except', 'In Progress'))) a
JOIN (Select '%' COLUMN_VALUE from dual) b on 1=1) params
on params.status like m.status;

This was a solution for a very unique problem, but it might help someone. Essentially there is no "in like" statement and there was no way to get an index for the first variable_n characters of the column, so I made this to make a fast dynamic "in like" for use in SSRS.

The list content ('Done', 'Finished except', 'In Progress') can be variable.

Target Unreachable, identifier resolved to null in JSF 2.2

I solved this problem.

My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.

Thanks @PM77-1


Stop setInterval call in JavaScript

clearInterval()

Note, you can start and pause your code with this capability. The name is a bit deceptive, since it says CLEAR, but it doesn't clear anything. It actually pauses.

Test with this code:

HTML:

<div id='count'>100</div>
<button id='start' onclick='start()'>Start</button>
<button id='stop' onclick='stop()'>Stop</button>

JavaScript:

_x000D_
_x000D_
let count;

function start(){
 count = setInterval(timer,100)  /// HERE WE RUN setInterval()
}

function timer(){
  document.getElementById('count').innerText--;
}


function stop(){
  clearInterval(count)   /// here we PAUSE  setInterval()  with clearInterval() code
}
_x000D_
_x000D_
_x000D_

TypeScript or JavaScript type casting

You can cast like this:

return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);

Or like this if you want to be compatible with tsx mode:

return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);

Just remember that this is a compile-time cast, and not a runtime cast.

Not receiving Google OAuth refresh token

    #!/usr/bin/env perl

    use strict;
    use warnings;
    use 5.010_000;
    use utf8;
    binmode STDOUT, ":encoding(utf8)";

    use Text::CSV_XS;
    use FindBin;
    use lib $FindBin::Bin . '/../lib';
    use Net::Google::Spreadsheets::V4;

    use Net::Google::DataAPI::Auth::OAuth2;

    use lib 'lib';
    use Term::Prompt;
    use Net::Google::DataAPI::Auth::OAuth2;
    use Net::Google::Spreadsheets;
    use Data::Printer ;


    my $oauth2 = Net::Google::DataAPI::Auth::OAuth2->new(
         client_id => $ENV{CLIENT_ID},
         client_secret => $ENV{CLIENT_SECRET},
         scope => ['https://www.googleapis.com/auth/spreadsheets'],
    );
    my $url = $oauth2->authorize_url();
    # system("open '$url'");
    print "go to the following url with your browser \n" ;
    print "$url\n" ;
    my $code = prompt('x', 'paste code: ', '', '');
    my $objToken = $oauth2->get_access_token($code);

    my $refresh_token = $objToken->refresh_token() ;

    print "my refresh token is : \n" ;
    # debug p($refresh_token ) ;
    p ( $objToken ) ;


    my $gs = Net::Google::Spreadsheets::V4->new(
            client_id      => $ENV{CLIENT_ID}
         , client_secret  => $ENV{CLIENT_SECRET}
         , refresh_token  => $refresh_token
         , spreadsheet_id => '1hGNULaWpYwtnMDDPPkZT73zLGDUgv5blwJtK7hAiVIU'
    );

    my($content, $res);

    my $title = 'My foobar sheet';

    my $sheet = $gs->get_sheet(title => $title);

    # create a sheet if does not exit
    unless ($sheet) {
         ($content, $res) = $gs->request(
              POST => ':batchUpdate',
              {
                    requests => [
                         {
                              addSheet => {
                                    properties => {
                                         title => $title,
                                         index => 0,
                                    },
                              },
                         },
                    ],
              },
         );

         $sheet = $content->{replies}[0]{addSheet};
    }

    my $sheet_prop = $sheet->{properties};

    # clear all cells
    $gs->clear_sheet(sheet_id => $sheet_prop->{sheetId});

    # import data
    my @requests = ();
    my $idx = 0;

    my @rows = (
         [qw(name age favorite)], # header
         [qw(tarou 31 curry)],
         [qw(jirou 18 gyoza)],
         [qw(saburou 27 ramen)],
    );

    for my $row (@rows) {
         push @requests, {
              pasteData => {
                    coordinate => {
                         sheetId     => $sheet_prop->{sheetId},
                         rowIndex    => $idx++,
                         columnIndex => 0,
                    },
                    data => $gs->to_csv(@$row),
                    type => 'PASTE_NORMAL',
                    delimiter => ',',
              },
         };
    }

    # format a header row
    push @requests, {
         repeatCell => {
              range => {
                    sheetId       => $sheet_prop->{sheetId},
                    startRowIndex => 0,
                    endRowIndex   => 1,
              },
              cell => {
                    userEnteredFormat => {
                         backgroundColor => {
                              red   => 0.0,
                              green => 0.0,
                              blue  => 0.0,
                         },
                         horizontalAlignment => 'CENTER',
                         textFormat => {
                              foregroundColor => {
                                    red   => 1.0,
                                    green => 1.0,
                                    blue  => 1.0
                              },
                              bold => \1,
                         },
                    },
              },
              fields => 'userEnteredFormat(backgroundColor,textFormat,horizontalAlignment)',
         },
    };

    ($content, $res) = $gs->request(
         POST => ':batchUpdate',
         {
              requests => \@requests,
         },
    );

    exit;

    #Google Sheets API, v4

    # Scopes
    # https://www.googleapis.com/auth/drive   View and manage the files in your Google D# # i# rive
    # https://www.googleapis.com/auth/drive.file View and manage Google Drive files and folders that you have opened or created with this app
    # https://www.googleapis.com/auth/drive.readonly   View the files in your Google Drive
    # https://www.googleapis.com/auth/spreadsheets  View and manage your spreadsheets in Google Drive
    # https://www.googleapis.com/auth/spreadsheets.readonly  View your Google Spreadsheets

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

And do not forget the "new" service type (from the k8s docu):

ExternalName: Maps the Service to the contents of the externalName field (e.g. foo.bar.example.com), by returning a CNAME record with its value. No proxying of any kind is set up.

Note: You need either kube-dns version 1.7 or CoreDNS version 0.0.8 or higher to use the ExternalName type.

IP to Location using Javascript

I wish to point out that if you use http://freegeoip.net/, you don't need to supply to it the IP address of the client's location. Just try these:

1) http://freegeoip.net/xml/

2) http://freegeoip.net/json/

3) http://freegeoip.net/csv/

However, I am unable to retrieve the information with AJAX calls, probably because of some cross-origin policy. Apparently they have not allowed public access to their system.

How to write data with FileOutputStream without losing old data?

Use the constructor for appending material to the file:

FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

So to append to a file say "abc.txt" use

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);

How to get folder path from file path with CMD

The accepted answer is helpful, but it isn't immediately obvious how to retrieve a filename from a path if you are NOT using passed in values. I was able to work this out from this thread, but in case others aren't so lucky, here is how it is done:

@echo off
setlocal enabledelayedexpansion enableextensions

set myPath=C:\Somewhere\Somewhere\SomeFile.txt
call :file_name_from_path result !myPath!
echo %result%
goto :eof

:file_name_from_path <resultVar> <pathVar>
(
    set "%~1=%~nx2"
    exit /b
)

:eof
endlocal

Now the :file_name_from_path function can be used anywhere to retrieve the value, not just for passed in arguments. This can be extremely helpful if the arguments can be passed into the file in an indeterminate order or the path isn't passed into the file at all.

How to set lifetime of session

The sessions on PHP works with a Cookie type session, while on server-side the session information is constantly deleted.

For set the time life in php, you can use the function session_set_cookie_params, before the session_start:

session_set_cookie_params(3600,"/");
session_start();

For ex, 3600 seconds is one hour, for 2 hours 3600*2 = 7200.

But it is session cookie, the browser can expire it by itself, if you want to save large time sessions (like remember login), you need to save the data in the server and a standard cookie in the client side.

You can have a Table "Sessions":

  • session_id int
  • session_hash varchar(20)
  • session_data text

And validating a Cookie, you save the "session id" and the "hash" (for security) on client side, and you can save the session's data on the server side, ex:

On login:

setcookie('sessid', $sessionid, 604800);      // One week or seven days
setcookie('sesshash', $sessionhash, 604800);  // One week or seven days
// And save the session data:
saveSessionData($sessionid, $sessionhash, serialize($_SESSION)); // saveSessionData is your function

If the user return:

if (isset($_COOKIE['sessid'])) {
    if (valide_session($_COOKIE['sessid'], $_COOKIE['sesshash'])) {
        $_SESSION = unserialize(get_session_data($_COOKIE['sessid']));
    } else {
        // Dont validate the hash, possible session falsification
    }
}

Obviously, save all session/cookies calls, before sending data.

How to wrap text around an image using HTML/CSS

Addition to BeNdErR's answer:
The "other TEXT" element should have float:none, like:

_x000D_
_x000D_
    <div style="width:100%;">_x000D_
        <div style="float:left;width:30%; background:red;">...something something something  random text</div>_x000D_
        <div style="float:none; background:yellow;"> text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text  </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Forking vs. Branching in GitHub

Forking creates an entirely new repository from existing repository (simply doing git clone on gitHub/bitbucket)

Forks are best used: when the intent of the ‘split’ is to create a logically independent project, which may never reunite with its parent.

Branch strategy creates a new branch over the existing/working repository

Branches are best used: when they are created as temporary places to work through a feature, with the intent to merge the branch with the origin.

More Specific :- In open source projects it is the owner of the repository who decides who can push to the repository. However, the idea of open source is that everybody can contribute to the project.

This problem is solved by forks: any time a developer wants to change something in an open source project, they don’t clone the official repository directly. Instead, they fork it to create a copy. When the work is finished, they make a pull request so that the owner of the repository can review the changes and decide whether to merge them to his project.

At its core forking is similar to feature branching, but instead of creating branches a fork of the repository is made, and instead of doing a merge request you create a pull request.

The below links provide the difference in a well-explained manner :

https://blog.gitprime.com/the-definitive-guide-to-forks-and-branches-in-git/

https://buddy.works/blog/5-types-of-git-workflows

http://www.continuousagile.com/unblock/branching.html

How to select an element with 2 classes

Just chain them together:

.a.b {
  color: #666;
}

How can I make an EXE file from a Python program?

Not on the freehackers list is gui2exe which can be used to build standalone Windows executables, Linux applications and Mac OS application bundles and plugins starting from Python scripts.

Check if a value exists in ArrayList

We can use contains method to check if an item exists if we have provided the implementation of equals and hashCode else object reference will be used for equality comparison. Also in case of a list contains is O(n) operation where as it is O(1) for HashSet so better to use later. In Java 8 we can use streams also to check item based on its equality or based on a specific property.

Java 8

CurrentAccount conta5 = new CurrentAccount("João Lopes", 3135);
boolean itemExists = lista.stream().anyMatch(c -> c.equals(conta5)); //provided equals and hashcode overridden
System.out.println(itemExists); // true

String nameToMatch = "Ricardo Vitor";
boolean itemExistsBasedOnProp = lista.stream().map(CurrentAccount::getName).anyMatch(nameToMatch::equals);
System.out.println(itemExistsBasedOnProp); //true

How to put labels over geom_bar in R with ggplot2

As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:

dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))

So that the x variable matches the corresponding variable in df, and so on. Then you simply include it using geom_text:

ggplot(df) + geom_bar(aes(x,fill=x)) + 
    geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
    opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),legend.title=theme_blank(),
        axis.title.y=theme_blank())

This example will plot just the percentages, but you can paste together the counts as well via something like this:

dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")

Note that in the current version of ggplot2, opts is deprecated, so we would use theme and element_blank now.

Display a jpg image on a JPanel

I would use a Canvas that I add to the JPanel, and draw the image on the Canvas. But Canvas is a quite heavy object, sine it is from awt.

No Application Encryption Key Has Been Specified

Open command prompt in the root folder of your project and run below command:

php artisan key:generate

It will generate Application Key for your application.

You can find the generated application key(APP_KEY) in .env file.

How to validate phone numbers using regex

Working example for Turkey, just change the

d{9}

according to your needs and start using it.

function validateMobile($phone)
{
    $pattern = "/^(05)\d{9}$/";
    if (!preg_match($pattern, $phone))
    {
        return false;
    }
    return true;
}

$phone = "0532486061";

if(!validateMobile($phone))
{
    echo 'Incorrect Mobile Number!';
}

$phone = "05324860614";
if(validateMobile($phone))
{
    echo 'Correct Mobile Number!';
}

How does ApplicationContextAware work in Spring?

ApplicationContextAware Interface ,the current application context, through which you can invoke the spring container services. We can get current applicationContext instance injected by below method in the class

public void setApplicationContext(ApplicationContext context) throws BeansException.

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

Nohup allows a client process to not be killed if a the parent process is killed, for argument when you logout. Even better still use:

nohup /bin/sh -c "echo \$\$ > $pidfile; exec $FOO_BIN $FOO_CONFIG  " > /dev/null

Nohup makes the process you start immune to termination which your SSH session and its child processes are kill upon you logging out. The command i gave provides you with a way you can store the pid of the application in a pid file so that you can correcly kill it later and allows the process to run after you have logged out.

HtmlSpecialChars equivalent in Javascript?

OWASP recommends that "[e]xcept for alphanumeric characters, [you should] escape all characters with ASCII values less than 256 with the &#xHH; format (or a named entity if available) to prevent switching out of [an] attribute."

So here's a function that does that, with a usage example:

_x000D_
_x000D_
function escapeHTML(unsafe) {
  return unsafe.replace(
    /[\u0000-\u002F]|[\u003A-\u0040]|[\u005B-\u00FF]/g,
    c => '&#' + ('000' + c.charCodeAt(0)).substr(-4, 4) + ';'
  )
}
document.querySelector('div').innerHTML =
  '<span class=' +
  escapeHTML('this should break it! " | / % * + , - / ; < = > ^') +
  '>' +
  escapeHTML('<script>alert("inspect the attributes")\u003C/script>') +
  '</span>'
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Disclaimer: You should verify the entity ranges I have provided to validate the safety yourself.

How can I completely uninstall nodejs, npm and node in Ubuntu

It bothered me too much while updating node version from 8.1.0 to 10.14.0

Here is what worked for me:

  1. Open terminal (Ctrl+Alt+T).

  2. Type which node, which will give a path something like /usr/local/bin/node

  3. Run the command sudo rm /usr/local/bin/node to remove the binary (adjust the path according to what you found in step 2). Now node -v shows you have no node version

  4. Download a script and run it to set up the environment:

    curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
    
  5. Install using sudo apt-get install nodejs

    Note: If you are getting error like

    node /usr/bin/env: node: No such file or directory
    

    just run

    ln -s /usr/bin/nodejs /usr/bin/node
    

    Source

  6. Now node -v will give v10.14.0

Worked for me.

Click in OK button inside an Alert (Selenium IDE)

Try Selenium 2.0b1. It has different core than the first version. It should support popup dialogs according to documentation:

Popup Dialogs

Starting with Selenium 2.0 beta 1, there is built in support for handling popup dialog boxes. After you’ve triggered and action that would open a popup, you can access the alert with the following:

Java

Alert alert = driver.switchTo().alert();

Ruby

driver.switch_to.alert

This will return the currently open alert object. With this object you can now accept, dismiss, read it’s contents or even type into a prompt. This interface works equally well on alerts, confirms, prompts. Refer to the JavaDocs for more information.

how to check if a file is a directory or regular file in python?

Many of the Python directory functions are in the os.path module.

import os
os.path.isdir(d)

How to make vim paste from (and copy to) system's clipboard?

I ran into this issue on a mid-2017 Macbook Pro running vim within iTerm2 as my primary development environment.

As other answers have suggested, I ran vim --version and noticed that it returns -clipboard, which means that the version of vim that shipped with my machine hasn't been compiled with the clipboard option.

The homebrew package for vim appears to compile with the clipboard option, so the fix for me was to:

  1. Run brew install vim
  2. Add set clipboard+=unnamed to my ~/.vimrc file
  3. Close and reopen iTerm2

What tool can decompile a DLL into C++ source code?

The closest you will ever get to doing such thing is a dissasembler, or debug info (Log2Vis.pdb).

How to loop through file names returned by find?

find <path> -xdev -type f -name *.txt -exec ls -l {} \;

This will list the files and give details about attributes.

How can I generate a list of files with their absolute path in Linux?

stat

Absolute path of a single file:

stat -c %n "$PWD"/foo/bar

Maximum length of the textual representation of an IPv6 address?

Watch out for certain headers such as HTTP_X_FORWARDED_FOR that appear to contain a single IP address. They may actually contain multiple addresses (a chain of proxies I assume).

They will appear to be comma delimited - and can be a lot longer than 45 characters total - so check before storing in DB.

VBA: Selecting range by variables

If you just want to select the used range, use

ActiveSheet.UsedRange.Select

If you want to select from A1 to the end of the used range, you can use the SpecialCells method like this

With ActiveSheet
    .Range(.Cells(1, 1), .Cells.SpecialCells(xlCellTypeLastCell)).Select
End With

Sometimes Excel gets confused on what is the last cell. It's never a smaller range than the actual used range, but it can be bigger if some cells were deleted. To avoid that, you can use Find and the asterisk wildcard to find the real last cell.

Dim rLastCell As Range

With Sheet1
    Set rLastCell = .Cells.Find("*", .Cells(1, 1), xlValues, xlPart, , xlPrevious)

    .Range(.Cells(1, 1), rLastCell).Select
End With

Finally, make sure you're only selecting if you really need to. Most of what you need to do in Excel VBA you can do directly to the Range rather than selecting it first. Instead of

.Range(.Cells(1, 1), rLastCell).Select
Selection.Font.Bold = True

You can

.Range(.Cells(1,1), rLastCells).Font.Bold = True

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

I was facing same problem when I installed JRE by Oracle and solved this problem after my research.

I moved the environment path C:\Program Files (x86)\Common Files\Oracle\Java\javapath below H:\Program Files\Java\jdk-13.0.1\bin

Like this:

Path

H:\Program Files\Java\jdk-13.0.1\bin
C:\Program Files (x86)\Common Files\Oracle\Java\javapath

OR

Path

%JAVA_HOME%
%JRE_HOME%

Getting RAW Soap Data from a Web Reference Client running in ASP.net

You can implement a SoapExtension that logs the full request and response to a log file. You can then enable the SoapExtension in the web.config, which makes it easy to turn on/off for debugging purposes. Here is an example that I have found and modified for my own use, in my case the logging was done by log4net but you can replace the log methods with your own.

public class SoapLoggerExtension : SoapExtension
{
    private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    private Stream oldStream;
    private Stream newStream;

    public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
    {
        return null;
    }

    public override object GetInitializer(Type serviceType)
    {
        return null;
    }

    public override void Initialize(object initializer)
    {

    }

    public override System.IO.Stream ChainStream(System.IO.Stream stream)
    {
        oldStream = stream;
        newStream = new MemoryStream();
        return newStream;
    }

    public override void ProcessMessage(SoapMessage message)
    {

        switch (message.Stage)
        {
            case SoapMessageStage.BeforeSerialize:
                break;
            case SoapMessageStage.AfterSerialize:
                Log(message, "AfterSerialize");
                    CopyStream(newStream, oldStream);
                    newStream.Position = 0;
                break;
                case SoapMessageStage.BeforeDeserialize:
                    CopyStream(oldStream, newStream);
                    Log(message, "BeforeDeserialize");
                break;
            case SoapMessageStage.AfterDeserialize:
                break;
        }
    }

    public void Log(SoapMessage message, string stage)
    {

        newStream.Position = 0;
        string contents = (message is SoapServerMessage) ? "SoapRequest " : "SoapResponse ";
        contents += stage + ";";

        StreamReader reader = new StreamReader(newStream);

        contents += reader.ReadToEnd();

        newStream.Position = 0;

        log.Debug(contents);
    }

    void ReturnStream()
    {
        CopyAndReverse(newStream, oldStream);
    }

    void ReceiveStream()
    {
        CopyAndReverse(newStream, oldStream);
    }

    public void ReverseIncomingStream()
    {
        ReverseStream(newStream);
    }

    public void ReverseOutgoingStream()
    {
        ReverseStream(newStream);
    }

    public void ReverseStream(Stream stream)
    {
        TextReader tr = new StreamReader(stream);
        string str = tr.ReadToEnd();
        char[] data = str.ToCharArray();
        Array.Reverse(data);
        string strReversed = new string(data);

        TextWriter tw = new StreamWriter(stream);
        stream.Position = 0;
        tw.Write(strReversed);
        tw.Flush();
    }
    void CopyAndReverse(Stream from, Stream to)
    {
        TextReader tr = new StreamReader(from);
        TextWriter tw = new StreamWriter(to);

        string str = tr.ReadToEnd();
        char[] data = str.ToCharArray();
        Array.Reverse(data);
        string strReversed = new string(data);
        tw.Write(strReversed);
        tw.Flush();
    }

    private void CopyStream(Stream fromStream, Stream toStream)
    {
        try
        {
            StreamReader sr = new StreamReader(fromStream);
            StreamWriter sw = new StreamWriter(toStream);
            sw.WriteLine(sr.ReadToEnd());
            sw.Flush();
        }
        catch (Exception ex)
        {
            string message = String.Format("CopyStream failed because: {0}", ex.Message);
            log.Error(message, ex);
        }
    }
}

[AttributeUsage(AttributeTargets.Method)]
public class SoapLoggerExtensionAttribute : SoapExtensionAttribute
{
    private int priority = 1; 

    public override int Priority
    {
        get { return priority; }
        set { priority = value; }
    }

    public override System.Type ExtensionType
    {
        get { return typeof (SoapLoggerExtension); }
    }
}

You then add the following section to your web.config where YourNamespace and YourAssembly point to the class and assembly of your SoapExtension:

<webServices>
  <soapExtensionTypes>
    <add type="YourNamespace.SoapLoggerExtension, YourAssembly" 
       priority="1" group="0" />
  </soapExtensionTypes>
</webServices>

DropDownList in MVC 4 with Razor

just use This

public ActionResult LoadCountries()
{
     List<SelectListItem> li = new List<SelectListItem>();
     li.Add(new SelectListItem { Text = "Select", Value = "0" });
     li.Add(new SelectListItem { Text = "India", Value = "1" });
     li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
     li.Add(new SelectListItem { Text = "China", Value = "3" });
     li.Add(new SelectListItem { Text = "Austrila", Value = "4" });
     li.Add(new SelectListItem { Text = "USA", Value = "5" });
     li.Add(new SelectListItem { Text = "UK", Value = "6" });
     ViewData["country"] = li;
     return View();
}

and in View use following.

 @Html.DropDownList("Country", ViewData["country"] as List<SelectListItem>)

if you want to get data from Dataset and populate these data in a list box then use following code.

List<SelectListItem> li= new List<SelectListItem>();
for (int rows = 0; rows <= ds.Tables[0].Rows.Count - 1; rows++)
{
    li.Add(new SelectListItem { Text = ds.Tables[0].Rows[rows][1].ToString(), Value = ds.Tables[0].Rows[rows][0].ToString() });
}
ViewData["FeedBack"] = li;
return View();

and in view write following code.

@Html.DropDownList("FeedBack", ViewData["FeedBack"] as List<SelectListItem>)

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.

The finally implemented code started like this:

    try
    {
        // Create a new instance of the AesManaged class.  This generates a new key and initialization vector (IV).
        AesManaged myAes = new AesManaged();

        // Override the cipher mode, key and IV
        myAes.Mode = CipherMode.ECB;
        myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
        myAes.Key = CipherKey;  // Byte array representing the key
        myAes.Padding = PaddingMode.None;

        // Create a encryption object to perform the stream transform.
        ICryptoTransform encryptor = myAes.CreateEncryptor();

        // TODO: perform the encryption / decryption as required...

    }
    catch (Exception ex)
    {
        // TODO: Log the error 
        throw ex;
    }

How do I clear my local working directory in Git?

To reset a specific file as git status suggests:

git checkout <filename>

To reset a folder

git checkout <foldername>/*

Start service in Android

Probably you don't have the service in your manifest, or it does not have an <intent-filter> that matches your action. Examining LogCat (via adb logcat, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.

More likely, you should start the service via:

startService(new Intent(this, UpdaterServiceManager.class));

Encrypt and decrypt a password in Java

Jasypt can do it for you easy and simple

T-SQL How to create tables dynamically in stored procedures?

You can write the below code:-

create procedure spCreateTable
   as
    begin
       create table testtb(Name varchar(20))
    end

execute it as:-

exec spCreateTable

How do I pass data between Activities in Android application?

Best way to pass data to one Activity to AnothetActivity by using Intent,

Check the code snipped

ActivityOne.java

Intent myIntent = new Intent(this, NewActivity.class);
myIntent.putExtra("key_name_one", "Your Data value here");
myIntent.putExtra("key_name_two", "Your data value here");
startActivity(myIntent)

On Your SecondActivity

SecondActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view);

    Intent intent = getIntent();

    String valueOne = intent.getStringExtra("key_name_one");
    String valueTwo = intent.getStringExtra("key_name_two");
}

How to Configure SSL for Amazon S3 bucket

It is not possible directly with S3, but you can create a Cloud Front distribution from you bucket. Then go to certificate manager and request a certificate. Amazon gives them for free. Ones you have successfully confirmed the certification, assign it to your Cloud Front distribution. Also remember to set the rule to re-direct http to https.

I'm hosting couple of static websites on Amazon S3, like my personal website to which I have assigned the SSL certificate as they have the Cloud Front distribution.

shorthand c++ if else statement

Yes:

bigInt.sign = !(number < 0);

The ! operator always evaluates to true or false. When converted to int, these become 1 and 0 respectively.

Of course this is equivalent to:

bigInt.sign = (number >= 0);

Here the parentheses are redundant but I add them for clarity. All of the comparison and relational operator evaluate to true or false.

Bootstrap get div to align in the center

In bootstrap you can use .text-centerto align center. also add .row and .col-md-* to your code.

align= is deprecated,

Added .col-xs-* for demo

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
  <div class="container">
    <div class="row">
      <div class="col-xs-4">
        <p>Hello there</p>
      </div>
      <div class="col-xs-4 text-center">
        <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
        <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
      </div>
      <div class="col-xs-4 text-right">
        <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
        <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
        <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
      </div>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

UPDATE(OCT 2017)

For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
  <div class="d-flex justify-content-between">
    <div class="p-1">
      <p>Hello there</p>
    </div>
    <div class="p-1">
      <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
      <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
    </div>
    <div class="p-1">
      <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
      <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
      <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How do you resize a form to fit its content automatically?

You could calculate the required height of the TreeView, by figuring out the height of a node, multiplying it by the number of nodes, then setting the form's MinimumSize property accordingly.

// assuming the treeview is populated!
nodeHeight = treeview1.Nodes[0].Bounds.Height;

this.MaximumSize = new Size(someMaximumWidth, someMaximumHeight);

int requiredFormHeight = (treeView1.GetNodeCount(true) * nodeHeight);

this.MinimumSize = new Size(this.Width, requiredFormHeight);

NB. This assumes though that the treeview1 is the only control on the form. When setting the requiredFormHeight variable you'll need to allow for other controls and height requirements surrounding the treeview, such as the tabcontrol you mentioned.

(I would however agree with @jgauffin and assess the rationale behind the requirement to resize a form everytime it loads without the user's consent - maybe let the user position and size the form and remember that instead??)

When do I use super()?

super is used to call the constructor, methods and properties of parent class.

pandas get rows which are NOT in other dataframe

extract the dissimilar rows using the merge function
df = df.merge(same.drop_duplicates(), on=['col1','col2'], 
               how='left', indicator=True)
save the dissimilar rows in CSV
df[df['_merge'] == 'left_only'].to_csv('output.csv')

Android Studio Gradle Configuration with name 'default' not found

For me it turned out to be an relative symbolic link (to the referenced project) that couldn't be used by grade. (I was referencing a library). Thats a pretty edgy edge-case but maybe it helps someone in the future.

I solved it by putting a absolute symbolic link.

Before ln -s ../library after ln -s /the/full/path/to/the/library

Angular 2 - Redirect to an external URL and open in a new tab

To solve this issue more globally, here is another way using a directive:

import { Directive, HostListener, ElementRef } from "@angular/core";

@Directive({
  selector: "[hrefExternalUrl]"
})
export class HrefExternalUrlDirective {
  constructor(elementRef: ElementRef) {}

  @HostListener("click", ["$event"])
  onClick(event: MouseEvent) {
    event.preventDefault();

    let url: string = (<any>event.currentTarget).getAttribute("href");

    if (url && url.indexOf("http") === -1) {
      url = `//${url}`;
    }

    window.open(url, "_blank");
  }
}

then it's as simple as using it like this:

<a [href]="url" hrefExternalUrl> Link </a>

and don't forget to declare the directive in your module.

Contain form within a bootstrap popover?

like this Working demo http://jsfiddle.net/7e2XU/21/show/# * Update: http://jsfiddle.net/kz5kjmbt/

 <div class="container">
    <div class="row" style="padding-top: 240px;"> <a href="#" class="btn btn-large btn-primary" rel="popover" data-content='
<form id="mainForm" name="mainForm" method="post" action="">
    <p>
        <label>Name :</label>
        <input type="text" id="txtName" name="txtName" />
    </p>
    <p>
        <label>Address 1 :</label>
        <input type="text" id="txtAddress" name="txtAddress" />
    </p>
    <p>
        <label>City :</label>
        <input type="text" id="txtCity" name="txtCity" />
    </p>
    <p>
        <input type="submit" name="Submit" value="Submit" />
    </p>
</form>
 data-placement="top" data-original-title="Fill in form">Open form</a>

    </div>
</div>

JavaScript code:

    $('a[rel=popover]').popover({
      html: 'true',
      placement: 'right'
    })

ScreenShot

working updated fiddle screenshot

Can we create an instance of an interface in Java?

Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:

interface ProgrammerInterview {
    public void read();
}

class Website {
    ProgrammerInterview p = new ProgrammerInterview() {
        public void read() {
            System.out.println("interface ProgrammerInterview class implementer");
        }
    };
}

This works fine. Was taken from this page:

http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

I am using xampp 1.7.3. Using inspiration from here: xampp 1.7.3 upgrade broken virtual hosts access forbidden

INSTEAD OF add <Directory> .. </Directory> in httpd-vhosts.conf, I add it in httpd.conf right after <Directory "D:/xampplite/cgi-bin"> .. </Directory>.

Here is what I add in httpd.conf:

<Directory "D:/CofeeShop">
    AllowOverride All
    Options  All
    Order allow,deny
    Allow from all
</Directory>

And here is what I add in httpd-vhosts.conf

<VirtualHost *:8001>
    ServerAdmin [email protected]
    DocumentRoot "D:/CofeeShop"
    ServerName localhost:8001
</VirtualHost>

I also add Listen 8001 in httpd.conf to complete my setting.

Hope it helps

iconv - Detected an illegal character in input string

I found one Solution :

echo iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($string));

use utf8_encode()

Using PowerShell to remove lines from a text file if it contains a string

Escape the | character using a backtick

get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt

Python timedelta in years

Even though this thread is already dead, might i suggest a working solution for this very same problem i was facing. Here it is (date is a string in the format dd-mm-yyyy):

def validatedate(date):
    parts = date.strip().split('-')

    if len(parts) == 3 and False not in [x.isdigit() for x in parts]: 
        birth = datetime.date(int(parts[2]), int(parts[1]), int(parts[0]))
        today = datetime.date.today()

        b = (birth.year * 10000) + (birth.month * 100) + (birth.day)
        t = (today.year * 10000) + (today.month * 100) + (today.day)

        if (t - 18 * 10000) >= b:
            return True

    return False

How to write the Fibonacci Sequence?

import time
start_time = time.time()



#recursive solution
def fib(x, y, upperLimit):
    return [x] + fib(y, (x+y), upperLimit) if x < upperLimit else [x]

#To test :

print(fib(0,1,40000000000000))
print("run time: " + str(time.time() - start_time))

Results

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853]

run time: 0.04298138618469238

How to select top n rows from a datatable/dataview in ASP.NET

In framework 3.5, dt.Rows.Cast<System.Data.DataRow>().Take(n)

Otherwise the way you mentioned

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

Click with the right mouse button on the file in your Google Drive. Choose the option to get a link which can be shared from the menu. You will see the file id now. Don't forget to undo the share.

Convert an array into an ArrayList

declaring the list (and initializing it with an empty arraylist)

List<Card> cardList = new ArrayList<Card>();

adding an element:

Card card;
cardList.add(card);

iterating over elements:

for(Card card : cardList){
    System.out.println(card);
}

Skip first couple of lines while reading lines in Python file

Here are the timeit results for the top 2 answers. Note that "file.txt" is a text file containing 100,000+ lines of random string with a file size of 1MB+.

Using itertools:

import itertools
from timeit import timeit

timeit("""with open("file.txt", "r") as fo:
    for line in itertools.islice(fo, 90000, None):
        line.strip()""", number=100)

>>> 1.604976346003241

Using two for loops:

from timeit import timeit

timeit("""with open("file.txt", "r") as fo:
    for i in range(90000):
        next(fo)
    for j in fo:
        j.strip()""", number=100)

>>> 2.427317383000627

clearly the itertools method is more efficient when dealing with large files.

Undo git update-index --assume-unchanged <file>

I assume (heh) you meant --assume-unchanged, since I don't see any --assume-changed option. The inverse of --assume-unchanged is --no-assume-unchanged.

sqlplus statement from command line

I'm able to execute your exact query by just making sure there is a semicolon at the end of my select statement. (Output is actual, connection params removed.)

echo "select 1 from dual;" | sqlplus -s username/password@host:1521/service 

Output:

         1
----------
         1

Note that is should matter but this is running on Mac OS X Snow Leopard and Oracle 11g.

Div 100% height works on Firefox but not in IE

I've done something very similar to what 'tvanfosson' said, that is, actually using JavaScript to constantly monitor the available height in the window via events like onresize, and use that information to change the container size accordingly (as pixels rather than percentage).

Keep in mind, this does mean a JavaScript dependency, and it isn't as smooth as a CSS solution. You'd also need to ensure that the JavaScript function is capable of correctly returning the window dimensions across all major browsers.

Let us know if one of the previously mentioned CSS solutions work, as it sounds like a better way to fix the problem.

How can I count all the lines of code in a directory recursively?

For sources only:

wc `find`

To filter, just use grep:

wc `find | grep .php$`

grunt: command not found when running from terminal

I have been hunting around trying to solve this one for a while and none of the suggested updates to bash seemed to be working. What I discovered was that some point my npm root was modified such that it was pointing to a Users/USER_NAME/.node/node_modules while the actual installation of npm was living at /usr/local/lib/node_modules. You can check this by running npm root and npm root -g (for the global installation). To correct the path you can call npm config set prefix /usr/local.

HTML: How to make a submit button with text + image in it?

Here is an other example:

<button type="submit" name="submit" style="border: none; background-color: white">

How to close current tab in a browser window?

Try this as well. Working for me on all three major browsers.

<!-- saved from url=(0014)about:internet -->
<a href="#" onclick="javascript:window.close();opener.window.focus();" >Close Window</a>

Can't check signature: public key not found

I got the same message but my files are decrypted as expected. Please check in your destination path if you could see the output file file.

Count the number of items in my array list

The only thing I would add to Mark Peters solution is that you don't need to iterate over the ArrayList - you should be able to use the addAll(Collection) method on the Set. You only need to iterate over the entire list to do the summations.

PHP How to find the time elapsed since a date time?

Had to do this recently - hope this helps someone. It doesn't cater for every possibility, but met my needs for a project.

https://github.com/duncanheron/twitter_date_format

https://github.com/duncanheron/twitter_date_format/blob/master/twitter_date_format.php

Setting Camera Parameters in OpenCV/Python

I had the same problem with openCV on Raspberry Pi... don't know if this can solve your problem, but what worked for me was

import time
import cv2


cap = cv2.VideoCapture(0)

cap.set(3,1280)

cap.set(4,1024)

time.sleep(2)

cap.set(15, -8.0)

the time you have to use can be different

Copy or rsync command

The command as written will create new directories and files with the current date and time stamp, and yourself as the owner. If you are the only user on your system and you are doing this daily it may not matter much. But if preserving those attributes matters to you, you can modify your command with

cp -pur /home/abc/* /mnt/windowsabc/

The -p will preserve ownership, timestamps, and mode of the file. This can be pretty important depending on what you're backing up.

The alternative command with rsync would be

rsync -avh /home/abc/* /mnt/windowsabc

With rsync, -a indicates "archive" which preserves all those attributes mentioned above. -v indicates "verbose" which just lists what it's doing with each file as it runs. -z is left out here for local copies, but is for compression, which will help if you are backing up over a network. Finally, the -h tells rsync to report sizes in human-readable formats like MB,GB,etc.

Out of curiosity, I ran one copy to prime the system and avoid biasing against the first run, then I timed the following on a test run of 1GB of files from an internal SSD drive to a USB-connected HDD. These simply copied to empty target directories.

cp -pur    : 19.5 seconds
rsync -ah  : 19.6 seconds
rsync -azh : 61.5 seconds

Both commands seem to be about the same, although zipping and unzipping obviously tax the system where bandwidth is not a bottleneck.

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I encountered this error too, it occurs because %HTTPPORT% isn’t part of the system variables yet.

The solution to this is NOT by manually typing in the url to your browser, which works but you have to keep doing it every single time.

Simply goto “this pc” or “my computer” right click on it and select properties, then select “advanced system settings” When the new window comes up select “Environment Variables...”

Now under system variables click new to create a new system variable. Type HTTPPORT into the variable name text box, Then type 8080 into the variable value text box. Click OK, close the windows and logout!

Thats an important step, make sure you log out. When you log back in, click the get started icon again and it will open without errors.

??

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

The technical limitations with using PUT and DELETE requests does not lie with PHP or Apache2; it is instead on the burden of the browser to sent those types of requests.

Simply putting <form action="" method="PUT"> will not work because there are no browsers that support that method (and they would simply default to GET, treating PUT the same as it would treat gibberish like FDSFGS). Sadly those HTTP verbs are limited to the realm of non-desktop application browsers (ie: web service consumers).

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

That works in new browsers i.e. IE11+ see table at the bottom of the article.

Parsing command-line arguments in C

I think that GNU GetOpt is not too immediate to use.

Qt and Boost could be a solution, but you need to download and compile a lot of code.

So I implemented a parser by myself that produces a std::map<std::string, std::string> of parameters.

For example, calling:

 ./myProgram -v -p 1234

map will be:

 ["-v"][""]
 ["-p"]["1234"]

Usage is:

int main(int argc, char *argv[]) {
    MainOptions mo(argc, argv);
    MainOptions::Option* opt = mo.getParamFromKey("-p");
    const string type = opt ? (*opt).second : "";
    cout << type << endl; /* Prints 1234 */
    /* Your check code */
}

MainOptions.h

#ifndef MAINOPTIONS_H_
#define MAINOPTIONS_H_

#include <map>
#include <string>

class MainOptions {
public:
    typedef std::pair<std::string, std::string> Option;
    MainOptions(int argc, char *argv[]);
    virtual ~MainOptions();
    std::string getAppName() const;
    bool hasKey(const std::string&) const;
    Option* getParamFromKey(const std::string&) const;
    void printOptions() const;
private:
    typedef std::map<std::string, std::string> Options;
    void parse();
    const char* const *begin() const;
    const char* const *end() const;
    const char* const *last() const;
    Options options_;
    int argc_;
    char** argv_;
    std::string appName_;
};

MainOptions.cpp

#include "MainOptions.h"

#include <iostream>

using namespace std;

MainOptions::MainOptions(int argc, char* argv[]) :
        argc_(argc),
        argv_(argv) {
    appName_ = argv_[0];
    this->parse();
}

MainOptions::~MainOptions() {
}

std::string MainOptions::getAppName() const {
    return appName_;
}

void MainOptions::parse() {
    typedef pair<string, string> Option;
    Option* option = new pair<string, string>();
    for (const char* const * i = this->begin() + 1; i != this->end(); i++) {
        const string p = *i;
        if (option->first == "" && p[0] == '-') {
            option->first = p;
            if (i == this->last()) {
                options_.insert(Option(option->first, option->second));
            }
            continue;
        } else if (option->first != "" && p[0] == '-') {
            option->second = "null"; /* or leave empty? */
            options_.insert(Option(option->first, option->second));
            option->first = p;
            option->second = "";
            if (i == this->last()) {
                options_.insert(Option(option->first, option->second));
            }
            continue;
        } else if (option->first != "") {
            option->second = p;
            options_.insert(Option(option->first, option->second));
            option->first = "";
            option->second = "";
            continue;
        }
    }
}

void MainOptions::printOptions() const {
    std::map<std::string, std::string>::const_iterator m = options_.begin();
    int i = 0;
    if (options_.empty()) {
        cout << "No parameters\n";
    }
    for (; m != options_.end(); m++, ++i) {
        cout << "Parameter [" << i << "] [" << (*m).first << " " << (*m).second
                << "]\n";
    }
}

const char* const *MainOptions::begin() const {
    return argv_;
}

const char* const *MainOptions::end() const {
    return argv_ + argc_;
}

const char* const *MainOptions::last() const {
    return argv_ + argc_ - 1;
}

bool MainOptions::hasKey(const std::string& key) const {
    return options_.find(key) != options_.end();
}

MainOptions::Option* MainOptions::getParamFromKey(
        const std::string& key) const {
    const Options::const_iterator i = options_.find(key);
    MainOptions::Option* o = 0;
    if (i != options_.end()) {
        o = new MainOptions::Option((*i).first, (*i).second);
    }
    return o;
}

IOError: [Errno 32] Broken pipe: Python

I haven't reproduced the issue, but perhaps this method would solve it: (writing line by line to stdout rather than using print)

import sys
with open('a.txt', 'r') as f1:
    for line in f1:
        sys.stdout.write(line)

You could catch the broken pipe? This writes the file to stdout line by line until the pipe is closed.

import sys, errno
try:
    with open('a.txt', 'r') as f1:
        for line in f1:
            sys.stdout.write(line)
except IOError as e:
    if e.errno == errno.EPIPE:
        # Handle error

You also need to make sure that othercommand is reading from the pipe before it gets too big - https://unix.stackexchange.com/questions/11946/how-big-is-the-pipe-buffer

Merge two HTML table cells

Set the colspan attribute to 2.

...but please don't use tables for layout.

EF LINQ include multiple and nested entities

One may write an extension method like this:

    /// <summary>
    /// Includes an array of navigation properties for the specified query 
    /// </summary>
    /// <typeparam name="T">The type of the entity</typeparam>
    /// <param name="query">The query to include navigation properties for that</param>
    /// <param name="navProperties">The array of navigation properties to include</param>
    /// <returns></returns>
    public static IQueryable<T> Include<T>(this IQueryable<T> query, params string[] navProperties)
        where T : class
    {
        foreach (var navProperty in navProperties)
            query = query.Include(navProperty);

        return query;
    }

And use it like this even in a generic implementation:

string[] includedNavigationProperties = new string[] { "NavProp1.SubNavProp", "NavProp2" };

var query = context.Set<T>()
.Include(includedNavigationProperties);

How to access the contents of a vector from a pointer to the vector in C++?

You can access the iterator methods directly:

std::vector<int> *intVec;
std::vector<int>::iterator it;

for( it = intVec->begin(); it != intVec->end(); ++it )
{
}

If you want the array-access operator, you'd have to de-reference the pointer. For example:

std::vector<int> *intVec;

int val = (*intVec)[0];

Best way to store date/time in mongodb

One datestamp is already in the _id object, representing insert time

So if the insert time is what you need, it's already there:

Login to mongodb shell

ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test

Create your database by inserting items

> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
> 

Lets make that database the one we are on now

> use penguins
switched to db penguins

Get the rows back:

> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }

Get each row in yyyy-MM-dd HH:mm:ss format:

> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53

If that last one-liner confuses you I have a walkthrough on how that works here: https://stackoverflow.com/a/27613766/445131

Text that shows an underline on hover

Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!

HTML

<span class="menu">Menu</span>

SCSS

.menu {
    position: relative;
    text-decoration: none;
    font-weight: 400;
    color: blue;
    transition: all .35s ease;

    &::before {
        content: "";
        position: absolute;
        width: 100%;
        height: 2px;
        bottom: 0;
        left: 0;
        background-color: yellow;
        visibility: hidden;
        -webkit-transform: scaleX(0);
        transform: scaleX(0);
        -webkit-transition: all 0.3s ease-in-out 0s;
        transition: all 0.3s ease-in-out 0s;
    }

    &:hover {
        color: yellow;

        &::before {
            visibility: visible;
            -webkit-transform: scaleX(1);
            transform: scaleX(1);
        }
    }
}

How to manually send HTTP POST requests from Firefox or Chrome browser?

You could also use Watir or Watin to automate browsers. Watir is written for ruby and Watin is for .Net languages. Not sure if it's what you are looking for though.

How to make a transparent HTML button?

**add the icon top button like this **

_x000D_
_x000D_
#copy_btn{_x000D_
 align-items: center;_x000D_
 position: absolute;_x000D_
 width: 30px;_x000D_
  height: 30px;_x000D_
     background-color: Transparent;_x000D_
    background-repeat:no-repeat;_x000D_
    border: none;_x000D_
    cursor:pointer;_x000D_
    overflow: hidden;_x000D_
    outline:none;_x000D_
}_x000D_
.icon_copy{_x000D_
 position: absolute;_x000D_
 padding: 0px;_x000D_
 top:0;_x000D_
 left: 0;_x000D_
width: 25px;_x000D_
  height: 35px;_x000D_
  _x000D_
}
_x000D_
<button id="copy_btn">_x000D_
_x000D_
                        <img class="icon_copy" src="./assest/copy.svg" alt="Copy Text">_x000D_
</button>
_x000D_
_x000D_
_x000D_

How do I copy a version of a single file from one git branch to another?

1) Ensure you're in branch where you need a copy of the file. for eg: i want sub branch file in master so you need to checkout or should be in master git checkout master

2) Now checkout specific file alone you want from sub branch into master,

git checkout sub_branch file_path/my_file.ext

here sub_branch means where you have that file followed by filename you need to copy.

Loading scripts after page load?

Focusing on one of the accepted answer's jQuery solutions, $.getScript() is an .ajax() request in disguise. It allows to execute other function on success by adding a second parameter:

$.getScript(url, function() {console.log('loaded script!')})

Or on the request's handlers themselves, i.e. success (.done() - script was loaded) or failure (.fail()):

_x000D_
_x000D_
$.getScript(_x000D_
    "https://code.jquery.com/color/jquery.color.js",_x000D_
    () => console.log('loaded script!')_x000D_
  ).done((script,textStatus ) => {_x000D_
    console.log( textStatus );_x000D_
    $(".block").animate({backgroundColor: "green"}, 1000);_x000D_
  }).fail(( jqxhr, settings, exception ) => {_x000D_
    console.log(exception + ': ' + jqxhr.status);_x000D_
  }_x000D_
);
_x000D_
.block {background-color: blue;width: 50vw;height: 50vh;margin: 1rem;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="block"></div>
_x000D_
_x000D_
_x000D_

What does the following Oracle error mean: invalid column index

the final sql statement is something like:

select col_1 from table_X where col_2 = 'abcd';

i run this inside my SQL IDE and everything is ok.

Next, i try to build this statement with java:

String queryString= "select col_1 from table_X where col_2 = '?';";
PreparedStatement stmt = con.prepareStatement(queryString);
stmt.setString(1, "abcd"); //raises java.sql.SQLException: Invalid column index

Although the sql statement (the first one, ran against the database) contains quotes around string values, and also finishes with a semicolumn, the string that i pass to the PreparedStatement should not contain quotes around the wildcard character ?, nor should it finish with semicolumn.

i just removed the characters that appear on white background

"select col_1 from table_X where col_2 = ' ? ' ; ";

to obtain

"select col_1 from table_X where col_2 = ?";

(i found the solution here: https://coderanch.com/t/424689/databases/java-sql-SQLException-Invalid-column)

Why are arrays of references illegal?

Just to add to all the conversation. Since arrays requires consecutive memory locations to store the item, so if we create an array of references then it's not guaranteed that they will be at consecutive memory location so accessing will be a problem and hence we can't even apply all the mathematical operations on array.

Convert String to SecureString

You can follow this:

string password = "test";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();

"This operation requires IIS integrated pipeline mode."

Press F4 in your Project for the property window. Then change the pipeline mode

enter image description here

How to present popover properly in iOS 8

Swift 2.0

Well I worked out. Have a look. Made a ViewController in StoryBoard. Associated with PopOverViewController class.

import UIKit

class PopOverViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()    
        self.preferredContentSize = CGSizeMake(200, 200)    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")    
    }    
    func dismiss(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}      

See ViewController:

//  ViewController.swift

import UIKit

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
{
    func showPopover(base: UIView)
    {
        if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("popover") as? PopOverViewController {    

            let navController = UINavigationController(rootViewController: viewController)
            navController.modalPresentationStyle = .Popover

            if let pctrl = navController.popoverPresentationController {
                pctrl.delegate = self

                pctrl.sourceView = base
                pctrl.sourceRect = base.bounds

                self.presentViewController(navController, animated: true, completion: nil)
            }
        }
    }    
    override func viewDidLoad(){
        super.viewDidLoad()
    }    
    @IBAction func onShow(sender: UIButton)
    {
        self.showPopover(sender)
    }    
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return .None
    }
}  

Note: The func showPopover(base: UIView) method should be placed before ViewDidLoad. Hope it helps !

How to select following sibling/xml tag using xpath

For completeness - adding to accepted answer above - in case you are interested in any sibling regardless of the element type you can use variation:

following-sibling::*

Get a list of checked checkboxes in a div using jQuery

Combination of two previous answers:

var selected = [];
$('#checkboxes input:checked').each(function() {
    selected.push($(this).attr('name'));
});

Xcode 'CodeSign error: code signing is required'

Be sure you code sign on the line "any iOS SDK" and not "Debug/Distribution/Release"

Here is exactly what I did :

Code signing identity -> don't code sign
* Debug -> don't code sign
** any iOS SDK -> [my developer profile]
* Distribution -> don't code sign
** any iOS SDK -> [my AppStore profile]
* Release -> don't code sign
** any iOS SDK -> [my AdHoc profile]

When I put my profiles one level above (at Debug/Ditribution/Release), it doesn't work for some reason (bug ?).

Hope it helps some of us !

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

Where you have written the code

public class Main {
    public static void main(String args[])
    {
        Calculate obj = new Calculate(1,2,'+');
        obj.getAnswer();
    }
}

Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.

Java Replace Line In Text File

If replacement is of different length:

  1. Read file until you find the string you want to replace.
  2. Read into memory the part after text you want to replace, all of it.
  3. Truncate the file at start of the part you want to replace.
  4. Write replacement.
  5. Write rest of the file from step 2.

If replacement is of same length:

  1. Read file until you find the string you want to replace.
  2. Set file position to start of the part you want to replace.
  3. Write replacement, overwriting part of file.

This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work.

Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. If encoding is UTF8, and your text is not Latin1 (or plain 7-bit ASCII), you have to check length of encoded byte array, not length of Java string.

How to pretty print XML from the command line?

This took me forever to find something that works on my mac. Here's what worked for me:

brew install xmlformat
cat unformatted.html | xmlformat

HTTPS setup in Amazon EC2

There must be also an answer for people who want a hassle free https on ec2 for mainly demo and testing purposes, one way they can achieve that very fast is:

With my answer here which describes How you can achieve https for testing purposes in minutes with EC2 without the hassle of creating certificates

Time complexity of Euclid's Algorithm

One trick for analyzing the time complexity of Euclid's algorithm is to follow what happens over two iterations:

a', b' := a % b, b % (a % b)

Now a and b will both decrease, instead of only one, which makes the analysis easier. You can divide it into cases:

  • Tiny A: 2a <= b
  • Tiny B: 2b <= a
  • Small A: 2a > b but a < b
  • Small B: 2b > a but b < a
  • Equal: a == b

Now we'll show that every single case decreases the total a+b by at least a quarter:

  • Tiny A: b % (a % b) < a and 2a <= b, so b is decreased by at least half, so a+b decreased by at least 25%
  • Tiny B: a % b < b and 2b <= a, so a is decreased by at least half, so a+b decreased by at least 25%
  • Small A: b will become b-a, which is less than b/2, decreasing a+b by at least 25%.
  • Small B: a will become a-b, which is less than a/2, decreasing a+b by at least 25%.
  • Equal: a+b drops to 0, which is obviously decreasing a+b by at least 25%.

Therefore, by case analysis, every double-step decreases a+b by at least 25%. There's a maximum number of times this can happen before a+b is forced to drop below 1. The total number of steps (S) until we hit 0 must satisfy (4/3)^S <= A+B. Now just work it:

(4/3)^S <= A+B
S <= lg[4/3](A+B)
S is O(lg[4/3](A+B))
S is O(lg(A+B))
S is O(lg(A*B)) //because A*B asymptotically greater than A+B
S is O(lg(A)+lg(B))
//Input size N is lg(A) + lg(B)
S is O(N)

So the number of iterations is linear in the number of input digits. For numbers that fit into cpu registers, it's reasonable to model the iterations as taking constant time and pretend that the total running time of the gcd is linear.

Of course, if you're dealing with big integers, you must account for the fact that the modulus operations within each iteration don't have a constant cost. Roughly speaking, the total asymptotic runtime is going to be n^2 times a polylogarithmic factor. Something like n^2 lg(n) 2^O(log* n). The polylogarithmic factor can be avoided by instead using a binary gcd.

Search all tables, all columns for a specific value SQL Server

You could query the sys.tables database view to get out the names of the tables, and then use this query to build yourself another query to do the update on the back of that. For instance:

select 'select * from '+name from sys.tables

will give you a script that will run a select * against all the tables in the system catalog, you could alter the string in the select clause to do your update, as long as you know the column name is the same on all the tables you wish to update, so your script would look something like:

select 'update '+name+' set comments = ''(*)''+comments where comments like ''%comment to be updated%'' ' from sys.tables

You could also then predicate on the tables query to only include tables that have a name in a certain format, or are in a subset you want to create the update script for.

Change background position with jQuery

rebellion's answer above won't actually work, because to CSS, 'background-position' is actually shorthand for 'background-position-x' and 'background-position-y' so the correct version of his code would be:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('background-position-x', newValueX);
        $('#carousel').css('background-position-y', newValue);
    }, function(){
        $('#carousel').css('background-position-x', oldValueX);
        $('#carousel').css('background-position-y', oldValueY);
    });
});

It took about 4 hours of banging my head against it to come to that aggravating realization.

Passing command line arguments in Visual Studio 2010?

Under Project->Properties->Debug, you should see a box for Command line arguments (This is in C# 2010, but it should basically be the same place)

pull out p-values and r-squared from a linear regression

You can see the structure of the object returned by summary() by calling str(summary(fit)). Each piece can be accessed using $. The p-value for the F statistic is more easily had from the object returned by anova.

Concisely, you can do this:

rSquared <- summary(fit)$r.squared
pVal <- anova(fit)$'Pr(>F)'[1]

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

Go to Start > Programs > Microsoft SQL Server > Enterprise Manager

Right-click the SQL Server instance name > Select Properties from the context menu > Select Security node in left navigation bar

Under Authentication section, select SQL Server and Windows Authentication

Note: The server must be stopped and re-started before this will take effect

Error 18452 (not associated with a trusted sql server connection)

Invalid attempt to read when no data is present

You have to call dr.Read() before attempting to read any data. That method will return false if there is nothing to read.

how to add background image to activity?

Place the Image in the folder drawable. drawable folder is in res. drawable have 5 variants drawable-hdpi drawable-ldpi drawable-mdpi drawable-xhdpi drawable-xxhdpi

How to uncheck a checkbox in pure JavaScript?

<html>
    <body>
        <input id="mycheck" type="checkbox">
    </body>

    <script language="javascript">
        var=check;
        document.getElementById("mycheck");
        check.checked="false";
    </script>
</html>

What is the main difference between PATCH and PUT request?

There are limitations in PUT over PATCH while making updates. Using PUT requires us to specify all attributes even if we want to change only one attribute. But if we use the PATCH method we can update only the fields we need and there is no need to mention all the fields. PATCH does not allow us to modify a value in an array, or remove an attribute or array entry.