Programs & Examples On #Android gridview

GridView is a subclass of AdapterView that displays items in a two-dimensional, scrollable grid.

Gridview with two columns and auto resized images

Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"/>

</FrameLayout>

Make a custom ImageView that maintains its aspect ratio:

src/com/example/graphicstest/SquareImageView.java

public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
    }
}

Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:

res/layout/grid_item.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <com.example.graphicstest.SquareImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"/>

</FrameLayout>

Now make some sort of adapter for your GridView:

src/com/example/graphicstest/MyAdapter.java

private final class MyAdapter extends BaseAdapter {
    private final List<Item> mItems = new ArrayList<Item>();
    private final LayoutInflater mInflater;

    public MyAdapter(Context context) {
        mInflater = LayoutInflater.from(context);

        mItems.add(new Item("Red",       R.drawable.red));
        mItems.add(new Item("Magenta",   R.drawable.magenta));
        mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
        mItems.add(new Item("Gray",      R.drawable.gray));
        mItems.add(new Item("Green",     R.drawable.green));
        mItems.add(new Item("Cyan",      R.drawable.cyan));
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Item getItem(int i) {
        return mItems.get(i);
    }

    @Override
    public long getItemId(int i) {
        return mItems.get(i).drawableId;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        ImageView picture;
        TextView name;

        if (v == null) {
            v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
            v.setTag(R.id.picture, v.findViewById(R.id.picture));
            v.setTag(R.id.text, v.findViewById(R.id.text));
        }

        picture = (ImageView) v.getTag(R.id.picture);
        name = (TextView) v.getTag(R.id.text);

        Item item = getItem(i);

        picture.setImageResource(item.drawableId);
        name.setText(item.name);

        return v;
    }

    private static class Item {
        public final String name;
        public final int drawableId;

        Item(String name, int drawableId) {
            this.name = name;
            this.drawableId = drawableId;
        }
    }
}

Set that adapter to your GridView:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GridView gridView = (GridView)findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(this));
}

And enjoy the results:

Example GridView

GridLayout (not GridView) how to stretch all children evenly

I wish this helps some one

Result

enter image description here

enter image description here

Code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:grid="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 0x0"
        grid:layout_column="0"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="0"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 0x1"
        grid:layout_column="1"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="0"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 0x2"
        grid:layout_column="2"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="0"
        grid:layout_rowWeight="1" />


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 1x0"
        grid:layout_column="0"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="1"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 1x1"
        grid:layout_column="1"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="1"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 1x2"
        grid:layout_column="2"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="1"
        grid:layout_rowWeight="1" />


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 2x0"
        grid:layout_column="0"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="2"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 2x1"
        grid:layout_column="1"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="2"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 2x2"
        grid:layout_column="2"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="2"
        grid:layout_rowWeight="1" />


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 3x0"
        grid:layout_column="0"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="3"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 3x1"
        grid:layout_column="1"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="3"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 3x2"
        grid:layout_column="2"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="3"
        grid:layout_rowWeight="1" />

</android.support.v7.widget.GridLayout>

GridView VS GridLayout in Android Apps

A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.

Whereas a GridLayout is a layout that places its children in a rectangular grid.

It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

The problem is the JSON - this cannot, by default, be deserialized into a Collection because it's not actually a JSON Array - that would look like this:

[
    {
        "name": "Test order1",
        "detail": "ahk ks"
    },
    {
        "name": "Test order2",
        "detail": "Fisteku"
    }
]

Since you're not controlling the exact process of deserialization (RestEasy does) - a first option would be to simply inject the JSON as a String and then take control of the deserialization process:

Collection<COrder> readValues = new ObjectMapper().readValue(
    jsonAsString, new TypeReference<Collection<COrder>>() { }
);

You would loose a bit of the convenience of not having to do that yourself, but you would easily sort out the problem.

Another option - if you cannot change the JSON - would be to construct a wrapper to fit the structure of your JSON input - and use that instead of Collection<COrder>.

Hope this helps.

Java: How to read a text file

Just for fun, here's what I'd probably do in a real project, where I'm already using all my favourite libraries (in this case Guava, formerly known as Google Collections).

String text = Files.toString(new File("textfile.txt"), Charsets.UTF_8);
List<Integer> list = Lists.newArrayList();
for (String s : text.split("\\s")) {
    list.add(Integer.valueOf(s));
}

Benefit: Not much own code to maintain (contrast with e.g. this). Edit: Although it is worth noting that in this case tschaible's Scanner solution doesn't have any more code!

