Programs & Examples On #Ikimagebrowserview

IKImageBrowserView is a Image Kit View for the Cocoa Framework on Mac OS X 10.5 and above.

<button> background image

You absolutely need a button tag element? because you can use instead an input type="button" element.

Then just link this CSS:

_x000D_
_x000D_
  input[type="button"]{
  width:150px;
  height:150px;
  /*just this*/ background-image: url(https://images.freeimages.com/images/large-previews/48d/marguerite-1372118.jpg);
  background-position: center;
  background-repeat: no-repeat;
  background-size: 150px 150px;
}
_x000D_
<input type="button"/>
_x000D_
_x000D_
_x000D_

How do I hide a menu item in the actionbar?

Create you menu options the normal way see code below and add a global reference within the class to the menu

Menu mMenu;  // global reference within the class
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_tcktdetails, menu);
    mMenu=menu;  // assign the menu to the new menu item you just created 
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_cancelticket) {
        cancelTicket();

        return true;
    }

    return super.onOptionsItemSelected(item);
}

Now you can toggle your menu by running this code with a button or within a function

if(mMenu != null) {
                mMenu.findItem(R.id.action_cancelticket).setVisible(false);
            }

append new row to old csv file python

with open('document.csv','a') as fd:
    fd.write(myCsvRow)

Opening a file with the 'a' parameter allows you to append to the end of the file instead of simply overwriting the existing content. Try that.

Getting Image from URL (Java)

You can try the this class to displays an image read from a URL within a JFrame.

public class ShowImageFromURL {

    public static void show(String urlLocation) {
        Image image = null;
        try {
            URL url = new URL(urlLocation);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");

            conn.connect();
            InputStream urlStream = conn.getInputStream();
            image = ImageIO.read(urlStream);

            JFrame frame = new JFrame();
            JLabel lblimage = new JLabel(new ImageIcon(image));
            frame.getContentPane().add(lblimage, BorderLayout.CENTER);
            frame.setSize(image.getWidth(null) + 50, image.getHeight(null) + 50);
            frame.setVisible(true);

        } catch (IOException e) {
            System.out.println("Something went wrong, sorry:" + e.toString());
            e.printStackTrace();
        }
    }
}

Ref : https://gist.github.com/aslamanver/92af3ac67406cfd116b7e4e177156926

Chmod recursively

Give 0777 to all files and directories starting from the current path :

chmod -R 0777 ./

How to get and set the current web page scroll position?

You're looking for the document.documentElement.scrollTop property.

Database corruption with MariaDB : Table doesn't exist in engine

Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.

UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

How to add a single item to a Pandas Series

TLDR: do not append items to a series one by one, better extend with an ordered collection

I think the question in its current form is a bit tricky. And the accepted answer does answer the question. But the more I use pandas, the more I understand that it's a bad idea to append items to a Series one by one. I'll try to explain why for pandas beginners.

You might think that appending data to a given Series might allow you to reuse some resources, but in reality a Series is just a container that stores a relation between an index and a values array. Each is a numpy.array under the hood, and the index is immutable. When you add to Series an item with a label that is missing in the index, a new index with size n+1 is created, and a new values values array of the same size. That means that when you append items one by one, you create two more arrays of the n+1 size on each step.

By the way, you can not append a new item by position (you will get an IndexError) and the label in an index does not have to be unique, that is when you assign a value with a label, you assign the value to all existing items with the the label, and a new row is not appended in this case. This might lead to subtle bugs.

The moral of the story is that you should not append data one by one, you should better extend with an ordered collection. The problem is that you can not extend a Series inplace. That is why it is better to organize your code so that you don't need to update a specific instance of a Series by reference.

If you create labels yourself and they are increasing, the easiest way is to add new items to a dictionary, then create a new Series from the dictionary (it sorts the keys) and append the Series to an old one. If the keys are not increasing, then you will need to create two separate lists for the new labels and the new values.

Below are some code samples:

In [1]: import pandas as pd
In [2]: import numpy as np

In [3]: s = pd.Series(np.arange(4)**2, index=np.arange(4))

In [4]: s
Out[4]:
0    0
1    1
2    4
3    9
dtype: int64

In [6]: id(s.index), id(s.values)
Out[6]: (4470549648, 4470593296)

When we update an existing item, the index and the values array stay the same (if you do not change the type of the value)

In [7]: s[2] = 14  

In [8]: id(s.index), id(s.values)
Out[8]: (4470549648, 4470593296)

But when you add a new item, a new index and a new values array is generated:

In [9]: s[4] = 16

In [10]: s
Out[10]:
0     0
1     1
2    14
3     9
4    16
dtype: int64

In [11]: id(s.index), id(s.values)
Out[11]: (4470548560, 4470595056)

That is if you are going to append several items, collect them in a dictionary, create a Series, append it to the old one and save the result:

In [13]: new_items = {item: item**2 for item in range(5, 7)}

In [14]: s2 = pd.Series(new_items)

In [15]: s2  # keys are guaranteed to be sorted!
Out[15]:
5    25
6    36
dtype: int64

In [16]: s = s.append(s2); s
Out[16]:
0     0
1     1
2    14
3     9
4    16
5    25
6    36
dtype: int64

How to use a FolderBrowserDialog from a WPF application

And here's my final version.

public static class MyWpfExtensions
{
    public static System.Windows.Forms.IWin32Window GetIWin32Window(this System.Windows.Media.Visual visual)
    {
        var source = System.Windows.PresentationSource.FromVisual(visual) as System.Windows.Interop.HwndSource;
        System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
        return win;
    }

    private class OldWindow : System.Windows.Forms.IWin32Window
    {
        private readonly System.IntPtr _handle;
        public OldWindow(System.IntPtr handle)
        {
            _handle = handle;
        }

        #region IWin32Window Members
        System.IntPtr System.Windows.Forms.IWin32Window.Handle
        {
            get { return _handle; }
        }
        #endregion
    }
}

And to actually use it:

var dlg = new FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dlg.ShowDialog(this.GetIWin32Window());

Non-recursive depth first search algorithm

Using Stack, here are the steps to follow: Push the first vertex on the stack then,

  1. If possible, visit an adjacent unvisited vertex, mark it, and push it on the stack.
  2. If you can’t follow step 1, then, if possible, pop a vertex off the stack.
  3. If you can’t follow step 1 or step 2, you’re done.

Here's the Java program following the above steps:

public void searchDepthFirst() {
    // begin at vertex 0
    vertexList[0].wasVisited = true;
    displayVertex(0);
    stack.push(0);
    while (!stack.isEmpty()) {
        int adjacentVertex = getAdjacentUnvisitedVertex(stack.peek());
        // if no such vertex
        if (adjacentVertex == -1) {
            stack.pop();
        } else {
            vertexList[adjacentVertex].wasVisited = true;
            // Do something
            stack.push(adjacentVertex);
        }
    }
    // stack is empty, so we're done, reset flags
    for (int j = 0; j < nVerts; j++)
            vertexList[j].wasVisited = false;
}

Can you get a Windows (AD) username in PHP?

You can say getenv('USERNAME')

Pushing from local repository to GitHub hosted remote

open the command prompt Go to project directory

type git remote add origin your git hub repository location with.git

converting CSV/XLS to JSON?

If you can't find an existing solution it's pretty easy to build a basic one in Java. I just wrote one for a client and it took only a couple hours including researching tools.

Apache POI will read the Excel binary. http://poi.apache.org/

JSONObject will build the JSON

After that it's just a matter of iterating through the rows in the Excel data and building a JSON structure. Here's some pseudo code for the basic usage.

FileInputStream inp = new FileInputStream( file );
Workbook workbook = WorkbookFactory.create( inp );

// Get the first Sheet.
Sheet sheet = workbook.getSheetAt( 0 );

    // Start constructing JSON.
    JSONObject json = new JSONObject();

    // Iterate through the rows.
    JSONArray rows = new JSONArray();
    for ( Iterator<Row> rowsIT = sheet.rowIterator(); rowsIT.hasNext(); )
    {
        Row row = rowsIT.next();
        JSONObject jRow = new JSONObject();

        // Iterate through the cells.
        JSONArray cells = new JSONArray();
        for ( Iterator<Cell> cellsIT = row.cellIterator(); cellsIT.hasNext(); )
        {
            Cell cell = cellsIT.next();
            cells.put( cell.getStringCellValue() );
        }
        jRow.put( "cell", cells );
        rows.put( jRow );
    }

    // Create the JSON.
    json.put( "rows", rows );

// Get the JSON text.
return json.toString();

MVC 4 client side validation not working

My problem was in web.config: UnobtrusiveJavaScriptEnabled was turned off

<appSettings>

<add key="ClientValidationEnabled" value="true" />

<add key="UnobtrusiveJavaScriptEnabled" value="false" />

</appSettings>

I changed to and now works:

`<add key="UnobtrusiveJavaScriptEnabled" value="true" />`

How to insert TIMESTAMP into my MySQL table?

$insertation = "INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIMESTAMP(), '$comments')";

You can use this Query. CURRENT_TIMESTAMP

Remember to use the parenthesis CURRENT_TIMESTAMP()

JavaScript null check

Q: The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.

A: Yes, data will be set to undefined. See section 10.5 Declaration Binding Instantiation of the spec. But accessing an undefined value does not raise an error. You're probably confusing this with accessing an undeclared variable in strict mode which does raise an error.

Q: The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.

Q: The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.

A: Correct. Note that the following tests are equivalent:

data != null
data != undefined
data !== null && data !== undefined

See section 11.9.3 The Abstract Equality Comparison Algorithm and section 11.9.6 The Strict Equality Comparison Algorithm of the spec.

Where does the .gitignore file belong?

You may also find a global .gitignore directly at the ~ path if you haven't created it in your folder project. This file is taken into account by all your .git projects.

Cannot refer to a non-final variable inside an inner class defined in a different method

You can only access final variables from the containing class when using an anonymous class. Therefore you need to declare the variables being used final (which is not an option for you since you are changing lastPrice and price), or don't use an anonymous class.

So your options are to create an actual inner class, in which you can pass in the variables and use them in a normal fashion

or:

There is a quick (and in my opinion ugly) hack for your lastPrice and price variable which is to declare it like so

final double lastPrice[1];
final double price[1];

and in your anonymous class you can set the value like this

price[0] = priceObject.getNextPrice(lastPrice[0]);
System.out.println();
lastPrice[0] = price[0];

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

Are you import them? Like this:

compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:recyclerview-v7:21.0.3'

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

Get city name using geolocation

After some searching and piecing together a couple of different solutions along with my own stuff, I came up with this function:

function parse_place(place)
{
    var location = [];

    for (var ac = 0; ac < place.address_components.length; ac++)
    {
        var component = place.address_components[ac];

        switch(component.types[0])
        {
            case 'locality':
                location['city'] = component.long_name;
                break;
            case 'administrative_area_level_1':
                location['state'] = component.long_name;
                break;
            case 'country':
                location['country'] = component.long_name;
                break;
        }
    };

    return location;
}

PHPExcel - creating multiple sheets by iteration

You can write different sheets as follows

