Programs & Examples On #Jquery cycle

The jQuery Cycle Plugin is a slideshow plugin that supports many different types of transition effects. It is the predecessor of jQuery Cycle2 plugin, which is recommended for new projects.

How to get ID of clicked element with jQuery

You just need to remove the hash from the beginning:

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id').substring(1);
    $container.cycle(id); 
    return false; 
}); 

How to get selected path and name of the file opened with file dialog?

The code starts file search from root colon, If I want to start search from a specific directory, to avoid going to that directory every time, where I should put one. I did it like

Sub GetFilePath()
FileSelected = "G:\Audits\A2010"
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
FileSelected = .SelectedItems(1)
End With

ActiveSheet.Range("C14") = FileSelected
End Sub

But it could not start reach from "G:\Audits\A2010"

ASP.NET Web Api: The requested resource does not support http method 'GET'

My issue was as simple as having a null reference that didn't show up in the returned message, I had to debug my API to see it.

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

You can do this go to Settings > Storage, clicking on the setting menu icon in the top right hand corner and selecting "USB computer connection". I then changed the storage mode to "Camera (PTP)". Done try re installing the driver from device manager.

How to obtain the start time and end time of a day?

public static Date beginOfDay(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    return cal.getTime();
}

public static Date endOfDay(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 23);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.SECOND, 59);
    cal.set(Calendar.MILLISECOND, 999);

    return cal.getTime();
}

What does MissingManifestResourceException mean and how to fix it?

The solution given by BlaM worked for me too.

I am a VS 2013 User. After going through many fixes but no luck, I tried this:

  1. Right-click the resource file, one-by-one, in case of multiple-files.
  2. Make sure, the property "Build Action" is set to "Embedded Resource".

That's it! :)

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

Property getters and setters

You can customize the set value using property observer. To do this use 'didSet' instead of 'set'.

class Point {

var x: Int {
    didSet {
        x = x * 2
    }
}
...

As for getter ...

class Point {

var doubleX: Int {
    get {
        return x / 2
    }
}
...

Execute JavaScript code stored as a string

Use eval as below. Eval should be used with caution, a simple search about "eval is evil" should throw some pointers.

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    eval(s);
}

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

How to get bitmap from a url in android?

This should do the trick:

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
} // Author: silentnuke

Don't forget to add the internet permission in your manifest.

HTML table with horizontal scrolling (first column fixed)

How about:

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed; _x000D_
  width: 100%;_x000D_
  *margin-left: -100px; /*ie7*/_x000D_
}_x000D_
td, th {_x000D_
  vertical-align: top;_x000D_
  border-top: 1px solid #ccc;_x000D_
  padding: 10px;_x000D_
  width: 100px;_x000D_
}_x000D_
.fix {_x000D_
  position: absolute;_x000D_
  *position: relative; /*ie7*/_x000D_
  margin-left: -100px;_x000D_
  width: 100px;_x000D_
}_x000D_
.outer {_x000D_
  position: relative;_x000D_
}_x000D_
.inner {_x000D_
  overflow-x: scroll;_x000D_
  overflow-y: visible;_x000D_
  width: 400px; _x000D_
  margin-left: 100px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th class=fix></th>_x000D_
        <th>Col 1</th>_x000D_
        <th>Col 2</th>_x000D_
        <th>Col 3</th>_x000D_
        <th>Col 4</th>_x000D_
        <th class="fix">Col 5</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header A</th>_x000D_
        <td>col 1 - A</td>_x000D_
        <td>col 2 - A (WITH LONGER CONTENT)</td>_x000D_
        <td>col 3 - A</td>_x000D_
        <td>col 4 - A</td>_x000D_
        <td class=fix>col 5 - A</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header B</th>_x000D_
        <td>col 1 - B</td>_x000D_
        <td>col 2 - B</td>_x000D_
        <td>col 3 - B</td>_x000D_
        <td>col 4 - B</td>_x000D_
        <td class=fix>col 5 - B</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header C</th>_x000D_
        <td>col 1 - C</td>_x000D_
        <td>col 2 - C</td>_x000D_
        <td>col 3 - C</td>_x000D_
        <td>col 4 - C</td>_x000D_
        <td class=fix>col 5 - C</td>_x000D_
      </tr>_x000D_
    </table>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can test it out in this jsbin: http://jsbin.com/uxecel/4/edit

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

They are the same when used for output, e.g. with printf.

However, these are different when used as input specifier e.g. with scanf, where %d scans an integer as a signed decimal number, but %i defaults to decimal but also allows hexadecimal (if preceded by 0x) and octal (if preceded by 0).

So 033 would be 27 with %i but 33 with %d.

While loop to test if a file exists in bash

works with bash and sh both:

touch /tmp/testfile
sleep 10 && rm /tmp/testfile &
until ! [ -f /tmp/testfile ]
do
   echo "testfile still exist..."
   sleep 1
done
echo "now testfile is deleted.."

adding multiple entries to a HashMap at once in one statement

Maps have also had factory methods added in Java 9. For up to 10 entries Maps have overloaded constructors that take pairs of keys and values. For example we could build a map of various cities and their populations (according to google in October 2016) as follow:

Map<String, Integer> cities = Map.of("Brussels", 1_139000, "Cardiff", 341_000);

The var-args case for Map is a little bit harder, you need to have both keys and values, but in Java, methods can’t have two var-args parameters. So the general case is handled by taking a var-args method of Map.Entry<K, V> objects and adding a static entry() method that constructs them. For example:

Map<String, Integer> cities = Map.ofEntries(
    entry("Brussels", 1139000), 
    entry("Cardiff", 341000)
);

Collection Factory Methods in Java 9

Django DateField default options

Your mistake is using the datetime module instead of the date module. You meant to do this:

from datetime import date
date = models.DateField(_("Date"), default=date.today)

If you only want to capture the current date the proper way to handle this is to use the auto_now_add parameter:

date = models.DateField(_("Date"), auto_now_add=True)

However, the modelfield docs clearly state that auto_now_add and auto_now will always use the current date and are not a default value that you can override.

How can I show a hidden div when a select option is selected?

Check this code. It awesome code for hide div using select item.

HTML

<select name="name" id="cboOptions" onchange="showDiv('div',this)" class="form-control" >
    <option value="1">YES</option>
    <option value="2">NO</option>
</select>

<div id="div1" style="display:block;">
    <input type="text" id="customerName" class="form-control" placeholder="Type Customer Name...">
    <input type="text" style="margin-top: 3px;" id="customerAddress" class="form-control" placeholder="Type Customer Address...">
    <input type="text" style="margin-top: 3px;" id="customerMobile" class="form-control" placeholder="Type Customer Mobile...">
</div>
<div id="div2" style="display:none;">
    <input type="text" list="cars" id="customerID" class="form-control" placeholder="Type Customer Name...">
    <datalist id="cars">
        <option>Value 1</option>
        <option>Value 2</option>
        <option>Value 3</option>
        <option>Value 4</option>
    </datalist>
</div>

JS

<script>
    function showDiv(prefix,chooser) 
    {
            for(var i=0;i<chooser.options.length;i++) 
            {
                var div = document.getElementById(prefix+chooser.options[i].value);
                div.style.display = 'none';
            }

            var selectedOption = (chooser.options[chooser.selectedIndex].value);

            if(selectedOption == "1")
            {
                displayDiv(prefix,"1");
            }
            if(selectedOption == "2")
            {
                displayDiv(prefix,"2");
            }
    }

    function displayDiv(prefix,suffix) 
    {
            var div = document.getElementById(prefix+suffix);
            div.style.display = 'block';
    }
</script>

Javascript logical "!==" operator?

You can find === and !== operators in several other dynamically-typed languages as well. It always means that the two values are not only compared by their "implied" value (i.e. either or both values might get converted to make them comparable), but also by their original type.

That basically means that if 0 == "0" returns true, 0 === "0" will return false because you are comparing a number and a string. Similarly, while 0 != "0" returns false, 0 !== "0" returns true.

How to disable the ability to select in a DataGridView?

Use the DataGridView.ReadOnly property

The code in the MSDN example illustrates the use of this property in a DataGridView control intended primarily for display. In this example, the visual appearance of the control is customized in several ways and the control is configured for limited interactivity.

Observe these settings in the sample code:

// Set property values appropriate for read-only
// display and limited interactivity
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.ColumnHeadersHeightSizeMode = 
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersWidthSizeMode = 
DataGridViewRowHeadersWidthSizeMode.DisableResizing;

A formula to copy the values from a formula to another column

Copy the cell. Paste special as link. Will update with original. No formula though.

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

What does axis in pandas mean?

I think there is an another way to understand it.

For a np.array,if we want eliminate columns we use axis = 1; if we want eliminate rows, we use axis = 0.

np.mean(np.array(np.ones(shape=(3,5,10))),axis = 0).shape # (5,10)
np.mean(np.array(np.ones(shape=(3,5,10))),axis = 1).shape # (3,10)
np.mean(np.array(np.ones(shape=(3,5,10))),axis = (0,1)).shape # (10,)

For pandas object, axis = 0 stands for row-wise operation and axis = 1 stands for column-wise operation. This is different from numpy by definition, we can check definitions from numpy.doc and pandas.doc

How to know a Pod's own IP address from inside a container in the Pod?

The container's IP address should be properly configured inside of its network namespace, so any of the standard linux tools can get it. For example, try ifconfig, ip addr show, hostname -I, etc. from an attached shell within one of your containers to test it out.

Time comparison

Java doesn't (yet) have a good built-in Time class (it has one for JDBC queries, but that's not what you want).

One option would be use the JodaTime APIs and its LocalTime class.

Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date comparison functions to see if it is before or after some other time:

SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");

try {
    Date userDate = parser.parse(someOtherDate);
    if (userDate.after(ten) && userDate.before(eighteen)) {
        ...
    }
} catch (ParseException e) {
    // Invalid date was entered
}

Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:

Pattern p = Pattern.compile("(\d{2}):(\d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
    String hourString = m.group(1);
    String minuteString = m.group(2);
    int hour = Integer.parseInt(hourString);
    int minute = Integer.parseInt(minuteString);

    if (hour >= 10 && hour <= 18) {
        ...
    }
}

It really all depends on what you are trying to accomplish.

SQL Insert into table only if record doesn't exist

Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id and date.

ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);

Then when inserting a record add the condition when a conflict is encountered:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value

This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.

Get Hard disk serial Number

Here's some code that may help:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

string serial_number="";

foreach (ManagementObject wmi_HD in searcher.Get())
{
    serial_number = wmi_HD["SerialNumber"].ToString();
}

MessageBox.Show(serial_number);

How do you concatenate Lists in C#?

Take a look at my implementation. It's safe from null lists.

 IList<string> all= new List<string>();

 if (letterForm.SecretaryPhone!=null)// first list may be null
     all=all.Concat(letterForm.SecretaryPhone).ToList();

 if (letterForm.EmployeePhone != null)// second list may be null
     all= all.Concat(letterForm.EmployeePhone).ToList(); 

 if (letterForm.DepartmentManagerName != null) // this is not list (its just string variable) so wrap it inside list then concat it 
     all = all.Concat(new []{letterForm.DepartmentManagerPhone}).ToList();

Time complexity of Euclid's Algorithm

The suitable way to analyze an algorithm is by determining its worst case scenarios. Euclidean GCD's worst case occurs when Fibonacci Pairs are involved. void EGCD(fib[i], fib[i - 1]), where i > 0.

For instance, let's opt for the case where the dividend is 55, and the divisor is 34 (recall that we are still dealing with fibonacci numbers).

enter image description here

As you may notice, this operation costed 8 iterations (or recursive calls).

Let's try larger Fibonacci numbers, namely 121393 and 75025. We can notice here as well that it took 24 iterations (or recursive calls).

enter image description here

You can also notice that each iterations yields a Fibonacci number. That's why we have so many operations. We can't obtain similar results only with Fibonacci numbers indeed.

Hence, the time complexity is going to be represented by small Oh (upper bound), this time. The lower bound is intuitively Omega(1): case of 500 divided by 2, for instance.

Let's solve the recurrence relation:

enter image description here

We may say then that Euclidean GCD can make log(xy) operation at most.