Drawback: you obviously may not want to add new library dependencies just for this. (Then again, you'd be silly not to make use of Guava in your projects. ;-)

How to add to the end of lines containing a pattern with sed or awk?

Solution with awk:

awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file

Simply: if the row starts with all print the row plus "anotherthing", else print just the row.

Java Generate Random Number Between Two Given Values

Assuming the upper is the upper bound and lower is the lower bound, then you can make a random number, r, between the two bounds with:

int r = (int) (Math.random() * (upper - lower)) + lower;

Retrieving the text of the selected <option> in <select> element

document.getElementById('test').options[document.getElementById('test').selectedIndex].text;

How to select clear table contents without destroying the table?

I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.

Sub CleanTheTable()
    Application.ScreenUpdating = False
    Sheets("Data").Select
    ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
    'Remove the filters if one exists.
    If ActiveSheet.FilterMode Then
    Selection.AutoFilter
    End If
    'Clear all lines but the first one in the table leaving formulas for the next go round.
    With Worksheets("Data").ListObjects("TestTable")
    .Range.AutoFilter
    On Error Resume Next
    .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
    .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
    ActiveWindow.SmallScroll Down:=-10000

    End With
Application.ScreenUpdating = True
End Sub

How to Disable landscape mode in Android?

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.co.nurture.bajajfinserv">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>


    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" android:screenOrientation="portrait">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

we can restrict the Activity in portrait or landscape mode by using the attribute or android:screenOrientation.

if we have more than one activity in my program then you have freedom to restrict any one of activity in any one the mode and it never effect the others which you don't want.

SQL Case Expression Syntax?

Here are the CASE statement examples from the PostgreSQL docs (Postgres follows the SQL standard here):

SELECT a,
   CASE WHEN a=1 THEN 'one'
        WHEN a=2 THEN 'two'
        ELSE 'other'
   END
FROM test;

or

SELECT a,
   CASE a WHEN 1 THEN 'one'
          WHEN 2 THEN 'two'
          ELSE 'other'
   END
FROM test;

Obviously the second form is cleaner when you are just checking one field against a list of possible values. The first form allows more complicated expressions.

Debugging JavaScript in IE7

IE8 has much improved developer tools. Until then it's best to write javascript for firefox first and then debug IE using alert() statements.

Regular expression for exact match of a string

In malfaux's answer '^' and '$' has been used to detect the beginning and the end of the text.
These are usually used to detect the beginning and the end of a line.
However this may be the correct way in this case.
But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.

/\b123456\b/

How to convert from []byte to int in Go Programming

var bs []byte
value, _ := strconv.ParseInt(string(bs), 10, 64)

Iterate through dictionary values?

If all your values are unique, you can make a reverse dictionary:

PIXO_reverse = {v: k for k, v in PIX0.items()}

Result:

>>> PIXO_reverse

{'320x240': 'QVGA', '640x480': 'VGA', '800x600': 'SVGA'}

Now you can use the same logic as before.

How to fire an event when v-model changes?

Vue2: if you only want to detect change on input blur (e.g. after press enter or click somewhere else) do (more info here)

<input @change="foo" v-model... >

If you wanna detect single character changes (during user typing) use

<input @keydown="foo" v-model... >

You can also use @keyup and @input events. If you wanna to pass additional parameters use in template e.g. @keyDown="foo($event, param1, param2)". Comparision below (editable version here)

_x000D_
_x000D_
new Vue({_x000D_
  el: "#app",_x000D_
  data: { _x000D_
    keyDown: { key:null, val: null,  model: null, modelCopy: null },_x000D_
    keyUp: { key:null, val: null,  model: null, modelCopy: null },_x000D_
    change: { val: null,  model: null, modelCopy: null },_x000D_
    input: { val: null,  model: null, modelCopy: null },_x000D_
    _x000D_
    _x000D_
  },_x000D_
  methods: {_x000D_
  _x000D_
    keyDownFun: function(event){                   // type of event: KeyboardEvent   _x000D_
      console.log(event);  _x000D_
      this.keyDown.key = event.key;                // or event.keyCode_x000D_
      this.keyDown.val = event.target.value;       // html current input value_x000D_
      this.keyDown.modelCopy = this.keyDown.model; // copy of model value at the moment on event handling_x000D_
    },_x000D_
    _x000D_
    keyUpFun: function(event){                     // type of event: KeyboardEvent_x000D_
      console.log(event);  _x000D_
      this.keyUp.key = event.key;                  // or event.keyCode_x000D_
      this.keyUp.val = event.target.value;         // html current input value_x000D_
      this.keyUp.modelCopy = this.keyUp.model;     // copy of model value at the moment on event handling_x000D_
    },_x000D_
    _x000D_
    changeFun: function(event) {                   // type of event: Event_x000D_
      console.log(event);_x000D_
      this.change.val = event.target.value;        // html current input value_x000D_
      this.change.modelCopy = this.change.model;   // copy of model value at the moment on event handling_x000D_
    },_x000D_
    _x000D_
    inputFun: function(event) {                    // type of event: Event_x000D_
      console.log(event);_x000D_
      this.input.val = event.target.value;         // html current input value_x000D_
      this.input.modelCopy = this.input.model;     // copy of model value at the moment on event handling_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
div {_x000D_
  margin-top: 20px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
Type in fields below (to see events details open browser console)_x000D_
_x000D_
<div id="app">_x000D_
  <div><input type="text" @keyDown="keyDownFun" v-model="keyDown.model"><br> @keyDown (note: model is different than value and modelCopy)<br> key:{{keyDown.key}}<br> value: {{ keyDown.val }}<br> modelCopy: {{keyDown.modelCopy}}<br> model: {{keyDown.model}}</div>_x000D_
  _x000D_
  <div><input type="text" @keyUp="keyUpFun" v-model="keyUp.model"><br> @keyUp (note: model change value before event occure) <br> key:{{keyUp.key}}<br> value: {{ keyUp.val }}<br> modelCopy: {{keyUp.modelCopy}}<br> model: {{keyUp.model}}</div>_x000D_
  _x000D_
  <div><input type="text" @change="changeFun" v-model="change.model"><br> @change (occures on enter key or focus change (tab, outside mouse click) etc.)<br> value: {{ change.val }}<br> modelCopy: {{change.modelCopy}}<br> model: {{change.model}}</div>_x000D_
  _x000D_
  <div><input type="text" @input="inputFun" v-model="input.model"><br> @input<br> value: {{ input.val }}<br> modelCopy: {{input.modelCopy}}<br> model: {{input.model}}</div>_x000D_
     _x000D_
</div>
_x000D_
_x000D_
_x000D_

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

Java generating non-repeating random numbers

public class Randoms {

static int z, a = 1111, b = 9999, r;

public static void main(String ... args[])
{
       rand();
}

    public static void rand() {

    Random ran = new Random();
    for (int i = 1; i == 1; i++) {
        z = ran.nextInt(b - a + 1) + a;
        System.out.println(z);
        randcheck();
    }
}

private static void randcheck() {

    for (int i = 3; i >= 0; i--) {
        if (z != 0) {
            r = z % 10;
            arr[i] = r;
            z = z / 10;
        }
    }
    for (int i = 0; i <= 3; i++) {
        for (int j = i + 1; j <= 3; j++) {
            if (arr[i] == arr[j]) {
                rand();
            }
        }

    }
}
}

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

Why does git perform fast-forward merges by default?

Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.

Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master.

alt text
(From nvie.com, Vincent Driessen, post "A successful Git branching model")

Incorporating a finished feature on develop

Finished features may be merged into the develop branch to add them to the upcoming release:

$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.

Jakub Narebski also mentions the config merge.ff:

By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set to false, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the --no-ff option from the command line).
When set to 'only', only such fast-forward merges are allowed (equivalent to giving the --ff-only option from the command line).


The fast-forward is the default because:

  • short-lived branches are very easy to create and use in Git
  • short-lived branches often isolate many commits that can be reorganized freely within that branch
  • those commits are actually part of the main branch: once reorganized, the main branch is fast-forwarded to include them.

But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.

In this case, you can end up setting this kind of config file:

[branch "master"]
# This is the list of cmdline options that should be added to git-merge 
# when I merge commits into the master branch.

# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.

# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.

mergeoptions = --no-commit --no-ff

The OP adds in the comments:

I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?

Jefromi answers:

I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.

To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.

More generally, I add:

it really depends on your development workflow:

  • if it is linear, one branch makes sense.
  • If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.

See "When should you branch?"

Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".

Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

Remove all pods and install again.

Steps:

  1. comment all pods and run pod install
  2. uncomment all pods and run pod install

How to delete a certain row from mysql table with same column values?

You need to specify the number of rows which should be deleted. In your case (and I assume that you only want to keep one) this can be done like this:

DELETE FROM your_table WHERE id_users=1 AND id_product=2
LIMIT (SELECT COUNT(*)-1 FROM your_table WHERE id_users=1 AND id_product=2)

Eclipse - Failed to create the java virtual machine

I tried several methods but didn't work. The only one that did is the one right at the bottom. I'll just list the other options I tried as well, for reference.

Some background, I migrated from Mars to Neon and copied over eclipse.ini almost exactly.

Reduce -XX:MaxPermSize and -Xmx

Like other answers have mentioned, progressively reduce these 2 flags (eg to 128m) and try again. If it still doesn't work at 128m then try other options below.

Find the offending flag by renaming eclipse.ini

Jon H's answer gave me a hint. Delete eclipse.ini (or rename it) and start eclipse. It should regen eclipse.ini and launch successfully (mine didn't regen eclipse.ini though eclipse launched fine).

If eclipse.ini did regen for you, then add each flag back one-by-one.

If not, revert the original eclipse.ini and remove each flag one-by-one until you've found the flag that causes an error.

For my case, I upgraded from Mars to Neon. The offending flag was -XX:+UseG1GC Removing this flag (and only this flag) worked for me. Setting back -Xmx and -XX:MaxPermSize to 1G worked for me as well.

What is "X-Content-Type-Options=nosniff"?

Description

Setting a server's X-Content-Type-Options HTTP response header to nosniff instructs browsers to disable content or MIME sniffing which is used to override response Content-Type headers to guess and process the data using an implicit content type. While this can be convenient in some scenarios, it can also lead to some attacks listed below. Configuring your server to return the X-Content-Type-Options HTTP response header set to nosniff will instruct browsers that support MIME sniffing to use the server-provided Content-Type and not interpret the content as a different content type.

Browser Support

The X-Content-Type-Options HTTP response header is supported in Chrome, Firefox and Edge as well as other browsers. The latest browser support is available on the Mozilla Developer Network (MDN) Browser Compatibility Table for X-Content-Type-Options:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options

Attacks Countered

  1. MIME Confusion Attack enables attacks via user generated content sites by allowing users uploading malicious code that is then executed by browsers which will interpret the files using alternate content types, e.g. implicit application/javascript vs. explicit text/plain. This can result in a "drive-by download" attack which is a common attack vector for phishing. Sites that host user generated content should use this header to protect their users. This is mentioned by VeraCode and OWASP which says the following:

    This reduces exposure to drive-by download attacks and sites serving user uploaded content that, by clever naming, could be treated by MSIE as executable or dynamic HTML files.

  2. Unauthorized Hotlinking can also be enabled by Content-Type sniffing. By hotlinking to sites with resources for one purpose, e.g. viewing, apps can rely on content-type sniffing and generate a lot of traffic on sites for another purpose where it may be against their terms of service, e.g. GitHub displays JavaScript code for viewing, but not for execution:

    Some pesky non-human users (namely computers) have taken to "hotlinking" assets via the raw view feature -- using the raw URL as the src for a <script> or <img> tag. The problem is that these are not static assets. The raw file view, like any other view in a Rails app, must be rendered before being returned to the user. This quickly adds up to a big toll on performance. In the past we've been forced to block popular content served this way because it put excessive strain on our servers.

How can I create a temp file with a specific extension with .NET?

I think you should try this:

string path = Path.GetRandomFileName();
path = Path.Combine(@"c:\temp", path);
path = Path.ChangeExtension(path, ".tmp");
File.Create(path);

It generates a unique filename and creates a file with that file name at a specified location.

jQuery: Check if div with certain class name exists

if ($(".mydivclass").size()){
   // code here
}

The size() method just returns the number of elements that the jQuery selector selects - in this case the number of elements with the class mydivclass. If it returns 0, the expression is false, and therefore there are none, and if it returns any other number, the divs must exist.

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

For this problem, I have finally put a new <i> tag to refresh the select instead. Don't try to trigger an event if the selected option is the same that the one already selected.

enter image description here

If user click on the "refresh" button, I trigger the onchange event of my select with :

const refreshEquipeEl = document.getElementById("refreshEquipe1");

function onClickRefreshEquipe(event){
    let event2 = new Event('change');
    equipesSelectEl.dispatchEvent(event2);
}
refreshEquipeEl.onclick = onClickRefreshEquipe;

This way, I don't need to try select the same option in my select.

Add zero-padding to a string

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');

Difference between using bean id and name in Spring configuration file

Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html), it wont be allowed as the bean id, because it's not a valid XML ID. In such cases you could skip defining the bean id and supply the bean name instead.
The name attribute also helps in defining aliases for your bean, since it allows specifying multiple identifiers for a given bean.

JavaScript: Get image dimensions

naturalWidth and naturalHeight

var img = document.createElement("img");
img.onload = function (event)
{
    console.log("natural:", img.naturalWidth, img.naturalHeight);
    console.log("width,height:", img.width, img.height);
    console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
}
img.src = "image.jpg";
document.body.appendChild(img);

// css for tests
img { width:50%;height:50%; }

Processing Symbol Files in Xcode

Annoying error. I solved it by plugging the cable directly into the iPad. For some reason the process would never finish if I had the iPad in Apple's pass-through stand.

Reversing a linked list in Java, recursively

Inspired by an article discussing immutable implementations of recursive data structures I put an alternate solution together using Swift.

The leading answer documents solution by highlighting the following topics:

  1. What is the reverse of nil (the empty list)?
    • Does not matter here, because we have nil protection in Swift.
  2. What is the reverse of a one element list?
    • The element itself
  3. What is the reverse of an n element list?
    • The reverse of the second element on followed by the first element.

I have called these out where applicable in the solution below.

/**
 Node is a class that stores an arbitrary value of generic type T 
 and a pointer to another Node of the same time.  This is a recursive 
 data structure representative of a member of a unidirectional linked
 list.
 */
public class Node<T> {
    public let value: T
    public let next: Node<T>?

    public init(value: T, next: Node<T>?) {
        self.value = value
        self.next = next
    }

    public func reversedList() -> Node<T> {
        if let next = self.next {
            // 3. The reverse of the second element on followed by the first element.
            return next.reversedList() + value
        } else {
            // 2. Reverse of a one element list is itself
            return self
        }
    }
}

/**
 @return Returns a newly created Node consisting of the lhs list appended with rhs value.
 */
public func +<T>(lhs: Node<T>, rhs: T) -> Node<T> {
    let tail: Node<T>?
    if let next = lhs.next {
        // The new tail is created recursively, as long as there is a next node.
        tail = next + rhs
    } else {
        // If there is not a next node, create a new tail node to append
        tail = Node<T>(value: rhs, next: nil)
    }
    // Return a newly created Node consisting of the lhs list appended with rhs value.
    return Node<T>(value: lhs.value, next: tail)
}

How to filter JSON Data in JavaScript or jQuery?

This is how you should do it : ( for google find)

$([
  {"name":"Lenovo Thinkpad 41A4298","website":"google222"},
  {"name":"Lenovo Thinkpad 41A2222","website":"google"}
  ])
    .filter(function (i,n){
        return n.website==='google';
    });

Better solution : ( Salman's)

$.grep( [{"name":"Lenovo Thinkpad 41A4298","website":"google"},{"name":"Lenovo Thinkpad 41A2222","website":"google"}], function( n, i ) {
  return n.website==='google';
});

http://jsbin.com/yakubixi/4/edit

How to filter for multiple criteria in Excel?

The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.

http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm

Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.

  1. E1 : Letters
  2. E2 : =m
  3. E3 : =h
  4. E4 : =j

I put the data starting on row 5:

  1. A5 : Letters
  2. A6 :
  3. A7 :
  4. ...

Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.

That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.

How to make VS Code to treat other file extensions as certain language?

This works for me.

enter image description here

{
"files.associations": {"*.bitesize": "yaml"}
 }

Comparing boxed Long values 127 and 128

TL;DR

Java caches boxed Integer instances from -128 to 127. Since you are using == to compare objects references instead of values, only cached objects will match. Either work with long unboxed primitive values or use .equals() to compare your Long objects.

Long (pun intended) version

Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.

Java caches Integer objects instances from the range -128 to 127. That said:

  • If you set to N Long variables the value 127 (cached), the same object instance will be pointed by all references. (N variables, 1 instance)
  • If you set to N Long variables the value 128 (not cached), you will have an object instance pointed by every reference. (N variables, N instances)

That's why this:

Long val1 = 127L;
Long val2 = 127L;

System.out.println(val1 == val2);

Long val3 = 128L;
Long val4 = 128L;

System.out.println(val3 == val4);

Outputs this:

true
false

For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true.

On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false on the comparison between them.

That happens solely because you are comparing two Long object references, not long primitive values, with the == operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with == operator.

Changing these variables to primitive long types will prevent this from happening, but in case you need to keep your code using Long objects, you can safely make these comparisons with the following approaches:

System.out.println(val3.equals(val4));                     // true
System.out.println(val3.longValue() == val4.longValue());  // true
System.out.println((long)val3 == (long)val4);              // true

(Proper null checking is necessary, even for castings)

IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.

Reference links:

How can I parse a YAML file from a Linux shell script?

My use case may or may not be quite the same as what this original post was asking, but it's definitely similar.

I need to pull in some YAML as bash variables. The YAML will never be more than one level deep.

YAML looks like so:

KEY:                value
ANOTHER_KEY:        another_value
OH_MY_SO_MANY_KEYS: yet_another_value
LAST_KEY:           last_value

Output like-a dis:

KEY="value"
ANOTHER_KEY="another_value"
OH_MY_SO_MANY_KEYS="yet_another_value"
LAST_KEY="last_value"

I achieved the output with this line:

sed -e 's/:[^:\/\/]/="/g;s/$/"/g;s/ *=/=/g' file.yaml > file.sh
  • s/:[^:\/\/]/="/g finds : and replaces it with =", while ignoring :// (for URLs)
  • s/$/"/g appends " to the end of each line
  • s/ *=/=/g removes all spaces before =

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Unfortunately triggering the onsubmit or submit events wont work in all browsers.

  • Works in IE and Chrome: #('form#ajaxForm')trigger('onsubmit');
  • Works in Firefox and Safari: #('form#ajaxForm')trigger('submit');

Also, if you trigger('submit') in Chrome or IE, it causes the entire page to be posted rather than doing an AJAX behavior.

What works for all browsers is removing the onsubmit event behavior and just calling submit() on the form itself.

<script type="text/javascript">
$(function() {

    $('form#ajaxForm').submit(function(event) { 
        eval($(this).attr('onsubmit')); return false; 
        });

    $('form#ajaxForm').find('a.submit-link').click( function() { 
        $'form#ajaxForm').submit();
        });

  }
</script>
  <% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
     new AjaxOptions
     {
       UpdateTargetId = "DescriptionDiv",
       HttpMethod = "post"
     }, new { id = "ajaxForm" } )) {%>
   Description:
   <%= Html.TextBox("Description", Model.Description) %><br />
   <a href="#" class="submit-link">Save</a> 
<% } %>

Also, the link doesn't have to be contained within the form in order for this to work.

Trying to handle "back" navigation button action in iOS

Perhaps this answers doesn't fit your explanation but question title. It's useful when you are trying to know when you tapped the back button on an UINavigationBar.

In this case you can use UINavigationBarDelegate protocol and implement one of this methods:

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;
- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item;

When didPopItem method is called, it's because you either tapped the back button or you used [UINavigationBar popNavigationItemAnimated:] method and the navigation bar did pop the item.

Now, if you want to know what action triggered the didPopItem method you can use a flag.

With this approach I don't need to manually add a left bar button item with an arrow image in order to make it similar to iOS back button, and be able to set my custom target/action.


Let's see an example:

I have a view controller that has a page view controller, and a custom page indicator view. I'm also using a custom UINavigationBar to display a title to know on what page am I and the back button to go back to the previous page. And I also can swipe to previous/next page on page controller.

#pragma mark - UIPageViewController Delegate Methods
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {

    if( completed ) {

        //...

        if( currentIndex > lastIndex ) {

            UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:@"Some page title"];

            [[_someViewController navigationBar] pushNavigationItem:navigationItem animated:YES];
            [[_someViewController pageControl] setCurrentPage:currentIndex];
        } else {
            _autoPop = YES; //We pop the item automatically from code.
            [[_someViewController navigationBar] popNavigationItemAnimated:YES];
            [[_someViewController pageControl] setCurrentPage:currentIndex];
        }
    }

}

So then I implement UINavigationBar delegate methods:

#pragma mark - UINavigationBar Delegate Methods
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
    if( !_autoPop ) {
        //Pop by back button tap
    } else {
        //Pop from code
    }

    _autoPop = NO;

    return YES;
}

In this case I used shouldPopItem because the pop is animated and I wanted to handle the back button immediately and not to wait until transition is finished.

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

Replace the

import android.support.v7.app.AppCompatActivity;

with import androidx.appcompat.app.AppCompatActivity

How can I get a list of all classes within current module in Python?

This is the line that I use to get all of the classes that have been defined in the current module (ie not imported). It's a little long according to PEP-8 but you can change it as you see fit.

import sys
import inspect

classes = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass) 
          if obj.__module__ is __name__]

This gives you a list of the class names. If you want the class objects themselves just keep obj instead.

classes = [obj for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass)
          if obj.__module__ is __name__]

This is has been more useful in my experience.

save a pandas.Series histogram plot to file

Use the Figure.savefig() method, like so:

ax = s.hist()  # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')

It doesn't have to end in pdf, there are many options. Check out the documentation.

Alternatively, you can use the pyplot interface and just call the savefig as a function to save the most recently created figure:

import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf')  # saves the current figure

Why doesn't calling a Python string method do anything unless you assign its output?

This is because strings are immutable in Python.

Which means that X.replace("hello","goodbye") returns a copy of X with replacements made. Because of that you need replace this line:

X.replace("hello", "goodbye")

with this line:

X = X.replace("hello", "goodbye")