$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("creater");
$objPHPExcel->getProperties()->setLastModifiedBy("Middle field");
$objPHPExcel->getProperties()->setSubject("Subject");
$objWorkSheet = $objPHPExcel->createSheet();
$work_sheet_count=3;//number of sheets you want to create
$work_sheet=0;
while($work_sheet<=$work_sheet_count){ 
     if($work_sheet==0){
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 1')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     if($work_sheet==1){
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 2')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     if($work_sheet==2){
         $objWorkSheet = $objPHPExcel->createSheet($work_sheet_count);
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 3')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     $work_sheet++;
}

$filename='file-name'.'.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cach

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

What's the difference between Instant and LocalDateTime?

One main difference is the Local part of LocalDateTime. If you live in Germany and create a LocalDateTime instance and someone else lives in USA and creates another instance at the very same moment (provided the clocks are properly set) - the value of those objects would actually be different. This does not apply to Instant, which is calculated independently from time zone.

LocalDateTime stores date and time without timezone, but it's initial value is timezone dependent. Instant's is not.

Moreover, LocalDateTime provides methods for manipulating date components like days, hours, months. An Instant does not.

apart from the nanosecond precision advantage of Instant and the time-zone part of LocalDateTime

Both classes have the same precision. LocalDateTime does not store timezone. Read javadocs thoroughly, because you may make a big mistake with such invalid assumptions: Instant and LocalDateTime.

Check if an object exists

the boolean value of an empty QuerySet is also False, so you could also just do...

...
if not user_object:
   do insert or whatever etc.

comparing elements of the same array in java

First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.

So, to check all pairs of elements you can do:

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.

A better approach would be to compare each element i to the rest of the array:

for (int i = 0; i < a.length; i++) {
    for (int k = i + 1; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

So if you have the indices [1...5] the comparison would go

  1. 1 -> 2
  2. 1 -> 3
  3. 1 -> 4
  4. 1 -> 5
  5. 2 -> 3
  6. 2 -> 4
  7. 2 -> 5
  8. 3 -> 4
  9. 3 -> 5
  10. 4 -> 5

So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.

Get current time in hours and minutes

I have another solution for your question .

In the first when use date the output is like this :

Thu 28 Jan 2021 22:29:40 IST

Then if you want only to show current time in hours and minutes you can use this command :

date | cut -d " " -f5 | cut -d ":" -f1-2 

Then the output :

22:29

How to split a file into equal parts, without breaking individual lines?

The script isn't even necessary, split(1) supports the wanted feature out of the box:
split -l 75 auth.log auth.log. The above command splits the file in chunks of 75 lines a piece, and outputs file on the form: auth.log.aa, auth.log.ab, ...

wc -l on the original file and output gives:

  321 auth.log
   75 auth.log.aa
   75 auth.log.ab
   75 auth.log.ac
   75 auth.log.ad
   21 auth.log.ae
  642 total

Rounded table corners CSS only

To adapt @luke flournoy's brilliant answer - and if you're not using th in your table, here's all the CSS you need to make a rounded table:

.my_table{
border-collapse: separate;
border-spacing: 0;
border: 1px solid grey;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}

.my_table tr:first-of-type {
  border-top-left-radius: 10px;
}

.my_table tr:first-of-type td:last-of-type {
  border-top-right-radius: 10px;
}

.my_table tr:last-of-type td:first-of-type {
  border-bottom-left-radius: 10px;
}

.my_table tr:last-of-type td:last-of-type {
  border-bottom-right-radius: 10px;
}

How to get a password from a shell script without echoing

The -s option of read is not defined in the POSIX standard. See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html. I wanted something that would work for any POSIX shell, so I wrote a little function that uses stty to disable echo.

#!/bin/sh

# Read secret string
read_secret()
{
    # Disable echo.
    stty -echo

    # Set up trap to ensure echo is enabled before exiting if the script
    # is terminated while echo is disabled.
    trap 'stty echo' EXIT

    # Read secret.
    read "$@"

    # Enable echo.
    stty echo
    trap - EXIT

    # Print a newline because the newline entered by the user after
    # entering the passcode is not echoed. This ensures that the
    # next line of output begins at a new line.
    echo
}

This function behaves quite similar to the read command. Here is a simple usage of read followed by similar usage of read_secret. The input to read_secret appears empty because it was not echoed to the terminal.

[susam@cube ~]$ read a b c
foo \bar baz \qux
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=bar c=baz qux
[susam@cube ~]$ unset a b c
[susam@cube ~]$ read_secret a b c

[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=bar c=baz qux
[susam@cube ~]$ unset a b c

Here is another that uses the -r option to preserve the backslashes in the input. This works because the read_secret function defined above passes all arguments it receives to the read command.

[susam@cube ~]$ read -r a b c
foo \bar baz \qux
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=\bar c=baz \qux
[susam@cube ~]$ unset a b c
[susam@cube ~]$ read_secret -r a b c

[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=\bar c=baz \qux
[susam@cube ~]$ unset a b c

Finally, here is an example that shows how to use the read_secret function to read a password in a POSIX compliant manner.

printf "Password: "
read_secret password
# Do something with $password here ...

setBackground vs setBackgroundDrawable (Android)

Use setBackgroundResource(R.drawable.xml/png)

How to show text on image when hovering?

This is what I use to make the text appear on hover:

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box_x000D_
}_x000D_
_x000D_
div {_x000D_
  position: relative;_x000D_
  top: 0px;_x000D_
  left: 0px;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  border-radius: 50%;_x000D_
  overflow: hidden;_x000D_
  text-align: center_x000D_
}_x000D_
_x000D_
img {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  position: absolute;_x000D_
  border-radius: 50%_x000D_
}_x000D_
_x000D_
img:hover {_x000D_
  opacity: 0;_x000D_
  transition:opacity 2s;_x000D_
}_x000D_
_x000D_
heading {_x000D_
  line-height: 40px;_x000D_
  font-weight: bold;_x000D_
  font-family: "Trebuchet MS";_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  display: block_x000D_
}_x000D_
_x000D_
div p {_x000D_
  z-index: -1;_x000D_
  width: 420px;_x000D_
  line-height: 20px;_x000D_
  display: inline-block;_x000D_
  padding: 200px 0px;_x000D_
  vertical-align: middle;_x000D_
  font-family: "Trebuchet MS";_x000D_
  height: 450px_x000D_
}
_x000D_
<div>_x000D_
  <img src="https://68.media.tumblr.com/20b34e8d12d4230f9b362d7feb148c57/tumblr_oiwytz4dh41tf8vylo1_1280.png">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing <br>elit. Reiciendis temporibus iure dolores aspernatur excepturi <br> corporis nihil in suscipit, repudiandae. Totam._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add results of two select commands in same query

Yes. It is possible :D

SELECT  SUM(totalHours) totalHours
FROM
        ( 
            select sum(hours) totalHours from resource
            UNION ALL
            select sum(hours) totalHours from projects-time
        ) s

As a sidenote, the tablename projects-time must be delimited to avoid syntax error. Delimiter symbols vary on RDBMS you are using.

How to get the Display Name Attribute of an Enum member via MVC Razor code?

I'm sorry to do this, but I couldn't use any of the other answers as-is and haven't time to duke it out in the comments.

Uses C# 6 syntax.

static class EnumExtensions
{
    /// returns the localized Name, if a [Display(Name="Localised Name")] attribute is applied to the enum member
    /// returns null if there isnt an attribute
    public static string DisplayNameOrEnumName(this Enum value)
    // => value.DisplayNameOrDefault() ?? value.ToString()
    {
        // More efficient form of ^ based on http://stackoverflow.com/a/17034624/11635
        var enumType = value.GetType();
        var enumMemberName = Enum.GetName(enumType, value);
        return enumType
            .GetEnumMemberAttribute<DisplayAttribute>(enumMemberName)
            ?.GetName() // Potentially localized
            ?? enumMemberName; // Or fall back to the enum name
    }

    /// returns the localized Name, if a [Display] attribute is applied to the enum member
    /// returns null if there is no attribute
    public static string DisplayNameOrDefault(this Enum value) =>
        value.GetEnumMemberAttribute<DisplayAttribute>()?.GetName();

    static TAttribute GetEnumMemberAttribute<TAttribute>(this Enum value) where TAttribute : Attribute =>
        value.GetType().GetEnumMemberAttribute<TAttribute>(value.ToString());

    static TAttribute GetEnumMemberAttribute<TAttribute>(this Type enumType, string enumMemberName) where TAttribute : Attribute =>
        enumType.GetMember(enumMemberName).Single().GetCustomAttribute<TAttribute>();
}

Can I run javascript before the whole page is loaded?

You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.

So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded event or functions like $.ready in jQuery.

Array of strings in groovy

Most of the time you would create a list in groovy rather than an array. You could do it like this:

names = ["lucas", "Fred", "Mary"]

Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:

names = "lucas Fred Mary".split()

Original purpose of <input type="hidden">?

basically hidden fields will be more useful and advantages to use with multi step form. we can use hidden fields to pass one step information to next step using hidden and keep it forwarding till the end step.

  1. CSRF tokens.

Cross-site request forgery is a very common website vulnerability. Requiring a secret, user-specific token in all form submissions will prevent CSRF attacks since attack sites cannot guess what the proper token is and any form submissions they perform on the behalf of the user will always fail.

  1. Save state in multi-page forms.

If you need to store what step in a multi-page form the user is currently on, use hidden input fields. The user doesn't need to see this information, so hide it in a hidden input field.

General rule: Use the field to store anything that the user doesn't need to see, but that you want to send to the server on form submission.

Command-line tool for finding out who is locking a file

Handle didn't find that WhatsApp is holding lock on a file .tmp.node in temp folder. ProcessExplorer - Find works better Look at this answer https://superuser.com/a/399660

How to make an app's background image repeat

// Prepared By Muhammad Mubashir.
// 26, August, 2011.
// Chnage Back Ground Image of Activity.

package com.ChangeBg_01;

import com.ChangeBg_01.R;

import android.R.color;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class ChangeBg_01Activity extends Activity
{
    TextView tv;
    int[] arr = new int[2];
    int i=0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv = (TextView)findViewById(R.id.tv);
        arr[0] = R.drawable.icon1;
        arr[1] = R.drawable.icon;

     // Load a background for the current screen from a drawable resource
        //getWindow().setBackgroundDrawableResource(R.drawable.icon1) ;

        final Handler handler=new Handler();
        final Runnable r = new Runnable()
        {
            public void run() 
            {
                //tv.append("Hello World");
                if(i== 2){
                    i=0;            
                }

                getWindow().setBackgroundDrawableResource(arr[i]);
                handler.postDelayed(this, 1000);
                i++;
            }
        };

        handler.postDelayed(r, 1000);
        Thread thread = new Thread()
        {
            @Override
            public void run() {
                try {
                    while(true) 
                    {
                        if(i== 2){
                            //finish();
                            i=0;
                        }
                        sleep(1000);
                        handler.post(r);
                        //i++;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };


    }
}

/*android:background="#FFFFFF"*/
/*
ImageView imageView = (ImageView) findViewById(R.layout.main);
imageView.setImageResource(R.drawable.icon);*/

// Now get a handle to any View contained 
// within the main layout you are using
/*        View someView = (View)findViewById(R.layout.main);

// Find the root view
View root = someView.getRootView();*/

// Set the color
/*root.setBackgroundColor(color.darker_gray);*/

How to detect orientation change in layout in Android?

Use the onConfigurationChanged method of Activity. See the following code:

@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

You also have to edit the appropriate element in your manifest file to include the android:configChanges Just see the code below:

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

NOTE: with Android 3.2 (API level 13) or higher, the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher, you must declare android:configChanges="orientation|screenSize" for API level 13 or higher.

Hope this will help you... :)

Search for one value in any column of any table inside a database

I found a fairly robust solution at https://gallery.technet.microsoft.com/scriptcenter/c0c57332-8624-48c0-b4c3-5b31fe641c58 , which I thought was worth pointing out. It searches columns of these types: varchar, char, nvarchar, nchar, text. It works great and supports specific table-searching as well as multiple search-terms.

What does the DOCKER_HOST variable do?

Ok, I think I got it.

The client is the docker command installed into OS X.

The host is the Boot2Docker VM.

The daemon is a background service running inside Boot2Docker.

This variable tells the client how to connect to the daemon.

When starting Boot2Docker, the terminal window that pops up already has DOCKER_HOST set, so that's why docker commands work. However, to run Docker commands in other terminal windows, you need to set this variable in those windows.

Failing to set it gives a message like this:

$ docker run hello-world
2014/08/11 11:41:42 Post http:///var/run/docker.sock/v1.13/containers/create: 
dial unix /var/run/docker.sock: no such file or directory

One way to fix that would be to simply do this:

$ export DOCKER_HOST=tcp://192.168.59.103:2375

But, as pointed out by others, it's better to do this:

$ $(boot2docker shellinit)
$ docker run hello-world
Hello from Docker. [...]

To spell out this possibly non-intuitive Bash command, running boot2docker shellinit returns a set of Bash commands that set environment variables:

export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1

Hence running $(boot2docker shellinit) generates those commands, and then runs them.

How to combine 2 plots (ggplot) into one plot?

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +
      geom_smooth(size=1)

AWS : The config profile (MyName) could not be found

For me it was because I had my .aws/config file looking like this:

[profile myname]
aws_access_key_id = ....
aws_secret_access_key = ....
region=us-west-1

I think the reason is I based it off my .aws/credentials file, which requires having [profile myname] for Zappa and maybe some other aws/elastic beanstalk tools.

When I changed config to this it worked great:

[myname]
aws_access_key_id = ....
aws_secret_access_key = ....
region=us-west-1

Rounded Corners Image in Flutter

Try This it works well.

Container(
  height: 220.0,
  width: double.infinity,
  decoration: BoxDecoration(
    borderRadius: new BorderRadius.only(
      topLeft: Radius.circular(10),
       topRight: Radius.circular(10),
    ),
    image: DecorationImage(
      fit: BoxFit.fill,
      image: NetworkImage(
        photoUrl,
      ),
     ),
   ),
);

Getting JavaScript object key list

_x000D_
_x000D_
var obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
  key4: 'value4'
};
var keys = [];

for (var k in obj) keys.push(k);

console.log("total " + keys.length + " keys: " + keys);
_x000D_
_x000D_
_x000D_

How to load an ImageView by URL in Android?

You'll have to download the image firstly

public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}

Then use the Imageview.setImageBitmap to set bitmap into the ImageView

How to connect to LocalDB in Visual Studio Server Explorer?

Scenario: Windows 8.1, VS2013 Ultimate, SQL Express Installed and running, SQL Server Browser Disabled. This worked for me:

  1. First I enabled SQL Server Browser under services.
  2. In Visual Studio: Open the Package Manager Console then type: Enable-Migrations; Then Type Enable-Migrations -ContextTypeName YourContextDbName that created the Migrations folder in VS.
  3. Inside the Migrations folder you will find the "Configuration.cs" file, turn on automatic migrations by: AutomaticMigrationsEnabled = true;
  4. Run your application again, the environment creates a DefaultConnection and you will see the new tables from your context. This new connection points to the localdb. The created connection string shows: Data Source=(LocalDb)\v11.0 ... (more parameters and path to the created mdf file)

You can now create a new connection with Server name: (LocalDb)\v11.0 (hit refresh) Connect to a database: Select your new database under the dropdown.

I hope it helps.

How can I expand and collapse a <div> using javascript?

So, first of all, your Javascript isn't even using jQuery. There are a couple ways to do this. For example:

First way, using the jQuery toggle method:

<div class="expandContent">
        <a href="#">Click Here to Display More Content</a>
 </div>
<div class="showMe" style="display:none">
        This content was hidden, but now shows up
</div>

<script>  
    $('.expandContent').click(function(){
        $('.showMe').toggle();
    });
</script>

jsFiddle: http://jsfiddle.net/pM3DF/

Another way is simply to use the jQuery show method:

<div class="expandContent">
        <a href="#">Click Here to Display More Content</a>
 </div>
<div class="showMe" style="display:none">
        This content was hidden, but now shows up
</div>

<script>
    $('.expandContent').click(function(){
        $('.showMe').show();
    });
</script>

jsFiddle: http://jsfiddle.net/Q2wfM/

Yet a third way is to use the slideToggle method of jQuery which allows for some effects. Such as $('#showMe').slideToggle('slow'); which will slowly display the hidden div.

Get index of a row of a pandas dataframe as an integer

To answer the original question on how to get the index as an integer for the desired selection, the following will work :

df[df['A']==5].index.item()

"Full screen" <iframe>

Adding this to your iframe might resolve the issue:

frameborder="0"  seamless="seamless"

PostgreSQL: how to convert from Unix epoch to date?

/* Current time */
 select now(); 

/* Epoch from current time;
   Epoch is number of seconds since 1970-01-01 00:00:00+00 */
 select extract(epoch from now()); 

/* Get back time from epoch */
 -- Option 1 - use to_timestamp function
 select to_timestamp( extract(epoch from now()));
 -- Option 2 - add seconds to 'epoch'
 select timestamp with time zone 'epoch' 
         + extract(epoch from now()) * interval '1 second';

/* Cast timestamp to date */
 -- Based on Option 1
 select to_timestamp(extract(epoch from now()))::date;
 -- Based on Option 2
 select (timestamp with time zone 'epoch' 
          + extract(epoch from now()) * interval '1 second')::date; 

 /* For column epoch_ms */
 select to_timestamp(extract(epoch epoch_ms))::date;

PostgreSQL Docs

Android studio doesn't list my phone under "Choose Device"

I had the same issue and couldn't get my Nexus 6P to show up as an available device until I changed the connection type from "Charging" to "Photo Transfer(PTP)" and installed the Google USB driver while in PTP mode. Installing the driver prior to that while in Charging mode yielded no results.

Link a .css on another folder

check this quick reminder of file path

Here is all you need to know about relative file paths:

  • Starting with "/" returns to the root directory and starts there
  • Starting with "../" moves one directory backwards and starts there
  • Starting with "../../" moves two directories backwards and starts there (and so on...)
  • To move forward, just start with the first subdirectory and keep moving forward

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

Encapsulation vs Abstraction?

Abstraction is the concept of describing something in simpler terms, i.e abstracting away the details, in order to focus on what is important (This is also seen in abstract art, for example, where the artist focuses on the building blocks of images, such as colour or shapes). The same idea translates to OOP by using an inheritance hierarchy, where more abstract concepts are at the top and more concrete ideas, at the bottom, build upon their abstractions. At its most abstract level there is no implementation details at all and perhaps very few commonalities, which are added as the abstraction decreases.

As an example, at the top might be an interface with a single method, then the next level, provides several abstract classes, which may or may not fill in some of the details about the top level, but branches by adding their own abstract methods, then for each of these abstract classes are concrete classes providing implementations of all the remaining methods.

Encapsulation is a technique. It may or may not be for aiding in abstraction, but it is certainly about information hiding and/or organisation. It demands data and functions be grouped in some way - of course good OOP practice demands that they should be grouped by abstraction. However, there are other uses which just aid in maintainability etc.

How to permanently set $PATH on Linux/Unix?

I think the most elegant way is:

1.add this in ~/.bashrc file Run this command

gedit ~/.bashrc

add your path inside it

export PATH=$PATH:/opt/node/bin

2.source ~/.bashrc

(Ubuntu)

PHP Header redirect not working

Try redirection with JavaScript:

<script type="text/javascript">
  window.location.href='index.php';
</script>

How can I make a button have a rounded border in Swift?

I have created a simple UIButton sublcass that uses the tintColor for its text and border colours and when highlighted changes its background to the tintColor.

class BorderedButton: UIButton {

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    layer.borderWidth = 1.0
    layer.borderColor = tintColor.CGColor
    layer.cornerRadius = 5.0
    clipsToBounds = true
    contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
    setTitleColor(tintColor, forState: .Normal)
    setTitleColor(UIColor.whiteColor(), forState: .Highlighted)
    setBackgroundImage(UIImage(color: tintColor), forState: .Highlighted)
}
}

This makes use of a UIImage extension that creates an image from a colour, I found that code here: https://stackoverflow.com/a/33675160

It works best when set to type Custom in interface builder as the default System type slightly modifies the colours when the button is highlighted.

Exporting the values in List to excel

Exporting values List to Excel

  1. Install in nuget next reference
  2. Install-Package Syncfusion.XlsIO.Net.Core -Version 17.2.0.35
  3. Install-Package ClosedXML -Version 0.94.2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClosedXML;
using ClosedXML.Excel;
using Syncfusion.XlsIO;

namespace ExporteExcel
{
    class Program
    {
        public class Auto
        {
            public string Marca { get; set; }

            public string Modelo { get; set; }
            public int Ano { get; set; }

            public string Color { get; set; }
            public int Peronsas { get; set; }
            public int Cilindros { get; set; }
        }
        static void Main(string[] args)
        {
            //Lista Estatica
            List<Auto> Auto = new List<Program.Auto>()
            {
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2019, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2018, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2017, Color= "Azul", Cilindros=6, Peronsas= 4 }
            };
            //Inizializar Librerias
            var workbook = new XLWorkbook();
            workbook.AddWorksheet("sheetName");
            var ws = workbook.Worksheet("sheetName");
            //Recorrer el objecto
            int row = 1;
            foreach (var c in Auto)
            {
                //Escribrie en Excel en cada celda
                ws.Cell("A" + row.ToString()).Value = c.Marca;
                ws.Cell("B" + row.ToString()).Value = c.Modelo;
                ws.Cell("C" + row.ToString()).Value = c.Ano;
                ws.Cell("D" + row.ToString()).Value = c.Color;
                ws.Cell("E" + row.ToString()).Value = c.Cilindros;
                ws.Cell("F" + row.ToString()).Value = c.Peronsas;
                row++;

            }
            //Guardar Excel 
            //Ruta = Nombre_Proyecto\bin\Debug
            workbook.SaveAs("Coches.xlsx");
        }
    }
}

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Font awesome use SVG icons. So, you can resize it for your requirment.

just use CSS class for that,

    .large-icon{
       font-size:10em;
       //or
      font-size:200%;
      //or
      font-size:50px;
    }

Is Java a Compiled or an Interpreted programming language ?

Kind of both. Firstly java compiled(some would prefer to say "translated") to bytecode, which then either compiled, or interpreted depending on mood of JIT.

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

I also came across this error. The problem it turned out was caused by a Trigger on the table I was trying to save to. The Trigger used 'INSTEAD OF INSERT' which means 0 rows ever got inserted to that table, hence the error. Luckily in may case the trigger functionality was incorrect, but I guess it could be a valid operation that should somehow be handled in code. Hope this helps somebody one day.

How to capture the "virtual keyboard show/hide" event in Android?

Not sure if anyone post this. Found this solution simple to use!. The SoftKeyboard class is on gist.github.com. But while keyboard popup/hide event callback we need a handler to properly do things on UI:

/*
Somewhere else in your code
*/
RelativeLayout mainLayout = findViewById(R.layout.main_layout); // You must use your root layout
InputMethodManager im = (InputMethodManager) getSystemService(Service.INPUT_METHOD_SERVICE);

/*
Instantiate and pass a callback
*/
SoftKeyboard softKeyboard;
softKeyboard = new SoftKeyboard(mainLayout, im);
softKeyboard.setSoftKeyboardCallback(new SoftKeyboard.SoftKeyboardChanged()
{

    @Override
    public void onSoftKeyboardHide() 
    {
        // Code here
        new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // Code here will run in UI thread
                    ...
                }
            });
    }

    @Override
    public void onSoftKeyboardShow() 
    {
        // Code here
        new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // Code here will run in UI thread
                    ...
                }
            });

    }   
});