Python variables as keys to dict

The globals() function returns a dictionary containing all your global variables.

>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> globals()
{'carrot': 3, 'apple': 1, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'banana': 'f'}

There is also a similar function called locals().

I realise this is probably not exactly what you want, but it may provide some insight into how Python provides access to your variables.

Edit: It sounds like your problem may be better solved by simply using a dictionary in the first place:

fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3

Ignore python multiple return value

One common convention is to use a "_" as a variable name for the elements of the tuple you wish to ignore. For instance:

def f():
    return 1, 2, 3

_, _, x = f()

Where to find htdocs in XAMPP Mac

Simply click in "Go To Application Folder" enter image description here

How to use "like" and "not like" in SQL MSAccess for the same field?

What I found out is that MS Access will reject --Not Like "BB*"-- if not enclosed in PARENTHESES, unlike --Like "BB*"-- which is ok without parentheses.

I tested these on MS Access 2010 and are all valid:

  1. Like "BB"

  2. (Like "BB")

  3. (Not Like "BB")

Angular JS Uncaught Error: [$injector:modulerr]

In development environments I recommend you to use not minified distributives. And all errors become more informative! Instead of angular.min.js, use angular.js.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.js">     
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js">

How to put a symbol above another in LaTeX?

Use \overset{above}{main} in math mode. In your case, \overset{a}{\#}.

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

How to access the ith column of a NumPy multidimensional array?

To get several and indepent columns, just:

> test[:,[0,2]]

you will get colums 0 and 2

How to read json file into java with simple JSON library

Sample Json

{
    "per_page": 3,
    "total": 12,
    "data": [{
            "last_name": "Bluth",
            "id": 1,
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
            "first_name": "George"
        },
        {
            "last_name": "Weaver",
            "id": 2,
            //"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
            "first_name": "Janet"
        },
        {
            "last_name": "Wong",
            "id": 3,
            //"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg",
            "first_name": "Emma"
        }
    ],
    "page": 1,
    "total_pages": 4
}

First If statement will convert the single data from the body Second if statement will differentiate the JsonArray object

public static String getvalueJpath(JSONObject responseJson, String Jpath ) {
        Object obj = responseJson;
        for(String s : Jpath.split("/"))
            if (s.isEmpty())
                if(!(s.contains("[") || s.contains("]")))
                    obj = ((JSONObject) obj).get(s);
                else
                    if(s.contains("[") || s.contains("]"))
                        obj = ((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("//[")[1].replaceAll("]", "")));

        return obj.toString();
    }
}

How to cancel an $http request in AngularJS?

This feature was added to the 1.1.5 release via a timeout parameter:

var canceler = $q.defer();
$http.get('/someUrl', {timeout: canceler.promise}).success(successCallback);
// later...
canceler.resolve();  // Aborts the $http request if it isn't finished.

What exactly is RESTful programming?

REST is an architectural style which is based on web-standards and the HTTP protocol (introduced in 2000).

In a REST based architecture, everything is a resource(Users, Orders, Comments). A resource is accessed via a common interface based on the HTTP standard methods(GET, PUT, PATCH, DELETE etc).

In a REST based architecture you have a REST server which provides access to the resources. A REST client can access and modify the REST resources.

Every resource should support the HTTP common operations. Resources are identified by global IDs (which are typically URIs).

REST allows that resources have different representations, e.g., text, XML, JSON etc. The REST client can ask for a specific representation via the HTTP protocol (content negotiation).

HTTP methods:

The PUT, GET, POST and DELETE methods are typical used in REST based architectures. The following table gives an explanation of these operations.

  • GET defines a reading access of the resource without side-effects. The resource is never changed via a GET request, e.g., the request has no side effects (idempotent).
  • PUT creates a new resource. It must also be idempotent.
  • DELETE removes the resources. The operations are idempotent. They can get repeated without leading to different results.
  • POST updates an existing resource or creates a new resource.

"Could not load type [Namespace].Global" causing me grief

I was befuddled by the same darn issue. I tried to remove and and the global.asax (closed VS2010 before adding). Cleaned the project/solution, checked for any changes in the web application configuration and other stuffs that had worked for other people here in SO threads. I finally cleaned the solution, deleted the bin/obj folders and stopped any running VS2010 development servers then I reverted all the changes back and found the application was running again. I redid the same things and now its working fine.

Happened again and this time this solution worked for me.

Rollback transaction after @Test

In addition to adding @Transactional on @Test method, you also need to add @Rollback(false)

How can a file be copied?

Function Copies
metadata
Copies
permissions
Uses file object Destination
may be directory
shutil.copy No Yes No Yes
shutil.copyfile No No No No
shutil.copy2 Yes Yes No Yes
shutil.copyfileobj No No Yes No

Eclipse: Enable autocomplete / content assist

I am not sure if this has to be explicitly enabled anywhere..but for this to work in the first place you need to include the javadoc jar files with the related jars in your project. Then when you do a Cntrl+Space it shows autocomplete and javadocs.

Use jQuery to scroll to the bottom of a div with lots of text

//note: use of stop function to prevent animation build-ups if called repeatedly
//subtracting container height brings scrollTo position to container bottom
scrollUp = function() {
    $("#scroller").stop().animate({ scrollTop: 0 }, "slow");
}

scrollDown = function() {
    var scroller = $('#scroller');
    var height = scroller[0].scrollHeight - $(scroller).height();

    $(scroller).stop().animate({ scrollTop: height }, "slow");
}

Filter items which array contains any of given values

There's also terms query which should save you some work. Here example from docs:

{
  "terms" : {
      "tags" : [ "blue", "pill" ],
      "minimum_should_match" : 1
  }
}

Under hood it constructs boolean should. So it's basically the same thing as above but shorter.

There's also a corresponding terms filter.

So to summarize your query could look like this:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "terms": {
        "tags": ["c", "d"]
      }
    }
  }
}

With greater number of tags this could make quite a difference in length.

how to select rows based on distinct values of A COLUMN only

Looking at your output maybe the following query can work, give it a try:

SELECT * FROM tablename
WHERE id IN
(SELECT MIN(id) FROM tablename GROUP BY EmailAddress)

This will select only one row for each distinct email address, the row with the minimum id which is what your result seems to portray

Make an HTTP request with android

UPDATE

This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:

Original Answer

First of all, request a permission to access network, add following to your manifest:

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

Then the easiest way is to use Apache http client bundled with Android:

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        String responseString = out.toString();
        out.close();
        //..more logic
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }

If you want it to run on separate thread I'd recommend extending AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }
    
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

You then can make a request by:

   new RequestTask().execute("http://stackoverflow.com");

Skip the headers when editing a csv file using Python

Doing row=1 won't change anything, because you'll just overwrite that with the results of the loop.

You want to do next(reader) to skip one row.

CSS rotate property in IE

There exists an on-line tool called IETransformsTranslator. With this tool you can make matrix filter transforms what works on IE6,IE7 & IE8. Just paste you CSS3 transform functions (e.g. rotate(15deg) ) and it will do the rest. http://www.useragentman.com/IETransformsTranslator/

Java : How to determine the correct charset encoding of a stream

You can certainly validate the file for a particular charset by decoding it with a CharsetDecoder and watching out for "malformed-input" or "unmappable-character" errors. Of course, this only tells you if a charset is wrong; it doesn't tell you if it is correct. For that, you need a basis of comparison to evaluate the decoded results, e.g. do you know beforehand if the characters are restricted to some subset, or whether the text adheres to some strict format? The bottom line is that charset detection is guesswork without any guarantees.

Android: How to overlay a bitmap and draw over a bitmap?

If the purpose is to obtain a bitmap, this is very simple:

Canvas canvas = new Canvas();
canvas.setBitmap(image);
canvas.drawBitmap(image2, new Matrix(), null);

In the end, image will contain the overlap of image and image2.

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

Change limit for "Mysql Row size too large"

I also encountered the same problem. I solve the problem by executing the following sql:

ALTER ${table} ROW_FORMAT=COMPRESSED;

But, I think u should know about the Row Storage.
There are two kinds of columns: variable-length column(such as VARCHAR, VARBINARY, and BLOB and TEXT types) and fixed-length column. They are stored in different types of pages.

Variable-length columns are an exception to this rule. Columns such as BLOB and VARCHAR that are too long to fit on a B-tree page are stored on separately allocated disk pages called overflow pages. We call such columns off-page columns. The values of these columns are stored in singly-linked lists of overflow pages, and each such column has its own list of one or more overflow pages. In some cases, all or a prefix of the long column value is stored in the B-tree, to avoid wasting storage and eliminating the need to read a separate page.

and when purpose of setting ROW_FORMAT is

When a table is created with ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED, InnoDB can store long variable-length column values (for VARCHAR, VARBINARY, and BLOB and TEXT types) fully off-page, with the clustered index record containing only a 20-byte pointer to the overflow page.

Wanna know more about DYNAMIC and COMPRESSED Row Formats

RestClientException: Could not extract response. no suitable HttpMessageConverter found

In my case @Ilya Dyoshin's solution didn't work: The mediatype "*" was not allowed. I fix this error by adding a new converter to the restTemplate this way during initialization of the MockRestServiceServer:

  MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = 
                      new MappingJackson2HttpMessageConverter();
  mappingJackson2HttpMessageConverter.setSupportedMediaTypes(
                                    Arrays.asList(
                                       MediaType.APPLICATION_JSON, 
                                       MediaType.APPLICATION_OCTET_STREAM));
  restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
  mockServer = MockRestServiceServer.createServer(restTemplate);

(Based on the solution proposed by Yashwant Chavan on the blog named technicalkeeda)

JN Gerbaux

How can I convert this foreach code to Parallel.ForEach?

For big file use the following code (you are less memory hungry)

Parallel.ForEach(File.ReadLines(txtProxyListPath.Text), line => {
    //Your stuff
});

How to test my servlet using JUnit

First off, in a real application, you would never get database connection info in a servlet; you would configure it in your app server.

There are ways, however, of testing Servlets without having a container running. One is to use mock objects. Spring provides a set of very useful mocks for things like HttpServletRequest, HttpServletResponse, HttpServletSession, etc:

http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/mock/web/package-summary.html

Using these mocks, you could test things like

What happens if username is not in the request?

What happens if username is in the request?

etc

You could then do stuff like:

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

public class MyServletTest {
    private MyServlet servlet;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;

    @Before
    public void setUp() {
        servlet = new MyServlet();
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    public void correctUsernameInRequest() throws ServletException, IOException {
        request.addParameter("username", "scott");
        request.addParameter("password", "tiger");

        servlet.doPost(request, response);

        assertEquals("text/html", response.getContentType());

        // ... etc
    }
}

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

python: How do I know what type of exception occurred?

Hope this will help a little more

import sys
varExcepHandling, varExcepHandlingZer = 2, 0
try:
  print(varExcepHandling/varExcepHandlingZer)
except Exception as ex: 
  print(sys.exc_info())

'sys.exc_info()' will return a tuple, if you only want the exception class name use 'sys.exc_info()[0]'

Note:- if you want to see all the exception classes just write dir(__builtin__)

How to filter a data frame

Another method utilizing the dplyr package:

library(dplyr)
df <- mtcars %>%
        filter(mpg > 25)

Without the chain (%>%) operator:

library(dplyr)
df <- filter(mtcars, mpg > 25)

Remove blue border from css custom-styled button in Chrome

Until all modern browsers will start support css-selector :focus-visible,
the simplest and possibly best way to save accessibility is to remove this tricky focus only for mouse users and to save it for keyboard users:

1.Use this tiny polyfill (about 10kb): https://github.com/WICG/focus-visible
2.Add next code somewhere in your css:

.js-focus-visible :focus:not(.focus-visible) {
  outline: none;
}

Browser-support of css4-selector :focus-visible right now very weak:
https://caniuse.com/#search=focus-visible

how to get the value of a textarea in jquery?

you should use val() instead of html()

var message = $('#message').val();

How to set minDate to current date in jQuery UI Datepicker?

Use this one :