More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace,strip,translate,lower/upper,join,...

You must assign their output to something if you want to use it and not throw it away, e.g.

X  = X.strip(' \t')
X2 = X.translate(...)
Y  = X.lower()
Z  = X.upper()
A  = X.join(':')
B  = X.capitalize()
C  = X.casefold()

and so on.

HTML table headers always visible at top of window when viewing a large table

The most simple answer only using CSS :D !!!

_x000D_
_x000D_
table {_x000D_
  /* Not required only for visualizing */_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
table thead tr th {_x000D_
  /* you could also change td instead th depending your html code */_x000D_
  background-color: green;_x000D_
  position: sticky;_x000D_
  z-index: 100;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
  /* Not required only for visualizing */_x000D_
  padding: 1em;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Col1</th>_x000D_
      <th>Col2</th>_x000D_
      <th>Col3</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>david</td>_x000D_
       <td>castro</td>_x000D_
       <td>rocks!</td>_x000D_
     </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Java String.split() Regex

You could split on a word boundary with \b

'python3' is not recognized as an internal or external command, operable program or batch file

You can also try this: Go to the path where Python is installed in your system. For me it was something like C:\Users\\Local Settings\Application Data\Programs\Python\Python37 In this folder, you'll find a python executable. Just create a duplicate and rename it to python3. Works every time.

enter image description here

Limit on the WHERE col IN (...) condition

Why not do a where IN a sub-select...

Pre-query into a temp table or something...

CREATE TABLE SomeTempTable AS
    SELECT YourColumn
    FROM SomeTable
    WHERE UserPickedMultipleRecordsFromSomeListOrSomething

then...

SELECT * FROM OtherTable
WHERE YourColumn IN ( SELECT YourColumn FROM SomeTempTable )

Sockets: Discover port availability using Java

A cleanup of the answer pointed out by David Santamaria:

/**
 * Check to see if a port is available.
 *
 * @param port
 *            the port to check for availability.
 */
public static boolean isPortAvailable(int port) {
    try (var ss = new ServerSocket(port); var ds = new DatagramSocket(port)) {
        return true;
    } catch (IOException e) {
        return false;
    }
}

This is still subject to a race condition pointed out by user207421 in the comments to David Santamaria's answer (something could grab the port after this method closes the ServerSocket and DatagramSocket and returns).

Storing a file in a database as opposed to the file system?

We made the decision to store as varbinary for http://www.freshlogicstudios.com/Products/Folders/ halfway expecting performance issues. I can say that we've been pleasantly surprised at how well it's worked out.

How to output an Excel *.xls file from classic ASP

You can always just export the HTML table to an XLS document. Excel does a pretty good job understanding HTML tables.

Another possiblitly is to export the HTML tables as a CSV or TSV file, but you would need to setup the formatting in your code. This isn't too difficult to accomplish.

There's some classes in the Microsoft.Office.Interop that allow you to create an Excel file programatically, but I have always found them to be a little clumsy. You can find a .NET version of creating a spreadsheet here, which should be pretty easy to modify for classic ASP.

As for .NET, I've always liked CarlosAG's Excel XML Writer Library. It has a nice generator so you can setup your Excel file, save it as an XML spreadsheet and it generates the code to do all the formatting and everything. I know it's not classic ASP, but I thought that I would throw it out there.


With what you're trying above, try adding the header:

"Content-Disposition", "attachment; filename=excelTest.xls"

See if that works. Also, I always use this for the content type:

  Response.ContentType = "application/octet-stream"
    Response.ContentType = "application/vnd.ms-excel"

HTTP redirect: 301 (permanent) vs. 302 (temporary)

301 redirects are cached indefinitely (at least by some browsers).

This means, if you set up a 301, visit that page, you not only get redirected, but that redirection gets cached.

When you visit that page again, your Browser* doesn't even bother to request that URL, it just goes to the cached redirection target.

The only way to undo a 301 for a visitor with that redirection in Cache, is re-redirecting back to the original URL**. In that case, the Browser will notice the loop, and finally really request the entered URL.

Obviously, that's not an option if you decided to 301 to facebook or any other resource you're not fully under control.

Unfortunately, many Hosting Providers offer a feature in their Admin Interface simply called "Redirection", which does a 301 redirect. If you're using this to temporarily redirect your domain to facebook as a coming soon page, you're basically screwed.

*at least Chrome and Firefox, according to How long do browsers cache HTTP 301s?. Just tried it with Chrome 45. Edit: Safari 7.0.6 on Mac also caches, a browser restart didn't help (Link says that on Safari 5 on Windows it does help.)

**I tried javascript window.location = '', because it would be the solution which could be applied in most cases - it doesn't work. It results in an undetected infinite Loop. However, php header('Location: new.url') does break the loop

Bottom Line: only use 301s if you're absolutely sure you're never going to use that URL again. Usually never on the root dir (example.com/)

How do I calculate the date in JavaScript three months prior to today?

As I don't seem to see it already suggested....

const d = new Date();
const day = d.getDate();
const goBack = 3;
for (let i = 0; i < goBack; i++) d.setDate(0);
d.setDate(day);

This will give you the date of today's date 3 months ago as .setDate(0) sets the date to the last day of last month irrespective of how many days a month contains. day is used to restore today's date value.

How do I make Git use the editor of my choice for commits?

Just because I came here looking for a one-time solution (in my case, I usually use vim but this one time I wanted to use VS Code) for a single command and others might want to know as well:

GIT_EDITOR='code -w' git rebase -i …

Here's my git/hub version just for context:

git version 2.24.2 (Apple Git-127)
hub version 2.14.1

Func delegate with no return type

Occasionally you will want to write a delegate for event handling, in which case you can take advantage of System.EvenHandler<T> which implicitly accepts an argument of type object in addition to the second parameter that should derive from EventArgs. EventHandlers will return void

I personally found this useful during testing for creating a one-off callback in a function body.

Android ADB stop application command like "force-stop" for non rooted device

If you want to kill the Sticky Service,the following command NOT WORKING:

adb shell am force-stop <PACKAGE>
adb shell kill <PID>

The following command is WORKING:

adb shell pm disable <PACKAGE>

If you want to restart the app,you must run command below first:

adb shell pm enable <PACKAGE>

How to add hyperlink in JLabel?

Use a JEditorPane with a HyperlinkListener.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

How to POST using HTTPclient content type = application/x-www-form-urlencoded

var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);

Or

var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);

C# nullable string error

System.String is a reference type and already "nullable".

Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

The generic collections will perform better than their non-generic counterparts, especially when iterating through many items. This is because boxing and unboxing no longer occurs.

How can I count text lines inside an DOM element? Can I?

getClientRects return the client rects like this and if you want to get the lines, use the follow function like this

function getRowRects(element) {
    var rects = [],
        clientRects = element.getClientRects(),
        len = clientRects.length,
        clientRect, top, rectsLen, rect, i;

    for(i=0; i<len; i++) {
        has = false;
        rectsLen = rects.length;
        clientRect = clientRects[i];
        top = clientRect.top;
        while(rectsLen--) {
            rect = rects[rectsLen];
            if (rect.top == top) {
                has = true;
                break;
            }
        }
        if(has) {
            rect.right = rect.right > clientRect.right ? rect.right : clientRect.right;
            rect.width = rect.right - rect.left;
        }
        else {
            rects.push({
                top: clientRect.top,
                right: clientRect.right,
                bottom: clientRect.bottom,
                left: clientRect.left,
                width: clientRect.width,
                height: clientRect.height
            });
        }
    }
    return rects;
}

Split string into array of character strings

Maybe you can use a for loop that goes through the String content and extract characters by characters using the charAt method.

Combined with an ArrayList<String> for example you can get your array of individual characters.

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

the mysqli_queryexcepts 2 parameters , first variable is mysqli_connectequivalent variable , second one is the query you have provided

$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);

$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");

Get a DataTable Columns DataType

You can get column type of DataTable with DataType attribute of datatable column like below:

var type = dt.Columns[0].DataType

dt : DataTable object.

0 : DataTable column index.

Hope It Helps

Ty :)

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

multipart/form-data

Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.

Please consult the appendix for information about security issues for forms.

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.

A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.

As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.

application/x-www-form-urlencoded

This is the default content type. Forms submitted with this content type must be encoded as follows:

Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by=' and name/value pairs are separated from each other by `&'.

application/x-www-form-urlencoded the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

Verifying a specific parameter with Moq

A simpler way would be to do:

ObjectA.Verify(
    a => a.Execute(
        It.Is<Params>(p => p.Id == 7)
    )
);

How to check if input file is empty in jQuery

  $("#customFile").change(function() { 
    var fileName = $("#customFile").val();  

    if(fileName) { // returns true if the string is not empty   
        $('.picture-selected').addClass('disable-inputs'); 
        $('#btn').removeClass('disabled');   
    } else { // no file was selected 
      $('.picture-selected').removeClass('disable-inputs'); 
      $('#btn').addClass('disabled');
    }  
  });

Remove all child elements of a DOM node in JavaScript

var myNode = document.getElementById("foo");
var fc = myNode.firstChild;

while( fc ) {
    myNode.removeChild( fc );
    fc = myNode.firstChild;
}

If there's any chance that you have jQuery affected descendants, then you must use some method that will clean up jQuery data.

$('#foo').empty();

The jQuery .empty() method will ensure that any data that jQuery associated with elements being removed will be cleaned up.

If you simply use DOM methods of removing the children, that data will remain.

How do I resize an image using PIL and maintain its aspect ratio?

If you are trying to maintain the same aspect ratio, then wouldn't you resize by some percentage of the original size?

For example, half the original size

half = 0.5
out = im.resize( [int(half * s) for s in im.size] )

Read Content from Files which are inside Zip file

Sample code you can use to let Tika take care of container files for you. http://wiki.apache.org/tika/RecursiveMetadata

Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

Can I delete data from the iOS DeviceSupport directory?

More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:

  1. Delete this folder after every few days interval. Most of the time, it occupy huge space!

      ~/Library/Developer/Xcode/DerivedData
    
  2. All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.

      ~/Library/Developer/Xcode/Archives
    
  3. iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.

    ~/Library/Developer/Xcode/iOS DeviceSupport
    
  4. Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.

      ~/Library/Developer/CoreSimulator 
    