ng if with angular for string contains

ES2015 UPDATE

ES2015 have String#includes method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true if the needle is found in haystack else returns false.

ng-if="haystack.includes(needle)"

Here, needle is the string that is to be searched in haystack.

See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.


You can use String#indexOf to get the index of the needle in haystack.

  1. If the needle is not present in the haystack -1 is returned.
  2. If needle is present at the beginning of the haystack 0 is returned.
  3. Else the index at which needle is, is returned.

The index can be compared with -1 to check whether needle is found in haystack.

ng-if="haystack.indexOf(needle) > -1" 

For Angular(2+)

*ngIf="haystack.includes(needle)"

get selected value in datePicker and format it

If you want to take the formatted value of input do this :

$("input").datepicker({ dateFormat: 'dd, mm, yy' });

later in your code when the date is set you could get it by

dateVariable = $("input").val();

If you want just to take a formatted value with datepicker you might want to use the utility

dateString = $.datepicker.formatDate('dd, MM, yy', new Date("20 April 2012"));

I've updated the jsfiddle for experimenting with this

How do I undo 'git add' before commit?

The question is not clearly posed. The reason is that git add has two meanings:

  1. adding a new file to the staging area, then undo with git rm --cached file.
  2. adding a modified file to the staging area, then undo with git reset HEAD file.