 onSelect: function(dateText) {
                 $("input#DateTo").datepicker('option', 'minDate', dateText);
            }

This may be useful : http://jsfiddle.net/injulkarnilesh/xNeTe/

Finding an elements XPath using IE Developer tool

Are you trying to find some work around getting xpath in IE?

There are many add-ons for other browsers like xpather for Chrome or xpather, xpath-checker and firebug for FireFox that will give you the xpath of an element in a second. But sadly there is no add-on or tool available that will do this for IE. For most cases you can get the xpath of the elements that fall in your script using the above tools in Firefox and tweak them a little (if required) to make them work in IE.

But if you are testing an application that will work only in IE or the specific scenario or page that has this element will open-up/play-out only in IE then you cannot use any of the above mention tools to find the XPATH. Well the only thing that works in this case is the Bookmarklets that were coded just for this purpose. Bookmarklets are JavaScript code that you will add in IE as bookmarks and later use to get the XPATH of the element you desire. Using these you can get the XPATH as easily as you get using xpather or any other firefox addon.

STEPS TO INSTALL BOOKMARKLETS

1)Open IE

2)Type about:blank in the address bar and hit enter

3)From Favorites main menu select ---> Add favorites

4) In the Add a favorite popup window enter name GetXPATH1.

5)Click add button in the add a favorite popup window.

6)Open the Favorites menu and right click the newly added favorite and select properties option.

7)GetXPATH1 Properties will open up. Select the web Document Tab.

8)Enter the following in the URL field.

javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}

9)Click Ok. Click YES on the popup alert.

10)Add another favorite by following steps 3 to 5, Name this favorite GetXPATH2 (step4)

11)Repeat steps 6 and 7 for GetXPATH2 that you just created.

12)Enter the following in the URL field for GetXPATH2

javascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o__o();

13)Repeat Step 9.

You are all done!!

Now to get the XPATH of elements just select the element with your mouse. This would involve clicking the left mouse button just before the element (link, button, image, checkbox, text etc) begins and dragging it till the element ends. Once you do this first select the favorite GetXPATH1 from the favorites menu and then select the second favorite GetXPATH2. At this point you will get a confirmation, hit allow access button. Now open up a notepad file, right click and select paste option. This will give you the XPATH of the element you seek.

Format a message using MessageFormat.format() in Java

Using an apostrophe (Unicode: \u2019) instead of a single quote ' fixed the issue without doubling the \'.

Export SQL query data to Excel

For anyone coming here looking for how to do this in C#, I have tried the following method and had success in dotnet core 2.0.3 and entity framework core 2.0.3

First create your model class.

public class User
{  
    public string Name { get; set; }  
    public int Address { get; set; }  
    public int ZIP { get; set; }  
    public string Gender { get; set; }  
} 

Then install EPPlus Nuget package. (I used version 4.0.5, probably will work for other versions as well.)

Install-Package EPPlus -Version 4.0.5

The create ExcelExportHelper class, which will contain the logic to convert dataset to Excel rows. This class do not have dependencies with your model class or dataset.

public class ExcelExportHelper
    {
        public static string ExcelContentType
        {
            get
            { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
        }

        public static DataTable ListToDataTable<T>(List<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dataTable = new DataTable();

            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
            }

            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }

                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

        public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
        {

            byte[] result = null;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
                int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;

                if (showSrNo)
                {
                    DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
                    dataColumn.SetOrdinal(0);
                    int index = 1;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        item[0] = index;
                        index++;
                    }
                }


                // add the content into the Excel file  
                workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);

                // autofit width of cells with small content  
                int columnIndex = 1;
                foreach (DataColumn column in dataTable.Columns)
                {
                    int maxLength;
                    ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
                    try
                    {
                        maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
                    }
                    catch (Exception) //nishanc
                    {
                        maxLength = columnCells.Max(cell => (cell.Value +"").ToString().Length);
                    }

                    //workSheet.Column(columnIndex).AutoFit();
                    if (maxLength < 150)
                    {
                        //workSheet.Column(columnIndex).AutoFit();
                    }


                    columnIndex++;
                }

                // format header - bold, yellow on black  
                using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
                {
                    r.Style.Font.Color.SetColor(System.Drawing.Color.White);
                    r.Style.Font.Bold = true;
                    r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    r.Style.Fill.BackgroundColor.SetColor(Color.Brown);
                }

                // format cells - add borders  
                using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
                {
                    r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Right.Style = ExcelBorderStyle.Thin;

                    r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
                }

                // removed ignored columns  
                for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
                {
                    if (i == 0 && showSrNo)
                    {
                        continue;
                    }
                    if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
                    {
                        workSheet.DeleteColumn(i + 1);
                    }
                }

                if (!String.IsNullOrEmpty(heading))
                {
                    workSheet.Cells["A1"].Value = heading;
                   // workSheet.Cells["A1"].Style.Font.Size = 20;

                    workSheet.InsertColumn(1, 1);
                    workSheet.InsertRow(1, 1);
                    workSheet.Column(1).Width = 10;
                }

                result = package.GetAsByteArray();
            }

            return result;
        }

        public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
        {
            return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
        }
    }

Now add this method where you want to generate the excel file, probably for a method in the controller. You can pass parameters for your stored procedure as well. Note that the return type of the method is FileContentResult. Whatever query you execute, important thing is you must have the results in a List.

[HttpPost]
public async Task<FileContentResult> Create([Bind("Id,StartDate,EndDate")] GetReport getReport)
{
    DateTime startDate = getReport.StartDate;
    DateTime endDate = getReport.EndDate;

    // call the stored procedure and store dataset in a List.
    List<User> users = _context.Reports.FromSql("exec dbo.SP_GetEmpReport @start={0}, @end={1}", startDate, endDate).ToList();
    //set custome column names
    string[] columns = { "Name", "Address", "ZIP", "Gender"};
    byte[] filecontent = ExcelExportHelper.ExportExcel(users, "Users", true, columns);
    // set file name.
    return File(filecontent, ExcelExportHelper.ExcelContentType, "Report.xlsx"); 
}

More details can be found here

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

To return a different view, you can specify the name of the view you want to return and model as follows:

return View("ViewName", yourModel);

if the view is in different folder under Views folder then use below absolute path:

return View("~/Views/FolderName/ViewName.aspx");

How to "scan" a website (or page) for info, and bring it into my program?

Use a HTML parser like Jsoup. This has my preference above the other HTML parsers available in Java since it supports jQuery like CSS selectors. Also, its class representing a list of nodes, Elements, implements Iterable so that you can iterate over it in an enhanced for loop (so there's no need to hassle with verbose Node and NodeList like classes in the average Java DOM parser).

Here's a basic kickoff example (just put the latest Jsoup JAR file in classpath):

package com.stackoverflow.q2835505;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Test {

    public static void main(String[] args) throws Exception {
        String url = "https://stackoverflow.com/questions/2835505";
        Document document = Jsoup.connect(url).get();

        String question = document.select("#question .post-text").text();
        System.out.println("Question: " + question);

        Elements answerers = document.select("#answers .user-details a");
        for (Element answerer : answerers) {
            System.out.println("Answerer: " + answerer.text());
        }
    }

}

As you might have guessed, this prints your own question and the names of all answerers.

file_put_contents - failed to open stream: Permission denied

If you are pulling from git from local to server, you will need to clear cache sometimes because of the view files it gets uploaded with it / or other cached files .

php artisan cache:clear

Sometimes it might just to the trick if your application was working before the git pull

Standard Android menu icons, for example refresh

Maybe a bit late. Completing the other answers, you have the hdpi refresh icon in:

"android_sdk"\platforms\"android_api_level"\data\res\drawable-hdpi\ic_menu_refresh.png

How to "pull" from a local branch into another one?

What you are looking for is merging.

git merge master

With pull you fetch changes from a remote repository and merge them into the current branch.

Open multiple Projects/Folders in Visual Studio Code

you can create a workspace and put folders in that : File > save workspace as and drag and drop your folders in saved workspace

How do you specify a debugger program in Code::Blocks 12.11?

  1. Click on settings in top tool bar;

  2. Click on debugger;

  3. In tree, highlight "gdb/cdb debugger" by clicking it

  4. Click "create configuration"

  5. Add "gdb.exe" (no quotes) as a configuration

  6. Delete default configuration

  7. Click on gdb.exe that you created in the tree (it should be the only one) and a dialogue will appear to the right for "executable path" with a button to the right.

  8. Click on that button and it will bring up the file that codeblocks is installed in. Just keep clicking until you create the path to the gdb.exe (it sort of finds itself).

How to find NSDocumentDirectory in Swift?

Swift 3.0 and 4.0

Directly getting first element from an array will potentially cause exception if the path is not found. So calling first and then unwrap is the better solution

if let documentsPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
    //This gives you the string formed path
}

if let documentsPathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
    //This gives you the URL of the path
}

How to copy a file from remote server to local machine?

I would recommend to use sftp, use this command sftp -oPort=7777 user@host where -oPort is custom port number of ssh , in case if u changed it to 7777, then u can use -oPort, else if use only port 22 then plain sftp user@host which asks for the password , then u can log in, and u can navigate to required location using cd /home/user then a simple command get table u can download it, If u want to download a directory/folder get -r someDirectory will do it. If u want the file permissions also to exist then get -Pr someDirectory. For uploading on to remote change get to put in above commands.

jQuery to loop through elements with the same class

Without jQuery updated

_x000D_
_x000D_
document.querySelectorAll('.testimonial').forEach(function (element, index) {_x000D_
    element.innerHTML = 'Testimonial ' + (index + 1);_x000D_
});
_x000D_
<div class="testimonial"></div>_x000D_
<div class="testimonial"></div>
_x000D_
_x000D_
_x000D_

What is the difference between Python's list methods append and extend?

Append vs Extend

enter image description here

With append you can append a single element that will extend the list:

>>> a = [1,2]
>>> a.append(3)
>>> a
[1,2,3]

If you want to extend more than one element you should use extend, because you can only append one elment or one list of element:

>>> a.append([4,5])
>>> a
>>> [1,2,3,[4,5]]

So that you get a nested list

Instead with extend, you can extend a single element like this

>>> a = [1,2]
>>> a.extend([3])
>>> a
[1,2,3]