(Here's a handy shell command for step 5: xcrun simctl delete unavailable )

  1. Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!

    ~/Library/Caches/com.apple.dt.Xcode
    
  2. Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.

     ~/Library/Application Support/MobileSync/Backup
    

Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac

I got back about 40GB!

How to search for file names in Visual Studio?

The best option now is to install Microsoft Visual Studio add on called Productivity Power Tools (VS 2010 version, VS 2013 version).

With this comes "Solution Navigator" (alternative to Solution Explorer, with a lot of benefits).

search solution navigator

BTW, this feature is built-in into Visual Studio 2012.

Using "Object.create" instead of "new"

You have to make a custom Object.create() function. One that addresses Crockfords concerns and also calls your init function.

This will work:

var userBPrototype = {
    init: function(nameParam) {
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};


function UserB(name) {
    function F() {};
    F.prototype = userBPrototype;
    var f = new F;
    f.init(name);
    return f;
}

var bob = UserB('bob');
bob.sayHello();

Here UserB is like Object.create, but adjusted for our needs.

If you want, you can also call:

var bob = new UserB('bob');

Access index of the parent ng-repeat from child ng-repeat

$parent doesn't work if there are multiple parents. instead of that we can define a parent index variable in init and use it

<div data-ng-init="parentIndex = $index" ng-repeat="f in foos">
  <div>
    <div data-ng-init="childIndex = $index" ng-repeat="b in foos.bars">
      <a ng-click="addSomething(parentIndex)">Add Something</a>
    </div>
  </div>
</div>

How to call external url in jquery?

All of these answers are wrong!

Like I said in my comment, the reason you're getting that error because the URL fails the "Same origin policy", but you can still us the AJAX function to hit another domain, see Nick Cravers answer on this similar question:

You need to trigger JSONP behavior with $.getJSON() by adding &callback=? on the querystring, like this:

$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?",
function(data) {
    doSomethingWith(data); 
}); 

You can test it here.

Without using JSONP you're hitting the same-origin policy which is blocking the XmlHttpRequest from getting any data back.

With this in mind, the follow code should work:

var fbURL="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";

$.ajax({
    url: fbURL+"&callback=?",
    data: "message="+commentdata,
    type: 'POST',
    success: function (resp) {
        alert(resp);
    },
    error: function(e) {
        alert('Error: '+e);
    }  
});

What's the most efficient way to erase duplicates and sort a vector?

If you don't want to modify the vector (erase, sort) then you can use the Newton library, In the algorithm sublibrary there is a function call, copy_single

template <class INPUT_ITERATOR, typename T>
    void copy_single( INPUT_ITERATOR first, INPUT_ITERATOR last, std::vector<T> &v )

so You can:

std::vector<TYPE> copy; // empty vector
newton::copy_single(first, last, copy);

where copy is the vector in where you want to push_back the copy of the unique elements. but remember you push_back the elements, and you don't create a new vector

anyway, this is faster because you don't erase() the elements (which takes a lot of time, except when you pop_back(), because of reassignment)

I make some experiments and it's faster.

Also, you can use:

std::vector<TYPE> copy; // empty vector
newton::copy_single(first, last, copy);
original = copy;

sometimes is still faster.

Run an Ansible task only when the variable contains a specific string

use this

when: "{{ 'value' in variable1}}"

instead of

when: "'value' in {{variable1}}"

Also for string comparison you can use

when: "{{ variable1 == 'value' }}"

Print array to a file

You could try:

$h = fopen('filename.txt', 'r+');
fwrite($h, var_export($your_array, true));

Procedure expects parameter which was not supplied

I had a problem where I would get the error when I supplied 0 to an integer param. And found that:

cmd.Parameters.AddWithValue("@Status", 0);

works, but this does not:

cmd.Parameters.Add(new SqlParameter("@Status", 0));

Cast Object to Generic Type for returning

If you do not want to depend on throwing exception (which you probably should not) you can try this:

public static <T> T cast(Object o, Class<T> clazz) {
    return clazz.isInstance(o) ? clazz.cast(o) : null;
}

Multi-statement Table Valued Function vs Inline Table Valued Function

There is another difference. An inline table-valued function can be inserted into, updated, and deleted from - just like a view. Similar restrictions apply - can't update functions using aggregates, can't update calculated columns, and so on.

A 'for' loop to iterate over an enum in Java

values() method may simply work:

for (Direction  d : Direction.values()) {
   //whatever you want to do with each of these enum values  
}

Insert a line break in mailto body

For the Single line and double line break here are the following codes.

Single break: %0D0A
Double break: %0D0A%0D0A

What is a lambda (function)?

You can think of it as an anonymous function - here's some more info: Wikipedia - Anonymous Function

"CASE" statement within "WHERE" clause in SQL Server 2008

I think that the beginning of your query should look like that:

SELECT
    tl.storenum [Store #], 
    co.ccnum [FuelFirst Card #], 
    co.dtentered [Date Entered],
    CASE st.reasonid 
        WHEN 1 THEN 'Active' 
        WHEN 2 THEN 'Not Active' 
        WHEN 0 THEN st.ccstatustypename 
        ELSE 'Unknown' 
    END [Status],
    CASE st.ccstatustypename 
        WHEN 'Active' THEN ' ' 
        WHEN 'Not Active' THEN ' ' 
        ELSE st.ccstatustypename 
        END [Reason],
    UPPER(REPLACE(REPLACE(co.personentered,'RT\\\\',''),'RACETRAC\\\\','')) [Person Entered],
    co.comments [Comments or Notes]
FROM comments co
    INNER JOIN cards cc ON co.ccnum=cc.ccnum
    INNER JOIN customerinfo ci ON cc.customerinfoid=ci.customerinfoid
    INNER JOIN ccstatustype st ON st.ccstatustypeid=cc.ccstatustypeid
    INNER JOIN customerstatus cs ON cs.customerstatuscd=ci.customerstatuscd
    INNER JOIN transactionlog tl ON tl.transactionlogid=co.transactionlogid
    LEFT JOIN stores s ON s.StoreNum = tl.StoreNum
WHERE 
    CASE 
      WHEN (LEN([TestPerson]) = 0 AND co.personentered  = co.personentered) OR (LEN([TestPerson]) <> 0 AND co.personentered LIKE '%'+TestPerson) THEN 1
      ELSE 0
      END = 1
    AND 

BUT

what is in the tail is completely not understandable

Difficulty with ng-model, ng-repeat, and inputs

This seems to be a binding issue.

The advice is don't bind to primitives.

Your ngRepeat is iterating over strings inside a collection, when it should be iterating over objects. To fix your problem

<body ng-init="models = [{name:'Sam'},{name:'Harry'},{name:'Sally'}]">
    <h1>Fun with Fields and ngModel</h1>
    <p>names: {{models}}</p>
    <h3>Binding to each element directly:</h3>
    <div ng-repeat="model in models">
        Value: {{model.name}}
        <input ng-model="model.name">                         
    </div>

jsfiddle: http://jsfiddle.net/jaimem/rnw3u/5/

why $(window).load() is not working in jQuery?

You're using jQuery version 3.1.0 and the load event is deprecated for use since jQuery version 1.8. The load event is removed from jQuery 3.0. Instead you can use on method and bind the JavaScript load event:

 $(window).on('load', function () {
      alert("Window Loaded");
 });

How to order citations by appearance using BibTeX?

The best I came up with is using the unsrt style, which seems to be a tweaked plain style. i.e.

\bibliographystyle{unsrt}
\bibliography{bibliography}

However what if my style is not the default?

Find kth smallest element in a binary search tree in Optimum way

For a binary search tree, an inorder traversal will return elements ... in order.

Just do an inorder traversal and stop after traversing k elements.

O(1) for constant values of k.

How to create a generic array in Java?

I made this code snippet to reflectively instantiate a class which is passed for a simple automated test utility.

Object attributeValue = null;
try {
    if(clazz.isArray()){
        Class<?> arrayType = clazz.getComponentType();
        attributeValue = Array.newInstance(arrayType, 0);
    }
    else if(!clazz.isInterface()){
        attributeValue = BeanUtils.instantiateClass(clazz);
    }
} catch (Exception e) {
    logger.debug("Cannot instanciate \"{}\"", new Object[]{clazz});
}

Note this segment:

    if(clazz.isArray()){
        Class<?> arrayType = clazz.getComponentType();
        attributeValue = Array.newInstance(arrayType, 0);
    }

for array initiating where Array.newInstance(class of array, size of array). Class can be both primitive (int.class) and object (Integer.class).

BeanUtils is part of Spring.

Determining if a number is prime

Someone above had the following.

bool check_prime(int num) {
for (int i = num - 1; i > 1; i--) {
    if ((num % i) == 0)
        return false;
}
return true;
}

This mostly worked. I just tested it in Visual Studio 2017. It would say that anything less than 2 was also prime (so 1, 0, -1, etc.)

Here is a slight modification to correct this.

bool check_prime(int number)
{
    if (number > 1)
    {
        for (int i = number - 1; i > 1; i--)
        {
            if ((number % i) == 0)
                return false;
        }
        return true;
    }
    return false;
}

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

How do I link to part of a page? (hash?)

You have two options:

You can either put an anchor in your document as follows:

<a name="ref"></a>

Or else you give an id to a any HTML element:

<h1 id="ref">Heading</h1>

Then simply append the hash #ref to the URL of your link to jump to the desired reference. Example:

<a href="document.html#ref">Jump to ref in document.html</a>

CSS Child vs Descendant selectors

Bascailly, "a b" selects all b's inside a, while "a>b" selects b's what are only children to the a, it will not select b what is child of b what is child of a.

This example illustrates the difference:

div span{background:red}
div>span{background:green}

<div><span>abc</span><span>def<span>ghi</span></span></div>

Background color of abc and def will be green, but ghi will have red background color.

IMPORTANT: If you change order of the rules to:

div>span{background:green}
div span{background:red}

All letters will have red background, because descendant selector selects child's too.

.NET DateTime to SqlDateTime Conversion

Is it possible that the date could actually be outside that range? Does it come from user input? If the answer to either of these questions is yes, then you should always check - otherwise you're leaving your application prone to error.

You can format your date for inclusion in an SQL statement rather easily:

var sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");

How to reload/refresh an element(image) in jQuery

This could be one of the two problems you mention yourself.

  1. The server is caching the image
  2. The jQuery does not fire or at least doesn't update the attribute

To be honest, I think it's number two. Would be a lot easier if we could see some more jQuery. But for a start, try remove the attribute first, and then set it again. Just to see if that helps:

$("#myimg").removeAttr("src").attr("src", "/myimg.jpg");

Even if this works, post some code since this is not optimal, imo :-)

How to download a branch with git?

Git clone and cd in the repo name:

$ git clone https://github.com/PabloEzequiel/iOS-AppleWach.git
Cloning into 'iOS-AppleWach'...
$ cd iOS-AppleWach

Switch to the branch (a GitHub page) that I want:

$ git checkout -b gh-pages origin/gh-pages
Branch gh-pages set up to track remote branch gh-pages from origin.
Switched to a new branch 'gh-pages'

And pull the branch:

$ git pull
Already up-to-date.

ls:

$ ls
index.html      params.json     stylesheets

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

For error 7302 in particular, I discovered, in my registry, when looking for OraOLEDB.Oracle that the InprocServer32 location was wrong.

If that's the case, or you can't find that string in the registry, then you'll have to install or re-register the component.

I had to delete the key from the GUID level, and then find the ProgID (OraOLEDB.Oracle) key, and delete that too. (The ProgID links to the CLSID as a pair).

Then I re-registered OraOLEDB.Oracle by calling regsvr32.exe on ORAOLEDB*.dll.

Just re-registering alone didn't solve the problem, I had to delete the registry keys to make it point to the correct location. Alternatively, hack the InprocServer32 location.

Now I have error 7308, about single threaded apartments; rolling on!

Check if a variable is a string in JavaScript

I recommend using the built-in functions from jQuery or lodash/Underscore. They're simpler to use and easier to read.

Either function will handle the case DRAX mentioned... that is, they both check if (A) the variable is a string literal or (B) it's an instance of the String object. In either case, these functions correctly identify the value as being a string.

lodash / Underscore.js

if(_.isString(myVar))
   //it's a string
else
   //it's something else

jQuery

if($.type(myVar) === "string")
   //it's a string
else
   //it's something else

See lodash Documentation for _.isString() for more details.

See jQuery Documentation for $.type() for more details.

Displaying the Indian currency symbol on a website

WebRupee is a web API for the Indian currency symbol. It provides a simple, cross browser method for using the Rrupee symbol on your webpage, blog or anywhere on the web.

Here is a method for printing the Indian currency symbol:

<html>
<head>
    <link rel="stylesheet" type="text/css" href="http://cdn.webrupee.com/font">
    <script src=http://cdn.webrupee.com/js type=”text/javascript”></script>
</head>
<body>
    Rupee Symbol: <span class="WebRupee">Rs.</span> 200

This means if somebody copies text from your site and pastes it somewhere else, he will see Rs and not some other or blank character.

You can now also use the new Rupee unicode symbol — U+20B9 INDIAN RUPEE SIGN. It can be used in this manner:

<span class="WebRupee">&#x20B9;</span> 500

Just include the following script and it will update all the "Rs" / "Rs." for you:

<script src="http://cdn.webrupee.com/js" type="text/javascript"></script>

Stop setInterval call in JavaScript

Use setTimeOut to stop the interval after some time.

var interVal = setInterval(function(){console.log("Running")  }, 1000);
 setTimeout(function (argument) {
    clearInterval(interVal);
 },10000);

Javascript: Fetch DELETE and PUT requests

Just Simple Answer. FETCH DELETE

function deleteData(item, url) {
  return fetch(url + '/' + item, {
    method: 'delete'
  })
  .then(response => response.json());
}

Angular 2 Show and Hide an element

Just add bind(this) in your setTimeout function it will start working

setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);

and in HTML change

<div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>

To

<div *ngIf="edited" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>

Compiling Java 7 code via Maven

right click on ur project in eclipse and open "Run Configurations"..check the jre version there. some times this will not change by default in eclipse,after even changing the version in the buildpath.

javascript filter array multiple conditions

You can do like this

_x000D_
_x000D_
var filter = {_x000D_
  address: 'England',_x000D_
  name: 'Mark'_x000D_
};_x000D_
var users = [{_x000D_
    name: 'John',_x000D_
    email: '[email protected]',_x000D_
    age: 25,_x000D_
    address: 'USA'_x000D_
  },_x000D_
  {_x000D_
    name: 'Tom',_x000D_
    email: '[email protected]',_x000D_
    age: 35,_x000D_
    address: 'England'_x000D_
  },_x000D_
  {_x000D_
    name: 'Mark',_x000D_
    email: '[email protected]',_x000D_
    age: 28,_x000D_
    address: 'England'_x000D_
  }_x000D_
];_x000D_
_x000D_
_x000D_
users= users.filter(function(item) {_x000D_
  for (var key in filter) {_x000D_
    if (item[key] === undefined || item[key] != filter[key])_x000D_
      return false;_x000D_
  }_x000D_
  return true;_x000D_
});_x000D_
_x000D_
console.log(users)
_x000D_
_x000D_
_x000D_

htaccess - How to force the client's browser to clear the cache?

Use the mod rewrite with R=301 - where you use a incremental version number:

To achieve > css/ver/file.css => css/file.css?v=ver

RewriteRule ^css/([0-9]+)/file.css$ css/file.css?v=$1 [R=301,L,QSA]

so example, css/10/file.css => css/file.css?v=10

Same can be applied to js/ files. Increment ver to force update, 301 forces re-cache

I have tested this across Chrome, Firefox, Opera etc

PS: the ?v=ver is just for readability, this does not cause the refresh

Find a line in a file and remove it

public static void deleteLine(String line, String filePath) {

    File file = new File(filePath);

    File file2 = new File(file.getParent() + "\\temp" + file.getName());
    PrintWriter pw = null;
    Scanner read = null;

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel src = null;
    FileChannel dest = null;

    try {


        pw = new PrintWriter(file2);
        read = new Scanner(file);

        while (read.hasNextLine()) {

            String currline = read.nextLine();

            if (line.equalsIgnoreCase(currline)) {
                continue;
            } else {
                pw.println(currline);
            }
        }

        pw.flush();

        fis = new FileInputStream(file2);
        src = fis.getChannel();
        fos = new FileOutputStream(file);
        dest = fos.getChannel();

        dest.transferFrom(src, 0, src.size());


    } catch (IOException e) {
        e.printStackTrace();
    } finally {     
        pw.close();
        read.close();

        try {
            fis.close();
            fos.close();
            src.close();
            dest.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (file2.delete()) {
            System.out.println("File is deleted");
        } else {
            System.out.println("Error occured! File: " + file2.getName() + " is not deleted!");
        }
    }

}

How can I sort an ArrayList of Strings in Java?

Collections.sort(teamsName.subList(1, teamsName.size()));

The code above will reflect the actual sublist of your original list sorted.

Storing and displaying unicode string (??????) using PHP and MySQL

CREATE DATABASE hindi_test
CHARACTER SET utf8
COLLATE utf8_unicode_ci;
USE hindi_test;
CREATE TABLE `hindi` (`data` varchar(200) COLLATE utf8_unicode_ci NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `hindi` (`data`) VALUES('????????');

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

Many JavaScript libraries (especially non-recent ones) do not handle IE9 well because it breaks with IE8 in the handling of a lot of things.

JS code that sniffs for IE will fail quite frequently in IE9, unless such code is rewritten to handle IE9 specifically.

Before the JS code is updated, you should use the "X-UA-Compatible" meta tag to force your web page into IE8 mode.

EDIT: Can't believe that, 3 years later and we're onto IE11, and there are still up-votes for this. :-) Many JS libraries should now at least support IE9 natively and most support IE10, so it is unlikely that you'll need the meta tag these days, unless you don't intend to upgrade your JS library. But beware that IE10 changes things regarding to cross-domain scripting and some CDN-based library code breaks. Check your library version. For example, Dojo 1.9 on the CDN will break on IE10, but 1.9.1 solves it.

EDIT 2: You REALLY need to get your acts together now. We are now in mid-2014!!! I am STILL getting up-votes for this! Revise your sites to get rid of old-IE hard-coded dependencies!

Sigh... If I had known that this would be by far my most popular answer, I'd probably have spent more time polishing it...

EDIT 3: It is now almost 2016. Upvotes still ticking up... I guess there are lots of legacy code out there... One day our programs will out-live us...

Populating VBA dynamic arrays

In addition to Cody's useful comments it is worth noting that at times you won't know how big your array should be. The two options in this situation are

  1. Creating an array big enough to handle anything you think will be thrown at it
  2. Sensible use of Redim Preserve

The code below provides an example of a routine that will dimension myArray in line with the lngSize variable, then add additional elements (equal to the initial array size) by use of a Mod test whenever the upper bound is about to be exceeded

Option Base 1

Sub ArraySample()
    Dim myArray() As String
    Dim lngCnt As Long
    Dim lngSize As Long

    lngSize = 10
    ReDim myArray(1 To lngSize)

    For lngCnt = 1 To lngSize*5
        If lngCnt Mod lngSize = 0 Then ReDim Preserve myArray(1 To UBound(myArray) + lngSize)
        myArray(lngCnt) = "I am record number " & lngCnt
    Next
End Sub

What is the simplest and most robust way to get the user's current location on Android?

From last more than one year, I was using the combination of GPS_PROVIDER and NETWORK_PROVIDER to get the current location and it was working good, but from last few months I'm getting location after a long delay, so I switched to latest API FusedLocationProviderClient and it is working pretty good.

Here is the class which I wrote to get current location by using FusedLocationProviderClient. In below code, I used a timer to wait for while to get the current location, I scheduled timer 15 seconds delay, you can change it according to you.

private static FusedLocationService ourInstance;
private final LocationRequest locationRequest;
private FusedLocationProviderClient mFusedLocationClient;
private Location mLastLocation;
private Context context;
private FindOutLocation findOutLocation;
private boolean callbackTriggered = false;
private Timer timer;

public static FusedLocationService getInstance(Context pContext) {

    if (null == ourInstance) ourInstance = new FusedLocationService(pContext);

    return ourInstance;
}

private FusedLocationService(Context pContext) {
    context = pContext;
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
    locationRequest = getLocationRequest();
    requestLocation(context);
}

public Location getLastKnownLocation() {
    return mLastLocation;
}

private void requestLocation(Context context) {

    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mFusedLocationClient.requestLocationUpdates(locationRequest, mLocationCallback, null);
    mFusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
        if (location != null) {
            mLastLocation = location;
            triggerCallback(mLastLocation);
        }
    });
}