If in doubt, use

git reset HEAD file

Because it does the expected thing in both cases.

Warning: if you do git rm --cached file on a file that was modified (a file that existed before in the repository), then the file will be removed on git commit! It will still exist in your file system, but if anybody else pulls your commit, the file will be deleted from their work tree.

git status will tell you if the file was a new file or modified:

On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   my_new_file.txt
    modified:   my_modified_file.txt

CRON command to run URL address every 5 minutes

Here is an example of the wget script in action:

wget -q -O /dev/null "http://example.com/cronjob.php" > /dev/null 2>&1

Using -O parameter like the above means that the output of the web request will be sent to STDOUT (standard output).

And the >/dev/null 2>&1 will instruct standard output to be redirected to a black hole. So no message from the executing program is returned to the screen.

How can I align YouTube embedded video in the center in bootstrap

<center><div class="video">
<iframe width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>
</div></center>

It seems to work, is this all you were asking for? I guess you could go about taking longer more involved routes, but this seemed simple enough.

Is there any difference between a GUID and a UUID?

One difference between GUID in SQL Server and UUID in PostgreSQL is letter case; SQL Server outputs upper while PostgreSQL outputs lower.

The hexadecimal values "a" through "f" are output as lower case characters and are case insensitive on input. - rfc4122#section-3

How to prevent downloading images and video files from my website?

Don't post them to your site.

Otherwise it is not possible.

PHP __get and __set magic methods

__get, __set, __call and __callStatic are invoked when the method or property is inaccessible. Your $bar is public and therefor not inaccessible.

See the section on Property Overloading in the manual:

  • __set() is run when writing data to inaccessible properties.
  • __get() is utilized for reading data from inaccessible properties.

The magic methods are not substitutes for getters and setters. They just allow you to handle method calls or property access that would otherwise result in an error. As such, there are much more related to error handling. Also note that they are considerably slower than using proper getter and setter or direct method calls.

Angular2: child component access parent class variable/function

If you use input property databinding with a JavaScript reference type (e.g., Object, Array, Date, etc.), then the parent and child will both have a reference to the same/one object. Any changes you make to the shared object will be visible to both parent and child.

In the parent's template:

<child [aList]="sharedList"></child>

In the child:

@Input() aList;
...
updateList() {
    this.aList.push('child');
}

If you want to add items to the list upon construction of the child, use the ngOnInit() hook (not the constructor(), since the data-bound properties aren't initialized at that point):

ngOnInit() {
    this.aList.push('child1')
}

This Plunker shows a working example, with buttons in the parent and child component that both modify the shared list.

Note, in the child you must not reassign the reference. E.g., don't do this in the child: this.aList = someNewArray; If you do that, then the parent and child components will each have references to two different arrays.

If you want to share a primitive type (i.e., string, number, boolean), you could put it into an array or an object (i.e., put it inside a reference type), or you could emit() an event from the child whenever the primitive value changes (i.e., have the parent listen for a custom event, and the child would have an EventEmitter output property. See @kit's answer for more info.)

Update 2015/12/22: the heavy-loader example in the Structural Directives guides uses the technique I presented above. The main/parent component has a logs array property that is bound to the child components. The child components push() onto that array, and the parent component displays the array.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

According to the latest updates for OpenCV 3.0 and higher, you need to change the Property Identifiers as follows in the code by Mehran:

cv2.cv.CV_CAP_PROP_POS_FRAMES

to

cv2.CAP_PROP_POS_FRAMES

and same applies to cv2.CAP_PROP_POS_FRAME_COUNT.

Hope it helps.

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

Unable to connect to SQL Server instance remotely

If you have more than one Instances... Then make sure the PORT Numbers of all Instances are Unique and no one's PORT Number is 1433 except Default One...

Writing string to a file on a new line every time

Just a note, file isn't supported in Python 3 and was removed. You can do the same with the open built-in function.

f = open('test.txt', 'w')
f.write('test\n')

How to set enum to null

Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 

PHP mkdir: Permission denied problem

I know that this thread is old, but perhaps this will help someone, one day.

The problem why PHP says "Permission denied" for mkdir() - wrong url path. So, to fix it, all you need it's to obtain correct path. I did it this way:

<?php

$root = $_SERVER["DOCUMENT_ROOT"];
$dir = $root . '/somefolder/';

if( !file_exists($dir) ) {
    mkdir($dir, 0755, true);
}

?>

HTML5 Video not working in IE 11

Although MP4 is supported in Internet explorer it does matter how you encode the file. Make sure you use BASELINE encoding when rendering the video file. This Fixed my issue with IE11

db.collection is not a function when using MongoClient v3.0

For those that want to continue using version ^3.0.1 be aware of the changes to how you use the MongoClient.connect() method. The callback doesn't return db instead it returns client, against which there is a function called db(dbname) that you must invoke to get the db instance you are looking for.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

Android device is not connected to USB for debugging (Android studio)

The solution for me was following the instructions at https://developer.android.com/studio/run/oem-usb.html#InstallingDriver. Specifically, the key part from that link that helped me to find the solution was this: "Install a USB Driver. First, find the appropriate driver for your device from the OEM drivers table below." This means that you cannot find a single link that applies to everyone as the solution. It will depend on your device! "So I visited the page to get OEM Drivers at https://developer.android.com/studio/run/oem-usb.html#Drivers. In my case, the device I was using was an LG K8 LTE. I had to go to http://www.lg.com/us/support/software-firmware-drivers#, Browse by product and I found the driver I needed under the Model Number "LGAS375 KG K8 ACG - AS375", Cell Phone Product. From http://www.lg.com/us/support-mobile/lg-LGAS375 I used the "Install the USB DRIVER" for Windows (http://tool.lime.gdms.lge.com/dn/downloader.dev?fileKey=UW00120120425).

Depending on the device model you are using, you will need to find the specific drivers that work for your phone, and that should work.

How to call a function, PostgreSQL

you declare your function as returning boolean, but it never returns anything.

Issue with Task Scheduler launching a task

On properties,

Check whether radio button is selected for

Run only when user is logged on 

If you selected for the above option then that is the reason why it is failed.

so change the option to

Run whether user is logged on or not

OR

In other case, user might have changed his/her login credentials

How to delete a row from GridView?

hi how to delete from datagridview

1.make query delete by id
2.type

tabletableadaptor.delete
query(datagridwiewX1.selectedrows[0].cell[0].value.tostring);

iPad browser WIDTH & HEIGHT standard

The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.

When page has no meta viewport tag:

  • Portrait: 980x1208
  • Landscape: 980x661

When page has either of these two meta tags:

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">

  • Portrait: 768x946
  • Landscape: 1024x690

With <meta name="viewport" content="width=device-width">:

  • Portrait: 768x946
  • Landscape: 768x518

With <meta name="viewport" content="height=device-height">:

  • Portrait: 980x1024
  • Landscape: 980x1024

With <meta name="viewport" content="height=device-height,width=device-width">:

  • Portrait: 768x1024
  • Landscape: 768x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">

  • Portrait: 768x1024
  • Landscape: 1024x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">

  • Portrait: 831x1024
  • Landscape: 1520x1024

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

I had this error after creating an empty ASP.Net application in Visual Studio. As soon as I added a file index.html to the main solution, it worked. So in my case, I just needed to add a file to the root of the project folder.

How to recover MySQL database from .myd, .myi, .frm files

For those that have Windows XP and have MySQL server 5.5 installed - the location for the database is C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.5\data, unless you changed the location within the MySql Workbench installation GUI.

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

i was trying the same, so i downloaded the .7zip version of XAMPP with php 5.6.33 from https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/5.6.33/

then followed the steps below: 1. rename c:\xampp\php to c:\xampp\php7 2. raname C:\xampp\apache\conf\extra\httpd-xampp.conf to httpd-xampp7.OLD 3. copy php folder from XAMPP_5.6 7zip archive to c:\xampp\ 4. copy file httpd-xampp.conf from XAMPP_5.6 7zip archive to C:\xampp\apache\conf\extra\

open xampp control panel and start Apache and then visit ( i am using port 82 instead of default 80) http://localhost and then click PHPInfo to see if it is working as expected.

Opening localhost shows dashboard

Opening phpinfo shows version 5.6

Pycharm/Python OpenCV and CV2 install error

In jetso nano this work for me.

$ git clone https://github.com/JetsonHacksNano/buildOpenCV
$ cd buildOpenCV

The PowerShell -and conditional operator

The code that you have shown will do what you want iff those properties equal "" when they are not filled in. If they equal $null when not filled in for example, then they will not equal "". Here is an example to prove the point that what you have will work for "":

$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False

Display tooltip on Label's hover?

You can use the "title attribute" for label tag.

<label title="Hello This Will Have Some Value">Hello...</label>

If you need more control over the looks,

1 . try http://getbootstrap.com/javascript/#tooltips as shown below. But you will need to include bootstrap.

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Hello This Will Have Some Value">Hello...</button>

2 . try https://jqueryui.com/tooltip/. But you will need to include jQueryUI.

<script type="text/javascript">
$(document).ready(function(){
$(this).tooltip();
});
</script>

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

First off, if you're starting a new project, go with Entity Framework ("EF") - it now generates much better SQL (more like Linq to SQL does) and is easier to maintain and more powerful than Linq to SQL ("L2S"). As of the release of .NET 4.0, I consider Linq to SQL to be an obsolete technology. MS has been very open about not continuing L2S development further.

1) Performance

This is tricky to answer. For most single-entity operations (CRUD) you will find just about equivalent performance with all three technologies. You do have to know how EF and Linq to SQL work in order to use them to their fullest. For high-volume operations like polling queries, you may want to have EF/L2S "compile" your entity query such that the framework doesn't have to constantly regenerate the SQL, or you can run into scalability issues. (see edits)

For bulk updates where you're updating massive amounts of data, raw SQL or a stored procedure will always perform better than an ORM solution because you don't have to marshal the data over the wire to the ORM to perform updates.

2) Speed of Development