Or, differently, from append, extend more elements in one time without nesting the list into the original one (that's the reason of the name extend)

>>> a.extend([4,5,6])
>>> a
[1,2,3,4,5,6]

Adding one element with both methods

enter image description here

Both append and extend can add one element to the end of the list, though append is simpler.

append 1 element

>>> x = [1,2]
>>> x.append(3)
>>> x
[1,2,3]

extend one element

>>> x = [1,2]
>>> x.extend([3])
>>> x
[1,2,3]

Adding more elements... with different results

If you use append for more than one element, you have to pass a list of elements as arguments and you will obtain a NESTED list!

>>> x = [1,2]
>>> x.append([3,4])
>>> x
[1,2,[3,4]]

With extend, instead, you pass a list as an argument, but you will obtain a list with the new element that is not nested in the old one.

>>> z = [1,2] 
>>> z.extend([3,4])
>>> z
[1,2,3,4]

So, with more elements, you will use extend to get a list with more items. However, appending a list will not add more elements to the list, but one element that is a nested list as you can clearly see in the output of the code.

enter image description here

enter image description here

build failed with: ld: duplicate symbol _OBJC_CLASS_$_Algebra5FirstViewController

I had this same issue with a library, and I tried all of the answers listed here and nothing helped.

I ended up simply removing the library from Link Binary With Libraries and then re-adding it and it worked fine.

How to find the size of an int[]?

This method work when you are using a class: In this example you will receive a array, so the only method that worked for me was these one:

template <typename T, size_t n, size_t m>   
Matrix& operator= (T (&a)[n][m])
{   

    int arows = n;
    int acols = m;

    p = new double*[arows];

    for (register int r = 0; r < arows; r++)
    {
        p[r] = new double[acols];


        for (register int c = 0; c < acols; c++)
        {
            p[r][c] = a[r][c]; //A[rows][columns]
        }

}

https://www.geeksforgeeks.org/how-to-print-size-of-an-array-in-a-function-in-c/

How to get string objects instead of Unicode from JSON?

There's no built-in option to make the json module functions return byte strings instead of unicode strings. However, this short and simple recursive function will convert any decoded JSON object from using unicode strings to UTF-8-encoded byte strings:

def byteify(input):
    if isinstance(input, dict):
        return {byteify(key): byteify(value)
                for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

Just call this on the output you get from a json.load or json.loads call.

A couple of notes:

  • To support Python 2.6 or earlier, replace return {byteify(key): byteify(value) for key, value in input.iteritems()} with return dict([(byteify(key), byteify(value)) for key, value in input.iteritems()]), since dictionary comprehensions weren't supported until Python 2.7.
  • Since this answer recurses through the entire decoded object, it has a couple of undesirable performance characteristics that can be avoided with very careful use of the object_hook or object_pairs_hook parameters. Mirec Miskuf's answer is so far the only one that manages to pull this off correctly, although as a consequence, it's significantly more complicated than my approach.

How to trim whitespace from a Bash variable?

#!/bin/bash

function trim
{
    typeset trimVar
    eval trimVar="\${$1}"
    read trimVar << EOTtrim
    $trimVar
EOTtrim
    eval $1=\$trimVar
}

# Note that the parameter to the function is the NAME of the variable to trim, 
# not the variable contents.  However, the contents are trimmed.


# Example of use:
while read aLine
do
    trim aline
    echo "[${aline}]"
done < info.txt



# File info.txt contents:
# ------------------------------
# ok  hello there    $
#    another  line   here     $
#and yet another   $
#  only at the front$
#$



# Output:
#[ok  hello there]
#[another  line   here]
#[and yet another]
#[only at the front]
#[]

Bootstrap modal appearing under background

set the z-index .modal to a highest value

For example, .sidebarwrapper has z-index of 1100, so set the z-index of .modal to 1101

.modal {
    z-index: 1101;
}

How to skip a iteration/loop in while-loop

Try to add continue; where you want to skip 1 iteration.

Unlike the break keyword, continue does not terminate a loop. Rather, it skips to the next iteration of the loop, and stops executing any further statements in this iteration. This allows us to bypass the rest of the statements in the current sequence, without stopping the next iteration through the loop.

http://www.javacoffeebreak.com/articles/loopyjava/index.html

How to free memory in Java?

* "For example, say you'd declared a List at the beginning of a method which grew in size to be very large, but was only required until half-way through the method. You could at this point set the List reference to null to allow the garbage collector to potentially reclaim this object before the method completes (and the reference falls out of scope anyway)." *

This is correct, but this solution may not be generalizable. While setting a List object reference to null -will- make memory available for garbage collection, this is only true for a List object of primitive types. If the List object instead contains reference types, setting the List object = null will not dereference -any- of the reference types contained -in- the list. In this case, setting the List object = null will orphan the contained reference types whose objects will not be available for garbage collection unless the garbage collection algorithm is smart enough to determine that the objects have been orphaned.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

I used the content+wrapper approach ... but I did something different than mentioned so far: I made sure that my wrapper's boundaries did NOT line up with the content's boundaries in the direction that I wanted to be visible.

Important NOTE: It was easy enough to get the content+wrapper, same-bounds approach to work on one browser or another depending on various css combinations of position, overflow-*, etc ... but I never could use that approach to get them all correct (Edge, Chrome, Safari, ...).

But when I had something like:

  <div id="hack_wrapper" // created solely for this purpose
       style="position:absolute; width:100%; height:100%; overflow-x:hidden;">
      <div id="content_wrapper"
           style="position:absolute; width:100%; height:15%; overflow:visible;">         
          ... content with too-much horizontal content ... 
      </div>
  </div>

... all browsers were happy.

How to open .SQLite files

If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:

sqlite3 database.sqlite

Replace database.sqlite with your database file. Then, if the database is small enough, you can view the entire contents with:

sqlite> .dump

Or you can list the tables:

sqlite> .tables

Regular SQL works here as well:

sqlite> select * from some_table;

Replace some_table as appropriate.

Checking the form field values before submitting that page

You can simply make the start_date required using

<input type="submit" value="Submit" required />

You don't even need the checkform() then.

Thanks

iOS Detection of Screenshot?

I found the answer!! Taking a screenshot interrupts any touches that are on the screen. This is why snapchat requires holding to see the picture. Reference: http://tumblr.jeremyjohnstone.com/post/38503925370/how-to-detect-screenshots-on-ios-like-snapchat

How to find the foreach index?

I normally do this when working with associative arrays:

foreach ($assoc_array as $key => $value) {
 //do something
}

This will work fine with non-associative arrays too. $key will be the index value. If you prefer, you can do this too:

foreach ($array as $indx => $value) {
  //do something
}

How to compile for Windows on Linux with gcc/g++?

mingw32 exists as a package for Linux. You can cross-compile and -link Windows applications with it. There's a tutorial here at the Code::Blocks forum. Mind that the command changes to x86_64-w64-mingw32-gcc-win32, for example.

Ubuntu, for example, has MinGW in its repositories:

$ apt-cache search mingw
[...]
g++-mingw-w64 - GNU C++ compiler for MinGW-w64
gcc-mingw-w64 - GNU C compiler for MinGW-w64
mingw-w64 - Development environment targeting 32- and 64-bit Windows
[...]

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Gwerder's solution wont work because hash = hmac.read(); happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write statement is un-necessary in this example.

Instead do this:

var crypto    = require('crypto');
var hmac;
var algorithm = 'sha1';
var key       = 'abcdeg';
var text      = 'I love cupcakes';
var hash;

hmac = crypto.createHmac(algorithm, key);

// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');

// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
    hash = hmac.read();
    //...do something with the hash...
});

More formally, if you wish, the line

hmac.end(text, function () {

could be written

hmac.end(text, 'utf8', function () {

because in this example text is a utf string

Creating a BAT file for python script

ECHO OFF
set SCRIPT_DRIVE = %1
set SCRIPT_DIRECTORY = %2
%SCRIPT_DRIVE%
cd %SCRIPT_DRIVE%%SCRIPT_DIRECTORY%
python yourscript.py`

Field 'id' doesn't have a default value?

Since mysql 5.6, there is a new default that makes sure you are explicitly inserting every field that doesn't have a default value set in the table definition.

to disable and test this: see this answer here: mysql error 1364 Field doesn't have a default values

I would recommend you test without it, then reenable it and make sure all your tables have default values for fields you are not explicitly passing in every INSERT query.

If a third party mysql viewer is giving this error, you are probably limited to the fix in that link.

Selenium WebDriver How to Resolve Stale Element Reference Exception?

Use webdriverwait with ExpectedCondition in try catch block with for loop EX: for python

for i in range(4):
    try:
        element = WebDriverWait(driver, 120).until( \
                EC.presence_of_element_located((By.XPATH, 'xpath')))
        element.click()    
        break
    except StaleElementReferenceException:
        print "exception "

AttributeError: 'module' object has no attribute 'urlopen'

Change TWO lines:

import urllib.request #line1

#Replace
urllib.urlopen("http://www.python.org")
#To
urllib.request.urlopen("http://www.python.org") #line2

If You got ERROR 403: Forbidden Error exception try this:

siteurl = "http://www.python.org"

req = urllib.request.Request(siteurl, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36'})
pageHTML = urllib.request.urlopen(req).read()

I hope your problem resolved.

SQL: Two select statements in one query

You can union the queries as long as the columns match.

SELECT name,
       games,
       goals
FROM   tblMadrid
WHERE  id = 1
UNION ALL
SELECT name,
       games,
       goals
FROM   tblBarcelona
WHERE  id = 2 

Watch multiple $scope attributes

A slightly safer solution to combine values might be to use the following as your $watch function:

function() { return angular.toJson([item1, item2]) }

or

$scope.$watch(
  function() {
    return angular.toJson([item1, item2]);
  },
  function() {
    // Stuff to do after either value changes
  });

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

How to replace master branch in Git, entirely, from another branch?

You should be able to use the "ours" merge strategy to overwrite master with seotweaks like this:

git checkout seotweaks
git merge -s ours master
git checkout master
git merge seotweaks

The result should be your master is now essentially seotweaks.

(-s ours is short for --strategy=ours)

From the docs about the 'ours' strategy:

This resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches. It is meant to be used to supersede old development history of side branches. Note that this is different from the -Xours option to the recursive merge strategy.

Update from comments: If you get fatal: refusing to merge unrelated histories, then change the second line to this: git merge --allow-unrelated-histories -s ours master

Need a good hex editor for Linux

I am a VIMer. I can do some rare Hex edits with:

  • :%!xxd to switch into hex mode

  • :%!xxd -r to exit from hex mode

But I strongly recommend ht

apt-cache show ht

Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>

Homepage: http://hte.sourceforge.net/

Note: The package is called ht, whereas the executable is named hte after the package was installed.

  1. Supported file formats
    • common object file format (COFF/XCOFF32)
    • executable and linkable format (ELF)
    • linear executables (LE)
    • standard DO$ executables (MZ)
    • new executables (NE)
    • portable executables (PE32/PE64)
    • java class files (CLASS)
    • Mach exe/link format (MachO)
    • X-Box executable (XBE)
    • Flat (FLT)
    • PowerPC executable format (PEF)
  2. Code & Data Analyser
    • finds branch sources and destinations recursively
    • finds procedure entries
    • creates labels based on this information
    • creates xref information
    • allows to interactively analyse unexplored code
    • allows to create/rename/delete labels
    • allows to create/edit comments
    • supports x86, ia64, alpha, ppc and java code
  3. Target systems
    • DJGPP
    • GNU/Linux
    • FreeBSD
    • OpenBSD
    • Win32

No function matches the given name and argument types

In my particular case the function was actually missing. The error message is the same. I am using the Postgresql plugin PostGIS and I had to reinstall that for whatever reason.

Is there an easy way to check the .NET Framework version?

I tried to combine all the answers into a single whole.

Using:

NetFrameworkUtilities.GetVersion() will return the currently available Version of the .NET Framework at this time or null if it is not present.

This example works in .NET Framework versions 3.5+. It does not require administrator rights.

I want to note that you can check the version using the operators < and > like this:

var version = NetFrameworkUtilities.GetVersion();
if (version != null && version < new Version(4, 5))
{
    MessageBox.Show("Your .NET Framework version is less than 4.5");
}

Code:

using System;
using System.Linq;
using Microsoft.Win32;

namespace Utilities
{
    public static class NetFrameworkUtilities
    {
        public static Version GetVersion() => GetVersionHigher4() ?? GetVersionLowerOr4();

        private static Version GetVersionLowerOr4()
        {
            using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP"))
            {
                var names = key?.GetSubKeyNames();

                //version names start with 'v', eg, 'v3.5' which needs to be trimmed off before conversion
                var text = names?.LastOrDefault()?.Remove(0, 1);
                if (string.IsNullOrEmpty(text))
                {
                    return null;
                }

                return text.Contains('.')
                    ? new Version(text)
                    : new Version(Convert.ToInt32(text), 0);
            }
        }

        private static Version GetVersionHigher4()
        {
            using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"))
            {
                var value = key?.GetValue("Release");
                if (value == null)
                {
                    return null;
                }

                // Checking the version using >= will enable forward compatibility,  
                // however you should always compile your code on newer versions of 
                // the framework to ensure your app works the same. 
                var releaseKey = Convert.ToInt32(value);
                if (releaseKey >= 461308) return new Version(4, 7, 1);
                if (releaseKey >= 460798) return new Version(4, 7);
                if (releaseKey >= 394747) return new Version(4, 6, 2);
                if (releaseKey >= 394254) return new Version(4, 6, 1);
                if (releaseKey >= 381029) return new Version(4, 6);
                if (releaseKey >= 379893) return new Version(4, 5, 2);
                if (releaseKey >= 378675) return new Version(4, 5, 1);
                if (releaseKey >= 378389) return new Version(4, 5);

                // This line should never execute. A non-null release key should mean 
                // that 4.5 or later is installed. 
                return new Version(4, 5);
            }
        }
    }
}

How to start new activity on button click

When button is clicked:

loginBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent= new Intent(getApplicationContext(), NextActivity.class);
        intent.putExtra("data", value); //pass data
        startActivity(intent);
    }
});

To received the extra data from NextActivity.class :

Bundle extra = getIntent().getExtras();
if (extra != null){
    String str = (String) extra.get("data"); // get a object
}

What is Join() in jQuery?

The practical use of this construct? It is a javascript replaceAll() on strings.

var s = 'stackoverflow_is_cool';  
s = s.split('_').join(' ');  
console.log(s);

will output:

stackoverflow is cool

GridView Hide Column by code

What most answers here don't explain is - what if you need to make columns visible again and invisible, all based on data dynamically? After all, shouldn't GridViews be data centric?

What if you want to turn ON or OFF columns based on your data?

My Gridview

<asp:GridView ID="gvLocationBoard" runat="server" AllowPaging="True" AllowSorting="True" ShowFooter="false" ShowHeader="true" Visible="true" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" GridLines="None"
            DataSourceID="sdsLocationBoard" OnDataBound="gvLocationBoard_DataBound" OnRowDataBound="gvLocationBoard_RowDataBound" PageSize="15" OnPreRender="gvLocationBoard_PreRender">
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <Columns>
                <asp:TemplateField HeaderText="StudentID" SortExpression="StudentID" Visible="False">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Student" SortExpression="StudentName">
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Eval("StudentName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Status" SortExpression="CheckStatusName" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:HiddenField ID="hfStatusID" runat="server" Value='<%# Eval("CheckStatusID") %>' />
                        <asp:Label ID="Label4" runat="server" Text='<%# Eval("CheckStatusName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="RollCallPeriod0" Visible="False">
                    <ItemTemplate>
                        <asp:CheckBox ID="cbRollCallPeriod0" runat="server" />
                        <asp:HiddenField ID="hfRollCallPeriod0" runat="server" Value='<%# Eval("RollCallPeriod") %>' />
                    </ItemTemplate>
                    <HeaderStyle Font-Size="Small" />
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="RollCallPeriod1" Visible="False">
                    <ItemTemplate>
                        <asp:CheckBox ID="cbRollCallPeriod1" runat="server" />
                        <asp:HiddenField ID="hfRollCallPeriod1" runat="server" Value='<%# Eval("RollCallPeriod") %>' />
                    </ItemTemplate>
                    <HeaderStyle Font-Size="Small" />
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
        ..
etc..

Note the `"RollCallPeriodn", where 'n' is a sequential number.

The way I do it, is to by design hide all columns that I know are going to be ON (visible="true") or OFF (visible="false") later, and depending on my data.

In my case I want to display Period Times up to a certain column. So for example, if today is 9am then I want to show periods 6am, 7am, 8am and 9am, but not 10am, 11am, etc.

On other days I want to show ALL the times. And so on.

So how do we do this?

Why not use PreRender to "reset" the Gridview?

protected void gvLocationBoard_PreRender(object sender, EventArgs e)
{
    GridView gv = (GridView)sender;
    int wsPos = 3;
    for (int wsCol = 0; wsCol < 19; wsCol++)
    {
        gv.Columns[wsCol + wsPos].HeaderText = "RollCallPeriod" + wsCol.ToString("{0,00}");
        gv.Columns[wsCol + wsPos].Visible = false;
    }
}

Now turn ON the columns you need based on finding the Start of the HeaderText and make the column visible if the header text is not the default.

  protected void gvLocationBoard_DataBound(object sender, EventArgs e)
    {
        //Show the headers for the Period Times directly from sdsRollCallPeriods
        DataSourceSelectArguments dss = new DataSourceSelectArguments();
        DataView dv = sdsRollCallPeriods.Select(dss) as DataView;
        DataTable dt = dv.ToTable() as DataTable;
        if (dt != null)
        {
            int wsPos = 0;
            int wsCol = 3;  //start of PeriodTimes column in gvLocationBoard
            foreach (DataRow dr in dt.Rows)
            {
                gvLocationBoard.Columns[wsCol + wsPos].HeaderText = dr.ItemArray[1].ToString();
                gvLocationBoard.Columns[wsCol + wsPos].Visible = !gvLocationBoard.Columns[wsCol + wsPos].HeaderText.StartsWith("RollCallPeriod");

                wsPos += 1;
            }
        }
    }

I won't reveal the SqlDataSource here, but suffice to say with the PreRender, I can reset my GridView and turn ON the columns I want with the headers I want.

So the way it works is that everytime you select a different date or time periods to display as headers, it resets the GridView to the default header text and Visible="false" status before it builds the gridview again. Otherwise, without the PreRender, the GridView will have the previous data's headers as the code behind wipes the default settings.

String concatenation in MySQL

MySQL is different from most DBMSs use of + or || for concatenation. It uses the CONCAT function:

SELECT CONCAT(first_name, " ", last_name) AS Name FROM test.student

As @eggyal pointed out in comments, you can enable string concatenation with the || operator in MySQL by setting the PIPES_AS_CONCAT SQL mode.

Bootstrap 3 grid with no gap

You'd need to override the negative margins from the .row in large screens either directly or with a custom class

@media (min-width: 768px){
    .row {
        margin-right: 0;
        margin-left: 0;
    }
}

Updated fiddle

Validate phone number using angular js

You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.

_x000D_
_x000D_
function form($scope){_x000D_
    $scope.onSubmit = function(){_x000D_
        alert("form submitted");_x000D_
    }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>_x000D_
<div ng-app ng-controller="form">_x000D_
<form name="myForm" ng-submit="onSubmit()">_x000D_
    <input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>_x000D_
    <span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>_x000D_
    <input type="submit" value="submit"/>_x000D_
</form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I work with a git repository within another repository?

If I understand your problem well you want the following things:

  1. Have your media files stored in one single git repository, which is used by many projects
  2. If you modify a media file in any of the projects in your local machine, it should immediately appear in every other project (so you don't want to commit+push+pull all the time)

Unfortunately there is no ultimate solution for what you want, but there are some things by which you can make your life easier.

First you should decide one important thing: do you want to store for every version in your project repository a reference to the version of the media files? So for example if you have a project called example.com, do you need know which style.css it used 2 weeks ago, or the latest is always (or mostly) the best?

If you don't need to know that, the solution is easy:

  1. create a repository for the media files and one for each project
  2. create a symbolic link in your projects which point to the locally cloned media repository. You can either create a relative symbolic link (e.g. ../media) and assume that everybody will checkout the project so that the media directory is in the same place, or write the name of the symbolic link into .gitignore, and everybody can decide where he/she puts the media files.

In most of the cases, however, you want to know this versioning information. In this case you have two choices:

  1. Store every project in one big repository. The advantage of this solution is that you will have only 1 copy of the media repository. The big disadvantage is that it is much harder to switch between project versions (if you checkout to a different version you will always modify ALL projects)

  2. Use submodules (as explained in answer 1). This way you will store the media files in one repository, and the projects will contain only a reference to a specific media repo version. But this way you will normally have many local copies of the media repository, and you cannot easily modify a media file in all projects.

If I were you I would probably choose the first or third solution (symbolic links or submodules). If you choose to use submodules you can still do a lot of things to make your life easier:

  1. Before committing you can rename the submodule directory and put a symlink to a common media directory. When you're ready to commit, you can remove the symlink and remove the submodule back, and then commit.

  2. You can add one of your copy of the media repository as a remote repository to all of your projects.

You can add local directories as a remote this way:

cd /my/project2/media
git remote add project1 /my/project1/media

If you modify a file in /my/project1/media, you can commit it and pull it from /my/project2/media without pushing it to a remote server:

cd /my/project1/media
git commit -a -m "message"
cd /my/project2/media
git pull project1 master

You are free to remove these commits later (with git reset) because you haven't shared them with other users.

Get host domain from URL?

Try this

Console.WriteLine(GetDomain.GetDomainFromUrl("http://support.domain.com/default.aspx?id=12345"));

It will output support.domain.com

Or try

Uri.GetLeftPart( UriPartial.Authority )

var functionName = function() {} vs function functionName() {}

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:

_x000D_
_x000D_
// TypeError: functionOne is not a function_x000D_
functionOne();_x000D_
_x000D_
var functionOne = function() {_x000D_
  console.log("Hello!");_x000D_
};
_x000D_
_x000D_
_x000D_

And, a function declaration:

_x000D_
_x000D_
// Outputs: "Hello!"_x000D_
functionTwo();_x000D_
_x000D_
function functionTwo() {_x000D_
  console.log("Hello!");_x000D_
}
_x000D_
_x000D_
_x000D_

Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.

_x000D_
_x000D_
'use strict';    _x000D_
{ // note this block!_x000D_
  function functionThree() {_x000D_
    console.log("Hello!");_x000D_
  }_x000D_
}_x000D_
functionThree(); // ReferenceError
_x000D_
_x000D_
_x000D_

How To Create Table with Identity Column

[id] [int] IDENTITY(1,1) NOT NULL,

of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.

enter image description here

How do I find out what all symbols are exported from a shared object?

Usually, you would also have a header file that you include in your code to access the symbols.

How to add some non-standard font to a website?

This could be done via CSS:

<style type="text/css">
@font-face {
    font-family: "My Custom Font";
    src: url(http://www.example.org/mycustomfont.ttf) format("truetype");
}
p.customfont { 
    font-family: "My Custom Font", Verdana, Tahoma;
}
</style>
<p class="customfont">Hello world!</p>

It is supported for all of the regular browsers if you use TrueType-Fonts (TTF), the Web Open Font Format (WOFF) or Embedded Opentype (EOT).

JavaScript to scroll long page to DIV

Answer posted here - same solution to your problem.

Edit: the JQuery answer is very nice if you want a smooth scroll - I hadn't seen that in action before.

The transaction manager has disabled its support for remote/network transactions

I had the same error message. For me changing pooling=False to ;pooling=true;Max Pool Size=200 in the connection string fixed the problem.

How do I deploy Node.js applications as a single executable file?

JXcore will allow you to turn any nodejs application into a single executable, including all dependencies, in either Windows, Linux, or Mac OS X.

Here is a link to the installer: https://github.com/jxcore/jxcore-release

And here is a link to how to set it up: http://jxcore.com/turn-node-applications-into-executables/

It is very easy to use and I have tested it in both Windows 8.1 and Ubuntu 14.04.

FYI: JXcore is a fork of NodeJS so it is 100% NodeJS compatible, with some extra features.

Log record changes in SQL server in an audit table

I know this is old, but maybe this will help someone else.

Do not log "new" values. Your existing table, GUESTS, has the new values. You'll have double entry of data, plus your DB size will grow way too fast that way.

I cleaned this up and minimized it for this example, but here is the tables you'd need for logging off changes:

CREATE TABLE GUESTS (
      GuestID INT IDENTITY(1,1) PRIMARY KEY, 
      GuestName VARCHAR(50), 
      ModifiedBy INT, 
      ModifiedOn DATETIME
)

CREATE TABLE GUESTS_LOG (
      GuestLogID INT IDENTITY(1,1) PRIMARY KEY, 
      GuestID INT, 
      GuestName VARCHAR(50), 
      ModifiedBy INT, 
      ModifiedOn DATETIME
)

When a value changes in the GUESTS table (ex: Guest name), simply log off that entire row of data, as-is, to your Log/Audit table using the Trigger. Your GUESTS table has current data, the Log/Audit table has the old data.

Then use a select statement to get data from both tables:

SELECT 0 AS 'GuestLogID', GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS] WHERE GuestID = 1
UNION
SELECT GuestLogID, GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS_LOG] WHERE GuestID = 1
ORDER BY ModifiedOn ASC

Your data will come out with what the table looked like, from Oldest to Newest, with the first row being what was created & the last row being the current data. You can see exactly what changed, who changed it, and when they changed it.

Optionally, I used to have a function that looped through the RecordSet (in Classic ASP), and only displayed what values had changed on the web page. It made for a GREAT audit trail so that users could see what had changed over time.

Split string into array of characters?

Safest & simplest is to just loop;

Dim buff() As String
ReDim buff(Len(my_string) - 1)
For i = 1 To Len(my_string)
    buff(i - 1) = Mid$(my_string, i, 1)
Next

If your guaranteed to use ansi characters only you can;

Dim buff() As String
buff = Split(StrConv(my_string, vbUnicode), Chr$(0))
ReDim Preserve buff(UBound(buff) - 1)

How do I include a file over 2 directories back?

../../../includes/boot.inc.php

Each instance of ../ means up/back one directory.

How to generate serial version UID in Intellij

Without any plugins:

You just need to enable highlight: (Idea v.2016, 2017 and 2018, previous versions may have same or similar settings)

File -> Settings -> Editor -> Inspections -> Java -> Serialization issues -> Serializable class without 'serialVersionUID' - set flag and click 'OK'. (For Macs, Settings is under IntelliJ IDEA -> Preferences...)

Now, if your class implements Serializable, you will see highlight and alt+Enter on class name will ask you to generate private static final long serialVersionUID.

UPD: a faster way to find this setting - you might use hotkey Ctrl+Shift+A (find action), type Serializable class without 'serialVersionUID' - the first is the one.

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

I've got solved my problem this way in EF on list of records from db

ListOfObjectToBeOrder.OrderBy(x => x.columnName).ToList();

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

As long as the server allows the ampresand character to be POSTed (not all do as it can be unsafe), all you should have to do is URL Encode the character. In the case of an ampresand, you should replace the character with %26.

.NET provides a nice way of encoding the entire string for you though:

string strNew = "&uploadfile=true&file=" + HttpUtility.UrlEncode(iCalStr);

How to turn off Wifi via ADB?

  1. go to location android/android-sdk/platform-tools
  2. shift+right click
  3. open cmd here and type the following commands

    1. adb shell
    2. su
    3. svc wifi enable/disable
  4. done!!!!!

Convert double to Int, rounded down

If the double is a Double with capital D (a boxed primitive value):

Double d = 4.97542;
int i = (int) d.doubleValue();

// or directly:
int i2 = d.intValue();

If the double is already a primitive double, then you simply cast it:

double d = 4.97542;
int i = (int) d;

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

The following simple steps help me:

First, initialize the repository to work with Git, so that any file changes are tracked:

git init

Then, check that the remote repository that you want to associate with the alias origin exists, if not create it in git first.

$ git ls-remote https://github.com/repo-owner/repo-name.git/

If it exists, associate it with the remote "origin":

git remote add origin https://github.com:/repo-owner/repo-name.git

and check to which URL, the remote "origin" belongs to by using git remote -v:

$ git remote -v
origin  https://github.com:/repo-owner/repo-name.git (fetch)
origin  https://github.com:/repo-owner/repo-name.git (push)

Next, verify if your origin is properly aliased as follows:

$ cat ./.git/config
:
[remote "origin"]
        url = https://github.com:/repo-owner/repo-name.git
        fetch = +refs/heads/*:refs/remotes/origin/*
:

You need to see this section [remote "origin"]. You can consider to use GitHub Desktop available for both Windows and MacOS, which help me to automatically populate the missing section/s in ~./git/config file OR you can manually add it, not great, but hey it works!

[Optional]
You might also want to change the origin alias to make it more intuitive, especially if you are working with multiple origin:

git remote rename origin mynewalias

or even remove it:

git remote rm origin

Finally, on your first push, if you want master in that repository to be your default upstream. you may want to add the -u parameter

git add .
git commit -m 'First commit'
git push -u origin master

How can I get file extensions with JavaScript?

var file = "hello.txt";
var ext = (function(file, lio) { 
  return lio === -1 ? undefined : file.substring(lio+1); 
})(file, file.lastIndexOf("."));

// hello.txt -> txt
// hello.dolly.txt -> txt
// hello -> undefined
// .hello -> hello

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

How to have an automatic timestamp in SQLite?

To complement answers above...

If you are using EF, adorn the property with Data Annotation [Timestamp], then go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:

modelBuilder.Entity<YourEntity>()
                .Property(b => b.Timestamp)
                .ValueGeneratedOnAddOrUpdate()
                .IsConcurrencyToken()
                .ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");

It will make a default value to every data that will be insert into this table.

How can I convert String to Int?

Be careful when using Convert.ToInt32() on a char! It will return the UTF-16 code of the character!

If you access the string only in a certain position using the [i] indexing operator, it will return a char and not a string!

String input = "123678";
                    ^
                    |
int indexOfSeven =  4;

int x = Convert.ToInt32(input[indexOfSeven]);             // Returns 55

int x = Convert.ToInt32(input[indexOfSeven].toString());  // Returns 7

SMTP connect() failed PHPmailer - PHP

 $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

How do I generate a stream from a string?

Another solution:

public static MemoryStream GenerateStreamFromString(string value)
{
    return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}

535-5.7.8 Username and Password not accepted

I had the same problem. Now its working fine after doing below changes.

https://www.google.com/settings/security/lesssecureapps

You should change the "Access for less secure apps" to Enabled (it was enabled, I changed to disabled and than back to enabled). After a while I could send email.

PHP Curl UTF-8 Charset

$output = curl_exec($ch);
$result = iconv("Windows-1251", "UTF-8", $output);

PostgreSQL Autoincrement

If you want to add sequence to id in the table which already exist you can use:

CREATE SEQUENCE user_id_seq;
ALTER TABLE user ALTER user_id SET DEFAULT NEXTVAL('user_id_seq');

How to convert a date String to a Date or Calendar object?

tl;dr

LocalDate.parse( "2015-01-02" )

java.time

Java 8 and later has a new java.time framework that makes these other answers outmoded. This framework is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See the Tutorial.

The old bundled classes, java.util.Date/.Calendar, are notoriously troublesome and confusing. Avoid them.

LocalDate

Like Joda-Time, java.time has a class LocalDate to represent a date-only value without time-of-day and without time zone.

ISO 8601

If your input string is in the standard ISO 8601 format of yyyy-MM-dd, you can ask that class to directly parse the string with no need to specify a formatter.

The ISO 8601 formats are used by default in java.time, for both parsing and generating string representations of date-time values.

LocalDate localDate = LocalDate.parse( "2015-01-02" );

Formatter

If you have a different format, specify a formatter from the java.time.format package. You can either specify your own formatting pattern or let java.time automatically localize as appropriate to a Locale specifying a human language for translation and cultural norms for deciding issues such as period versus comma.

Formatting pattern

Read the DateTimeFormatter class doc for details on the codes used in the format pattern. They vary a bit from the old outmoded java.text.SimpleDateFormat class patterns.

Note how the second argument to the parse method is a method reference, syntax added to Java 8 and later.

String input = "January 2, 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "MMMM d, yyyy" , Locale.US );
LocalDate localDate = LocalDate.parse ( input , formatter );

Dump to console.

System.out.println ( "localDate: " + localDate );

localDate: 2015-01-02

Localize automatically

Or rather than specify a formatting pattern, let java.time localize for you. Call DateTimeFormatter.ofLocalizedDate, and be sure to specify the desired/expected Locale rather than rely on the JVM’s current default which can change at any moment during runtime(!).

String input = "January 2, 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG );
formatter = formatter.withLocale ( Locale.US );
LocalDate localDate = LocalDate.parse ( input , formatter );

Dump to console.

System.out.println ( "input: " + input + " | localDate: " + localDate );

input: January 2, 2015 | localDate: 2015-01-02

set the width of select2 input (through Angular-ui directive)

With > 4.0 of select2 I am using

$("select").select2({
  dropdownAutoWidth: true
});

These others did not work:

  • dropdownCssClass: 'bigdrop'
  • width: '100%'
  • width: 'resolve'

How to add "active" class to wp_nav_menu() current menu item (simple way)

In addition to previous answers, if your menu items are Categories and you want to highlight them when navigating through posts, check also for current-post-ancestor:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
    if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}

What is the difference between _tmain() and main() in C++?

With a little effort of templatizing this, it wold work with any list of objects.

#include <iostream>
#include <string>
#include <vector>

char non_repeating_char(std::string str){
    while(str.size() >= 2){
        std::vector<size_t> rmlist; 
        for(size_t  i = 1;  i < str.size(); i++){        
            if(str[0] == str[i]) {
                rmlist.push_back(i);
            }      
        }          

        if(rmlist.size()){            
            size_t s = 0;  // Need for terator position adjustment   
            str.erase(str.begin() + 0);
            ++s;
            for (size_t j : rmlist){   
                str.erase(str.begin() + (j-s));                
                ++s;
            }
         continue;
        }
        return str[0];
   }
    if(str.size() == 1) return str[0];
    else return -1;
}

int main(int argc, char ** args)
{
    std::string test = "FabaccdbefafFG";
    test = args[1];
    char non_repeating = non_repeating_char(test);
    Std::cout << non_repeating << '\n';
}

Best way to Bulk Insert from a C# DataTable

This is going to be largely dependent on the RDBMS you're using, and whether a .NET option even exists for that RDBMS.

If you're using SQL Server, use the SqlBulkCopy class.

For other database vendors, try googling for them specifically. For example a search for ".NET Bulk insert into Oracle" turned up some interesting results, including this link back to Stack Overflow: Bulk Insert to Oracle using .NET.

How to calculate combination and permutation in R?

It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.

MVC 4 @Scripts "does not exist"

For me this solved the problem, in NuGet package manager console write following:

update-package microsoft.aspnet.mvc -reinstall

How to plot a histogram using Matplotlib in Python with a list of data?

If you want a histogram, you don't need to attach any 'names' to x-values, as on x-axis you would have data bins:

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

np.random.seed(42)
x = np.random.normal(size=1000)

plt.hist(x, density=True, bins=30)  # density=False would make counts
plt.ylabel('Probability')
plt.xlabel('Data');

enter image description here

Note, the number of bins=30 was chosen arbitrarily, and there is Freedman–Diaconis rule to be more scientific in choosing the "right" bin width:

![enter image description here , where IQR is Interquartile range and n is total number of datapoints to plot

So, according to this rule one may calculate number of bins as:

q25, q75 = np.percentile(x,[.25,.75])
bin_width = 2*(q75 - q25)*len(x)**(-1/3)
bins = round((x.max() - x.min())/bin_width)
print("Freedman–Diaconis number of bins:", bins)
plt.hist(x, bins = bins);

Freedman–Diaconis number of bins: 82

enter image description here

And finally you can make your histogram a bit fancier with PDF line, titles, and legend:

import scipy.stats as st

plt.hist(x, density=True, bins=82, label="Data")
mn, mx = plt.xlim()
plt.xlim(mn, mx)
kde_xs = np.linspace(mn, mx, 300)
kde = st.gaussian_kde(x)
plt.plot(kde_xs, kde.pdf(kde_xs), label="PDF")
plt.legend(loc="upper left")
plt.ylabel('Probability')
plt.xlabel('Data')
plt.title("Histogram");

enter image description here

However, if you have limited number of data points, like in OP, a bar plot would make more sense to represent your data. Then you may attach labels to x-axis:

x = np.arange(3)
plt.bar(x, height=[1,2,3])
plt.xticks(x, ['a','b','c'])

enter image description here

Git command to show which specific files are ignored by .gitignore

It should be sufficient to use

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

as that covers everything covered by

git ls-files --others -i --exclude-from=.git/info/exclude

therefore the latter is redundant.


You can make this easier by adding an alias to your ~/.gitconfig file:

git config --global alias.ignored "ls-files --others -i --exclude-standard"

Now you can just type git ignored to see the list. Much easier to remember, and faster to type.

If you prefer the more succinct display of Jason Geng's solution, you can add an alias for that like this:

git config --global alias.ignored "status --ignored -s"

However the more verbose output is more useful for troubleshooting problems with your .gitignore files, as it lists every single cotton-pickin' file that is ignored. You would normally pipe the results through grep to see if a file you expect to be ignored is in there, or if a file you don't want to be ignore is in there.

git ignored | grep some-file-that-isnt-being-ignored-properly

Then, when you just want to see a short display, it's easy enough to remember and type

git status --ignored

(The -s can normally be left off.)

HTTP test server accepting GET/POST requests

https://www.mockable.io. It has nice feature of getting endpoints without login (24h temporary account)

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

private String getColumn(int c) {
    String s = "";
    do {
        s = (char)('A' + (c % 26)) + s;
        c /= 26;
    } while (c-- > 0);
    return s;
}

Its not exactly base 26, there is no 0 in the system. If there was, 'Z' would be followed by 'BA' not by 'AA'.

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Just read the JavaDoc for the asList method:

Returns a {@code List} of the objects in the specified array. The size of the {@code List} cannot be modified, i.e. adding and removing are unsupported, but the elements can be set. Setting an element modifies the underlying array.

This is from Java 6 but it looks like it is the same for the android java.

EDIT

The type of the resulting list is Arrays.ArrayList, which is a private class inside Arrays.class. Practically speaking, it is nothing but a List-view on the array that you've passed with Arrays.asList. With a consequence: if you change the array, the list is changed too. And because an array is not resizeable, remove and add operation must be unsupported.

Bash array with spaces in elements

Another solution is using a "while" loop instead a "for" loop:

index=0
while [ ${index} -lt ${#Array[@]} ]
  do
     echo ${Array[${index}]}
     index=$(( $index + 1 ))
  done

How do I find out what version of WordPress is running?

Every WP install has a readme.html file.

So just type www.yourdomain.com/readme.html

How to read Excel cell having Date with Apache POI?

If you know the cell number, then i would recommend using getDateCellValue() method Here's an example for the same that worked for me - java.util.Date date = row.getCell().getDateCellValue(); System.out.println(date);

How to connect to Mysql Server inside VirtualBox Vagrant?

Log in to your box with ssh [email protected] -p 2222 (password vagrant)

Then: sudo nano /etc/mysql/my.cnf and comment out the following lines with #

#skip-external-locking 
#bind-address

save it & exit

then: sudo service mysql restart

Then you can connect through SSH to your MySQL server.

Call to undefined function App\Http\Controllers\ [ function name ]

say you define the static getFactorial function inside a CodeController

then this is the way you need to call a static function, because static properties and methods exists with in the class, not in the objects created using the class.

CodeController::getFactorial($index);

----------------UPDATE----------------

To best practice I think you can put this kind of functions inside a separate file so you can maintain with more easily.

to do that

create a folder inside app directory and name it as lib (you can put a name you like).

this folder to needs to be autoload to do that add app/lib to composer.json as below. and run the composer dumpautoload command.

"autoload": {
    "classmap": [
                "app/commands",
                "app/controllers",
                ............
                "app/lib"
    ]
},

then files inside lib will autoloaded.

then create a file inside lib, i name it helperFunctions.php

inside that define the function.

if ( ! function_exists('getFactorial'))
{

    /**
     * return the factorial of a number
     *
     * @param $number
     * @return string
     */
    function getFactorial($date)
    {
        $fact = 1;

        for($i = 1; $i <= $num ;$i++)
            $fact = $fact * $i;

        return $fact;

     }
}

and call it anywhere within the app as

$fatorial_value = getFactorial(225);

CMake: How to build external projects and include their targets

I was searching for similar solution. The replies here and the Tutorial on top is informative. I studied posts/blogs referred here to build mine successful. I am posting complete CMakeLists.txt worked for me. I guess, this would be helpful as a basic template for beginners.

"CMakeLists.txt"

cmake_minimum_required(VERSION 3.10.2)

# Target Project
project (ClientProgram)

# Begin: Including Sources and Headers
include_directories(include)
file (GLOB SOURCES "src/*.c")
# End: Including Sources and Headers


# Begin: Generate executables
add_executable (ClientProgram ${SOURCES})
# End: Generate executables


# This Project Depends on External Project(s) 
include (ExternalProject)

# Begin: External Third Party Library
set (libTLS ThirdPartyTlsLibrary)
ExternalProject_Add (${libTLS}
PREFIX          ${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
# Begin: Download Archive from Web Server
URL             http://myproject.com/MyLibrary.tgz
URL_HASH        SHA1=<expected_sha1sum_of_above_tgz_file>
DOWNLOAD_NO_PROGRESS ON
# End: Download Archive from Web Server

# Begin: Download Source from GIT Repository
#    GIT_REPOSITORY  https://github.com/<project>.git
#    GIT_TAG         <Refer github.com releases -> Tags>
#    GIT_SHALLOW     ON
# End: Download Source from GIT Repository

# Begin: CMAKE Comamnd Argiments
CMAKE_ARGS      -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
CMAKE_ARGS      -DUSE_SHARED_LIBRARY:BOOL=ON
# End: CMAKE Comamnd Argiments    
)

# The above ExternalProject_Add(...) construct wil take care of \
# 1. Downloading sources
# 2. Building Object files
# 3. Install under DCMAKE_INSTALL_PREFIX Directory

# Acquire Installation Directory of 
ExternalProject_Get_Property (${libTLS} install_dir)

# Begin: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# Include PATH that has headers required by Target Project
include_directories (${install_dir}/include)

# Import librarues from External Project required by Target Project
add_library (lmytls SHARED IMPORTED)
set_target_properties (lmytls PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmytls.so)
add_library (lmyxdot509 SHARED IMPORTED)
set_target_properties(lmyxdot509 PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmyxdot509.so)

# End: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# End: External Third Party Library

# Begin: Target Project depends on Third Party Component
add_dependencies(ClientProgram ${libTLS})
# End: Target Project depends on Third Party Component

# Refer libraries added above used by Target Project
target_link_libraries (ClientProgram lmytls lmyxdot509)

AngularJS - Passing data between pages

app.factory('persistObject', function () {

        var persistObject = [];

        function set(objectName, data) {
            persistObject[objectName] = data;
        }
        function get(objectName) {
            return persistObject[objectName];
        }

        return {
            set: set,
            get: get
        }
    });

Fill it with data like this

persistObject.set('objectName', data); 

Get the object data like this

persistObject.get('objectName'); 

How to debug Lock wait timeout exceeded on MySQL?

Here is what I ultimately had to do to figure out what "other query" caused the lock timeout problem. In the application code, we track all pending database calls on a separate thread dedicated to this task. If any DB call takes longer than N-seconds (for us it's 30 seconds) we log:

-- Pending InnoDB transactions
SELECT * FROM information_schema.innodb_trx ORDER BY trx_started; 

-- Optionally, log what transaction holds what locks
SELECT * FROM information_schema.innodb_locks;

With above, we were able to pinpoint concurrent queries that locked the rows causing the deadlock. In my case, they were statements like INSERT ... SELECT which unlike plain SELECTs lock the underlying rows. You can then reorganize the code or use a different transaction isolation like read uncommitted.

Good luck!

Event when window.location.href changes

I use this script in my extension "Grab Any Media" and work fine ( like youtube case )

var oldHref = document.location.href;

window.onload = function() {

    var
         bodyList = document.querySelector("body")

        ,observer = new MutationObserver(function(mutations) {

            mutations.forEach(function(mutation) {

                if (oldHref != document.location.href) {

                    oldHref = document.location.href;

                    /* Changed ! your code here */

                }

            });

        });

    var config = {
        childList: true,
        subtree: true
    };

    observer.observe(bodyList, config);

};

Gson library in Android Studio

If you are going to use it with Retrofit library, I suggest you to use Square's gson library as:

implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

How do you determine a processing time in Python?

Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use timeit's default_timer():

>>> import timeit
>>> tic=timeit.default_timer()
>>> # Do Stuff
>>> toc=timeit.default_timer()
>>> toc - tic #elapsed time in seconds

This will return the elapsed wall clock (real) time, not CPU time. And as described in the timeit documentation chooses the most precise available real-world timer depending on the platform.

ALso, beginning with Python 3.3 this same functionality is available with the time.perf_counter performance counter. Under 3.3+ timeit.default_timer() refers to this new counter.

For more precise/complex performance calculations, timeit includes more sophisticated calls for automatically timing small code snippets including averaging run time over a defined set of repetitions.

Check if a String contains a special character

Visit each character in the string to see if that character is in a blacklist of special characters; this is O(n*m).

The pseudo-code is:

for each char in string:
  if char in blacklist:
    ...

The complexity can be slightly improved by sorting the blacklist so that you can early-exit each check. However, the string find function is probably native code, so this optimisation - which would be in Java byte-code - could well be slower.

Browser detection

Here's a way you can request info about the browser being used, you can use this to do your if statement

System.Web.HttpBrowserCapabilities browser = Request.Browser;
    string s = "Browser Capabilities\n"
        + "Type = "                    + browser.Type + "\n"
        + "Name = "                    + browser.Browser + "\n"
        + "Version = "                 + browser.Version + "\n"
        + "Major Version = "           + browser.MajorVersion + "\n"
        + "Minor Version = "           + browser.MinorVersion + "\n"
        + "Platform = "                + browser.Platform + "\n"
        + "Is Beta = "                 + browser.Beta + "\n"
        + "Is Crawler = "              + browser.Crawler + "\n"
        + "Is AOL = "                  + browser.AOL + "\n"
        + "Is Win16 = "                + browser.Win16 + "\n"
        + "Is Win32 = "                + browser.Win32 + "\n"
        + "Supports Frames = "         + browser.Frames + "\n"
        + "Supports Tables = "         + browser.Tables + "\n"
        + "Supports Cookies = "        + browser.Cookies + "\n"
        + "Supports VBScript = "       + browser.VBScript + "\n"
        + "Supports JavaScript = "     + 
            browser.EcmaScriptVersion.ToString() + "\n"
        + "Supports Java Applets = "   + browser.JavaApplets + "\n"
        + "Supports ActiveX Controls = " + browser.ActiveXControls 
              + "\n";

MSDN Article

Spring MVC + JSON = 406 Not Acceptable

I had the same issue, in my case the following was missing from my xxx-servlet.xml config file

<mvc:annotation-driven/>

As soon I added this it it worked.

Jenkins Host key verification failed

I ran into this issue and it turned out the problem was that the jenkins service wasn't being run as the jenkins user. So running the commands as the jenkins user worked just fine.

Swift: Reload a View Controller

Whatever code you are writing in viewDidLoad, Add that in viewWillappear(). This will solve your problem.

How to use concerns in Rails 4

This post helped me understand concerns.

# app/models/trader.rb
class Trader
  include Shared::Schedule
end

# app/models/concerns/shared/schedule.rb
module Shared::Schedule
  extend ActiveSupport::Concern
  ...
end

Adding script tag to React/JSX

You can find best answer at the following link:

https://cleverbeagle.com/blog/articles/tutorial-how-to-load-third-party-scripts-dynamically-in-javascript

const loadDynamicScript = (callback) => {
const existingScript = document.getElementById('scriptId');

if (!existingScript) {
    const script = document.createElement('script');
    script.src = 'url'; // URL for the third-party library being loaded.
    script.id = 'libraryName'; // e.g., googleMaps or stripe
    document.body.appendChild(script);

    script.onload = () => {
      if (callback) callback();
    };
  }

  if (existingScript && callback) callback();
};

Git: Remove committed file after push

If you want to remove the file from the remote repo, first remove it from your project with --cache option and then push it:

git rm --cache /path/to/file
git commit -am "Remove file"
git push

(This works even if the file was added to the remote repo some commits ago) Remember to add to .gitignore the file extensions that you don't want to push.

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

CodeIgniter: 404 Page Not Found on Live Server

There are a number of things you can check here. I'll go over each one with you.

1, When moving to a live server from localhost(htdocs) you need to make sure that the version of PHP you are using is supported.

To test this: Create an 'index.php' file and add the below line only.

<?php phpinfo(); ?>

Just press 'Ctrl + F' and search "version". You will find the php version. It may need to be 5.3+ to support features.

2, Check your config/config.php and check your $config['base_url'] and $config['index_page'] screen shot below

enter image description here

I recommend putting site name in the base url example: 'www.site.com/' but remove the index.php for cleaning.

3, MOST LIKELY THE REASON SO START WITH THIS

It most likely is the .htaccess file. Here is mine Made by Elliot Haughton. Put this in your root directory and change line 9 'RewriteBase /' if necessary.

<IfModule mod_rewrite.c>
RewriteEngine On
# !IMPORTANT! Set your RewriteBase here and don't forget trailing and leading
# slashes.
# If your page resides at
# http://www.example.com/mypage/test1
# then use
# RewriteBase /mypage/test1/
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin 
ErrorDocument 404 /index.php

(Make sure you use both parts above. The editor broke it in two but all code above is one .htaccess file).

If none of the above works, give me a shout back and we'll step through it.

Removing "http://" from a string

$new_website = substr($str, ($pos = strrpos($str, '//')) !== false ? $pos + 2 : 0); 

This would remove everything before the '//'.

EDIT

This one is tested. Using strrpos() instead or strpos().

How do I make an asynchronous GET request in PHP?

I found this interesting link to do asynchronous processing(get request).

askapache

Furthermore you could do asynchronous processing by using a message queue like for instance beanstalkd.

Difference between Constructor and ngOnInit

Constructor

The constructor function comes with every class, constructors are not specific to Angular but are concepts derived from Object oriented designs. The constructor creates an instance of the component class.

OnInit

The ngOnInit function is one of an Angular component’s life-cycle methods. Life cycle methods (or hooks) in Angular components allow you to run a piece of code at different stages of the life of a component. Unlike the constructor method, ngOnInit method comes from an Angular interface (OnInit) that the component needs to implement in order to use this method. The ngOnInit method is called shortly after the component is created.

Send mail via Gmail with PowerShell V2's Send-MailMessage

Send email with attachment using PowerShell -

      $EmailTo = "[email protected]"  // [email protected]
      $EmailFrom = "[email protected]"  // [email protected]
      $Subject = "zx"  //subject
      $Body = "Test Body"  // Body of message
      $SMTPServer = "smtp.gmail.com" 
      $filenameAndPath = "G:\abc.jpg"  // Attachment
      $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body)
      $attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
      $SMTPMessage.Attachments.Add($attachment)
      $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
      $SMTPClient.EnableSsl = $true 
      $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("[email protected]", "xxxxxxxx"); // xxxxxx-password
      $SMTPClient.Send($SMTPMessage)

JavaScript: Check if mouse button down?

        var mousedown = 0;
        $(function(){
            document.onmousedown = function(e){
                mousedown = mousedown | getWindowStyleButton(e);
                e = e || window.event;
                console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
            }

            document.onmouseup = function(e){
                mousedown = mousedown ^ getWindowStyleButton(e);
                e = e || window.event;
                console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
            }

            document.oncontextmenu = function(e){
                // to suppress oncontextmenu because it blocks
                // a mouseup when two buttons are pressed and 
                // the right-mouse button is released before
                // the other button.
                return false;
            }
        });

        function getWindowStyleButton(e){
            var button = 0;
                if (e) {
                    if (e.button === 0) button = 1;
                    else if (e.button === 1) button = 4;
                    else if (e.button === 2) button = 2;  
                }else if (window.event){
                    button = window.event.button;
                }
            return button;
        }

this cross-browser version works fine for me.

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

Rationale for the / POSIX PATH rule

The rule was mentioned at: Why do you need ./ (dot-slash) before executable or script name to run it in bash? but I would like to explain why I think that is a good design in more detail.

First, an explicit full version of the rule is:

  • if the path contains / (e.g. ./someprog, /bin/someprog, ./bin/someprog): CWD is used and PATH isn't
  • if the path does not contain / (e.g. someprog): PATH is used and CWD isn't

Now, suppose that running:

someprog

would search:

  • relative to CWD first
  • relative to PATH after

Then, if you wanted to run /bin/someprog from your distro, and you did:

someprog

it would sometimes work, but others it would fail, because you might be in a directory that contains another unrelated someprog program.

Therefore, you would soon learn that this is not reliable, and you would end up always using absolute paths when you want to use PATH, therefore defeating the purpose of PATH.

This is also why having relative paths in your PATH is a really bad idea. I'm looking at you, node_modules/bin.

Conversely, suppose that running:

./someprog

Would search:

  • relative to PATH first
  • relative to CWD after

Then, if you just downloaded a script someprog from a git repository and wanted to run it from CWD, you would never be sure that this is the actual program that would run, because maybe your distro has a:

/bin/someprog

which is in you PATH from some package you installed after drinking too much after Christmas last year.

Therefore, once again, you would be forced to always run local scripts relative to CWD with full paths to know what you are running:

"$(pwd)/someprog"

which would be extremely annoying as well.

Another rule that you might be tempted to come up with would be:

relative paths use only PATH, absolute paths only CWD

but once again this forces users to always use absolute paths for non-PATH scripts with "$(pwd)/someprog".

The / path search rule offers a simple to remember solution to the about problem:

  • slash: don't use PATH
  • no slash: only use PATH

which makes it super easy to always know what you are running, by relying on the fact that files in the current directory can be expressed either as ./somefile or somefile, and so it gives special meaning to one of them.

Sometimes, is slightly annoying that you cannot search for some/prog relative to PATH, but I don't see a saner solution to this.

How to run a specific Android app using Terminal?

I used all the above answers and it was giving me errors so I tried

adb shell monkey -p com.yourpackage.name -c android.intent.category.LAUNCHER 1

and it worked. One advantage is you dont have to specify your launcher activity if you use this command.

Why would you use Expression<Func<T>> rather than Func<T>?

I'd like to add some notes about the differences between Func<T> and Expression<Func<T>>:

  • Func<T> is just a normal old-school MulticastDelegate;
  • Expression<Func<T>> is a representation of lambda expression in form of expression tree;
  • expression tree can be constructed through lambda expression syntax or through the API syntax;
  • expression tree can be compiled to a delegate Func<T>;
  • the inverse conversion is theoretically possible, but it's a kind of decompiling, there is no builtin functionality for that as it's not a straightforward process;
  • expression tree can be observed/translated/modified through the ExpressionVisitor;
  • the extension methods for IEnumerable operate with Func<T>;
  • the extension methods for IQueryable operate with Expression<Func<T>>.

There's an article which describes the details with code samples:
LINQ: Func<T> vs. Expression<Func<T>>.

Hope it will be helpful.

Is there a PowerShell "string does not contain" cmdlet or syntax?

If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:

Get-Content $FileName | foreach-object { `
   if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }

or better (IMO)

Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}

Python: Binding Socket: "Address already in use"

You need to set the allow_reuse_address before binding. Instead of the SimpleHTTPServer run this snippet:

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler, bind_and_activate=False)
httpd.allow_reuse_address = True
httpd.server_bind()
httpd.server_activate()
httpd.serve_forever()

This prevents the server from binding before we got a chance to set the flags.

ReferenceError: fetch is not defined

If it has to be accessible with a global scope

global.fetch = require("node-fetch");

This is a quick dirty fix, please try to eliminate this usage in production code.

Iterating through a JSON object

Adding another solution (Python 3) - Iterating over json files in a directory and on each file iterating over all objects and printing relevant fields.

See comments in the code.

import os,json

data_path = '/path/to/your/json/files'  

# 1. Iterate over directory
directory = os.fsencode(data_path)
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    # 2. Take only json files
    if filename.endswith(".json"):
        file_full_path=data_path+filename
        # 3. Open json file 
        with open(file_full_path, encoding='utf-8', errors='ignore') as json_data:
            data_in_file = json.load(json_data, strict=False)
            # 4. Iterate over objects and print relevant fields
            for json_object in data_in_file:
                print("ttl: %s, desc: %s" % (json_object['title'],json_object['description']) )

how to call a variable in code behind to aspx page

The field must be declared public for proper visibility from the ASPX markup. In any case, you could declare a property:


private string clients;
public string Clients { get { return clients; } }

UPDATE: It can also be declared as protected, as stated in the comments below.

Then, to call it on the ASPX side:

<%=Clients%>

Note that this won't work if you place it on a server tag attribute. For example:

<asp:Label runat="server" Text="<%=Clients%>" />

This isn't valid. This is:

<div><%=Clients%></div>

Android studio - Failed to find target android-18

What worked for me in Android Studio (0.8.1):

  1. Right click on project name and open Module Settings
  2. Verify SDK Locations SDK
  3. Verify Gradle and Plugin Versions (Review the error message hints for the proper version to use) Gradke
  4. On the app Module set the Compile SDK Version to android-L (latest)
  5. Set the Build Tools version to largest available value (in my case 20.0.0) Build

These changes via the UI make the equivalent changes represented in other answers but is a better way to proceed because on close, all appropriate files (current and future) will be updated automatically (which is helpful when confronted by the many places where issues can occur).

NB: It is very important to review the Event Log and note that Android Studio provides helpful messages on alternative ways to resolve such issues.

Android - Start service on boot

Looks very similar to mine but I use the full package name for the receiver:

<receiver android:name=".StartupIntentReceiver">

I have:

<receiver android:name="com.your.package.AutoStart"> 

Angular - How to apply [ngStyle] conditions

[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"

How do you make a LinearLayout scrollable?

Wrap the linear layout with a <ScrollView>

See here for an example:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout 
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       xmlns:android="http://schemas.android.com/apk/res/android">
       <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <LinearLayout 
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:orientation="vertical">
                  <!-- Content here -->
            </LinearLayout>
      </ScrollView>
 </LinearLayout>

Note: fill_parent is deprecated and renamed to match_parent in API Level 8 and higher.

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

jQuery find and replace string

You could do something like this:

$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

It will be better to mark all tags with text that needs to be examined with a suitable class name.

Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.

onchange event for html.dropdownlist

try this :

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() 
{ Text = "Newest to Oldest", Value = "0" }, new SelectListItem() 
{ Text = "Oldest to Newest", Value = "1" }},
new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })

What is the reason behind "non-static method cannot be referenced from a static context"?

You can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.

Math operations from string

If you want to do it safely, you may want to use http://docs.python.org/library/ast.html#ast.literal_eval

from this answer: Python "safe" eval (string to bool/int/float/None/string)

It might not do math, but you could parse the math operators and then operate on safely evaluated terms.

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

LEFT OUTER JOIN in LINQ

Here is a fairly easy to understand version using method syntax:

IEnumerable<JoinPair> outerLeft =
    lefts.SelectMany(l => 
        rights.Where(r => l.Key == r.Key)
              .DefaultIfEmpty(new Item())
              .Select(r => new JoinPair { LeftId = l.Id, RightId = r.Id }));

How can I start PostgreSQL server on Mac OS X?

The cleanest way by far to start/stop/restart PostgreSQL if you have installed it through brew is to simply unload and/or load the launchd configuration file that comes with the installation:

launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

The first line will stop PostgreSQL and the second line will start it. There isn't any need to specify any data directories, etc. since everything is in that file.

How to find when a web page was last updated

There is another way to find the page update which could be useful for some occasions (if works:).

If the page has been indexed by Google, or by Wayback Machine you can try to find out what date(s) was(were) saved by them (these methods do not work for any page, and have some limitations, which are extensively investigated in this webmasters.stackexchange question's answers. But in many cases they can help you to find out the page update date(s):

  1. Google way: Go by link https://www.google.com.ua/search?q=site%3Awww.example.com&biw=1855&bih=916&source=lnt&tbs=cdr%3A1%2Ccd_min%3A1%2F1%2F2000%2Ccd_max%3A&tbm=
    • You can change text in search field by any page URL you want.
    • For example, the current stackoverflow question page search gives us as a result May 14, 2014 - which is the question creation date: enter image description here
  2. Wayback machine way: Go by link https://web.archive.org/web/*/www.example.com
    • for this stackoverflow page wayback machine gives us more results: Saved 6 times between June 7, 2014 and November 23, 2016., and you can view all saved copies for each date

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

eclipse won't start - no java virtual machine was found

eclipse.ini:

--launcher.defaultAction  
--launcher.XXMaxPermSize  
256M  
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize<br/>
256m  
--launcher.defaultAction  
openFile  
-showsplash  
org.eclipse.platform
-vm
C:\Program Files\Java\jdk1.7.0_21\jre\bin\server\jvm.dll<br/>
--launcher.XXMaxPermSize  
256m  
--launcher.defaultAction  
openFile  
-vmargs  
-Dosgi.requiredJavaVersion=1.7  

That worked for me. It doesnt have to be on the beginning, but surely it cant be at the end of the file.

How do I put my website's logo to be the icon image in browser tabs?

  1. ADD THIS
**<HEAD>**

  < link rel="icon" href="directory/image.png">

Then run and enjoy it

How to get the data-id attribute?

Try

this.dataset.id

_x000D_
_x000D_
$("#list li").on('click', function() {_x000D_
  alert( this.dataset.id );_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>_x000D_
_x000D_
<ul id="list" class="grid">_x000D_
  <li data-id="id-40" class="win">_x000D_
    <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">_x000D_
      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />_x000D_
    </a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_