private LocationRequest getLocationRequest() {
    LocationRequest locationRequest = new LocationRequest();
    long INTERVAL = 10 * 1000;
    long FASTEST_INTERVAL = 5 * 1000;
    locationRequest.setInterval(INTERVAL);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    return locationRequest;
}

private LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        for (Location location : locationResult.getLocations()) {
            if (location != null) mLastLocation = location;
        }
        if (null != mLastLocation) triggerCallback(mLastLocation);
    }
};

public static abstract class FindOutLocation {
    public abstract void gotLocation(Location location);
}

@SuppressLint("MissingPermission")
public void findLocation(FindOutLocation findOutLocation) {
    long TIMER_TIME_OUT = 15 * 1000;
    this.findOutLocation = findOutLocation;
    callbackTriggered = false;

    try {
        requestLocation(context);
        timer = new Timer();
        timer.schedule(new GetLastLocation(context), TIMER_TIME_OUT);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private class GetLastLocation extends TimerTask {
    Context context;

    GetLastLocation(Context context) {
        this.context = context;
    }

    @Override
    public void run() {
        triggerCallback(mLastLocation);
    }
}

private void triggerCallback(Location location) {
    if (null != location) mLastLocation = location;
    if (!callbackTriggered && null != findOutLocation) {
        callbackTriggered = true;
        removeLocationUpdates();
        findOutLocation.gotLocation(location);
        findOutLocation = null;
    }
}

private void removeLocationUpdates() {
    if (null != timer) timer.cancel();
    if (null != mFusedLocationClient)
        mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}

And called this from activity, here is the code

    FusedLocationService.FindOutLocation findOutLocation = new FusedLocationService.FindOutLocation() {
        @Override
        public void gotLocation(Location currentLocation) {
            if (currentLocation != null) {
                /*TODO DO SOMETHING WITH CURRENT LOCATION*/
            }
        }
    };
    FusedLocationService.getInstance(this).findLocation(findOutLocation);

Add following entries in the AndroidManifest.xml

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

<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />

Select All Rows Using Entity Framework

You can use:

ptx.[tablename].Select( o => true)

CMD: Export all the screen content to a text file

If you want to append a file instead of constantly making a new one/deleting the old one's content, use double > marks. A single > mark will overwrite all the file's content.

Overwrite file

MyCommand.exe>file.txt

^This will open file.txt if it already exists and overwrite the data, or create a new file and fill it with your output

Append file from its end-point

MyCommand.exe>>file.txt

^This will append file.txt from its current end of file if it already exists, or create a new file and fill it with your output.


Update #1 (advanced):

My batch-fu has improved over time, so here's some minor updates.

If you want to differentiate between error output and normal output for a program that correctly uses Standard streams, STDOUT/STDERR, you can do this with minor changes to the syntax. I'll just use > for overwriting for these examples, but they work perfectly fine with >> for append, in regards to file-piping output re-direction.

The 1 before the >> or > is the flag for STDOUT. If you need to actually output the number one or two before the re-direction symbols, this can lead to strange, unintuitive errors if you don't know about this mechanism. That's especially relevant when outputting a single result number into a file. 2 before the re-direction symbols is for STDERR.

Now that you know that you have more than one stream available, this is a good time to show the benefits of outputting to nul. Now, outputting to nul works the same way conceptually as outputting to a file. You don't see the content in your console. Instead of it going to file or your console output, it goes into the void.

STDERR to file and suppress STDOUT

MyCommand.exe 1>nul 2>errors.txt

STDERR to file to only log errors. Will keep STDOUT in console

MyCommand.exe 2>errors.txt

STDOUT to file and suppress STDERR

MyCommand.exe 1>file.txt 2>nul

STDOUT only to file. Will keep STDERR in console

MyCommand.exe 1>file.txt

STDOUT to one file and STDERR to another file

MyCommand.exe 1>stdout.txt 2>errors.txt

The only caveat I have here is that it can create a 0-byte file for an unused stream if one of the streams never gets used. Basically, if no errors occurred, you might end up with a 0-byte errors.txt file.

Update #2

I started noticing weird behavior when writing console apps that wrote directly to STDERR, and realized that if I wanted my error output to go to the same file when using basic piping, I either had to combine streams 1 and 2 or just use STDOUT. The problem with that problem is I didn't know about the correct way to combine streams, which is this:

%command% > outputfile 2>&1

Therefore, if you want all STDOUT and STDERR piped into the same stream, make sure to use that like so:

MyCommand.exe > file.txt 2>&1

The redirector actually defaults to 1> or 1>>, even if you don't explicitly use 1 in front of it if you don't use a number in front of it, and the 2>&1 combines the streams.

Update #3 (simple)

Null for Everything

If you want to completely suppress STDOUT and STDERR you can do it this way. As a warning not all text pipes use STDOUT and STDERR but it will work for a vast majority of use cases.

STD* to null MyCommand.exe>nul 2>&1

Copying a CMD or Powershell session's command output

If all you want is the command output from a CMD or Powershell session that you just finished up, or any other shell for that matter you can usually just select that console from that session, CTRL + A to select all content, then CTRL + C to copy the content. Then you can do whatever you like with the copied content while it's in your clipboard.

How can I make a TextBox be a "password box" and display stars when using MVVM?

To get or set the Password in a PasswordBox, use the Password property. Such as

string password = PasswordBox.Password;

This doesn't support Databinding as far as I know, so you'd have to set the value in the codebehind, and update it accordingly.

Opacity of background-color, but not the text

I use an alpha-transparent PNG for that:

div.semi-transparent {
  background: url('semi-transparent.png');
}

For IE6, you'd need to use a PNG fix (1, 2), though.

How to change color of Android ListView separator line?

There are two ways to doing the same:

  1. You may set the value of android:divider="#FFCCFF" in layout xml file. With this you also have to specify height of divider like this android:dividerHeight="5px".

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
      <ListView 
      android:id="@+id/lvMyList"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:divider="#FFCCFF"
      android:dividerHeight="5px"/>
    
    </LinearLayout>
    
  2. You may also do this by programmatically...

    ListView listView = getListView();
    ColorDrawable myColor = new ColorDrawable(
        this.getResources().getColor(R.color.myColor)
    );
    listView.setDivider(myColor);
    listView.setDividerHeight();
    

NodeJS accessing file with relative path

You can use the path module to join the path of the directory in which helper1.js lives to the relative path of foobar.json. This will give you the absolute path to foobar.json.

var fs = require('fs');
var path = require('path');

var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');

This should work on Linux, OSX, and Windows assuming a UTF8 encoding.

Create numpy matrix filled with NaNs

Yet another possibility not yet mentioned here is to use NumPy tile:

a = numpy.tile(numpy.nan, (3, 3))

Also gives

array([[ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN]])

I don't know about speed comparison.

MySQL: ALTER TABLE if column not exists

I used this approach (Without using stored procedure):

SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbl_name' AND COLUMN_NAME = 'column_name'

If it didnt return any rows then the column doesn't exists then alter the table:

ALTER TABLE tbl_name ADD COLUMN column_name TINYINT(1) NOT NULL DEFAULT 1

Hope this helps.

How to send string from one activity to another?

You can use intents, which are messages sent between activities. In a intent you can put all sort of data, String, int, etc.

In your case, in activity2, before going to activity1, you will store a String message this way :

Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);

In activity1, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :

Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");

Then you can set the text in the TextView:

TextView txtView = (TextView) findViewById(R.id.your_resource_textview);    
txtView.setText(message);

Hope this helps !

How to avoid HTTP error 429 (Too Many Requests) python

As MRA said, you shouldn't try to dodge a 429 Too Many Requests but instead handle it accordingly. You have several options depending on your use-case:

1) Sleep your process. The server usually includes a Retry-after header in the response with the number of seconds you are supposed to wait before retrying. Keep in mind that sleeping a process might cause problems, e.g. in a task queue, where you should instead retry the task at a later time to free up the worker for other things.

2) Exponential backoff. If the server does not tell you how long to wait, you can retry your request using increasing pauses in between. The popular task queue Celery has this feature built right-in.

3) Token bucket. This technique is useful if you know in advance how many requests you are able to make in a given time. Each time you access the API you first fetch a token from the bucket. The bucket is refilled at a constant rate. If the bucket is empty, you know you'll have to wait before hitting the API again. Token buckets are usually implemented on the other end (the API) but you can also use them as a proxy to avoid ever getting a 429 Too Many Requests. Celery's rate_limit feature uses a token bucket algorithm.

Here is an example of a Python/Celery app using exponential backoff and rate-limiting/token bucket:

class TooManyRequests(Exception):
"""Too many requests"""

@task(
   rate_limit='10/s',
   autoretry_for=(ConnectTimeout, TooManyRequests,),
   retry_backoff=True)
def api(*args, **kwargs):
  r = requests.get('placeholder-external-api')

  if r.status_code == 429:
    raise TooManyRequests()

No Spring WebApplicationInitializer types detected on classpath

Watch out if you are using Maven. Your folder's structure must be right.

When using Maven, the WEB-INF directory must be inside webapp:

src/main/webapp/WEB-INF

Force Intellij IDEA to reread all maven dependencies

Press Ctrl+Shift+A to find actions, and input "reimport", you will find the "Reimport All Maven Projects".

On a Mac, use ?+?+A instead.

What does the colon (:) operator do?

It's used in for loops to iterate over a list of objects.

for (Object o: list)
{
    // o is an element of list here
}

Think of it as a for <item> in <list> in Python.

Jquery $(this) Child Selector

The best way with the HTML you have would probably be to use the next function, like so:

var div = $(this).next('.class2');

Since the click handler is happening to the <a>, you could also traverse up to the parent DIV, then search down for the second DIV. You would do this with a combination of parent and children. This approach would be best if the HTML you put up is not exactly like that and the second DIV could be in another location relative to the link:

var div = $(this).parent().children('.class2');

If you wanted the "search" to not be limited to immediate children, you would use find instead of children in the example above.

Also, it is always best to prepend your class selectors with the tag name if at all possible. ie, if only <div> tags are going to have those classes, make the selector be div.class1, div.class2.

How to handle onchange event on input type=file in jQuery?

Or could be:

$('input[type=file]').change(function () {
    alert("hola");
});

To be specific: $('input[type=file]#fileUpload1').change(...

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

In my.cnf file check below 2 steps.

  • check this value -

    old_passwords=0;

    it should be 0.

  • check this also-

    [mysqld] default_authentication_plugin= mysql_native_password Another value to check is to make sure

    [mysqld] section should be like this.

How can I update npm on Windows?

To update NPM, this worked for me:

  • Navigate in your shell to your node installation directory, eg C:\Program Files (x86)\nodejs
  • run npm install npm (no -g option)

How do I block or restrict special characters from input fields with jquery?

Restrict specials characters on keypress. Here's a test page for key codes: http://www.asquare.net/javascript/tests/KeyCode.html

var specialChars = [62,33,36,64,35,37,94,38,42,40,41];

some_element.bind("keypress", function(event) {
// prevent if in array
   if($.inArray(event.which,specialChars) != -1) {
       event.preventDefault();
   }
});

In Angular, I needed a proper currency format in my textfield. My solution:

var angularApp = angular.module('Application', []);

...

// new angular directive
angularApp.directive('onlyNum', function() {
    return function( scope, element, attrs) {

        var specialChars = [62,33,36,64,35,37,94,38,42,40,41];

        // prevent these special characters
        element.bind("keypress", function(event) {
            if($.inArray(event.which,specialChars) != -1) {
                prevent( scope, event, attrs)
             }
        });

        var allowableKeys = [8,9,37,39,46,48,49,50,51,52,53,54,55,56
            ,57,96,97,98,99,100,101,102,103,104,105,110,190];

        element.bind("keydown", function(event) {
            if($.inArray(event.which,allowableKeys) == -1) {
                prevent( scope, event, attrs)
            }
        });
    };
})

// scope.$apply makes angular aware of your changes
function prevent( scope, event, attrs) {
    scope.$apply(function(){
        scope.$eval(attrs.onlyNum);
        event.preventDefault();
    });
    event.preventDefault();
}

In the html add the directive

<input only-num type="text" maxlength="10" id="amount" placeholder="$XXXX.XX"
   autocomplete="off" ng-model="vm.amount" ng-change="vm.updateRequest()">

and in the corresponding angular controller I only allow there to be only 1 period, convert text to number and add number rounding on 'blur'

...

this.updateRequest = function() {
    amount = $scope.amount;
    if (amount != undefined) {
        document.getElementById('spcf').onkeypress = function (e) {
        // only allow one period in currency
        if (e.keyCode === 46 && this.value.split('.').length === 2) {
            return false;
        }
    }
    // Remove "." When Last Character and round the number on blur
    $("#amount").on("blur", function() {
      if (this.value.charAt(this.value.length-1) == ".") {
          this.value.replace(".","");
          $("#amount").val(this.value);
      }
      var num = parseFloat(this.value);
      // check for 'NaN' if its safe continue
      if (!isNaN(num)) {
        var num = (Math.round(parseFloat(this.value) * 100) / 100).toFixed(2);
        $("#amount").val(num);
      }
    });
    this.data.amountRequested = Math.round(parseFloat(amount) * 100) / 100;
}

...

Creating Roles in Asp.net Identity MVC 5

    public static void createUserRole(string roleName)
    {
        if (!System.Web.Security.Roles.RoleExists(roleName))
        {
            System.Web.Security.Roles.CreateRole(roleName);
        }
    }

How to convert OutputStream to InputStream?

Old post but might help others, Use this way:

OutputStream out = new ByteArrayOutputStream();
...
out.write();
...
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(out.toString().getBytes()));

How to create a sticky left sidebar menu using bootstrap 3?

You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix component is no longer included:

Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.

Select top 1 result using JPA

To use getSingleResult on a TypedQuery you can use

query.setFirstResult(0);
query.setMaxResults(1);
result = query.getSingleResult();

How do I open the "front camera" on the Android platform?

With the release of Android 2.3 (Gingerbread), you can now use the android.hardware.Camera class to get the number of cameras, information about a specific camera, and get a reference to a specific Camera. Check out the new Camera APIs here.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Look at https://stackoverflow.com/a/4726838/2963099

Turn off pre compiled headers:

Project Properties -> C++ -> Precompiled Headers

set Precompiled Header to "Not Using Precompiled Header".

Docker Compose wait for container X before starting Y

Natively that is not possible, yet. See also this feature request.

So far you need to do that in your containers CMD to wait until all required services are there.

In the Dockerfiles CMD you could refer to your own start script that wraps starting up your container service. Before you start it, you wait for a depending one like:

Dockerfile

FROM python:2-onbuild
RUN ["pip", "install", "pika"]
ADD start.sh /start.sh
CMD ["/start.sh"]

start.sh

#!/bin/bash
while ! nc -z rabbitmq 5672; do sleep 3; done
python rabbit.py

Probably you need to install netcat in your Dockerfile as well. I do not know what is pre-installed on the python image.

There are a few tools out there that provide easy to use waiting logic, for simple tcp port checks:

For more complex waits:

Convert char array to a int number in C

So, the idea is to convert character numbers (in single quotes, e.g. '8') to integer expression. For instance char c = '8'; int i = c - '0' //would yield integer 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.

char t[5] = {'-', '9', '0', '8', '\0'}; //Should be terminated properly.

int s = 1;
int i = -1;
int res = 0;

if (c[0] == '-') {
  s = -1;
  i = 0;
}

while (c[++i] != '\0') { //iterate until the array end
  res = res*10 + (c[i] - '0'); //generating the integer according to read parsed numbers.
}

res = res*s; //answer: -908

PHP's array_map including keys

I always like the javascript variant of array map. The most simple version of it would be:

/**
 * @param  array    $array
 * @param  callable $callback
 * @return array
 */
function arrayMap(array $array, callable $callback)
{
    $newArray = [];

    foreach( $array as $key => $value )
    {
        $newArray[] = call_user_func($callback, $value, $key, $array);
    }

    return $newArray;
}

So now you can just pass it a callback function how to construct the values.

$testArray = [
    "first_key" => "first_value", 
    "second_key" => "second_value"
];

var_dump(
    arrayMap($testArray, function($value, $key) {
        return $key . ' loves ' . $value;
    });
);

Is there any way to delete local commits in Mercurial?

If you are familiar with git you'll be happy to use histedit that works like git rebase -i.

Clear image on picturebox

You should try. When you clear your Graphics you must choose color. SystemColors.Control is native color of form

Graphics g = pB.CreateGraphics();
g.Clear(SystemColors.Control);

git replace local version with remote version

I would checkout the remote file from the "master" (the remote/origin repository) like this:

git checkout master <FileWithPath>

Example: git checkout master components/indexTest.html

Simple two column html layout without using tables

All the previous answers only provide a hard-coded location of where the first column ends and the second column starts. I would have expected that this is not required or even not wanted.

Recent CSS versions know about an attribute called columns which makes column based layouts super easy. For older browsers you need to include -moz-columns and -webkit-columns, too.

Here's a very simple example which creates up to three columns if each of them has at least 200 pixes width, otherwise less columns are used:

<html>
  <head>
    <title>CSS based columns</title>
  </head>
  <body>
    <h1>CSS based columns</h1>
    <ul style="columns: 3 200px; -moz-columns: 3 200px; -webkit-columns: 3 200px;">
      <li>Item one</li>
      <li>Item two</li>
      <li>Item three</li>
      <li>Item four</li>
      <li>Item five</li>
      <li>Item six</li>
      <li>Item eight</li>
      <li>Item nine</li>
      <li>Item ten</li>
      <li>Item eleven</li>
      <li>Item twelve</li>
      <li>Item thirteen</li>
    </ul>
  </body>
</html>

Visual Studio Code Search and Replace with Regular Expressions

So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:

Visual studio code's search & replace tab If you mean to disable the code, you just have to put <h1> in search, and replace to ####.

But if you want to use this regex instead, you may enable it in the icon: .* and use the regex: <h1>(.+?)<\/h1> and replace to: #### $1.

And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:

Git pull a certain branch from GitHub

I am not sure I fully understand the problem, but pulling an existing branch is done like this (at least it works for me :)

git pull origin BRANCH

This is assuming that your local branch is created off of the origin/BRANCH.

How to access form methods and controls from a class in C#?

You need access to the object.... you can't simply ask the form class....

eg...

you would of done some thing like

Form1.txtLog.Text = "blah"

instead of

Form1 blah = new Form1();
blah.txtLog.Text = "hello"

You have not accepted the license agreements of the following SDK components

Go to your $ANDROID_HOME/tools/bin and fire the cmd

./sdkmanager --licenses

Accept All licenses listed there.

After this just go to the licenses folder in sdk and check that it's having these five files:

android-sdk-license, android-googletv-license, android-sdk-preview-license, google-gdk-license, mips-android-sysimage-license

Give a retry and build again, still jenkins giving 'licenses not accepted' then you have to give full permission to your 'sdk' directory and all it's parent directories. Here is the command:

sudo chmod -R 777 /opt/

If you having sdk in /opt/ directory.

Difference between View and ViewGroup in Android

View is the SuperClass of All component like TextView, EditText, ListView, etc.. while ViewGroup is Collection of Views(TextView, EditText, ListView, etc..), somewhat like container.

How to use jQuery Plugin with Angular 4?

You are not required to declare any jQuery variable as you installed @types/jquery.

declare var jquery:any;   // not required
declare var $ :any;   // not required

You should have access to jQuery everywhere.

The following should work:

jQuery('.title').slideToggle();

API vs. Webservice

another example: google map api vs google direction api web service, while the former serves (delivers) javascript file to the site (which can then be used as an api to make new functions) , the later is a Rest web service delivering data (in json or xml format), which can be processed (but not used in an api sense).

Calling a Fragment method from a parent Activity

First you create method in your fragment like

public void name()
{


}

in your activity you add this

add onCreate() method

myfragment fragment=new myfragment()

finally call the method where you want to call add this

fragment.method_name();

try this code

How do I correctly setup and teardown for my pytest class with tests?

According to Fixture finalization / executing teardown code, the current best practice for setup and teardown is to use yield instead of return:

import pytest

@pytest.fixture()
def resource():
    print("setup")
    yield "resource"
    print("teardown")

class TestResource:
    def test_that_depends_on_resource(self, resource):
        print("testing {}".format(resource))

Running it results in

$ py.test --capture=no pytest_yield.py
=== test session starts ===
platform darwin -- Python 2.7.10, pytest-3.0.2, py-1.4.31, pluggy-0.3.1
collected 1 items

pytest_yield.py setup
testing resource
.teardown


=== 1 passed in 0.01 seconds ===

Another way to write teardown code is by accepting a request-context object into your fixture function and calling its request.addfinalizer method with a function that performs the teardown one or multiple times:

import pytest

@pytest.fixture()
def resource(request):
    print("setup")

    def teardown():
        print("teardown")
    request.addfinalizer(teardown)
    
    return "resource"

class TestResource:
    def test_that_depends_on_resource(self, resource):
        print("testing {}".format(resource))

How to install both Python 2.x and Python 3.x in Windows

I did this in three steps by following the instructions here: This is all taken directly from here: http://ipython.readthedocs.io/en/stable/install/kernel_install.html. I'm currently running Python 2.x on Windows 8 and have Anaconda 4.2.13 installed.

1) First install the latest version of python:

conda create -n python3 python=3 ipykernel

2) Next activate python3

activate python3

3) Install the kernel:

python -m ipykernel install --user

If you have Python 3 installed and want to install 2, switch the 2 and the 3 above. When you open a new notebook, you can now choose between Python 2 or 3.

Can CSS detect the number of children an element has?

NOTE: This solution will return the children of sets of certain lengths, not the parent element as you have asked. Hopefully, it's still useful.

Andre Luis came up with a method: http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/ Unfortunately, it only works in IE9 and above.

Essentially, you combine :nth-child() with other pseudo classes that deal with the position of an element. This approach allows you to specify elements from sets of elements with specific lengths.

For instance :nth-child(1):nth-last-child(3) matches the first element in a set while also being the 3rd element from the end of the set. This does two things: guarantees that the set only has three elements and that we have the first of the three. To specify the second element of the three element set, we'd use :nth-child(2):nth-last-child(2).


Example 1 - Select all list elements if set has three elements:

li:nth-child(1):nth-last-child(3),
li:nth-child(2):nth-last-child(2),
li:nth-child(3):nth-last-child(1) {
    width: 33.3333%;
}

Example 1 alternative from Lea Verou:

li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}


Example 2 - target last element of set with three list elements:

li:nth-child(3):last-child {
    /* I'm the last of three */
}

Example 2 alternative:

li:nth-child(3):nth-last-child(1) {
    /* I'm the last of three */
}


Example 3 - target second element of set with four list elements:

li:nth-child(2):nth-last-child(3) {
    /* I'm the second of four */
}

How to grep for contents after pattern?