In most scenarios, EF will blow away naked SQL/stored procs when it comes to speed of development. The EF designer can update your model from your database as it changes (upon request), so you don't run into synchronization issues between your object code and your database code. The only time I would not consider using an ORM is when you're doing a reporting/dashboard type application where you aren't doing any updating, or when you're creating an application just to do raw data maintenance operations on a database.

3) Neat/Maintainable code

Hands down, EF beats SQL/sprocs. Because your relationships are modeled, joins in your code are relatively infrequent. The relationships of the entities are almost self-evident to the reader for most queries. Nothing is worse than having to go from tier to tier debugging or through multiple SQL/middle tier in order to understand what's actually happening to your data. EF brings your data model into your code in a very powerful way.

4) Flexibility

Stored procs and raw SQL are more "flexible". You can leverage sprocs and SQL to generate faster queries for the odd specific case, and you can leverage native DB functionality easier than you can with and ORM.

5) Overall

Don't get caught up in the false dichotomy of choosing an ORM vs using stored procedures. You can use both in the same application, and you probably should. Big bulk operations should go in stored procedures or SQL (which can actually be called by the EF), and EF should be used for your CRUD operations and most of your middle-tier's needs. Perhaps you'd choose to use SQL for writing your reports. I guess the moral of the story is the same as it's always been. Use the right tool for the job. But the skinny of it is, EF is very good nowadays (as of .NET 4.0). Spend some real time reading and understanding it in depth and you can create some amazing, high-performance apps with ease.

EDIT: EF 5 simplifies this part a bit with auto-compiled LINQ Queries, but for real high volume stuff, you'll definitely need to test and analyze what fits best for you in the real world.

How do you convert Html to plain text?

I had the same question, just my html had a simple pre-known layout, like:

<DIV><P>abc</P><P>def</P></DIV>

So I ended up using such simple code:

string.Join (Environment.NewLine, XDocument.Parse (html).Root.Elements ().Select (el => el.Value))

Which outputs:

abc
def

How to restore SQL Server 2014 backup in SQL Server 2008

No, it is not possible. Stack Overflow wants me to answer with a longer answer, so I will say no again.

Documentation: https://docs.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql#compatibility

Backups that are created by more recent version of SQL Server cannot be restored in earlier versions of SQL Server.

Two divs side by side - Fluid display

Here's my answer for those that are Googling:

CSS:

.column {
    float: left;
    width: 50%;
}

/* Clear floats after the columns */
.container:after {
    content: "";
    display: table;
    clear: both;
}

Here's the HTML:

<div class="container">
    <div class="column"></div>
    <div class="column"></div>
</div>

Access VBA | How to replace parts of a string with another string

You could use a function similar to this also, it would allow you to add in different cases where you would like to change values:

Public Function strReplace(varValue As Variant) as Variant

    Select Case varValue

        Case "Avenue"
            strReplace = "Ave"

        Case "North"
            strReplace = "N"

        Case Else
            strReplace = varValue

    End Select

End Function

Then your SQL would read something like:

SELECT strReplace(Address) As Add FROM Tablename

select2 - hiding the search box

Version 4.0.3

Try not to mix user interface requirements with your JavaScript code.

You can hide the search box in the markup with the attribute:

data-minimum-results-for-search="Infinity"

Markup

<select class="select2" data-minimum-results-for-search="Infinity"></select>

Example

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".select2").select2();_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>_x000D_
_x000D_
<label>without search box</label>_x000D_
<select class="select2" data-width="100%" data-minimum-results-for-search="Infinity">_x000D_
  <option>one</option>_x000D_
  <option>two</option>_x000D_
</select>_x000D_
_x000D_
<label>with search box</label>_x000D_
<select class="select2" data-width="100%">_x000D_
  <option>one</option>_x000D_
  <option>two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Take nth column in a text file

For the sake of completeness:

while read _ _ one _ two _; do
    echo "$one $two"
done < file.txt

Instead of _ an arbitrary variable (such as junk) can be used as well. The point is just to extract the columns.

Demo:

$ while read _ _ one _ two _; do echo "$one $two"; done < /tmp/file.txt
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495

How to shutdown my Jenkins safely?

  1. jenkinsUrl/safeRestart - Let you to wait for running JOBS to get complete and do a RESTART.
  2. jenkinsUrl/restart - Do a restart immediately without waiting for the jobs which are running currently.
  3. jenkinsUrl/exit - It stops/shutdown the JENKINS services
  4. jenkinsUrl/reload - To reload the configuration changes.

SQL, How to Concatenate results?

In my opinion, if you are using SQL Server 2017 or later, using STRING_AGG( ... ) is the best solution:

More at:

https://stackoverflow.com/a/42778050/1260488

Now() function with time trim

I would prefer to make a function that doesn't work with strings:

'---------------------------------------------------------------------------------------
' Procedure : RemoveTimeFromDate
' Author    : berend.nieuwhof
' Date      : 15-8-2013
' Purpose   : removes the time part of a String and returns the date as a date
'---------------------------------------------------------------------------------------
'
Public Function RemoveTimeFromDate(DateTime As Date) As Date


    Dim dblNumber As Double

    RemoveTimeFromDate = CDate(Floor(CDbl(DateTime)))

End Function

Private Function Floor(ByVal x As Double, Optional ByVal Factor As Double = 1) As Double
    Floor = Int(x / Factor) * Factor
End Function

Oracle SQL : timestamps in where clause

For everyone coming to this thread with fractional seconds in your timestamp use:

to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')

Notepad++: Multiple words search in a file (may be in different lines)?

<shameless-plug>

Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here

Feel free to post any issues/suggestions here.

</shameless-plug>

Oracle SQL - select within a select (on the same table!)

This is something I'd use the LAG function for:

SELECT eh.gc_staff_number,
       eh.start_date,
       LAG(eh.end_date) OVER (PARTITION BY eh.gc_staff_number
                                  ORDER BY eh.end_date) AS prev_end_date
  FROM EMPLOYMENT_HISTORY eh
 WHERE eh.current_flag = 'Y'

If you wanted to peek a row ahead, you'd use the LEAD function.

Compatibility:

To my knowledge, this is supported 9i+ but I haven't confirmed that 8i is supported like the documentation claims.

LEAD and LAG are finally ANSI, but only Oracle and PostgreSQL v8.4+ support them currently.

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers

The headers you are trying to set are response headers. They have to be provided, in the response, by the server you are making the request to.

They have no place being set on the client. It would be pointless having a means to grant permissions if they could be granted by the site that wanted permission instead of the site that owned the data.

Play a Sound with Python

pyMedia's sound example does just that. This should be all you need.

import time, wave, pymedia.audio.sound as sound
f= wave.open( 'YOUR FILE NAME', 'rb' )
sampleRate= f.getframerate()
channels= f.getnchannels()
format= sound.AFMT_S16_LE
snd= sound.Output( sampleRate, channels, format )
s= f.readframes( 300000 )
snd.play( s )

How get all values in a column using PHP?

First things is this is only for advanced developers persons Who all are now beginner to php dont use this function if you are using the huge project in core php use this function

function displayAllRecords($serverName, $userName, $password, $databaseName,$sqlQuery='')
{
    $databaseConnectionQuery =  mysqli_connect($serverName, $userName, $password, $databaseName);
    if($databaseConnectionQuery === false)
    {
        die("ERROR: Could not connect. " . mysqli_connect_error());
        return false;
    }

    $resultQuery = mysqli_query($databaseConnectionQuery,$sqlQuery);
    $fetchFields = mysqli_fetch_fields($resultQuery);
    $fetchValues = mysqli_fetch_fields($resultQuery);

    if (mysqli_num_rows($resultQuery) > 0) 
    {           

        echo "<table class='table'>";
        echo "<tr>";
        foreach ($fetchFields as $fetchedField)
         {          
            echo "<td>";
            echo "<b>" . $fetchedField->name . "<b></a>";
            echo "</td>";
        }       
        echo "</tr>";
        while($totalRows = mysqli_fetch_array($resultQuery)) 
        {           
            echo "<tr>";                                
            for($eachRecord = 0; $eachRecord < count($fetchValues);$eachRecord++)
            {           
                echo "<td>";
                echo $totalRows[$eachRecord];
                echo "</td>";               
            }
            echo "<td><a href=''><button>Edit</button></a></td>";
            echo "<td><a href=''><button>Delete</button></a></td>";
            echo "</tr>";           
        } 
        echo "</table>";        

    } 
    else
    {
      echo "No Records Found in";
    }
}

All set now Pass the arguments as For Example

$queryStatment = "SELECT * From USERS "; $testing = displayAllRecords('localhost','root','root@123','email',$queryStatment); echo $testing;

Here

localhost indicates Name of the host,

root indicates the username for database

root@123 indicates the password for the database

$queryStatment for generating Query

hope it helps

Foreach loop, determine which is the last iteration of the loop

What about little simpler approach.

Item last = null;
foreach (Item result in Model.Results)
{
    // do something with each item

    last = result;
}

//Here Item 'last' contains the last object that came in the last of foreach loop.
DoSomethingOnLastElement(last);

How to hide a <option> in a <select> menu with CSS?

Simple answer: You can't. Form elements have very limited styling capabilities.

The best alternative would be to set disabled=true on the option (and maybe a gray colour, since only IE does that automatically), and this will make the option unclickable.

Alternatively, if you can, completely remove the option element.

MySQL Select last 7 days

The WHERE clause is misplaced, it has to follow the table references and JOIN operations.

Something like this:

 FROM tartikel p1 
 JOIN tartikelpict p2 
   ON p1.kArtikel = p2.kArtikel 
  AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC

EDIT (three plus years later)

The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"

As to a question about writing a condition that checks a date range of "last 7 days"...

That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.

To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".

If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT

 SELECT DATE(NOW()) + INTERVAL -1 DAY 

and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:

 WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY

For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...

 WHERE datetimecol >= NOW() + INTERVAL -7 DAY
   AND datetimecol <  NOW() + INTERVAL  0 DAY

the last seven complete days, not including today

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

or past six complete days plus so far today ...

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
   AND datetimecol <  NOW()       + INTERVAL  0 DAY

I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.

SET @clock = '2017-11-17 11:47:47' ;

SELECT DATE(@clock)
     , DATE(@clock) + INTERVAL -7 DAY 
     , @clock + INTERVAL -6 DAY 

Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.

(Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax.

And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,

Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is

  WHERE datetimecol >= '2017-11-10 00:00'
    AND datetimecol <  '2017-11-17 00:00'

And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...

  WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
    AND datetimecol <  '2017-11-17 00:00' + INTERVAL 0 SECOND

The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy', m/d/yyyy, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.

How to change Android usb connect mode to charge only?

I have been searching for this for ages on my CM 11 android phone, running kitkat.

Well.. finally I found it. It's hidden in a totally unintuitive location:

  1. Go to settings
  2. Go to storage
  3. Open the menu and choose USB computer connection

Here you can choose between Media Device (MTP), Camera (PTP) and Mass storage (UMS). Turn them all off to get it to charge only.

Sadly, if the option is not there, it is not supported by the phone. This seems to be the case for my HTC One (M7).

When is a C++ destructor called?

1) If the object is created via a pointer and that pointer is later deleted or given a new address to point to, does the object that it was pointing to call its destructor (assuming nothing else is pointing to it)?

It depends on the type of pointers. For example, smart pointers often delete their objects when they are deleted. Ordinary pointers do not. The same is true when a pointer is made to point to a different object. Some smart pointers will destroy the old object, or will destroy it if it has no more references. Ordinary pointers have no such smarts. They just hold an address and allow you to perform operations on the objects they point to by specifically doing so.

2) Following up on question 1, what defines when an object goes out of scope (not regarding to when an object leaves a given {block}). So, in other words, when is a destructor called on an object in a linked list?

That's up to the implementation of the linked list. Typical collections destroy all their contained objects when they are destroyed.

So, a linked list of pointers would typically destroy the pointers but not the objects they point to. (Which may be correct. They may be references by other pointers.) A linked list specifically designed to contain pointers, however, might delete the objects on its own destruction.

A linked list of smart pointers could automatically delete the objects when the pointers are deleted, or do so if they had no more references. It's all up to you to pick the pieces that do what you want.

3) Would you ever want to call a destructor manually?

Sure. One example would be if you want to replace an object with another object of the same type but don't want to free memory just to allocate it again. You can destroy the old object in place and construct a new one in place. (However, generally this is a bad idea.)

// pointer is destroyed because it goes out of scope,
// but not the object it pointed to. memory leak
if (1) {
 Foo *myfoo = new Foo("foo");
}


// pointer is destroyed because it goes out of scope,
// object it points to is deleted. no memory leak
if(1) {
 Foo *myfoo = new Foo("foo");
 delete myfoo;
}

// no memory leak, object goes out of scope
if(1) {
 Foo myfoo("foo");
}

Proper use of mutexes in Python

I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:

from threading import Thread, Lock

mutex = Lock()

def processData(data):
    mutex.acquire()
    try:
        print('Do some stuff')
    finally:
        mutex.release()

while True:
    t = Thread(target = processData, args = (some_data,))
    t.start()

But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.

An alternative, for Python 2.6 and later, is to use Python's multiprocessing package. It mirrors the threading package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:

from multiprocessing import Process, Lock

mutex = Lock()

def processData(data):
    with mutex:
        print('Do some stuff')

if __name__ == '__main__':
    while True:
        p = Process(target = processData, args = (some_data,))
        p.start()

How can I change text color via keyboard shortcut in MS word 2010

You could use a macro, but it’s simpler to use styles. Define a character style that has the desired text color and assign a shortcut key to it, say Alt+R. In order to be able to switch color using just the keyboard, define another character style, say “normal”, that has no special feature—just for use to get normal text after switching to your colored style, and assign another shortcut to it, say Alt+N. Then you would just type text, press Alt+R to switch to colored text, type that text, press Alt+N to resume normal text color, etc.

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

How to pass a parameter to Vue @click event handler

When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}.

@click is just shorthand for v-on:click directive so the same rules apply.

In your case, simply use @click="addToCount(item.contactID)"

How can I list the contents of a directory in Python?

One way:

import os
os.listdir("/home/username/www/")

Another way:

glob.glob("/home/username/www/*")

Examples found here.

The glob.glob method above will not list hidden files.

Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir method on Path objects:

from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")

How to vertically align label and input in Bootstrap 3?

This works perfectly for me in Bootstrap 4.

<div class="form-row align-items-center">
   <div class="col-md-2">
     <label for="FirstName" style="margin-bottom:0rem !important;">First Name</label>
 </div>
 <div class="col-md-10">
    <input type="text" id="FirstName" name="FirstName" class="form-control" val=""/>
  /div>
</div>

How to place two forms on the same page?

You could make two forms with 2 different actions

<form action="login.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="submit" value="Login">
</form>

<br />

<form action="register.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="submit" value="Register">
</form>

Or do this

<form action="doStuff.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="hidden" name="action" value="login">
    <input type="submit" value="Login">
</form>

<br />

<form action="doStuff.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="hidden" name="action" value="register">
    <input type="submit" value="Register">
</form>

Then you PHP file would work as a switch($_POST['action']) ... furthermore, they can't click on both links at the same time or make a simultaneous request, each submit is a separate request.

Your PHP would then go on with the switch logic or have different php files doing a login procedure then a registration procedure

$.widget is not a function

May be include Jquery Widget first, then Draggable? I guess that will solve the problem.....

Detect a finger swipe through JavaScript on the iPhone and Android

If anyone is trying to use jQuery Mobile on Android and has problems with JQM swipe detection

(I had some on Xperia Z1, Galaxy S3, Nexus 4 and some Wiko phones too) this can be useful :

 //Fix swipe gesture on android
    if(android){ //Your own device detection here
        $.event.special.swipe.verticalDistanceThreshold = 500
        $.event.special.swipe.horizontalDistanceThreshold = 10
    }

Swipe on android wasn't detected unless it was a very long, precise and fast swipe.

With these two lines it works correctly

Most efficient way to create a zero filled JavaScript array?

ES6 solution:

[...new Array(5)].map(x => 0); // [0, 0, 0, 0, 0]

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How to instantiate, initialize and populate an array in TypeScript?

If you really want to have named parameters plus have your objects be instances of your class, you can do the following:

class bar {
    constructor (options?: {length: number; height: number;}) {
        if (options) {
            this.length = options.length;
            this.height = options.height;
        }
    }
    length: number;
    height: number;
}

class foo {
    bars: bar[] = new Array();
}

var ham = new foo();
ham.bars = [
    new bar({length: 4, height: 2}),
    new bar({length: 1, height: 3})
];

Also here's the related item on typescript issue tracker.

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

This expands on a previous answer. The best solution I've found is to make an innocuous CSS attribute that only appears if a CSS3 media query is met, and then have the JS test for that attribute.

So for instance, in the CSS you'd have:

@media screen only and (orientation:landscape)
{
    //  Some innocuous rule here
    body
    {
        background-color: #fffffe;
    }
}
@media screen only and (orientation:portrait)
{
    //  Some innocuous rule here
    body
    {
        background-color: #fffeff;
    }
}

You then go to JavaScript (I'm using jQuery for funsies). Color declarations may be weird, so you may want to use something else, but this is the most foolproof method I've found for testing it. You can then just use the resize event to pick up on switching. Put it all together for:

function detectOrientation(){
    //  Referencing the CSS rules here.
    //  Change your attributes and values to match what you have set up.
    var bodyColor = $("body").css("background-color");
    if (bodyColor == "#fffffe") {
        return "landscape";
    } else
    if (bodyColor == "#fffeff") {
        return "portrait";
    }
}
$(document).ready(function(){
    var orientation = detectOrientation();
    alert("Your orientation is " + orientation + "!");
    $(document).resize(function(){
        orientation = detectOrientation();
        alert("Your orientation is " + orientation + "!");
    });
});

The best part of this is that as of my writing this answer, it doesn't appear to have any effect on desktop interfaces, since they (generally) don't (seem to) pass any argument for orientation to the page.

PHP-FPM and Nginx: 502 Bad Gateway

I made all this similar tweaks, but from time to time I was getting 501/502 errors (daily).

This are my settings on /etc/php5/fpm/pool.d/www.conf to avoid 501 and 502 nginx errors… The server has 16Gb RAM. This configuration is for a 8Gb RAM server so…

sudo nano /etc/php5/fpm/pool.d/www.conf

then set the following values for

pm.max_children = 70
pm.start_servers = 20
pm.min_spare_servers = 20
pm.max_spare_servers = 35
pm.max_requests = 500

After this changes restart php-fpm

sudo service php-fpm restart

Programmatically find the number of cores on a machine

For Win32:

While GetSystemInfo() gets you the number of logical processors, use GetLogicalProcessorInformationEx() to get the number of physical processors.

How to append multiple values to a list in Python

letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
... 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
    

The provider is not compatible with the version of Oracle client

You should "ignore" all the x86/x64 talk here for starters and instead try the ODP.NET Managed Driver (if you are using .Net v4+):

https://www.nuget.org/packages/Oracle.ManagedDataAccess/

https://www.nuget.org/packages/Oracle.ManagedDataAccess.EntityFramework/

Oracle ODP.net Managed vs Unmanaged Driver

Avoid all the "unmanaged" what DLL what architecture issues! :D (about time Oracle).

The NuGet package (also works for 11g):

enter image description here

The old / manual method:

For info on how to convert to using the managed libraries:

  • First, here is a great code comparison of managed vs unmanaged: http://docs.oracle.com/cd/E51173_01/win.122/e17732/intro005.htm#ODPNT148
  • Ensure you have downloaded the ODP.NET, Managed Driver Xcopy version only
  • From the downloaded zip file, copy and paste into your project directory:
    • Oracle.ManagedDataAccessDTC.dll
    • Oracle.ManagedDataAccess.dll
  • Add a reference to Oracle.ManagedDataAccess.dll
  • Ensure your exe is released (added to Application Folder in VS2010) with both dlls

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

export IGNORE_WARNINGS=1

It does display warnings, but continues with the build

Add JsonArray to JsonObject

I think it is a problem(aka. bug) with the API you are using. JSONArray implements Collection (the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject has an overloaded put() method which takes a Collection and wraps it in a JSONArray (thus causing the problem). I think you need to force the other JSONObject.put() method to be used:

    jsonObject.put("aoColumnDefs",(Object)arr);

You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection) method is broken.

Changing user agent on urllib2.urlopen

Setting the User-Agent from everyone's favorite Dive Into Python.

The short story: You can use Request.add_header to do this.

You can also pass the headers as a dictionary when creating the Request itself, as the docs note:

headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments. This is often used to “spoof” the User-Agent header, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11", while urllib2‘s default user agent string is "Python-urllib/2.6" (on Python 2.6).

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

It is too late but might be it can help anyone

  1. Create unique name for every control
  2. Validate by using fromname[uniquname].$error

Sample code:

<input 
    ng-model="r.QTY" 
    class="span1" 
    name="QTY{{$index}}" 
    ng-pattern="/^[\d]*\.?[\d]*$/" required/>
<div ng-messages="formName['QTY' +$index].$error"
     ng-show="formName['QTY' +$index].$dirty || formName.$submitted">
   <div ng-message="required" class='error'>Required</div>
   <div ng-message="pattern" class='error'>Invalid Pattern</div>
</div>

See working demo here

How to add new column to MYSQL table?

your table:

q1 | q2 | q3 | q4 | q5

you can also do

ALTER TABLE yourtable ADD q6 VARCHAR( 255 ) after q5

Creating a timer in python

# this is kind of timer, stop after the input minute run out.    
import time
min=int(input('>>')) 
while min>0:
    print min
    time.sleep(60) # every minute 
    min-=1  # take one minute 

Concatenating multiple text files into a single file in Bash

Be careful, because none of these methods work with a large number of files. Personally, I used this line:

for i in $(ls | grep ".txt");do cat $i >> output.txt;done

EDIT: As someone said in the comments, you can replace $(ls | grep ".txt") with $(ls *.txt)

EDIT: thanks to @gnourf_gnourf expertise, the use of glob is the correct way to iterate over files in a directory. Consequently, blasphemous expressions like $(ls | grep ".txt") must be replaced by *.txt (see the article here).

Good Solution

for i in *.txt;do cat $i >> output.txt;done

Why do we use web.xml?

Web.xml is called as deployment descriptor file and its is is an XML file that contains information on the configuration of the web application, including the configuration of servlets.

Convert JSON to Map

Using the GSON library:

import com.google.gson.Gson;
import com.google.common.reflect.TypeToken;
import java.lang.reclect.Type;

Use the following code:

Type mapType = new TypeToken<Map<String, Map>>(){}.getType();  
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);