grep 'potato:' file.txt | sed 's/^.*: //'

grep looks for any line that contains the string potato:, then, for each of these lines, sed replaces (s/// - substitute) any character (.*) from the beginning of the line (^) until the last occurrence of the sequence : (colon followed by space) with the empty string (s/...// - substitute the first part with the second part, which is empty).

or

grep 'potato:' file.txt | cut -d\   -f2

For each line that contains potato:, cut will split the line into multiple fields delimited by space (-d\ - d = delimiter, \ = escaped space character, something like -d" " would have also worked) and print the second field of each such line (-f2).

or

grep 'potato:' file.txt | awk '{print $2}'

For each line that contains potato:, awk will print the second field (print $2) which is delimited by default by spaces.

or

grep 'potato:' file.txt | perl -e 'for(<>){s/^.*: //;print}'

All lines that contain potato: are sent to an inline (-e) Perl script that takes all lines from stdin, then, for each of these lines, does the same substitution as in the first example above, then prints it.

or

awk '{if(/potato:/) print $2}' < file.txt

The file is sent via stdin (< file.txt sends the contents of the file via stdin to the command on the left) to an awk script that, for each line that contains potato: (if(/potato:/) returns true if the regular expression /potato:/ matches the current line), prints the second field, as described above.

or

perl -e 'for(<>){/potato:/ && s/^.*: // && print}' < file.txt

The file is sent via stdin (< file.txt, see above) to a Perl script that works similarly to the one above, but this time it also makes sure each line contains the string potato: (/potato:/ is a regular expression that matches if the current line contains potato:, and, if it does (&&), then proceeds to apply the regular expression described above and prints the result).

Ping with timestamp on Windows CLI

Another powershell method (I only wanted failures)

$ping = new-object System.Net.NetworkInformation.Ping
$target="192.168.0.1"
Write-Host "$(Get-Date -format 's') Start ping to $target"
while($true){
    $reply = $ping.send($target)
    if ($reply.status -eq "Success"){
        # ignore success    
        Start-Sleep -Seconds 1
    }
    else{
        Write-Host "$(Get-Date -format 's') Destination unreachable" $target

    }
}

Convert the values in a column into row names in an existing data frame

This should do:

samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]

So in short, no there is no alternative to reassigning.

Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:

R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
   b c
a  1 A
b  2 B
c  3 C
d  4 D
e  5 E
f  6 F
g  7 G
h  8 H
i  9 I
j 10 J
R> 

How can I get the intersection, union, and subset of arrays in Ruby?

I assume X and Y are arrays? If so, there's a very simple way to do this:

x = [1, 1, 2, 4]
y = [1, 2, 2, 2]

# intersection
x & y            # => [1, 2]

# union
x | y            # => [1, 2, 4]

# difference
x - y            # => [4]

Source

Calling Java from Python

Here is my summary of this problem: 5 Ways of Calling Java from Python

http://baojie.org/blog/2014/06/16/call-java-from-python/ (cached)

Short answer: Jpype works pretty well and is proven in many projects (such as python-boilerpipe), but Pyjnius is faster and simpler than JPype

I have tried Pyjnius/Jnius, JCC, javabridge, Jpype and Py4j.

Py4j is a bit hard to use, as you need to start a gateway, adding another layer of fragility.

How do I save a stream to a file in C#?

//If you don't have .Net 4.0  :)

public void SaveStreamToFile(Stream stream, string filename)
{  
   using(Stream destination = File.Create(filename))
      Write(stream, destination);
}

//Typically I implement this Write method as a Stream extension method. 
//The framework handles buffering.

public void Write(Stream from, Stream to)
{
   for(int a = from.ReadByte(); a != -1; a = from.ReadByte())
      to.WriteByte( (byte) a );
}

/*
Note, StreamReader is an IEnumerable<Char> while Stream is an IEnumbable<byte>.
The distinction is significant such as in multiple byte character encodings 
like Unicode used in .Net where Char is one or more bytes (byte[n]). Also, the
resulting translation from IEnumerable<byte> to IEnumerable<Char> can loose bytes
or insert them (for example, "\n" vs. "\r\n") depending on the StreamReader instance
CurrentEncoding.
*/

How do you use bcrypt for hashing passwords in PHP?

For OAuth 2 passwords:

$bcrypt = new \Zend\Crypt\Password\Bcrypt;
$bcrypt->create("youpasswordhere", 10)

What is a "slug" in Django?

It's a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server - in What is a "slug" in Django? the slug is 'in-django-what-is-a-slug', but the slug is not used to determine the page served (on this site at least)

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

Specify the name of columns in the CSV in the load data infile statement.

The code is like this:

LOAD DATA INFILE '/path/filename.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(column_name3, column_name5);

Here you go with adding data to only two columns(you can choose them with the name of the column) to the table.

The only thing you have to take care is that you have a CSV file(filename.csv) with two values per line(row). Otherwise please mention. I have a different solution.

Thank you.

Refresh Page and Keep Scroll Position

If you don't want to use local storage then you could attach the y position of the page to the url and grab it with js on load and set the page offset to the get param you passed in, i.e.:

//code to refresh the page
var page_y = $( document ).scrollTop();
window.location.href = window.location.href + '?page_y=' + page_y;


//code to handle setting page offset on load
$(function() {
    if ( window.location.href.indexOf( 'page_y' ) != -1 ) {
        //gets the number from end of url
        var match = window.location.href.split('?')[1].match( /\d+$/ );
        var page_y = match[0];

        //sets the page offset 
        $( 'html, body' ).scrollTop( page_y );
    }
});

Ruby optional parameters

Time has moved on and since version 2 Ruby supports named parameters:

def ldap_get ( base_dn, filter, scope: "some_scope", attrs: nil )
  p attrs
end

ldap_get("first_arg", "second_arg", attrs: "attr1, attr2") # => "attr1, attr2"

Move / Copy File Operations in Java

Try to use org.apache.commons.io.FileUtils (General file manipulation utilities). Facilities are provided in the following methods:

(1) FileUtils.moveDirectory(File srcDir, File destDir) => Moves a directory.

(2) FileUtils.moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) => Moves a directory to another directory.

(3) FileUtils.moveFile(File srcFile, File destFile) => Moves a file.

(4) FileUtils.moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) => Moves a file to a directory.

(5) FileUtils.moveToDirectory(File src, File destDir, boolean createDestDir) => Moves a file or directory to the destination directory.

It's simple, easy and fast.

Best way to remove duplicate entries from a data table

Do dtEmp on your current working DataTable:

DataTable distinctTable = dtEmp.DefaultView.ToTable( /*distinct*/ true);

It's nice.

How to obtain values of request variables using Python and Flask

If you want to retrieve POST data:

first_name = request.form.get("firstname")

If you want to retrieve GET (query string) data:

first_name = request.args.get("firstname")

Or if you don't care/know whether the value is in the query string or in the post data:

first_name = request.values.get("firstname") 

request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.

Sort array by firstname (alphabetically) in Javascript

in simply words you can use this method

users.sort(function(a,b){return a.firstname < b.firstname ? -1 : 1});

Sending email in .NET through Gmail

I hope this code will work fine. You can have a try.

// Include this.                
using System.Net.Mail;

string fromAddress = "[email protected]";
string mailPassword = "*****";       // Mail id password from where mail will be sent.
string messageBody = "Write the body of the message here.";


// Create smtp connection.
SmtpClient client = new SmtpClient();
client.Port = 587;//outgoing port for the mail.
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(fromAddress, mailPassword);


// Fill the mail form.
var send_mail = new MailMessage();

send_mail.IsBodyHtml = true;
//address from where mail will be sent.
send_mail.From = new MailAddress("[email protected]");
//address to which mail will be sent.           
send_mail.To.Add(new MailAddress("[email protected]");
//subject of the mail.
send_mail.Subject = "put any subject here";

send_mail.Body = messageBody;
client.Send(send_mail);

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

The page is not found cause the associated controller doesn't exit. Just create the specific Controller. If you try to show the home page, and use Visual Studio 2015, follow this steps:

  1. Right click on Controller folder, and then select Add > Controller;
  2. Select MVC 5 Controller - Empty;
  3. Click in Add;
  4. Put HomeController for the controller name;
  5. Build the project and after Run your project again

I hope this help

Twitter Bootstrap 3: How to center a block

You can use class .center-block in combination with style="width:400px;max-width:100%;" to preserve responsiveness.

Using .col-md-* class with .center-block will not work because of the float on .col-md-*.

Is there a function to split a string in PL/SQL?

There is a simple way folks. Use REPLACE function. Here is an example of comma separated string ready to be passed to IN clause.

In PL/SQL:

StatusString :=   REPLACE('Active,Completed', ',', ''',''');

In SQL Plus:

Select  REPLACE('Active,Completed', ',', ''',''') from dual;

How do I get the HTTP status code with jQuery?

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

iText - add content to existing PDF file

iText has more than one way of doing this. The PdfStamper class is one option. But I find the easiest method is to create a new PDF document then import individual pages from the existing document into the new PDF.

// Create output PDF
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();

// Load existing PDF
PdfReader reader = new PdfReader(templateInputStream);
PdfImportedPage page = writer.getImportedPage(reader, 1); 

// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);

// Add your new data / text here
// for example...
document.add(new Paragraph("my timestamp")); 

document.close();

This will read in a PDF from templateInputStream and write it out to outputStream. These might be file streams or memory streams or whatever suits your application.

Installing a plain plugin jar in Eclipse 3.5

This is how you can go about it:

  1. Close Eclipse
  2. Download a jar plugin (let's assume its testNG.jar)
  3. Copy testNG.jar to a certain folder (say C:\Project\resources\plugins)
  4. In your Eclipse installation folder, there is a folder named dropins (could be C:\eclipse\dropins), create a .link file in that folder, (like plugins.link)
  5. Open this file with any text editor and enter this one line:
    path=C:/Project/resources/plugins
  6. Save the file and start Eclipse.

And you are good to go!

Please do not forget to change your backward slashes in your plugins folder path to forward slashes on step 5. I used to forget and it would take my time unnecessarily.

How do I use 3DES encryption/decryption in Java?

Here's a very simply static encrypt/decrypt class biased on the Bouncy Castle no padding example by Jose Luis Montes de Oca. This one is using "DESede/ECB/PKCS7Padding" so I don't have to bother manually padding.


    package com.zenimax.encryption;

    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.NoSuchProviderException;
    import java.security.Security;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;

    /**
     * 
     * @author Matthew H. Wagner
     */
    public class TripleDesBouncyCastle {
        private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/PKCS7Padding";
        private static String ALGORITHM = "DESede";
        private static String BOUNCY_CASTLE_PROVIDER = "BC";

        private static void init()
        {
            Security.addProvider(new BouncyCastleProvider());
        }

        public static byte[] encode(byte[] input, byte[] key)
                throws IllegalBlockSizeException, BadPaddingException,
                NoSuchAlgorithmException, NoSuchProviderException,
                NoSuchPaddingException, InvalidKeyException {
            init();
            SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
            Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
                    BOUNCY_CASTLE_PROVIDER);
            encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
            return encrypter.doFinal(input);
        }

        public static byte[] decode(byte[] input, byte[] key)
                throws IllegalBlockSizeException, BadPaddingException,
                NoSuchAlgorithmException, NoSuchProviderException,
                NoSuchPaddingException, InvalidKeyException {
            init();
            SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
            Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
                    BOUNCY_CASTLE_PROVIDER);
            decrypter.init(Cipher.DECRYPT_MODE, keySpec);
            return decrypter.doFinal(input);
        }
    }

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

How to force HTTPS using a web.config file

For those using ASP.NET MVC. You can use the RequireHttpsAttribute to force all responses to be HTTPS:

GlobalFilters.Filters.Add(new RequireHttpsAttribute());

Other things you may also want to do to help secure your site:

  1. Force Anti-Forgery tokens to use SSL/TLS:

    AntiForgeryConfig.RequireSsl = true;
    
  2. Require Cookies to require HTTPS by default by changing the Web.config file:

    <system.web>
        <httpCookies httpOnlyCookies="true" requireSSL="true" />
    </system.web>
    
  3. Use the NWebSec.Owin NuGet package and add the following line of code to enable Strict Transport Security (HSTS) across the site. Don't forget to add the Preload directive below and submit your site to the HSTS Preload site. More information here and here. Note that if you are not using OWIN, there is a Web.config method you can read up on on the NWebSec site.

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHsts(options => options.MaxAge(days: 720).Preload());
    
  4. Use the NWebSec.Owin NuGet package and add the following line of code to enable Public Key Pinning (HPKP) across the site. More information here and here.

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHpkp(options => options
        .Sha256Pins(
            "Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
            "Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=")
        .MaxAge(days: 30));
    
  5. Include the https scheme in any URL's used. Content Security Policy (CSP) HTTP header and Subresource Integrity (SRI) do not play nice when you imit the scheme in some browsers. It is better to be explicit about HTTPS. e.g.

    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js">
    </script>
    
  6. Use the ASP.NET MVC Boilerplate Visual Studio project template to generate a project with all of this and much more built in. You can also view the code on GitHub.

How can I wait for 10 second without locking application UI in android

1with handler:

handler.sendEmptyMessageDelayed(1, 10000);
}

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (msg.what == 1) {
           //your code
        }
    }
};

Pair/tuple data type in Go

You can do this. It looks more wordy than a tuple, but it's a big improvement because you get type checking.

Edit: Replaced snippet with complete working example, following Nick's suggestion. Playground link: http://play.golang.org/p/RNx_otTFpk