How to use java.Set

Since it is a HashSet you will need to override hashCode and equals methods. http://preciselyconcise.com/java/collections/d_set.php has an example explaining how to implement hashCode and equals methods

Difference between \w and \b regular expression meta characters

\w matches a word character. \b is a zero-width match that matches a position character that has a word character on one side, and something that's not a word character on the other. (Examples of things that aren't word characters include whitespace, beginning and end of the string, etc.)

\w matches a, b, c, d, e, and f in "abc def"
\b matches the (zero-width) position before a, after c, before d, and after f in "abc def"

See: http://www.regular-expressions.info/reference.html/

How to write to Console.Out during execution of an MSTest test

I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.

[TestMethod]
public void OneIsOne()
{
    using (ConsoleRedirector cr = new ConsoleRedirector())
    {
        Assert.IsFalse(cr.ToString().Contains("New text"));
        /* call some method that writes "New text" to stdout */
        Assert.IsTrue(cr.ToString().Contains("New text"));
    }
}

The disposable ConsoleRedirector is defined as:

internal class ConsoleRedirector : IDisposable
{
    private StringWriter _consoleOutput = new StringWriter();
    private TextWriter _originalConsoleOutput;
    public ConsoleRedirector()
    {
        this._originalConsoleOutput = Console.Out;
        Console.SetOut(_consoleOutput);
    }
    public void Dispose()
    {
        Console.SetOut(_originalConsoleOutput);
        Console.Write(this.ToString());
        this._consoleOutput.Dispose();
    }
    public override string ToString()
    {
        return this._consoleOutput.ToString();
    }
}

How to use data-binding with Fragment

I have been finding Answer for my application and here is the answer for Kotlin Language.


private lateinit var binding: FragmentForgetPasswordBinding

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
binding=DataBindingUtil.inflate(inflater,R.layout.fragment_forget_password,container,false)
        val viewModel=ViewModelProvider(this).get(ForgetPasswordViewModel::class.java)
        binding.recoveryViewModel=viewModel
        viewModel.forgetPasswordInterface=this
        return binding.root
}

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

The GUI can be fickle at times. The error you got when using T-SQL is because you're trying to overwrite an existing database, but did not specify to overwrite/replace the existing database. The following might work:

Use Master
Go
RESTORE DATABASE Publications
  FROM DISK = 'C:\Publications_backup_2012_10_15_010004_5648316.bak'
  WITH 
    MOVE 'Publications' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.mdf',--adjust path
    MOVE 'Publications_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.ldf'
, REPLACE -- Add REPLACE to specify the existing database which should be overwritten.

show/hide html table columns using css

One line of code using jQuery:

$('td:nth-child(2)').hide();

// If your table has header(th), use this:
//$('td:nth-child(2),th:nth-child(2)').hide();

Source: Hide a Table Column with a Single line of jQuery code

The multi-part identifier could not be bound

I was struggling with the same error message in SQL SERVER, since I had multiple joins, changing the order of the joins solved it for me.

Google Maps API warning: NoApiKeys

Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.

What are the obj and bin folders (created by Visual Studio) used for?

The obj folder holds object, or intermediate, files, which are compiled binary files that haven't been linked yet. They're essentially fragments that will be combined to produce the final executable. The compiler generates one object file for each source file, and those files are placed into the obj folder.

The bin folder holds binary files, which are the actual executable code for your application or library.

Each of these folders are further subdivided into Debug and Release folders, which simply correspond to the project's build configurations. The two types of files discussed above are placed into the appropriate folder, depending on which type of build you perform. This makes it easy for you to determine which executables are built with debugging symbols, and which were built with optimizations enabled and ready for release.

Note that you can change where Visual Studio outputs your executable files during a compile in your project's Properties. You can also change the names and selected options for your build configurations.

How to change fontFamily of TextView in Android

You can define a custom FontFamily like this:

/res/font/usual.xml:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:ignore="UnusedAttribute">
    <font
        android:fontStyle="normal"
        android:fontWeight="200"
        android:font="@font/usual_regular"
        app:fontStyle="normal"
        app:fontWeight="200"
        app:font="@font/usual_regular" />

    <font
        android:fontStyle="italic"
        android:fontWeight="200"
        android:font="@font/usual_regular_italic"
        app:fontStyle="italic"
        app:fontWeight="200"
        app:font="@font/usual_regular_italic" />

    <font
        android:fontStyle="normal"
        android:fontWeight="600"
        android:font="@font/usual_bold"
        app:fontStyle="normal"
        app:fontWeight="600"
        app:font="@font/usual_bold" />

    <font
        android:fontStyle="italic"
        android:fontWeight="600"
        android:font="@font/usual_bold_italic"
        app:fontStyle="italic"
        app:fontWeight="600"
        app:font="@font/usual_bold_italic" />
</font-family>

Now you can do

android:fontFamily="@font/usual"

Assuming your other font resources are there as well, with lowercase letters and _s.

How to save a data frame as CSV to a user selected location using tcltk

Take a look at the write.csv or the write.table functions. You just have to supply the file name the user selects to the file parameter, and the dataframe to the x parameter:

write.csv(x=df, file="myFileName")

"continue" in cursor.forEach()

In my opinion the best approach to achieve this by using the filter method as it's meaningless to return in a forEach block; for an example on your snippet:

// Fetch all objects in SomeElements collection
var elementsCollection = SomeElements.find();
elementsCollection
.filter(function(element) {
  return element.shouldBeProcessed;
})
.forEach(function(element){
  doSomeLengthyOperation();
});

This will narrow down your elementsCollection and just keep the filtred elements that should be processed.

Cannot construct instance of - Jackson

You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-

  @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    @JsonSubTypes({ 
      @Type(value = Bike.class, name = "bike"), 
      @Type(value = Auto.class, name = "auto"), 
      @Type(value = Car.class, name = "car")
    })
    public abstract class Vehicle {
        // fields, constructors, getters, setters
    }

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

Set the Value of a Hidden field using JQuery

Drop the hash - that's for identifying the id attribute.

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

Pickle uses different protocols to convert your data to a binary stream.

You must specify in python 3 a protocol lower than 3 in order to be able to load the data in python 2. You can specify the protocol parameter when invoking pickle.dump.

Firestore Getting documents id from collection

To obtain the id of the documents in a collection, you must use snapshotChanges()

    this.shirtCollection = afs.collection<Shirt>('shirts');
    // .snapshotChanges() returns a DocumentChangeAction[], which contains
    // a lot of information about "what happened" with each change. If you want to
    // get the data and the id use the map operator.
    this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Shirt;
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    });

Documentation https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example

Quick unix command to display specific lines in the middle of a file?

I'd first split the file into few smaller ones like this

$ split --lines=50000 /path/to/large/file /path/to/output/file/prefix

and then grep on the resulting files.

How do I generate sourcemaps when using babel and webpack?

If optimizing for dev + production, you could try something like this in your config:

const dev = process.env.NODE_ENV !== 'production'

// in config

{
  devtool: dev ? 'eval-cheap-module-source-map' : 'source-map',
}

From the docs:

  • devtool: "eval-cheap-module-source-map" offers SourceMaps that only maps lines (no column mappings) and are much faster
  • devtool: "source-map" cannot cache SourceMaps for modules and need to regenerate complete SourceMap for the chunk. It’s something for production.

I am using webpack 2.1.0-beta.19

How do you initialise a dynamic array in C++?

Maybe use std::fill_n()?

char* c = new char[length];
std::fill_n(c,length,0);

Nullable DateTime conversion

Make sure those two types are nullable DateTime

var lastPostDate = reader[3] == DBNull.Value ?
                                        null : 
                                   (DateTime?) Convert.ToDateTime(reader[3]);
  • Usage of DateTime? instead of Nullable<DateTime> is a time saver...
  • Use better indent of the ? expression like I did.

I have found this excellent explanations in Eric Lippert blog:

The specification for the ?: operator states the following:

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

  • If X and Y are the same type, then this is the type of the conditional expression.

  • Otherwise, if an implicit conversion exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

  • Otherwise, if an implicit conversion exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

  • Otherwise, no expression type can be determined, and a compile-time error occurs.

The compiler doesn't check what is the type that can "hold" those two types.

In this case:

  • null and DateTime aren't the same type.
  • null doesn't have an implicit conversion to DateTime
  • DateTime doesn't have an implicit conversion to null

So we end up with a compile-time error.

Best way to create a simple python web service

web.py is probably the simplest web framework out there. "Bare" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something.

"Hello, World!" according to web.py isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing for free:

import web

urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:        
    def GET(self, name):
        if not name: 
            name = 'world'
        return 'Hello, ' + name + '!'

if __name__ == "__main__":
    app.run()

Decode HTML entities in Python string?

This probably isnt relevant here. But to eliminate these html entites from an entire document, you can do something like this: (Assume document = page and please forgive the sloppy code, but if you have ideas as to how to make it better, Im all ears - Im new to this).

import re
import HTMLParser

regexp = "&.+?;" 
list_of_html = re.findall(regexp, page) #finds all html entites in page
for e in list_of_html:
    h = HTMLParser.HTMLParser()
    unescaped = h.unescape(e) #finds the unescaped value of the html entity
    page = page.replace(e, unescaped) #replaces html entity with unescaped value

Text overflow ellipsis on two lines

Not sure what your target is, but do you want the text to come on the second line?

Here is your jsFiddle: http://jsfiddle.net/8kvWX/4/ just removed the following:

     white-space:nowrap;  

Im not sure if this is what your are looking for or not.

Regards,

Mee

Google Maps v3 - limit viewable area and zoom level

myOptions = {
        center: myLatlng,
        minZoom: 6,
        maxZoom: 9,
        styles: customStyles,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

How do I set the background color of Excel cells using VBA?

It doesn't work if you use Function, but works if you Sub. However, you cannot call a sub from a cell using formula.

How to use MySQL dump from a remote machine

This topic shows up on the first page of my google result, so here's a little useful tip for new comers.

You could also dump the sql and gzip it in one line:

mysqldump -u [username] -p[password] [database_name] | gzip > [filename.sql.gz]

How to set HttpResponse timeout for Android in Java

If you're using the default http client, here's how to do it using the default http params:

HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 3000);

Original credit goes to http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/

Pointer arithmetic for void pointer in C

cast it to a char pointer an increment your pointer forward x bytes ahead.

input type=file show only button

Here is a simplified version of @ampersandre's popular solution that works in all major browsers. Asp.NET markup

<asp:TextBox runat="server" ID="FilePath" CssClass="form-control"
    style="float:left; display:inline; margin-right:5px; width:300px"
    ReadOnly="True" ClientIDMode="Static" />
<div class="inputWrapper">
    <div id="UploadFile" style="height:38px; font-size:16px; 
      text-align:center">Upload File</div>
    <div>
      <input name="FileUpload" id="FileInput" runat="server" 
             type="File" />
    </div>
  </div>
  <asp:Button ID="UploadButton" runat="server" 
    style="display:none" OnClick="UploadButton_Click" />
</div>
<asp:HiddenField ID="hdnFileName" runat="server" ClientIDMode="Static" />

JQuery Code

$(document).ready(function () {

   $('#UploadFile').click(function () {
       alert('UploadFile clicked');
       $('[id$="FileInput"]').trigger('click');
   });

   $('[id$="FileInput"]').change(function (event) {
       var target = event.target;
       var tmpFile = target.files[0].name;
       alert('FileInput changed:' + tmpFile);
       if (tmpFile.length > 0) {
          $('#hdnFileName').val(tmpFile);
       }
       $('[id$="UploadButton"]').trigger('click');
   });
});

css code

.inputWrapper {
height: 38px;
width: 102px;
overflow: hidden;
position: relative;
padding: 6px 6px;
cursor: pointer;
white-space:nowrap;
/*Using a background color, but you can use a background image to represent
 a button*/
background-color: #DEDEDE;
border: 1px solid gray;
border-radius: 4px;
-moz-user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
user-select: none;
}

Uses a hidden "UploadButton" click trigger for server postback with standard . The with "Upload File" text pushes the input control out of view in the wrapper div when it overflows so there is no need to apply any styles for the "file input" control div. The $([id$="FileInput"]) selector allows section of ids with standard ASP.NET prefixes applied. The FilePath textbox value in set from server code behind from hdnFileName.Value once file is uploaded.

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

At the end of the ~.profile file add::

export GOPATH="$HOME/go"
export PATH="$PATH:/usr/local/go/bin"
export PATH="$PATH:$GOPATH/bin"

"The import org.springframework cannot be resolved."

Right click project name in Eclipse, -->Maven-->Select Maven Profiles... Then tick the maven profile you want to set. After click OK, Eclipse will automatically import the maven setting to your project. If you check your project's Property, you will find Maven Dependencies Library has been added.

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

Building on Oded's answer, you could also set the default option but not make it a selectable option if it's just dummy text. For example you could do:

<option selected="selected" disabled="disabled">Select a language</option>

This would show "Select a language" before the user clicks the select box but the user wouldn't be able to select it because of the disabled attribute.

Merging multiple PDFs using iTextSharp in c#.net

Using iTextSharp.dll

protected void Page_Load(object sender, EventArgs e)
{
    String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
    MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
    if (System.IO.File.Exists(destinationFile))
        System.IO.File.Delete(destinationFile);

    string[] sSrcFile;
    sSrcFile = new string[2];

    string[] arr = new string[2];
    for (int i = 0; i <= sourceFiles.Length - 1; i++)
    {
        if (sourceFiles[i] != null)
        {
            if (sourceFiles[i].Trim() != "")
                arr[i] = sourceFiles[i].ToString();
        }
    }

    if (arr != null)
    {
        sSrcFile = new string[2];

        for (int ic = 0; ic <= arr.Length - 1; ic++)
        {
            sSrcFile[ic] = arr[ic].ToString();
        }
    }
    try
    {
        int f = 0;

        PdfReader reader = new PdfReader(sSrcFile[f]);
        int n = reader.NumberOfPages;
        Response.Write("There are " + n + " pages in the original file.");
        Document document = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

        document.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;

        int rotation;
        while (f < sSrcFile.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;

                document.SetPageSize(PageSize.A4);
                document.NewPage();
                page = writer.GetImportedPage(reader, i);

                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                Response.Write("\n Processed page " + i);
            }

            f++;
            if (f < sSrcFile.Length)
            {
                reader = new PdfReader(sSrcFile[f]);
                n = reader.NumberOfPages;
                Response.Write("There are " + n + " pages in the original file.");
            }
        }
        Response.Write("Success");
        document.Close();
    }
    catch (Exception e)
    {
        Response.Write(e.Message);
    }


}

gradlew: Permission Denied

Could also be fixed with

git update-index --chmod=+x gradlew

com.android.build.transform.api.TransformException

I changed a couple of pngs and the build number in the gradle and now I get this. No amount of cleaning and restarting helped. Disabling Instant Run fixed it for me. YMMV

Cleanest way to write retry logic?

Keep it simple with C# 6.0

public async Task<T> Retry<T>(Func<T> action, TimeSpan retryInterval, int retryCount)
{
    try
    {
        return action();
    }
    catch when (retryCount != 0)
    {
        await Task.Delay(retryInterval);
        return await Retry(action, retryInterval, --retryCount);
    }
}

Angular ForEach in Angular4/Typescript?

arrayData.forEach((key : any, val: any) => {
                        key['index'] = val + 1;

                        arrayData2.forEach((keys : any, vals :any) => {
                            if (key.group_id == keys.id) {
                                key.group_name = keys.group_name;
                            }
                        })
                    })

Converting Date and Time To Unix Timestamp

Seems like getTime is not function on above answer.

Date.parse(currentDate)/1000

Difference between $(this) and event.target?

Within an event handler function or object method, one way to access the properties of "the containing element" is to use the special this keyword. The this keyword represents the owner of the function or method currently being processed. So:

  • For a global function, this represents the window.

  • For an object method, this represents the object instance.

  • And in an event handler, this represents the element that received the event.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown() {
            alert(this);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown();alert(this);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object Window
object HTMLParagraphElement

An Event object is associated with all events. It has properties that provide information "about the event", such as the location of a mouse click in the web page.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown(event) {
            var theEvent = event ? event : window.event;
            var locString = "X = " + theEvent.screenX + " Y = " + theEvent.screenY;
            alert(event);
                    alert(locString);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown(event);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object MouseEvent
X = 982 Y = 329

Find records with a date field in the last 24 hours

There are so many ways to do this. The listed ones work great, but here's another way if you have a datetime field:

SELECT [fields] 
FROM [table] 
WHERE timediff(now(), my_datetime_field) < '24:00:00'

timediff() returns a time object, so don't make the mistake of comparing it to 86400 (number of seconds in a day), or your output will be all kinds of wrong.

Advantages of using display:inline-block vs float:left in CSS

While I agree that in general inline-block is better, there's one extra thing to take into account if you're using percentage widths to create a responsive grid (or if you want pixel-perfect widths):

If you're using inline-block for grids that total 100% or near to 100% width, you need to make sure your HTML markup contains no white space between columns.

With floats, this is not something you need to worry about - the columns float over any whitespace or other content between columns. This question's answers have some good tips on ways to remove HTML whitespace without making your code ugly.

If for any reason you can't control the HTML markup (e.g. a restrictive CMS), you can try the tricks described here, or you might need to compromise and use floats instead of inline-block. There are also ugly CSS tricks that should only be used in extreme circumstances, like font-size:0; on the column container then reapply font size within each column.

For example:

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

What does "exited with code 9009" mean during this build?

I think in my case there were russian symbols in path (all projects were in user folder). When I put solution in another folder (directly on disk), everything became ok.

How do you specify the Java compiler version in a pom.xml file?

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>(whatever version is current)</version>
        <configuration>
          <!-- or whatever version you use -->
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>

See the config page for the maven compiler plugin:

http://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html

Oh, and: don't use Java 1.3.x, current versions are Java 1.7.x or 1.8.x

nodejs - first argument must be a string or Buffer - when using response.write with http.request

The first argument must be one of type string or Buffer. Received type object

 at write_

I was getting like the above error while I passing body data to the request module.

I have passed another parameter that is JSON: true and its working.

var option={
url:"https://myfirstwebsite/v1/appdata",
json:true,
body:{name:'xyz',age:30},
headers://my credential
}
rp(option)
.then((res)=>{
res.send({response:res});})
.catch((error)=>{
res.send({response:error});})

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

What worked for me tho is this library https://pypi.org/project/silence-tensorflow/

Install this library and do as instructed on the page, it works like a charm!

MySQL Data Source not appearing in Visual Studio

Stuzor and hexcodes solution worked for me as well. However, if you do want the latest connector you have to download another product. From the oracle website:

Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).

What does axis in pandas mean?

I have been trying to figure out the axis for the last hour as well. The language in all the above answers, and also the documentation is not at all helpful.

To answer the question as I understand it now, in Pandas, axis = 1 or 0 means which axis headers do you want to keep constant when applying the function.

Note: When I say headers, I mean index names

Expanding your example:

+------------+---------+--------+
|            |  A      |  B     |
+------------+---------+---------
|      X     | 0.626386| 1.52325|
+------------+---------+--------+
|      Y     | 0.626386| 1.52325|
+------------+---------+--------+

For axis=1=columns : We keep columns headers constant and apply the mean function by changing data. To demonstrate, we keep the columns headers constant as:

+------------+---------+--------+
|            |  A      |  B     |

Now we populate one set of A and B values and then find the mean

|            | 0.626386| 1.52325|  

Then we populate next set of A and B values and find the mean

|            | 0.626386| 1.52325|

Similarly, for axis=rows, we keep row headers constant, and keep changing the data: To demonstrate, first fix the row headers:

+------------+
|      X     |
+------------+
|      Y     |
+------------+

Now populate first set of X and Y values and then find the mean

+------------+---------+
|      X     | 0.626386
+------------+---------+
|      Y     | 0.626386
+------------+---------+

Then populate the next set of X and Y values and then find the mean:

+------------+---------+
|      X     | 1.52325 |
+------------+---------+
|      Y     | 1.52325 |
+------------+---------+

In summary,

When axis=columns, you fix the column headers and change data, which will come from the different rows.

When axis=rows, you fix the row headers and change data, which will come from the different columns.

How to execute Table valued function

A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:

select * from FN('myFunc')

How can I start pagenumbers, where the first section occurs in LaTex?

You can also reset page number counter:

\setcounter{page}{1}

However, with this technique you get wrong page numbers in Acrobat in the top left page numbers field:

\maketitle: 1
\tableofcontents: 2
\setcounter{page}{1}
\section{Introduction}: 1
...

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

"This project is incompatible with the current version of Visual Studio"

I had this error and found it was due to the presence an 'Import' XML tag inside the .csproj.user file. Once I removed it, Visual Studio could open the project again.

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

Another possibile solution is

$sContent = htmlspecialchars($sHTML);
$oDom = new DOMDocument();
$oDom->loadHTML($sContent);
echo html_entity_decode($oDom->saveHTML());