package main

import "fmt"

func main() {
    queue := make(chan struct {string; int})
    go sendPair(queue)
    pair := <-queue
    fmt.Println(pair.string, pair.int)
}

func sendPair(queue chan struct {string; int}) {
    queue <- struct {string; int}{"http:...", 3}
}

Anonymous structs and fields are fine for quick and dirty solutions like this. For all but the simplest cases though, you'd do better to define a named struct just like you did.

Local and global temporary tables in SQL Server

I didn't see any answers that show users where we can find a Global Temp table. You can view Local and Global temp tables in the same location when navigating within SSMS. Screenshot below taken from this link.

Databases --> System Databases --> tempdb --> Temporary Tables

enter image description here

Undoing accidental git stash pop

From git stash --help

Recovering stashes that were cleared/dropped erroneously
   If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the
   following incantation to get a list of stashes that are still in your repository, but not reachable any more:

       git fsck --unreachable |
       grep commit | cut -d\  -f3 |
       xargs git log --merges --no-walk --grep=WIP

This helped me better than the accepted answer with the same scenario.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

In my case,I use the below solution

Front-end or Angular

post(
    this.serverUrl, dataObjToPost,
    {
      headers: new HttpHeaders({
           'Content-Type':  'application/json',
         })
    }
)

back-end (I use php)

header("Access-Control-Allow-Origin: http://localhost:4200");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
print_r($request);

What is a CSRF token? What is its importance and how does it work?

Cross-Site Request Forgery (CSRF) in simple words

  • Assume you are currently logged into your online banking at www.mybank.com
  • Assume a money transfer from mybank.com will result in a request of (conceptually) the form http://www.mybank.com/transfer?to=<SomeAccountnumber>;amount=<SomeAmount>. (Your account number is not needed, because it is implied by your login.)
  • You visit www.cute-cat-pictures.org, not knowing that it is a malicious site.
  • If the owner of that site knows the form of the above request (easy!) and correctly guesses you are logged into mybank.com (requires some luck!), they could include on their page a request like http://www.mybank.com/transfer?to=123456;amount=10000 (where 123456 is the number of their Cayman Islands account and 10000 is an amount that you previously thought you were glad to possess).
  • You retrieved that www.cute-cat-pictures.org page, so your browser will make that request.
  • Your bank cannot recognize this origin of the request: Your web browser will send the request along with your www.mybank.com cookie and it will look perfectly legitimate. There goes your money!

This is the world without CSRF tokens.

Now for the better one with CSRF tokens:

  • The transfer request is extended with a third argument: http://www.mybank.com/transfer?to=123456;amount=10000;token=31415926535897932384626433832795028841971.
  • That token is a huge, impossible-to-guess random number that mybank.com will include on their own web page when they serve it to you. It is different each time they serve any page to anybody.
  • The attacker is not able to guess the token, is not able to convince your web browser to surrender it (if the browser works correctly...), and so the attacker will not be able to create a valid request, because requests with the wrong token (or no token) will be refused by www.mybank.com.

Result: You keep your 10000 monetary units. I suggest you donate some of that to Wikipedia.

(Your mileage may vary.)

EDIT from comment worth reading:

It would be worthy to note that script from www.cute-cat-pictures.org normally does not have access to your anti-CSRF token from www.mybank.com because of HTTP access control. This note is important for some people who unreasonably send a header Access-Control-Allow-Origin: * for every website response without knowing what it is for, just because they can't use the API from another website.

How to center an image horizontally and align it to the bottom of the container?

have you tried:

.image_block{
text-align: center;
vertical-align: bottom;
}

How to upgrade scikit-learn package in anaconda

If you are using Jupyter in anaconda, after conda update scikit-learn in terminal, close anaconda and restart, otherwise the error will occur again.

How does String.Index work in Swift

enter image description here

All of the following examples use

var str = "Hello, playground"

startIndex and endIndex

  • startIndex is the index of the first character
  • endIndex is the index after the last character.

Example

// character
str[str.startIndex] // H
str[str.endIndex]   // error: after last character

// range
let range = str.startIndex..<str.endIndex
str[range]  // "Hello, playground"

With Swift 4's one-sided ranges, the range can be simplified to one of the following forms.

let range = str.startIndex...
let range = ..<str.endIndex

I will use the full form in the follow examples for the sake of clarity, but for the sake of readability, you will probably want to use the one-sided ranges in your code.

after

As in: index(after: String.Index)

  • after refers to the index of the character directly after the given index.

Examples

// character
let index = str.index(after: str.startIndex)
str[index]  // "e"

// range
let range = str.index(after: str.startIndex)..<str.endIndex
str[range]  // "ello, playground"

before

As in: index(before: String.Index)

  • before refers to the index of the character directly before the given index.

Examples

// character
let index = str.index(before: str.endIndex)
str[index]  // d

// range
let range = str.startIndex..<str.index(before: str.endIndex)
str[range]  // Hello, playgroun

offsetBy

As in: index(String.Index, offsetBy: String.IndexDistance)

  • The offsetBy value can be positive or negative and starts from the given index. Although it is of the type String.IndexDistance, you can give it an Int.

Examples

// character
let index = str.index(str.startIndex, offsetBy: 7)
str[index]  // p

// range
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
str[range]  // play

limitedBy

As in: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

  • The limitedBy is useful for making sure that the offset does not cause the index to go out of bounds. It is a bounding index. Since it is possible for the offset to exceed the limit, this method returns an Optional. It returns nil if the index is out of bounds.

Example

// character
if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
    str[index]  // p
}

If the offset had been 77 instead of 7, then the if statement would have been skipped.

Why is String.Index needed?

It would be much easier to use an Int index for Strings. The reason that you have to create a new String.Index for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters.

It is possibly to hide this complexity behind an Int index extension, but I am reluctant to do so. It is good to be reminded of what is actually happening.

Simple and fast method to compare images for similarity

I face the same issues recently, to solve this problem(simple and fast algorithm to compare two images) once and for all, I contribute an img_hash module to opencv_contrib, you can find the details from this link.

img_hash module provide six image hash algorithms, quite easy to use.

Codes example

origin lenaorigin lena

blur lenablur lena

resize lenaresize lena

shift lenashift lena

#include <opencv2/core.hpp>
#include <opencv2/core/ocl.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/img_hash.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>

void compute(cv::Ptr<cv::img_hash::ImgHashBase> algo)
{
    auto input = cv::imread("lena.png");
    cv::Mat similar_img;

    //detect similiar image after blur attack
    cv::GaussianBlur(input, similar_img, {7,7}, 2, 2);
    cv::imwrite("lena_blur.png", similar_img);
    cv::Mat hash_input, hash_similar;
    algo->compute(input, hash_input);
    algo->compute(similar_img, hash_similar);
    std::cout<<"gaussian blur attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;

    //detect similar image after shift attack
    similar_img.setTo(0);
    input(cv::Rect(0,10, input.cols,input.rows-10)).
            copyTo(similar_img(cv::Rect(0,0,input.cols,input.rows-10)));
    cv::imwrite("lena_shift.png", similar_img);
    algo->compute(similar_img, hash_similar);
    std::cout<<"shift attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;

    //detect similar image after resize
    cv::resize(input, similar_img, {120, 40});
    cv::imwrite("lena_resize.png", similar_img);
    algo->compute(similar_img, hash_similar);
    std::cout<<"resize attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;
}

int main()
{
    using namespace cv::img_hash;

    //disable opencl acceleration may(or may not) boost up speed of img_hash
    cv::ocl::setUseOpenCL(false);

    //if the value after compare <= 8, that means the images
    //very similar to each other
    compute(ColorMomentHash::create());

    //there are other algorithms you can try out
    //every algorithms have their pros and cons
    compute(AverageHash::create());
    compute(PHash::create());
    compute(MarrHildrethHash::create());
    compute(RadialVarianceHash::create());
    //BlockMeanHash support mode 0 and mode 1, they associate to
    //mode 1 and mode 2 of PHash library
    compute(BlockMeanHash::create(0));
    compute(BlockMeanHash::create(1));
}

In this case, ColorMomentHash give us best result

  • gaussian blur attack : 0.567521
  • shift attack : 0.229728
  • resize attack : 0.229358

Pros and cons of each algorithm

Performance under different attacks

The performance of img_hash is good too

Speed comparison with PHash library(100 images from ukbench) compute performance comparison performance

If you want to know the recommend thresholds for these algorithms, please check this post(http://qtandopencv.blogspot.my/2016/06/introduction-to-image-hash-module-of.html). If you are interesting about how do I measure the performance of img_hash modules(include speed and different attacks), please check this link(http://qtandopencv.blogspot.my/2016/06/speed-up-image-hashing-of-opencvimghash.html).

What is the meaning of the prefix N in T-SQL statements and when should I use it?

It's declaring the string as nvarchar data type, rather than varchar

You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.

To quote from Microsoft:

Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.


If you want to know the difference between these two data types, see this SO post:

What is the difference between varchar and nvarchar?

How can I read the client's machine/computer name from the browser?

Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.

EDIT: Not possible across all browser at least.

How to sparsely checkout only one single file from a git repository?

Originally, I mentioned in 2012 git archive (see Jared Forsyth's answer and Robert Knight's answer), since git1.7.9.5 (March 2012), Paul Brannan's answer:

git archive --format=tar --remote=origin HEAD:path/to/directory -- filename | tar -O -xf -

But: in 2013, that was no longer possible for remote https://github.com URLs.
See the old page "Can I archive a repository?"

The current (2018) page "About archiving content and data on GitHub" recommends using third-party services like GHTorrent or GH Archive.


So you can also deal with local copies/clone:

You could alternatively do the following if you have a local copy of the bare repository as mentioned in this answer,

git --no-pager --git-dir /path/to/bar/repo.git show branch:path/to/file >file

Or you must clone first the repo, meaning you get the full history: - in the .git repo - in the working tree.

  • But then you can do a sparse checkout (if you are using Git1.7+),:
    • enable the sparse checkout option (git config core.sparsecheckout true)
    • adding what you want to see in the .git/info/sparse-checkout file
    • re-reading the working tree to only display what you need

To re-read the working tree:

$ git read-tree -m -u HEAD

That way, you end up with a working tree including precisely what you want (even if it is only one file)


Richard Gomes points (in the comments) to "How do I clone, fetch or sparse checkout a single directory or a list of directories from git repository?"

A bash function which avoids downloading the history, which retrieves a single branch and which retrieves a list of files or directories you need.

How to give the background-image path in CSS?

you can also add inline css for adding image as a background as per below example

<div class="item active" style="background-image: url(../../foo.png);">

SVN undo delete before commit

The simplest solution I could find was to delete the parent directory from the working copy (with rm -rf, not svn delete), and then run svn update in the grandparent. Eg, if you deleted a/b/c, rm -rf a/b, cd a, svn up. That brings everything back. Of course, this is only a good solution if you have no other uncommitted changes in the parent directory that you want to keep.

Hopefully this page will be at the top of the results next time I google this question. It would be even better if someone suggested a cleaner method, of course.

How to get the excel file name / path in VBA

   strScriptFullname = WScript.ScriptFullName 
   strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\")) 

How to access /storage/emulated/0/

https://productforums.google.com/forum/#!msg/nexus/WIcHUNQfRLU/ALpViG86AwAJ

Mr Expensive Toys said: Am amazed that this problem is still showing up as it started happening as far back as Honeycomb.

So, the /storage/emulated/0/DCIM/Camera is the same folder as your normal DCIM/Camera folder. Its just a symlink. So the files are actually in the right location you just have an app that put bad data into the MediaStore Database.

When accessing files from your PC your are actually enumerating the MediaStorage database for files. Its not pulling a traditional directory lists. So what you see is based on what is in that database and the path entries in the database. Files in the database pointing to emulated directories aren't shown as they are assumed to be duplicates as its the same physical directory as your normal DCIM/Camera. What is going on is that some poorly written third party apps are inserting entries into the database with the /storage/emulated/0/DCIM/Camera path instead of the proper root path to DCIM/Camera. Which means that the MTP service can't see them when you are hooked up to your PC.

Usually the easiest way to fix the problem is to just clear the MediaStore databases to get the bad entries out of the MediaStore Database and let the system reindex the files and put into the database with the proper paths.

Settings->apps Hit 3 dot menu in top right and select Show System Find Media Storage, Select it, Select Storage, then Clear Data Find External Storage, Select it , Select Storage, then Clear Data Turn phone off, turn phone back on, wait for indexer service to rebuild the data.

When you are done the files should show up with proper directory tree and be visible from the PC. Depending on amount of files on the phone it can take as 10-20 minutes to rebuild the media database as the service walks the phone directories, getting meta data, creating thumbnails, etc.

How do I shrink my SQL Server Database?

This may seem bizarre, but it's worked for me and I have written a C# program to automate this.

Step 1: Truncate the transaction log (Back up only the transaction log, turning on the option to remove inactive transactions)

Step 2: Run a database shrink, moving all the pages to the start of the files

Step 3: Truncate the transaction log again, as step 2 adds log entries

Step 4: Run a database shrink again.

My stripped down code, which uses the SQL DMO library, is as follows:

SQLDatabase.TransactionLog.Truncate();
SQLDatabase.Shrink(5, SQLDMO.SQLDMO_SHRINK_TYPE.SQLDMOShrink_NoTruncate);
SQLDatabase.TransactionLog.Truncate();
SQLDatabase.Shrink(5, SQLDMO.SQLDMO_SHRINK_TYPE.SQLDMOShrink_Default);