Programs & Examples On #Multi query

How to suppress Pandas Future warning ?

Warnings are annoying. As mentioned in other answers, you can suppress them using:

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

But if you want to handle them one by one and you are managing a bigger codebase, it will be difficult to find the line of code which is causing the warning. Since warnings unlike errors don't come with code traceback. In order to trace warnings like errors, you can write this at the top of the code:

import warnings
warnings.filterwarnings("error")

But if the codebase is bigger and it is importing bunch of other libraries/packages, then all sort of warnings will start to be raised as errors. In order to raise only certain type of warnings (in your case, its FutureWarning) as error, you can write:

import warnings
warnings.simplefilter(action='error', category=FutureWarning)

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Volley - POST/GET parameters

For the GET parameters there are two alternatives:

First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:

String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s",
                           num1,
                           num2);

StringRequest myReq = new StringRequest(Method.GET,
                                        uri,
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener());
queue.add(myReq);

where num1 and num2 are String variables that contain your values.

Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.

For the POST parameters probably sometimes will be easier than the accepted answer to do it like:

StringRequest myReq = new StringRequest(Method.POST,
                                        "http://somesite.com/some_endpoint.php",
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener()) {

    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("param1", num1);
        params.put("param2", num2);
        return params;
    };
};
queue.add(myReq);

e.g. to just override the getParams() method.

You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.

C# - Making a Process.Start wait until the process has start-up

Like others have already said, it's not immediately obvious what you're asking. I'm going to assume that you want to start a process and then perform another action when the process "is ready".

Of course, the "is ready" is the tricky bit. Depending on what you're needs are, you may find that simply waiting is sufficient. However, if you need a more robust solution, you can consider using a named Mutex to control the control flow between your two processes.

For example, in your main process, you might create a named mutex and start a thread or task which will wait. Then, you can start the 2nd process. When that process decides that "it is ready", it can open the named mutex (you have to use the same name, of course) and signal to the first process.

How to export dataGridView data Instantly to Excel on button click?

using Excel = Microsoft.Office.Interop.Excel;


private void btnExportExcel_Click(object sender, EventArgs e)
{
    try
    {
        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
        excel.Visible = true;
        Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
        Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
        int StartCol = 1;
        int StartRow = 1;
        int j = 0, i = 0;

        //Write Headers
        for (j = 0; j < dgvSource.Columns.Count; j++)
        {
            Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
            myRange.Value2 = dgvSource.Columns[j].HeaderText;
        }

        StartRow++;

        //Write datagridview content
        for (i = 0; i < dgvSource.Rows.Count; i++)
        {
            for (j = 0; j < dgvSource.Columns.Count; j++)
            {
                try
                {
                    Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
                    myRange.Value2 = dgvSource[j, i].Value == null ? "" : dgvSource[j, i].Value;
                }
                catch
                {
                    ;
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

Pointer vs. Reference

Pointers:

  • Can be assigned nullptr (or NULL).
  • At the call site, you must use & if your type is not a pointer itself, making explicitly you are modifying your object.
  • Pointers can be rebound.

References:

  • Cannot be null.
  • Once bound, cannot change.
  • Callers don't need to explicitly use &. This is considered sometimes bad because you must go to the implementation of the function to see if your parameter is modified.

Aligning label and textbox on same line (left and right)

you can use style

   <td  colspan="2">
     <div style="float:left; width:80px"><asp:Label ID="Label6" runat="server" Text="Label"></asp:Label></div>

    <div style="float: right; width:100px">    
            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    </div>

     <div style="clear:both"></div>

    </td>

What are the various "Build action" settings in Visual Studio project properties and what do they do?

How about this page from Microsoft Connect (explaining the DesignData and DesignDataWithDesignTimeCreatableTypes) types. Quoting:

The following describes the two Build Actions for Sample Data files.

Sample data .xaml files must be assigned one of the below Build Actions:

DesignData: Sample data types will be created as faux types. Use this Build Action when the sample data types are not creatable or have read-only properties that you want to defined sample data values for.

DesignDataWithDesignTimeCreatableTypes: Sample data types will be created using the types defined in the sample data file. Use this Build Action when the sample data types are creatable using their default empty constructor.

Not so incredibly exhaustive, but it at least gives a hint. This MSDN walkthrough also gives some ideas. I don't know whether these Build Actions are applicable for non-Silverlight projects also.

System.Net.WebException HTTP status code

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

How to convert local time string to UTC?

I've had the most success with python-dateutil:

from dateutil import tz

def datetime_to_utc(date):
    """Returns date in UTC w/o tzinfo"""
    return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date

Converting milliseconds to a date (jQuery/JavaScript)

You can simply us the Datejs library in order to convert the date to your desired format.

I've run couples of test and it works.

Below is a snippet illustrating how you can achieve that:

var d = new Date(1469433907836);

d.toLocaleString(); // expected output: "7/25/2016, 1:35:07 PM"

d.toLocaleDateString(); // expected output: "7/25/2016"

d.toDateString();  // expected output: "Mon Jul 25 2016"

d.toTimeString(); // expected output: "13:35:07 GMT+0530 (India Standard Time)"

d.toLocaleTimeString(); // expected output: "1:35:07 PM"

How does one reorder columns in a data frame?

You can also use the subset function:

data <- subset(data, select=c(3,2,1))

You should better use the [] operator as in the other answers, but it may be useful to know that you can do a subset and a column reorder operation in a single command.

Update:

You can also use the select function from the dplyr package:

data = data %>% select(Time, out, In, Files)

I am not sure about the efficiency, but thanks to dplyr's syntax this solution should be more flexible, specially if you have a lot of columns. For example, the following will reorder the columns of the mtcars dataset in the opposite order:

mtcars %>% select(carb:mpg)

And the following will reorder only some columns, and discard others:

mtcars %>% select(mpg:disp, hp, wt, gear:qsec, starts_with('carb'))

Read more about dplyr's select syntax.

Calling JMX MBean method from a shell script

@Dougnukem answer helped me a lot. I have taken the Groovy approach (using groovy 2.3.3).

I did some changes on Dougnukem code. This will work with Java 7 and will print two attributes to stdout every 10 sec.

        package com.my.company.jmx
        import groovy.util.GroovyMBean;
        import javax.management.remote.JMXServiceURL
        import javax.management.remote.JMXConnectorFactory
        import java.lang.management.*

            class Monitor {
                static main(args) {
                    def serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:5019/jmxrmi'
                    String beanName = "Catalina:type=DataSource,class=javax.sql.DataSource,name=\"jdbc/CommonDB\""
                    println  "numIdle,numActive"

                    while(1){
                        def server = JMXConnectorFactory.connect(new JMXServiceURL(serverUrl))
                       //make sure to reconnect in case the jvm was restrated 
                        server.connect()
                        GroovyMBean mbean = new GroovyMBean(server.MBeanServerConnection, beanName)
                        println  "${mbean.numIdle},${mbean.numActive}"
                        server.close()
                        sleep(10000)
                    }

                }
            }

Compile this code into a jar using maven-compiler-plugin so you will not require groovy installation only the groovy-all.jar . Below is the relevant plugin definition and dependency.

   <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <compilerId>groovy-eclipse-compiler</compilerId>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.codehaus.groovy</groupId>
                        <artifactId>groovy-eclipse-compiler</artifactId>
                        <version>2.8.0-01</version>
                    </dependency>
                    <dependency>
                        <groupId>org.codehaus.groovy</groupId>
                        <artifactId>groovy-eclipse-batch</artifactId>
                        <version>2.3.4-01</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.3</version>
        </dependency>
    </dependencies>

Wrap it with a bat or a shell and it will print the data to stdout.

How do I pass multiple parameter in URL?

This

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"&param2="+lon);

must work. For whatever strange reason1, you need ? before the first parameter and & before the following ones.

Using a compound parameter like

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);

would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20 or + (but this is even worse style).


1 Stating that ? separates the path and the parameters and that & separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.

Comparison of C++ unit test frameworks

Boost Test Library is a very good choice especially if you're already using Boost.

// TODO: Include your class to test here.
#define BOOST_TEST_MODULE MyTest
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(MyTestCase)
{
    // To simplify this example test, let's suppose we'll test 'float'.
    // Some test are stupid, but all should pass.
    float x = 9.5f;

    BOOST_CHECK(x != 0.0f);
    BOOST_CHECK_EQUAL((int)x, 9);
    BOOST_CHECK_CLOSE(x, 9.5f, 0.0001f); // Checks differ no more then 0.0001%
}

It supports:

  • Automatic or manual tests registration
  • Many assertions
  • Automatic comparison of collections
  • Various output formats (including XML)
  • Fixtures / Templates...

PS: I wrote an article about it that may help you getting started: C++ Unit Testing Framework: A Boost Test Tutorial

How do you make websites with Java?

Look into creating Applets if you want to make a website with Java. You most likely wont need to use anything but regular Java, unless you want something more specialized.

Python - converting a string of numbers into a list of int

Split on commas, then map to integers:

map(int, example_string.split(','))

Or use a list comprehension:

[int(s) for s in example_string.split(',')]

The latter works better if you want a list result, or you can wrap the map() call in list().

This works because int() tolerates whitespace:

>>> example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
>>> list(map(int, example_string.split(',')))  # Python 3, in Python 2 the list() call is redundant
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
>>> [int(s) for s in example_string.split(',')]
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]

Splitting on just a comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values.

Where can I find Android's default icons?

\path-to-your-android-sdk-folder\platforms\android-xx\data\res

how to hide a vertical scroll bar when not needed

overflow: auto; or overflow: hidden; should do it I think.

How to solve PHP error 'Notice: Array to string conversion in...'

<?php
ob_start();
var_dump($_POST['C']);
$result = ob_get_clean();
?>

if you want to capture the result in a variable

How to select option in drop down protractorjs e2e tests

Here is how to do it by either option value or index. This example is a bit crude, but it shows how to do what you want:

html:

<mat-form-field id="your-id">
    <mat-select>
        <mat-option [value]="1">1</mat-option>
        <mat-option [value]="2">2</mat-option>
    </mat-select>
</mat-form-field>

ts:

function selectOptionByOptionValue(selectFormFieldElementId, valueToFind) {

  const formField = element(by.id(selectFormFieldElementId));
  formField.click().then(() => {

    formField.element(by.tagName('mat-select'))
      .getAttribute('aria-owns').then((optionIdsString: string) => {
        const optionIds = optionIdsString.split(' ');    

        for (let optionId of optionIds) {
          const option = element(by.id(optionId));
          option.getText().then((text) => {
            if (text === valueToFind) {
              option.click();
            }
          });
        }
      });
  });
}

function selectOptionByOptionIndex(selectFormFieldElementId, index) {

  const formField = element(by.id(selectFormFieldElementId));
  formField.click().then(() => {

    formField.element(by.tagName('mat-select'))
      .getAttribute('aria-owns').then((optionIdsString: string) => {
        const optionIds = optionIdsString.split(' ');

        const optionId = optionIds[index];
        const option = element(by.id(optionId));
        option.click();
      });
  });
}

selectOptionByOptionValue('your-id', '1'); //selects first option
selectOptionByOptionIndex('your-id', 1); //selects second option

How do I enable php to work with postgresql?

I have to add in httpd.conf this line (Windows):

LoadFile "C:/Program Files (x86)/PostgreSQL/8.3/bin/libpq.dll"

How to rename with prefix/suffix?

The easiest way to bulk rename files in directory is:

ls | xargs -I fileName mv fileName fileName.suffix

Connection failed: SQLState: '01000' SQL Server Error: 10061

  1. Windows firewall blocks the sql server. Even if you open the 1433 port from exceptions, in the client machine it sets the connection point to dynamic port. Add also the sql server to the exceptions.

"C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn\Sqlservr.exe"

More info

  1. This page helped me to solve the problem. Especially

or if you feel brave, locate the alias in the registry and delete it there.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo\

How do I add my bot to a channel?

Now all clients allow to do it, but it's not pretty simple.
In any Telegram client:

  1. Open Channel info (in app title)
  2. Choose Administrators
  3. Add Administrator
  4. There will be no bots in contact list, so you need to search for it. Enter your bot's username
  5. Clicking on it you make it as administrator.

enter image description here

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

Shortest distance between a point and a line segment

Didn't see a Java implementation here, so I translated the Javascript function from the accepted answer to Java code:

static double sqr(double x) {
    return x * x;
}
static double dist2(DoublePoint v, DoublePoint w) {
    return sqr(v.x - w.x) + sqr(v.y - w.y);
}
static double distToSegmentSquared(DoublePoint p, DoublePoint v, DoublePoint w) {
    double l2 = dist2(v, w);
    if (l2 == 0) return dist2(p, v);
    double t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
    if (t < 0) return dist2(p, v);
    if (t > 1) return dist2(p, w);
    return dist2(p, new DoublePoint(
            v.x + t * (w.x - v.x),
            v.y + t * (w.y - v.y)
    ));
}
static double distToSegment(DoublePoint p, DoublePoint v, DoublePoint w) {
    return Math.sqrt(distToSegmentSquared(p, v, w));
}
static class DoublePoint {
    public double x;
    public double y;

    public DoublePoint(double x, double y) {
        this.x = x;
        this.y = y;
    }
}

Access multiple viewchildren using @viewchild

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l?i?v?e? ?d?e?m?o?

How to edit a JavaScript alert box title?

You can do this in IE:

<script language="VBScript">
Sub myAlert(title, content)
      MsgBox content, 0, title
End Sub
</script>

<script type="text/javascript">
myAlert("My custom title", "Some content");
</script>

(Although, I really wish you couldn't.)

Anonymous method in Invoke call

myControl.Invoke(new MethodInvoker(delegate() {...}))

Create an empty data.frame

If you are looking for shortness :

read.csv(text="col1,col2")

so you don't need to specify the column names separately. You get the default column type logical until you fill the data frame.

bash echo number of lines of file given in a bash variable without the file name

(apply on Mac, and probably other Unixes)

Actually there is a problem with the wc approach: it does not count the last line if it does not terminate with the end of line symbol.

Use this instead

nbLines=$(cat -n file.txt | tail -n 1 | cut -f1 | xargs)

or even better (thanks gniourf_gniourf):

nblines=$(grep -c '' file.txt)

Note: The awk approach by chilicuil also works.

Css Move element from left to right animated

It's because you aren't giving the un-hovered state a right attribute.

right isn't set so it's trying to go from nothing to 0px. Obviously because it has nothing to go to, it just 'warps' over.

If you give the unhovered state a right:90%;, it will transition how you like.

Just as a side note, if you still want it to be on the very left of the page, you can use the calc css function.

Example:

right: calc(100% - 100px)
                     ^ width of div

You don't have to use left then.

Also, you can't transition using left or right auto and will give the same 'warp' effect.

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    background:red;_x000D_
    transition:2s;_x000D_
    -webkit-transition:2s;_x000D_
    -moz-transition:2s;_x000D_
    position:absolute;_x000D_
    right:calc(100% - 100px);_x000D_
}_x000D_
div:hover {_x000D_
  right:0;_x000D_
}
_x000D_
<p>_x000D_
  <b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions._x000D_
</p>_x000D_
<div></div>_x000D_
<p>Hover over the red square to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

CanIUse says that the calc() function only works on IE10+

port 8080 is already in use and no process using 8080 has been listed

In windows " wmic process where processid="pid of the process running" get commandline " worked for me. The culprit was wrapper.exe process of webhuddle jboss soft.

How to exit git log or git diff

Actually, there are three ways to do it, precisely.

Type any of the following 3 commands.

  1. :q
  2. :z or
  3. Ctrl + z

P.S.: Sometimes, for someone, one of these options doesn't seem to work and for others it works.

Converting cv::Mat to IplImage*

Mat image1;
IplImage* image2=cvCloneImage(&(IplImage)image1);

Guess this will do the job.

Edit: If you face compilation errors, try this way:

cv::Mat image1;
IplImage* image2;
image2 = cvCreateImage(cvSize(image1.cols,image1.rows),8,3);
IplImage ipltemp=image1;
cvCopy(&ipltemp,image2);

Add an object to an Array of a custom class

If you want to create a garage and fill it up with new cars that can be accessed later, use this code:

for (int i = 0; i < garage.length; i++)
     garage[i] = new Car("argument");

Also, the cars are later accessed using:

garage[0];
garage[1];
garage[2];
etc.

Swift: declare an empty dictionary

Use this will work.

var emptyDict = [String: String]()

How do I see the current encoding of a file in Sublime Text?

With the EncodingHelper plugin you can view the encoding of the file on the status bar. Also you can convert the encoding of the file and extended another functionalities.

Demo

JavaScript: replace last occurrence of text in a string

Not as elegant as the regex answers above, but easier to follow for the not-as-savvy among us:

function removeLastInstance(badtext, str) {
    var charpos = str.lastIndexOf(badtext);
    if (charpos<0) return str;
    ptone = str.substring(0,charpos);
    pttwo = str.substring(charpos+(badtext.length));
    return (ptone+pttwo);
}

I realize this is likely slower and more wasteful than the regex examples, but I think it might be helpful as an illustration of how string manipulations can be done. (It can also be condensed a bit, but again, I wanted each step to be clear.)

Add padding to HTML text input field

padding-right works for me in Firefox/Chrome on Windows but not in IE. Welcome to the wonderful world of IE standards non-compliance.

See: http://jsfiddle.net/SfPju/466/

HTML

<input type="text" class="foo" value="abcdefghijklmnopqrstuvwxyz"/>

CSS

.foo
{
    padding-right: 20px;
}

How to find difference between two Joda-Time DateTimes in minutes

DateTime d1 = ...;
DateTime d2 = ...;
Period period = new Period(d1, d2, PeriodType.minutes());
int differenceMinutes = period.getMinutes();

In practice I think this will always give the same result as the answer based on Duration. For a different time unit than minutes, though, it might be more correct. For example there are 365 days from 2016/2/2 to 2017/2/1, but actually it's less than 1 year and should truncate to 0 years if you use PeriodType.years().

In theory the same could happen for minutes because of leap seconds, but Joda doesn't support leap seconds.

Why does JSHint throw a warning if I am using const?

I spent ages trying to fix this. Every solution talks about 'setting options'. I don't know what that means. Finally, I figured it out. You can just include a commented out line at the top of the file /*jshint esversion: 6 */.

Solution

Get visible items in RecyclerView

Addendum:

The proposed functions findLast...Position() do not work correctly in a scenario with a collapsing toolbar while the toolbar is expanded.

It seems that the recycler view has a fixed height, and while the toolbar is expanded, the recycler is moved down, partially out of the screen. As a consequence the results of the proposed functions are too high. Example: The last visible item is told to be #9, but in fact item #7 is the last one that is on screen.

This behaviour is also the reason why my view often failed to scroll to the correct position, i.e. scrollToPosition() did not work correctly (I finally collapsed the toolbar programmatically).

Finding the length of a Character Array in C

Provided the char array is null terminated,

char chararray[10] = { 0 };
size_t len = strlen(chararray);

What's the best way to get the current URL in Spring MVC?

in jsp file:

request.getAttribute("javax.servlet.forward.request_uri")

Error - Unable to access the IIS metabase

Thank you to everyone that answered. Since this was closed for a long time I couldn't provide much feedback, but I did eventually fix my problem. I tried many of these other solutions and they didn't fix my issue, but I'm sure they help when the root cause is different.

My Solution

I solved this problem by turning off the IIS and .Net Framework features within Windows 7 and then turning them back on. It seems like this re-installation is what fixed my issue. I still don't know what caused the problem, but at least one other developer on my team had the same issue.

How can I set the default timezone in node.js?

Sometimes you may be running code on a virtual server elsewhere - That can get muddy when running NODEJS or other flavors.

Here is a fix that will allow you to use any timezone easily.

Check here for list of timezones

Just put your time zone phrase within the brackets of your FORMAT line.

In this case - I am converting EPOCH to Eastern.

//RE: https://www.npmjs.com/package/date-and-time
const date = require('date-and-time');

let unixEpochTime = (seconds * 1000);
const dd=new Date(unixEpochTime);
let myFormattedDateTime = date.format(dd, 'YYYY/MM/DD HH:mm:ss A [America/New_York]Z');
let myFormattedDateTime24 = date.format(dd, 'YYYY/MM/DD HH:mm:ss [America/New_York]Z');

How to programmatically clear application data

if android version is above kitkat you may use this as well

public void onClick(View view) {

    Context context = getApplicationContext(); // add this line
    if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
        ((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
            .clearApplicationUserData();
        return;
    }

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

I had the same error for a different package. My problem was that a dependent project was referencing a different version. I changed them to be the same version and all was good.

Animate text change in UILabel

If you would like to do this in Swift with a delay try this:

delay(1.0) {
        UIView.transitionWithView(self.introLabel, duration: 0.25, options: [.TransitionCrossDissolve], animations: {
            self.yourLabel.text = "2"
            }, completion:  { finished in

                self.delay(1.0) {
                    UIView.transitionWithView(self.introLabel, duration: 0.25, options: [.TransitionCrossDissolve], animations: {
                        self.yourLabel.text = "1"
                        }, completion:  { finished in

                    })
                }

        })
    }

using the following function created by @matt - https://stackoverflow.com/a/24318861/1982051:

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

which will become this in Swift 3

func delay(_ delay:Double, closure:()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.after(when: when, execute: closure)
}

detect key press in python?

More things can be done with keyboard module. You can install this module using pip install keyboard Here are some of the methods:


Method #1:

Using the function read_key():

import keyboard

while True:
    if keyboard.read_key() == "p":
        print("You pressed p")
        break

This is gonna break the loop as the key p is pressed.


Method #2:

Using function wait:

import keyboard

keyboard.wait("p")
print("You pressed p")

It will wait for you to press p and continue the code as it is pressed.


Method #3:

Using the function on_press_key:

import keyboard

keyboard.on_press_key("p", lambda _:print("You pressed p"))

It needs a callback function. I used _ because the keyboard function returns the keyboard event to that function.

Once executed, it will run the function when the key is pressed. You can stop all hooks by running this line:

keyboard.unhook_all()

Method #4:

This method is sort of already answered by user8167727 but I disagree with the code they made. It will be using the function is_pressed but in an other way:

import keyboard

while True:
    if keyboard.is_pressed("p"):
        print("You pressed p")
        break

It will break the loop as p is pressed.


Notes:

  • keyboard will read keypresses from the whole OS.
  • keyboard requires root on linux

How do I put an already-running process under nohup?

The command to separate a running job from the shell ( = makes it nohup) is disown and a basic shell-command.

From bash-manpage (man bash):

disown [-ar] [-h] [jobspec ...]

Without options, each jobspec is removed from the table of active jobs. If the -h option is given, each jobspec is not removed from the table, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If no jobspec is present, and neither the -a nor the -r option is supplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs. The return value is 0 unless a jobspec does not specify a valid job.

That means, that a simple

disown -a

will remove all jobs from the job-table and makes them nohup

Append a Lists Contents to another List C#

if you want to get "terse" :)

List<string>GlobalStrings = new List<string>(); 

for(int x=1; x<10; x++) GlobalStrings.AddRange(new List<string> { "some value", "another value"});

Select from multiple tables without a join?

You could try this notattion:

SELECT * from table1,table2 

More complicated one :

SELECT table1.field1,table1.field2, table2.field3,table2.field8 from table1,table2 where table1.field2 = something and table2.field3 = somethingelse

Error to run Android Studio

Widows 7 64 bit.

  1. JAVA_HOME point to my JRE (NOT JDK) directory
  2. Coping of tools.jar from JDK\lib directory to ANDROIDSTUDIO\lib directory solve the problem

How to check Grants Permissions at Run-Time?

fun hasPermission(permission: String): Boolean {
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true // must be granted after installed.
      return mAppSet.appContext.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}

Setting CSS pseudo-class rules from JavaScript

As already stated this is not something that browsers support.

If you aren't coming up with the styles dynamically (i.e. pulling them out of a database or something) you should be able to work around this by adding a class to the body of the page.

The css would look something like:

a:hover { background: red; }
.theme1 a:hover { background: blue; }

And the javascript to change this would be something like:

// Look up some good add/remove className code if you want to do this
// This is really simplified

document.body.className += " theme1";  

Hiding the scroll bar on an HTML page

Yes, sort of..

When you ask the question, "Can the scroll-bars of a browser be removed in some way, rather than simply hidden or camouflaged", everyone will say "Not possible" because it is not possible to remove the scrollbars from all browsers in a compliant and cross-compatible way, and then there's the whole argument of usability.

However, it is possible to prevent the browser from ever having the need to generate and display scrollbars if you do not allow your webpage to overflow.

This just means that we have to proactively substitute the same behavior that the browser would typically do for us and tell the browser thanks but no thanks buddy. Rather than try to remove scrollbars (which we all know is not possible) we can avoid scrolling (perfectly feasible) and scroll within the elements that we make and have more control over.

Create a div with overflow hidden. Detect when the user attempts to scroll, but is unable to because we've disabled the browsers ability to scroll with overflow: hidden.. and instead move the content up using JavaScript when this occurs. Thereby creating our own scrolling without the browsers default scrolling or use a plugin like iScroll.

---

For the sake of being thorough; all the vendor specific ways of manipulating scroll-bars:

Internet Explorer 5.5+

*These properties were never part of the CSS specification, nor were they ever approved or vendor prefixed, but they work in Internet Explorer and Konqueror. These can also be set locally in the user style sheet for each application. In Internet Explorer you find it under the "Accessibility" tab, in Konqueror under the "Stylesheets" tab.

body, html { /* These are defaults and can be replaced by hexadecimal color values */
    scrollbar-base-color: aqua;
    scrollbar-face-color: ThreeDFace;
    scrollbar-highlight-color: ThreeDHighlight;
    scrollbar-3dlight-color: ThreeDLightShadow;
    scrollbar-shadow-color: ThreeDDarkShadow;
    scrollbar-darkshadow-color: ThreeDDarkShadow;
    scrollbar-track-color: Scrollbar;
    scrollbar-arrow-color: ButtonText;
}

As of Internet Explorer 8 these properties were vendor prefixed by Microsoft, but they were still never approved by W3C.

-ms-scrollbar-base-color
-ms-scrollbar-face-color
-ms-scrollbar-highlight-color
-ms-scrollbar-3dlight-color
-ms-scrollbar-shadow-color
-ms-scrollbar-darkshadow-color
-ms-scrollbar-base-color
-ms-scrollbar-track-color

Further details about Internet Explorer

Internet Explorer makes scroll available which sets whether or not to disable or enable scroll bars; it can also be used to get the value of the position of the scroll bars.

With Microsoft Internet Explorer 6 and later, when you use the !DOCTYPE declaration to specify standards-compliant mode, this attribute applies to the HTML element. When standards-compliant mode is not specified, as with earlier versions of Internet Explorer, this attribute applies to the BODY element, NOT the HTML element.

It's also worth noting that when working with .NET the ScrollBar class in System.Windows.Controls.Primitives in the Presentation framework is responsible for rendering the scrollbars.

http://msdn.microsoft.com/en-us/library/ie/ms534393(v=vs.85).aspx


WebKit

WebKit extensions related to scroll-bar customization are:

::-webkit-scrollbar {}             /* 1 */
::-webkit-scrollbar-button {}      /* 2 */
::-webkit-scrollbar-track {}       /* 3 */
::-webkit-scrollbar-track-piece {} /* 4 */
::-webkit-scrollbar-thumb {}       /* 5 */
::-webkit-scrollbar-corner {}      /* 6 */
::-webkit-resizer {}               /* 7 */

Enter image description here

These can each be combined with additional pseudo-selectors:

  • :horizontal – The horizontal pseudo-class applies to any scrollbar pieces that have a horizontal orientation.
  • :vertical – The vertical pseudo-class applies to any scrollbar pieces that have a vertical orientation.
  • :decrement – The decrement pseudo-class applies to buttons and track pieces. It indicates whether or not the button or track piece will decrement the view’s position when used (e.g., up on a vertical scrollbar, left on a horizontal scrollbar).
  • :increment – The increment pseudo-class applies to buttons and track pieces. It indicates whether or not a button or track piece will increment the view’s position when used (e.g., down on a vertical scrollbar, right on a horizontal scrollbar).
  • :start – The start pseudo-class applies to buttons and track pieces. It indicates whether the object is placed before the thumb.
  • :end – The end pseudo-class applies to buttons and track pieces. It indicates whether the object is placed after the thumb.
  • :double-button – The double-button pseudo-class applies to buttons and track pieces. It is used to detect whether a button is part of a pair of buttons that are together at the same end of a scrollbar. For track pieces it indicates whether the track piece abuts a pair of buttons.
  • :single-button – The single-button pseudo-class applies to buttons and track pieces. It is used to detect whether a button is by itself at the end of a scrollbar. For track pieces it indicates whether the track piece abuts a singleton button.
  • :no-button – Applies to track pieces and indicates whether or not the track piece runs to the edge of the scrollbar, i.e., there is no button at that end of the track.
  • :corner-present – Applies to all scrollbar pieces and indicates whether or not a scrollbar corner is present.
  • :window-inactive – Applies to all scrollbar pieces and indicates whether or not the window containing the scrollbar is currently active. (In recent nightlies, this pseudo-class now applies to ::selection as well. We plan to extend it to work with any content and to propose it as a new standard pseudo-class.)

Examples of these combinations

::-webkit-scrollbar-track-piece:start { /* Select the top half (or left half) or scrollbar track individually */ }
::-webkit-scrollbar-thumb:window-inactive { /* Select the thumb when the browser window isn't in focus */ }
::-webkit-scrollbar-button:horizontal:decrement:hover { /* Select the down or left scroll button when it's being hovered by the mouse */ }

Further details about Chrome

addWindowScrollHandler public static HandlerRegistration addWindowScrollHandler(Window.ScrollHandler handler)

  Adds a Window.ScrollEvent handler Parameters:   handler - the handler Returns:   returns the handler registration [source](http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/Window.html#addWindowScrollHandler(com.google.gwt.user.client.Window.ScrollHandler) )


Mozilla

Mozilla does have some extensions for manipulating the scroll-bars, but they are all recommended not to be used.

  • -moz-scrollbars-none They recommend using overflow:hidden in place of this.
  • -moz-scrollbars-horizontal Similar to overflow-x
  • -moz-scrollbars-vertical Similar to overflow-y
  • -moz-hidden-unscrollable Only works internally within a users profile settings. Disables scrolling XML root elements and disables using arrow keys and mouse wheel to scroll web pages.

  • Mozilla Developer Docs on 'Overflow'

Further details about Mozilla

This is not really useful as far as I know, but it's worth noting that the attribute which controls whether or not scrollbars are displayed in Firefox is (reference link):

  • Attribute:       scrollbars
  • Type:              nsIDOMBarProp
  • Description:  The object that controls whether or not scrollbars are shown in the window. This attribute is "replaceable" in JavaScript. Read only

Last but not least, padding is like magic.

As has been previously mentioned in some other answers, here is an illustration which is sufficiently self-explanatory.

Enter image description here


History lesson

Scroll bars

Just because I'm curious, I wanted to learn about the origin of scrollbars, and these are the best references I found.

Miscellaneous

In an HTML5 specification draft, the seamless attribute was defined to prevent scroll-bars from appearing in iFrames so that they could be blended with surrounding content on a page. Though this element does not appear in the latest revision.

The scrollbar BarProp object is a child of the window object and represents the user interface element that contains a scrolling mechanism, or some similar interface concept. window.scrollbars.visible will return true if the scroll bars are visible.

interface Window {
  // The current browsing context
  readonly attribute WindowProxy window;
  readonly attribute WindowProxy self;
           attribute DOMString name;
  [PutForwards=href] readonly attribute Location location;
  readonly attribute History history;
  readonly attribute UndoManager undoManager;
  Selection getSelection();
  [Replaceable] readonly attribute BarProp locationbar;
  [Replaceable] readonly attribute BarProp menubar;
  [Replaceable] readonly attribute BarProp personalbar;
  [Replaceable] readonly attribute BarProp scrollbars;
  [Replaceable] readonly attribute BarProp statusbar;
  [Replaceable] readonly attribute BarProp toolbar;
  void close();
  void focus();
  void blur();
  // Truncated

The History API also includes features for scroll restoration on page navigation to persist the scroll position on page load.

window.history.scrollRestoration can be used to check the status of scrollrestoration or change its status (appending ="auto"/"manual". Auto is the default value. Changing it to manual means that you as the developer will take ownership of any scroll changes that may be required when a user traverses the app's history. If you need to, you can keep track of the scroll position as you push history entries with history.pushState().

---

Further reading:

Examples

Package structure for a Java project?

I usually like to have the following:

  • bin (Binaries)
  • doc (Documents)
  • inf (Information)
  • lib (Libraries)
  • res (Resources)
  • src (Source)
  • tst (Test)

These may be considered unconventional, but I find it to be a very nice way to organize things.

How can you use php in a javascript function

I think you're confusing server code with client code.

JavaScript runs on the client after it has received data from the server (like a webpage).

PHP runs on the server before it sends the data.

So there are two ways with interacting with JavaScript with php.

Like above, you can generate javascript with php in the same fashion you generate HTML with php.

Or you can use an AJAX request from javascript to interact with the server. The server can respond with data and the javascript can receive that and do something with it.

I'd recommend going back to the basics and studying how HTTP works in the server-client relationship. Then study the concept of server side languages and client side languages.

Then take a tutorial with ajax, and you will start getting the concept.

Good luck, google is your friend.

How to remove the first character of string in PHP?

To remove first Character of string in PHP,

$string = "abcdef";     
$new_string = substr($string, 1);

echo $new_string;
Generates: "bcdef"

Add Items to ListView - Android

public OnClickListener moreListener = new OnClickListener() {

    @Override
      public void onClick(View v) {
          adapter.add("aaaa")
      }
}

How do I improve ASP.NET MVC application performance?

When accessing data via LINQ rely on IQueryable ...

Why use AsQueryable() instead of List()?

... and leverge a good Repository pattern:

Loading Subrecords in the Repository Pattern

This will optimize data access to ensure only the data needed is loaded and when only it is needed.

How do I merge my local uncommitted changes into another Git branch?

A shorter alternative to the previously mentioned stash approach would be:

Temporarily move the changes to a stash.

  1. git stash

Create and switch to a new branch and then pop the stash to it in just one step.

  1. git stash branch new_branch_name

Then just add and commit the changes to this new branch.

automating telnet session using bash scripts

Here is how to use telnet in bash shell/expect

#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed

set ip [lindex $argv 0]
set port [lindex $argv 1]

set timeout 5
spawn telnet $ip $port
expect "'^]'."

how to define variable in jquery

Try this :

var name = $("#txtname").val();
alert(name);

What's the actual use of 'fail' in JUnit test case?

Some cases where I have found it useful:

  • mark a test that is incomplete, so it fails and warns you until you can finish it
  • making sure an exception is thrown:
try{
  // do stuff...
  fail("Exception not thrown");
}catch(Exception e){
  assertTrue(e.hasSomeFlag());
}

Note:

Since JUnit4, there is a more elegant way to test that an exception is being thrown: Use the annotation @Test(expected=IndexOutOfBoundsException.class)

However, this won't work if you also want to inspect the exception, then you still need fail().

Meaning of *& and **& in C++

First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.

void foo(int*& x, int**& y) {
    // modifying x or y here will modify a or b in main
}

int main() {
    int val = 42;
    int *a  = &val;
    int **b = &a;

    foo(a, b);
    return 0;
}

How to find rows that have a value that contains a lowercase letter

SELECT * FROM my_table 
WHERE UPPER(some_field) != some_field

This should work with funny characters like åäöøüæï. You might need to use a language-specific utf-8 collation for the table.

ASP.NET MVC get textbox input value

Another way by using ajax method:

View:

@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart"  />

<script>
    $(function () {
        $('#btnStart').unbind('click');
        $('#btnStart').on('click', function () {
            $.ajax({
                url: "/yourControllerName/yourMethod",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({
                    txtValue: $("#txtValue").val()
                }),
                async: false
            });
       });
   });
</script>

Controller:

[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
    // do what you want with txtValue
    ...
}

Is it possible to put a ConstraintLayout inside a ScrollView?

I had NestedScrollView inside ConstraintLayout, and this NestedScrollView has one ConstraintLayout.

If you're facing issue with NestedScrollView,

add android:fillViewport="true" to NestedScrollView, worked.

Bootstrap 4 datapicker.js not included

Most of bootstrap datepickers as I write this answer are rather buggy when included in Bootstrap 4. In my view the least code adding solution is a jQuery plugin. I used this one https://plugins.jquery.com/datetimepicker/ - you can see its usage here: https://xdsoft.net/jqplugins/datetimepicker/ It sure is not as smooth as the whole BS interface, but it only requires its css and js files along with jQuery which is already included in bootstrap.

Generate a heatmap in MatPlotLib using a scatter data set

Make a 2-dimensional array that corresponds to the cells in your final image, called say heatmap_cells and instantiate it as all zeroes.

Choose two scaling factors that define the difference between each array element in real units, for each dimension, say x_scale and y_scale. Choose these such that all your datapoints will fall within the bounds of the heatmap array.

For each raw datapoint with x_value and y_value:

heatmap_cells[floor(x_value/x_scale),floor(y_value/y_scale)]+=1

Question mark and colon in statement. What does it mean?

It means if "OperationURL[1]" evaluates to "GET" then return "GetRequestSignature()" else return "". I'm guessing "GetRequestSignature()" here returns a string. The syntax CONDITION ? A : B basically stands for an if-else where A is returned when CONDITION is true and B is returned when CONDITION is false.

Passing parameters in Javascript onClick event

This is happening because they're all referencing the same i variable, which is changing every loop, and left as 10 at the end of the loop. You can resolve it using a closure like this:

link.onclick = function(j) { return function() { onClickLink(j+''); }; }(i);

You can give it a try here

Or, make this be the link you clicked in that handler, like this:

link.onclick = function(j) { return function() { onClickLink.call(this, j); }; }(i);

You can try that version here

Text editor to open big (giant, huge, large) text files

Free read-only viewers:

  • Large Text File Viewer (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size.
  • klogg (Windows, macOS, Linux) – A maintained fork of glogg, its main feature is regular expression search. It can also watch files, allows the user to mark lines, and has serious optimizations built in. But from a UI standpoint, it's ugly and clunky.
  • LogExpert (Windows) – "A GUI replacement for tail." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.
  • Lister (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings.
  • loxx (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files.

Free editors:

  • Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, Vim (Windows, macOS, Linux), Emacs (Windows, macOS, Linux), Notepad++ (Windows), Sublime Text (Windows, macOS, Linux), and VS Code (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM.
  • Large File Editor (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode.
  • GigaEdit (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow.

Builtin programs (no installation required):

  • less (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too.
  • Notepad (Windows) – Decent with large files, especially with word wrap turned off.
  • MORE (Windows) – This refers to the Windows MORE, not the Unix more. A console program that allows you to view a file, one screen at a time.

Web viewers:

Paid editors:

  • 010 Editor (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files.
  • SlickEdit (Windows, macOS, Linux) – Opens large files.
  • UltraEdit (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file...
  • EmEditor (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report).
  • BssEditor (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use.

What's the difference between SoftReference and WeakReference in Java?

The only real difference between a soft reference and a weak reference is that

the garbage collector uses algorithms to decide whether or not to reclaim a softly reachable object, but always reclaims a weakly reachable object.

Passing $_POST values with cURL

Check out the cUrl PHP documentation page. It will help much more than just with example scripts.

How to center a "position: absolute" element

Div vertically and horizontally aligned center

top: 0;
bottom: 0;
margin: auto;
position: absolute;
left: 0;
right: 0;

Note : Elements should have width and height to be set

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

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

Peak memory usage of a linux/unix process

time -f '%M' <run_program>

How can I get a specific field of a csv file?

import csv
inf = csv.reader(open('yourfile.csv','r'))
for row in inf:
  print row[1]

How to use hex() without 0x in Python?

Python 3.6+:

>>> i = 240
>>> f'{i:02x}'
'f0'

Python import csv to list

Pandas is pretty good at dealing with data. Here is one example how to use it:

import pandas as pd

# Read the CSV into a pandas data frame (df)
#   With a df you can do many things
#   most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')

# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]

# or export it as a list of dicts
dicts = df.to_dict().values()

One big advantage is that pandas deals automatically with header rows.

If you haven't heard of Seaborn, I recommend having a look at it.

See also: How do I read and write CSV files with Python?

Pandas #2

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
dicts = df.to_dict('records')

The content of df is:

     country   population population_time    EUR
0    Germany   82521653.0      2016-12-01   True
1     France   66991000.0      2017-01-01   True
2  Indonesia  255461700.0      2017-01-01  False
3    Ireland    4761865.0             NaT   True
4      Spain   46549045.0      2017-06-01   True
5    Vatican          NaN             NaT   True

The content of dicts is

[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
 {'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
 {'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
 {'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
 {'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
 {'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]

Pandas #3

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]

The content of lists is:

[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
 ['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
 ['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
 ['Ireland', 4761865.0, NaT, True],
 ['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
 ['Vatican', nan, NaT, True]]

'readline/readline.h' file not found

This command helped me on linux mint when i had exact same problem

gcc filename.c -L/usr/include -lreadline -o filename

You could use alias if you compile it many times Forexample:

alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'

logger configuration to log to file and print to stdout

Here is a complete, nicely wrapped solution based on Waterboy's answer and various other sources. It supports logging to both console and log file, allows for different log level settings, provides colorized output and is easily configurable (also available as Gist):

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# -------------------------------------------------------------------------------
#                                                                               -
#  Python dual-logging setup (console and log file),                            -
#  supporting different log levels and colorized output                         -
#                                                                               -
#  Created by Fonic <https://github.com/fonic>                                  -
#  Date: 04/05/20                                                               -
#                                                                               -
#  Based on:                                                                    -
#  https://stackoverflow.com/a/13733863/1976617                                 -
#  https://uran198.github.io/en/python/2016/07/12/colorful-python-logging.html  -
#  https://en.wikipedia.org/wiki/ANSI_escape_code#Colors                        -
#                                                                               -
# -------------------------------------------------------------------------------

# Imports
import os
import sys
import logging

# Logging formatter supporting colored output
class LogFormatter(logging.Formatter):

    COLOR_CODES = {
        logging.CRITICAL: "\033[1;35m", # bright/bold magenta
        logging.ERROR:    "\033[1;31m", # bright/bold red
        logging.WARNING:  "\033[1;33m", # bright/bold yellow
        logging.INFO:     "\033[0;37m", # white / light gray
        logging.DEBUG:    "\033[1;30m"  # bright/bold black / dark gray
    }

    RESET_CODE = "\033[0m"

    def __init__(self, color, *args, **kwargs):
        super(LogFormatter, self).__init__(*args, **kwargs)
        self.color = color

    def format(self, record, *args, **kwargs):
        if (self.color == True and record.levelno in self.COLOR_CODES):
            record.color_on  = self.COLOR_CODES[record.levelno]
            record.color_off = self.RESET_CODE
        else:
            record.color_on  = ""
            record.color_off = ""
        return super(LogFormatter, self).format(record, *args, **kwargs)

# Setup logging
def setup_logging(console_log_output, console_log_level, console_log_color, logfile_file, logfile_log_level, logfile_log_color, log_line_template):

    # Create logger
    # For simplicity, we use the root logger, i.e. call 'logging.getLogger()'
    # without name argument. This way we can simply use module methods for
    # for logging throughout the script. An alternative would be exporting
    # the logger, i.e. 'global logger; logger = logging.getLogger("<name>")'
    logger = logging.getLogger()

    # Set global log level to 'debug' (required for handler levels to work)
    logger.setLevel(logging.DEBUG)

    # Create console handler
    console_log_output = console_log_output.lower()
    if (console_log_output == "stdout"):
        console_log_output = sys.stdout
    elif (console_log_output == "stderr"):
        console_log_output = sys.stderr
    else:
        print("Failed to set console output: invalid output: '%s'" % console_log_output)
        return False
    console_handler = logging.StreamHandler(console_log_output)

    # Set console log level
    try:
        console_handler.setLevel(console_log_level.upper()) # only accepts uppercase level names
    except:
        print("Failed to set console log level: invalid level: '%s'" % console_log_level)
        return False

    # Create and set formatter, add console handler to logger
    console_formatter = LogFormatter(fmt=log_line_template, color=console_log_color)
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)

    # Create log file handler
    try:
        logfile_handler = logging.FileHandler(logfile_file)
    except Exception as exception:
        print("Failed to set up log file: %s" % str(exception))
        return False

    # Set log file log level
    try:
        logfile_handler.setLevel(logfile_log_level.upper()) # only accepts uppercase level names
    except:
        print("Failed to set log file log level: invalid level: '%s'" % logfile_log_level)
        return False

    # Create and set formatter, add log file handler to logger
    logfile_formatter = LogFormatter(fmt=log_line_template, color=logfile_log_color)
    logfile_handler.setFormatter(logfile_formatter)
    logger.addHandler(logfile_handler)

    # Success
    return True

# Main function
def main():

    # Setup logging
    script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    if (not setup_logging(console_log_output="stdout", console_log_level="warning", console_log_color=True,
                        logfile_file=script_name + ".log", logfile_log_level="debug", logfile_log_color=False,
                        log_line_template="%(color_on)s[%(created)d] [%(threadName)s] [%(levelname)-8s] %(message)s%(color_off)s")):
        print("Failed to setup logging, aborting.")
        return 1

    # Log some messages
    logging.debug("Debug message")
    logging.info("Info message")
    logging.warning("Warning message")
    logging.error("Error message")
    logging.critical("Critical message")

# Call main function
if (__name__ == "__main__"):
    sys.exit(main())

NOTE regarding Microsoft Windows 10:
For colors to actually appear on Microsoft Windows 10, ANSI terminal mode has to be enabled first. Here is a function to do just that:

# Enable ANSI terminal on Microsoft Windows 10
# https://stackoverflow.com/a/36760881/1976617
# https://docs.microsoft.com/en-us/windows/console/setconsolemode
def windows_enable_ansi_terminal():
    if (sys.platform != "win32"):
        return None
    try:
        import ctypes
        kernel32 = ctypes.windll.kernel32
        result = kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
        if (result == 0): raise Exception
        return True
    except:
        return False

How to use su command over adb shell?

The su command does not execute anything, it just raise your privileges.

Try adb shell su -c YOUR_COMMAND.

Comprehensive methods of viewing memory usage on Solaris

# echo ::memstat | mdb -k
Page Summary                Pages                MB  %Tot
------------     ----------------  ----------------  ----
Kernel                       7308                57   23%
Anon                         9055                70   29%
Exec and libs                1968                15    6%
Page cache                   2224                17    7%
Free (cachelist)             6470                50   20%
Free (freelist)              4641                36   15%

Total                       31666               247
Physical                    31256               244

Getting today's date in YYYY-MM-DD in Python?

This works:

from datetime import date
today =date.today()

Output in this time: 2020-08-29

Additional:

this_year = date.today().year
this_month = date.today().month
this_day = date.today().day
print(today)
print(this_year)
print(this_month)
print(this_day)

How to resolve Unneccessary Stubbing exception

For me neither the @Rule nor the @RunWith(MockitoJUnitRunner.Silent.class) suggestions worked. It was a legacy project where we upgraded to mockito-core 2.23.0.

We could get rid of the UnnecessaryStubbingException by using:

Mockito.lenient().when(mockedService.getUserById(any())).thenReturn(new User());

instead of:

when(mockedService.getUserById(any())).thenReturn(new User());

Needless to say that you should rather look at the test code, but we needed to get the stuff compiled and the tests running first of all ;)

addID in jQuery?

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

If input value is blank, assign a value of "empty" with Javascript

I'm guessing this is what you want...

When the form is submitted, check if the value is empty and if so, send a value = empty.

If so, you could do the following with jQuery.

$('form').submit(function(){
    var input = $('#test').val();
    if(input == ''){
         $('#test').val('empty');
    }    
});

HTML

<form> 
    <input id="test" type="text" />
</form>

http://jsfiddle.net/jasongennaro/NS6Ca/

Click your cursor in the box and then hit enter to see the form submit the value.

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.

That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'? Absolutely!

String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"

Everything seems to work fine to me! indexOf can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.

It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!

String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;

It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):

In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).


Would this be the culprit to the funky characters?

Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.

That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.


Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence) overload.

System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU

The replaceAll solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.

Regular expression \p{L} and \p{N}

\p{L} matches a single code point in the category "letter".
\p{N} matches any kind of numeric character in any script.

Source: regular-expressions.info

If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.

Show hidden div on ng-click within ng-repeat

Remove the display:none, and use ng-show instead:

<ul class="procedures">
    <li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
        <h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="showDetails">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Here's the fiddle: http://jsfiddle.net/asmKj/


You can also use ng-class to toggle a class:

<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">

I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/

How to check "hasRole" in Java Code with Spring Security?

My Approach with the help of Java8 , Passing coma separated roles will give you true or false

    public static Boolean hasAnyPermission(String permissions){
    Boolean result = false;
    if(permissions != null && !permissions.isEmpty()){
        String[] rolesArray = permissions.split(",");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        for (String role : rolesArray) {
            boolean hasUserRole = authentication.getAuthorities().stream().anyMatch(r -> r.getAuthority().equals(role));
            if (hasUserRole) {
                result = true;
                break;
            }
        }
    }
    return result;
}

How to call Android contacts list?

hi i have a code to save the contact in your database by shared preference here is my code

public class Main22Activity extends AppCompatActivity {
    EditText nameInput,phoneInput;
    TextView LargeText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main22);
        nameInput = (EditText) findViewById(R.id.nameInput);
        phoneInput = (EditText) findViewById(R.id.phoneInput);

        LargeText = (TextView) findViewById(R.id.textView2);
    }

    public void saveInfo (View view){
        SharedPreferences sharedPref = getSharedPreferences("nameInfo" , Context.MODE_PRIVATE);
        SharedPreferences.Editor editor= sharedPref.edit();
        editor.putString("name", nameInput.getText().toString());
        editor.putString("phone", phoneInput.getText().toString());
        editor.apply();
        Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
    }

    public void displayData(View view){
        SharedPreferences sharedPref = getSharedPreferences("nameInfo" , Context.MODE_PRIVATE);
        String name = sharedPref.getString("name", "");
        String ph = sharedPref.getString ("phone","");
        LargeText.setText(name + " " + ph);
    }
}

jQuery Date Picker - disable past dates

jQuery API documentation - datepicker

The minimum selectable date. When set to null, there is no minimum.

Multiple types supported:

Date: A date object containing the minimum date.
Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.
String: A string in the format defined by the dateFormat option, or a relative date.
Relative dates must contain value and period pairs; valid periods are y for years, m for months, w for weeks, and d for days. For example, +1m +7d represents one month and seven days from today.

In order not to display previous dates other than today

$('#datepicker').datepicker({minDate: 0});

How to install Hibernate Tools in Eclipse?

Instructions for Eclipse Indigo:

Once installed click on Window -> Show View -> Others. A new window pops up. Click on folder Hibernate and select Hibernate Configurations to setup a DB connection. It is possible to setup a new connection using an existing Hiberbate properties file or creating a JDBC connection.

Once setup your DB connection click on Ping to test everything is correct.

Lastly, click on the Open HQL Editor button (third button on the top Hibernate Configurations menu) to run a HQL query.

PHP foreach change original array values

Use &:

foreach($arr as &$value) {
    $value = $newVal;
}

& passes a value of the array as a reference and does not create a new instance of the variable. Thus if you change the reference the original value will change.

PHP documentation for Passing by Reference

Edit 2018

This answer seems to be favored by a lot of people on the internet, which is why I decided to add more information and words of caution.
While pass by reference in foreach (or functions) is a clean and short solution, for many beginners this might be a dangerous pitfall.

  1. Loops in PHP don't have their own scope. - @Mark Amery

    This could be a serious problem when the variables are being reused in the same scope. Another SO question nicely illustrates why that might be a problem.

  2. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. - PHP docs for foreach.

    Unsetting a record or changing the hash value (the key) during the iteration on the same loop could lead to potentially unexpected behaviors in PHP < 7. The issue gets even more complicated when the array itself is a reference.

  3. Foreach performance.
    In general, PHP prefers pass by value due to the copy-on-write feature. It means that internally PHP will not create duplicate data unless the copy of it needs to be changed. It is debatable whether pass by reference in foreach would offer a performance improvement. As it is always the case, you need to test your specific scenario and determine which option uses less memory and CPU time. For more information see the SO post linked below by NikiC.

  4. Code readability.
    Creating references in PHP is something that quickly gets out of hand. If you are a novice and don't have full control of what you are doing, it is best to stay away from references. For more information about & operator take a look at this guide: Reference — What does this symbol mean in PHP?
    For those who want to learn more about this part of PHP language: PHP References Explained

A very nice technical explanation by @NikiC of the internal logic of PHP foreach loops:
How does PHP 'foreach' actually work?

Numpy - add row to array

As this question is been 7 years before, in the latest version which I am using is numpy version 1.13, and python3, I am doing the same thing with adding a row to a matrix, remember to put a double bracket to the second argument, otherwise, it will raise dimension error.

In here I am adding on matrix A

1 2 3
4 5 6

with a row

7 8 9

same usage in np.r_

A= [[1, 2, 3], [4, 5, 6]]
np.append(A, [[7, 8, 9]], axis=0)

    >> array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
#or 
np.r_[A,[[7,8,9]]]

Just to someone's intersted, if you would like to add a column,

array = np.c_[A,np.zeros(#A's row size)]

following what we did before on matrix A, adding a column to it

np.c_[A, [2,8]]

>> array([[1, 2, 3, 2],
          [4, 5, 6, 8]])

Combine a list of data frames into one data frame by row

bind-plot

Code:

library(microbenchmark)

dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
  dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
                            c=rep(LETTERS,10),d=rep(LETTERS,10))
}


mb <- microbenchmark(
plyr::rbind.fill(dflist),
dplyr::bind_rows(dflist),
data.table::rbindlist(dflist),
plyr::ldply(dflist,data.frame),
do.call("rbind",dflist),
times=1000)

ggplot2::autoplot(mb)

Session:

R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

> packageVersion("plyr")
[1] ‘1.8.4’
> packageVersion("dplyr")
[1] ‘0.5.0’
> packageVersion("data.table")
[1] ‘1.9.6’

UPDATE: Rerun 31-Jan-2018. Ran on the same computer. New versions of packages. Added seed for seed lovers.

enter image description here

set.seed(21)
library(microbenchmark)

dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
  dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
                            c=rep(LETTERS,10),d=rep(LETTERS,10))
}


mb <- microbenchmark(
  plyr::rbind.fill(dflist),
  dplyr::bind_rows(dflist),
  data.table::rbindlist(dflist),
  plyr::ldply(dflist,data.frame),
  do.call("rbind",dflist),
  times=1000)

ggplot2::autoplot(mb)+theme_bw()


R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

> packageVersion("plyr")
[1] ‘1.8.4’
> packageVersion("dplyr")
[1] ‘0.7.2’
> packageVersion("data.table")
[1] ‘1.10.4’

UPDATE: Rerun 06-Aug-2019.

enter image description here

set.seed(21)
library(microbenchmark)

dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
  dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
                            c=rep(LETTERS,10),d=rep(LETTERS,10))
}


mb <- microbenchmark(
  plyr::rbind.fill(dflist),
  dplyr::bind_rows(dflist),
  data.table::rbindlist(dflist),
  plyr::ldply(dflist,data.frame),
  do.call("rbind",dflist),
  purrr::map_df(dflist,dplyr::bind_rows),
  times=1000)

ggplot2::autoplot(mb)+theme_bw()

R version 3.6.0 (2019-04-26)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.2 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so

packageVersion("plyr")
packageVersion("dplyr")
packageVersion("data.table")
packageVersion("purrr")

>> packageVersion("plyr")
[1] ‘1.8.4’
>> packageVersion("dplyr")
[1] ‘0.8.3’
>> packageVersion("data.table")
[1] ‘1.12.2’
>> packageVersion("purrr")
[1] ‘0.3.2’

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

Look for this:

ANY page in your project that has a missing, or different Namespace...

If you have ANY page in your project with <NO Namespace> , OR a

DIFFERENT Namespace than Default.aspx, you will get this

"Cannot load Default.aspx", or this: "Default.aspx does not belong here".

ALSO: If you have a Redirect to a page in your Solution/Project and the page which is to be Redirected To has a bad namespace -- you may not get a compiler error, until you try and run. If the Redirect is removed or commented-out, the error goes away...

BTW -- What the hell do these error messages mean? Is this MS.Access, with the "misdirection" -- ??

DGK

Calling Javascript from a html form

In this bit of code:

getRadioButtonValue(this["whichThing"]))

you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.

EDIT To get the value out of the radio buttons, grab the JQuery library, and then use this:

  $('input[name=whichThing]:checked').val() 

Edit 2 Due to the desire to reinvent the wheel, here's non-Jquery code:

var t = '';
for (i=0; i<document.myform.whichThing.length; i++) {
     if (document.myform.whichThing[i].checked==true) {
         t = t + document.myform.whichThing[i].value;
     }
}

or, basically, modify the original line of code to read thusly:

getRadioButtonValue(document.myform.whichThing))

Edit 3 Here's your homework:

      function handleClick() {
        alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
        //event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
    </script>
  </head>
<body>
<form name="aye" onSubmit="return handleClick()">
     <input name="Submit"  type="submit" value="Update" />
     Which of the following do you like best?
     <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
     <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
     <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>

Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.

In the function itself, I modified the how the form was being accessed. The structure is: document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.

The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.

EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.

See the difference in this method:

function handleClick() {
   alert("Direct Access: " + document.aye["whichThing"]);
   alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
   return false; // prevent further bubbling of event
}

Is it possible to ignore one single specific line with Pylint?

Pylint message control is documented in the Pylint manual:

Is it possible to locally disable a particular message?

Yes, this feature has been added in Pylint 0.11. This may be done by adding # pylint: disable=some-message,another-one at the desired block level or at the end of the desired line of code.

You can use the message code or the symbolic names.

For example,

def test():
    # Disable all the no-member violations in this function
    # pylint: disable=no-member
    ...
global VAR # pylint: disable=global-statement

The manual also has further examples.

There is a wiki that documents all Pylint messages and their codes.

How to vertically align <li> elements in <ul>?

You can use flexbox for this.

ul {
    display: flex;
    align-items: center;
}

A detailed explanation of how to use flexbox can be found here.

Find index of last occurrence of a sub-string using T-SQL

This worked very well for me.

REVERSE(SUBSTRING(REVERSE([field]), CHARINDEX(REVERSE('[expr]'), REVERSE([field])) + DATALENGTH('[expr]'), DATALENGTH([field])))

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

Following solution is clean and works perfectly.

  1. Download Elevate zip file from https://www.winability.com/download/Elevate.zip

  2. Inside zip you should find two files: Elevate.exe and Elevate64.exe. (The latter is a native 64-bit compilation, if you require that, although the regular 32-bit version, Elevate.exe, should work fine with both the 32- and 64-bit versions of Windows)

  3. Copy the file Elevate.exe into a folder where Windows can always find it (such as C:/Windows). Or you better you can copy in same folder where you are planning to keep your bat file.

  4. To use it in a batch file, just prepend the command you want to execute as administrator with the elevate command, like this:

 elevate net start service ...

How can I switch my signed in user in Visual Studio 2013?

I have Visual Studio 2013 Express. I had to delete the registry key under:

hkey_current_user\software\Microsoft\VSCommon\12.\clientservices\tokenstorge\VWDExpress\ideuser

How to create a shared library with cmake?

I'm trying to learn how to do this myself, and it seems you can install the library like this:

cmake_minimum_required(VERSION 2.4.0)

project(mycustomlib)

# Find source files
file(GLOB SOURCES src/*.cpp)

# Include header files
include_directories(include)

# Create shared library
add_library(${PROJECT_NAME} SHARED ${SOURCES})

# Install library
install(TARGETS ${PROJECT_NAME} DESTINATION lib/${PROJECT_NAME})

# Install library headers
file(GLOB HEADERS include/*.h)
install(FILES ${HEADERS} DESTINATION include/${PROJECT_NAME})

SQL Server: how to create a stored procedure

To Create SQL server Store procedure in SQL server management studio

  • Expand your database
  • Expand programmatically
  • Right-click on Stored-procedure and Select "new Stored Procedure"

Now, Write your Store procedure, for example, it can be something like below

USE DatabaseName;  
GO  
CREATE PROCEDURE ProcedureName 
 @LastName nvarchar(50),   
 @FirstName nvarchar(50)   
AS   

SET NOCOUNT ON;  
 
//Your SQL query here, like
Select  FirstName, LastName, Department  
FROM HumanResources.vEmployeeDepartmentHistory  
WHERE FirstName = @FirstName AND LastName = @LastName  
GO  

Where, DatabaseName = name of your database
ProcedureName = name of SP
InputValue = your input parameter value (@LastName and @FirstName) and type = parameter type example nvarchar(50) etc.

Source: Stored procedure in sql server (With Example)

To Execute the above stored procedure you can use sample query as below

EXECUTE ProcedureName @FirstName = N'Pilar', @LastName = N'Ackerman';  

Reading json files in C++

Essentially javascript and C++ work on two different principles. Javascript creates an "associative array" or hash table, which matches a string key, which is the field name, to a value. C++ lays out structures in memory, so the first 4 bytes are an integer, which is an age, then maybe we have a fixed-wth 32 byte string which represents the "profession".

So javascript will handle things like "age" being 18 in one record and "nineteen" in another. C++ can't. (However C++ is much faster).

So if we want to handle JSON in C++, we have to build the associative array from the ground up. Then we have to tag the values with their types. Is it an integer, a real value (probably return as "double"), boolean, a string? It follows that a JSON C++ class is quite a large chunk of code. Effectively what we are doing is implementing a bit of the javascript engine in C++. We then pass our JSON parser the JSON as a string, and it tokenises it, and gives us functions to query the JSON from C++.

How set the android:gravity to TextView from Java side in Android

This will center the text in a text view:

TextView ta = (TextView) findViewById(R.layout.text_view);
LayoutParams lp = new LayoutParams();
lp.gravity = Gravity.CENTER_HORIZONTAL;
ta.setLayoutParams(lp);

How to schedule a stored procedure in MySQL

You can use mysql scheduler to run it each 5 seconds. You can find samples at http://dev.mysql.com/doc/refman/5.1/en/create-event.html

Never used it but I hope this would work:

CREATE EVENT myevent
    ON SCHEDULE EVERY 5 SECOND
    DO
      CALL delete_rows_links();

CSS how to make an element fade in and then fade out?

A way to do this would be to set the color of the element to black, and then fade to the color of the background like this:

<style> 
p {
animation-name: example;
animation-duration: 2s;
}

@keyframes example {
from {color:black;}
to {color:white;}
}
</style>
<p>I am FADING!</p>

I hope this is what you needed!

Disable sorting on last column when using jQuery DataTables

Its work for me - you can try this


dataTable({
    "paging":   true,
    "ordering": false,
    "info":     true,
})

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History

Converting a string to an integer on Android

Use regular expression:

String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""));

output: i=1234;

If you need first number combination then you should try below code:

String s="abc123xyz456";
int i=NumberFormat.getInstance().parse(s).intValue();

output: i=123;

How do I show multiple recaptchas on a single page?

I know this question is old but in case if anyone will look for it in the future. It is possible to have two captcha's on one page. Pink to documentation is here: https://developers.google.com/recaptcha/docs/display Example below is just a copy form doc and you dont have to specify different layouts.

<script type="text/javascript">
  var verifyCallback = function(response) {
    alert(response);
  };
  var widgetId1;
  var widgetId2;
  var onloadCallback = function() {
    // Renders the HTML element with id 'example1' as a reCAPTCHA widget.
    // The id of the reCAPTCHA widget is assigned to 'widgetId1'.
    widgetId1 = grecaptcha.render('example1', {
      'sitekey' : 'your_site_key',
      'theme' : 'light'
    });
    widgetId2 = grecaptcha.render(document.getElementById('example2'), {
      'sitekey' : 'your_site_key'
    });
    grecaptcha.render('example3', {
      'sitekey' : 'your_site_key',
      'callback' : verifyCallback,
      'theme' : 'dark'
    });
  };
</script>

python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.

How to unpack pkl file?

Handy one-liner

pkl() (
  python -c 'import pickle,sys;d=pickle.load(open(sys.argv[1],"rb"));print(d)' "$1"
)
pkl my.pkl

Will print __str__ for the pickled object.

The generic problem of visualizing an object is of course undefined, so if __str__ is not enough, you will need a custom script.

Get single row result with Doctrine NativeQuery

Both getSingleResult() and getOneOrNullResult() will throw an exception if there is more than one result. To fix this problem you could add setMaxResults(1) to your query builder.

 $firstSubscriber = $entity->createQueryBuilder()->select('sub')
        ->from("\Application\Entity\Subscriber", 'sub')
        ->where('sub.subscribe=:isSubscribe')
        ->setParameter('isSubscribe', 1)  
        ->setMaxResults(1)
        ->getQuery()
        ->getOneOrNullResult();

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

Parse query string in JavaScript

Here is a fast and easy way of parsing query strings in JavaScript:

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}

Now make a request to page.html?x=Hello:

console.log(getQueryVariable('x'));

iPhone app could not be installed at this time

This can also happen if you disable cellular data for "App Store" (for example, while on vacation) and forget to turn it back on. The solution here is to simply re-enable it in Settings -> Cellular.

Select all 'tr' except the first one

Since tr:not(:first-child) is not supported by IE 6, 7, 8. You can use the help of jQuery. You may find it here

Facebook login "given URL not allowed by application configuration"

I was getting this problem while using a tunnel because I:

  1. had the tunnel url:port set in the FB app settings
  2. but was accessing the local server by pointing my browser to "http://localhost:3000"

once i started punching the tunnel url:port into the browser, i was good to go.

i'm using Rails and Facebooker, but might help others just the same.

How to filter (key, value) with ng-repeat in AngularJs?

Also you can use ng-repeat with ng-if:

<div ng-repeat="(key, value) in order" ng-if="value > 0">

Android List View Drag and Drop sort

Now it's pretty easy to implement for RecyclerView with ItemTouchHelper. Just override onMove method from ItemTouchHelper.Callback:

 @Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
    mMovieAdapter.swap(viewHolder.getAdapterPosition(), target.getAdapterPosition());
    return true;
}

Pretty good tutorial on this can be found at medium.com : Drag and Swipe with RecyclerView

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

How to set the size of a column in a Bootstrap responsive table

You could use inline styles and define the width in the <th> tag. Make it so that the sum of the widths = 100%.

    <tr>
        <th style="width:10%">Size</th>
        <th style="width:30%">Bust</th>
        <th style="width:50%">Waist</th>
        <th style="width:10%">Hips</th>
    </tr>

Bootply demo

Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.

How to get the last element of a slice?

Bit less elegant but can also do:

sl[len(sl)-1: len(sl)]

How To Include CSS and jQuery in my WordPress plugin?

Accepted answer is incomplete. You should use the right hook: wp_enqueue_scripts

Example:

    function add_my_css_and_my_js_files(){
        wp_enqueue_script('your-script-name', $this->urlpath  . '/your-script-filename.js', array('jquery'), '1.2.3', true);
        wp_enqueue_style( 'your-stylesheet-name', plugins_url('/css/new-style.css', __FILE__), false, '1.0.0', 'all');
    }
    add_action('wp_enqueue_scripts', "add_my_css_and_my_js_files");

Downloading a Google font and setting up an offline site that uses it

The other answers are not wrong, but I found this to be the fastest way.

  1. Download the zip file from Google fonts and unzip it.
  2. Upload the font files 3 at a time to http://www.fontsquirrel.com/tools/webfont-generator
  3. Download the results.

Results contain all font formats: woff, svg, ttf, eot.

AND as an added bonus they generate the css file for you too!

Deny direct access to all .php files except index.php

Allow only 2 ip , all other will block

Order Deny,Allow
Deny from all
Allow from 173.11.227.73 108.222.245.179

How to retrieve element value of XML using Java?

If the XML is well formed then you can convert it to Document. By using the XPath you can get the XML Elements.

String xml = "<stackusers><name>Yash</name><age>30</age></stackusers>";

Form XML-String Create Document and find the elements using its XML-Path.

Document doc = getDocument(xml, true);

    public static Document getDocument(String xmlData, boolean isXMLData) throws Exception {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setNamespaceAware(true);
        dbFactory.setIgnoringComments(true);
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc;
        if (isXMLData) {
            InputSource ips = new org.xml.sax.InputSource(new StringReader(xmlData));
            doc = dBuilder.parse(ips);
        } else {
            doc = dBuilder.parse( new File(xmlData) );
        }
        return doc;
    }

Use org.apache.xpath.XPathAPI to get Node or NodeList.

System.out.println("XPathAPI:"+getNodeValue(doc, "/stackusers/age/text()"));

NodeList nodeList = getNodeList(doc, "/stackusers");
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList));
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList.item(0)));

    public static String getNodeValue(Document doc, String xpathExpression) throws Exception {
        Node node = org.apache.xpath.XPathAPI.selectSingleNode(doc, xpathExpression);
        String nodeValue = node.getNodeValue();
        return nodeValue;
    }
    public static NodeList getNodeList(Document doc, String xpathExpression) throws Exception {
        NodeList result = org.apache.xpath.XPathAPI.selectNodeList(doc, xpathExpression);
        return result;
    }

Using javax.xml.xpath.XPathFactory

System.out.println("javax.xml.xpath.XPathFactory:"+getXPathFactoryValue(doc, "/stackusers/age"));

    static XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
    public static String getXPathFactoryValue(Document doc, String xpathExpression) throws XPathExpressionException, TransformerException, IOException {
        Node node = (Node) xpath.evaluate(xpathExpression, doc, XPathConstants.NODE);
        String nodeStr = getXmlContentAsString(node);
        return nodeStr;
    }

Using Document Element.

System.out.println("DocumentElementText:"+getDocumentElementText(doc, "age"));

    public static String getDocumentElementText(Document doc, String elementName) {
        return doc.getElementsByTagName(elementName).item(0).getTextContent();
    }

Get value in between two strings.

String nodeVlaue = org.apache.commons.lang.StringUtils.substringBetween(xml, "<age>", "</age>");
System.out.println("StringUtils.substringBetween():"+nodeVlaue);

Full Example:

public static void main(String[] args) throws Exception {
    String xml = "<stackusers><name>Yash</name><age>30</age></stackusers>";
    Document doc = getDocument(xml, true);
    
    String nodeVlaue = org.apache.commons.lang.StringUtils.substringBetween(xml, "<age>", "</age>");
    System.out.println("StringUtils.substringBetween():"+nodeVlaue);
    
    System.out.println("DocumentElementText:"+getDocumentElementText(doc, "age"));
    System.out.println("javax.xml.xpath.XPathFactory:"+getXPathFactoryValue(doc, "/stackusers/age"));
    
    System.out.println("XPathAPI:"+getNodeValue(doc, "/stackusers/age/text()"));
    NodeList nodeList = getNodeList(doc, "/stackusers");
    System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList));
    System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList.item(0)));
}
public static String getXmlContentAsString(Node node) throws TransformerException, IOException {
    StringBuilder stringBuilder = new StringBuilder();
    NodeList childNodes = node.getChildNodes();
    int length = childNodes.getLength();
    for (int i = 0; i < length; i++) {
        stringBuilder.append( toString(childNodes.item(i), true) );
    }
    return stringBuilder.toString();
}

OutPut:

StringUtils.substringBetween():30
DocumentElementText:30
javax.xml.xpath.XPathFactory:30
XPathAPI:30
XPathAPI NodeList:<stackusers>
   <name>Yash</name>
   <age>30</age>
</stackusers>
XPathAPI NodeList:<name>Yash</name><age>30</age>

Install apps silently, with granted INSTALL_PACKAGES permission

Try this LD_LIBRARY_PATH=/vendor/lib:/system/lib before pm install. It works well.

How to rename a file using Python

import shutil
import os

files = os.listdir("./pics/") 

for key in range(0, len(files)):
   print files[key]
   shutil.move("./pics/" + files[key],"./pics/img" + str(key) + ".jpeg")

This should do it. python 3+

Bytes of a string in Java

There's a method called getBytes(). Use it wisely .

No converter found capable of converting from type to type

If you look at the exception stack trace it says that, it failed to convert from ABDeadlineType to DeadlineType. Because your repository is going to return you the objects of ABDeadlineType. How the spring-data-jpa will convert into the other one(DeadlineType). You should return the same type from repository and then have some intermediate util class to convert it into your model class.

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();
}

preg_match in JavaScript?

var myregexp = /\[(\d+)\]\[(\d+)\]/;
var match = myregexp.exec(text);
if (match != null) {
    var productId = match[1];
    var shopId = match[2];
} else {
    // no match
}

Python conversion from binary string to hexadecimal

bstr = '0000 0100 1000 1101'.replace(' ', '')
hstr = '%0*X' % ((len(bstr) + 3) // 4, int(bstr, 2))

Download all stock symbol list of a market

Exchanges will usually publish an up-to-date list of securities on their web pages. For example, these pages offer CSV downloads:

NASDAQ Updated their site, so you will have to modify the URLS:

NASDAQ

AMEX

NYSE

Depending on your requirement, you could create the map of these URLs by exchange in your own code.

How to test code dependent on environment variables using JUnit?

I use System.getEnv() to get the map and I keep as a field, so I can mock it:

public class AAA {

    Map<String, String> environmentVars; 

    public String readEnvironmentVar(String varName) {
        if (environmentVars==null) environmentVars = System.getenv();   
        return environmentVars.get(varName);
    }
}



public class AAATest {

         @Test
         public void test() {
              aaa.environmentVars = new HashMap<String,String>();
              aaa.environmentVars.put("NAME", "value");
              assertEquals("value",aaa.readEnvironmentVar("NAME"));
         }
}

How to check a boolean condition in EL?

You can check this way too

<c:if test="${theBooleanVariable ne true}">It's false!</c:if>

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

That's called SQL INJECTION. The ' tries to open/close a string in your mysql query. You should always escape any string that gets into your queries.

for example,

instead of this:

"VALUES ('$sender_id') "

do this:

"VALUES ('". mysql_real_escape_string($sender_id)  ."') "

(or equivalent, of course)

However, it's better to automate this, using PDO, named parameters, prepared statements or many other ways. Research about this and SQL Injection (here you have some techniques).

Hope it helps. Cheers

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Add Bootstrap Glyphicon to Input Box

You can use its Unicode HTML

So to add a user icon, just add &#xe008; to the placeholder attribute, or wherever you want it.

You may want to check this cheat sheet.

Example:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<input type="text" class="form-control" placeholder="&#xe008; placeholder..." style="font-family: 'Glyphicons Halflings', Arial">_x000D_
<input type="text" class="form-control" value="&#xe008; value..." style="font-family: 'Glyphicons Halflings', Arial">_x000D_
<input type="submit" class="btn btn-primary" value="&#xe008; submit-button" style="font-family: 'Glyphicons Halflings', Arial">
_x000D_
_x000D_
_x000D_

Don't forget to set the input's font to the Glyphicon one, using the following code: font-family: 'Glyphicons Halflings', Arial, where Arial is the font of the regular text in the input.

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

Linux / Bash, using ps -o to get process by specific name?

Sorry, much late to the party, but I'll add here that if you wanted to capture processes with names identical to your search string, you could do

pgrep -x PROCESS_NAME

-x          Require an exact match of the process name, or argument list if -f is given.
             The default is to match any substring.

This is extremely useful if your original process created child processes (possibly zombie when you query) which prefix the original process' name in their own name and you are trying to exclude them from your results. There are many UNIX daemons which do this. My go-to example is ninja-dev-sync.

How to center a subview of UIView

Before we'll begin, let's just remind that origin point is the Upper Left corner CGPoint of a view. An important thing to understand about views and parents.

Lets take a look at this simple code, a view controller that adds to it's view a black square:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        createDummyView()
        super.view.backgroundColor = UIColor.cyanColor();
    }

    func createDummyView(){
        var subView = UIView(frame: CGRect(x: 15, y: 50, width: 50 , height: 50));
        super.view.addSubview(subView);
        view.backgroundColor = UIColor.blackColor()
    }

}

This will create this view: the black rectangle origin and center does fit the same coordinates as it's parent

enter image description here

Now let's try to add subView another SubSubView, and giving subSubview same origin as subView, but make subSubView a child view of subView

We'll add this code:

var subSubView = UIView();
subSubView.frame.origin = subView.frame.origin;
subSubView.frame.size = CGSizeMake(20, 20);
subSubView.backgroundColor = UIColor.purpleColor()
subView.addSubview(subSubView)

And this is the result:

enter image description here

Because of this line:

subSubView.frame.origin = subView.frame.origin;

You expect for the purple rectangle's origin to be same as it's parent (the black rectangle) but it goes under it, and why is that? Because when you add a view to another view, the subView frame "world" is now it's parent BOUND RECTANGLE, if you have a view that it's origin on the main screen is at coords (15,15) for all it's sub views, the upper left corner will be (0,0)

This is why you need to always refer to a parent by it's bound rectangle, which is the "world" of it's subViews, lets fix this line to:

subSubView.frame.origin = subView.bounds.origin;

And see the magic, the subSubview is now located exactly in it's parent origin:

enter image description here

So, you like "ok I only wanted to center my view by my parents view, what's the big deal?" well, it isn't big deal, you just need to "translate" the parent Center point which is taken from it's frame to parent's bounds center by doing this:

subSubView.center = subView.convertPoint(subView.center, fromView: subSubView);

You're actually telling him "take parents view center, and convert it into subSubView world".

And you'll get this result:

enter image description here

Getting error "No such module" using Xcode, but the framework is there

In rare cases this error might be fixed by setting proper platform here [ProjectNavigator]->[Project]->[Target]-> (Architectures) BaseSDK

enter image description here

When creating a framework I've chosen accidentally wrong template (as I was creating macOS framework previously) because it was set to like my previous choice. When adding a target it is easy to miss out configuring platform so double check that.

enter image description here

C# getting its own class name

For reference, if you have a type that inherits from another you can also use

this.GetType().BaseType.Name

Show space, tab, CRLF characters in editor of Visual Studio

My problem was hitting CTRL+F and space

This marked all spaces brown. Spent 10 minutes to "turn it off" :P

Reading a List from properties file and load with spring annotation @Value

if using property placeholders then ser1702544 example would become

@Value("#{myConfigProperties['myproperty'].trim().replaceAll(\"\\s*(?=,)|(?<=,)\\s*\", \"\").split(',')}") 

With placeholder xml:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
    <property name="properties" ref="myConfigProperties" />
    <property name="placeholderPrefix"><value>$myConfigProperties{</value></property>
</bean>    

<bean id="myConfigProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
     <property name="locations">
         <list>
                <value>classpath:myprops.properties</value>
         </list>
     </property>
</bean> 

Rails :include vs. :joins

The difference between joins and include is that using the include statement generates a much larger SQL query loading into memory all the attributes from the other table(s).

For example, if you have a table full of comments and you use a :joins => users to pull in all the user information for sorting purposes, etc it will work fine and take less time than :include, but say you want to display the comment along with the users name, email, etc. To get the information using :joins, it will have to make separate SQL queries for each user it fetches, whereas if you used :include this information is ready for use.

Great example:

http://railscasts.com/episodes/181-include-vs-joins

Typescript export vs. default export

I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default declaration for a class, and instead append the export tag to the class declaration. The imported class should be instead listed in the import command of the module.

That is: instead of

class Foo {
    // ...
}
export default Foo;

and the simple import Foo from './foo'; in the module that will import, one should use

export class Foo {
    // ...
}

and import {Foo} from './foo' in the importer.

The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in export default can lead to problems

C programming: Dereferencing pointer to incomplete type error

You are using the pointer newFile without allocating space for it.

struct stasher_file *newFile = malloc(sizeof(stasher_file));

Also you should put the struct name at the top. Where you specified stasher_file is to create an instance of that struct.

struct stasher_file {
    char name[32];
    int  size;
    int  start;
    int  popularity;
};

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

Simple Solution

If you are working with pure html/js/css files.

Install this small server(link) app in chrome. Open the app and point the file location to your project directory.

Goto the url shown in the app.

Edit: Smarter solution using Gulp

Step 1: To install Gulp. Run following command in your terminal.

npm install gulp-cli -g
npm install gulp -D

Step 2: Inside your project directory create a file named gulpfile.js. Copy the following content inside it.

var gulp        = require('gulp');
var bs          = require('browser-sync').create();   

gulp.task('serve', [], () => {
        bs.init({
            server: {
               baseDir: "./",
            },
            port: 5000,
            reloadOnRestart: true,
            browser: "google chrome"
        });
        gulp.watch('./**/*', ['', bs.reload]);
});

Step 3: Install browser sync gulp plugin. Inside the same directory where gulpfile.js is present, run the following command

npm install browser-sync gulp --save-dev

Step 4: Start the server. Inside the same directory where gulpfile.js is present, run the following command

gulp serve

How to install Ruby 2.1.4 on Ubuntu 14.04

First of all, install the prerequisite libraries:

sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Then install rbenv, which is used to install Ruby:

cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL

rbenv install 2.3.1
rbenv global 2.3.1
ruby -v

Then (optional) tell Rubygems to not install local documentation:

echo "gem: --no-ri --no-rdoc" > ~/.gemrc

Credits: https://gorails.com/setup/ubuntu/14.10

Warning!!! There are issues with Gnome-Shell. See comment below.

Maximum packet size for a TCP connection

The absolute limitation on TCP packet size is 64K (65535 bytes), but in practicality this is far larger than the size of any packet you will see, because the lower layers (e.g. ethernet) have lower packet sizes.

The MTU (Maximum Transmission Unit) for Ethernet, for instance, is 1500 bytes. Some types of networks (like Token Ring) have larger MTUs, and some types have smaller MTUs, but the values are fixed for each physical technology.

Understanding Bootstrap's clearfix class

The :before pseudo element isn't needed for the clearfix hack itself.

It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.

display:table is being used because display:block doesn't do the trick. Using display:block margins will collapse even with a :before element.

There is one caveat: if vertical-align:baseline is used in table cells with clearfixed <div> elements, Firefox won't align well. Then you might prefer using display:block despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.

Using getline() with file input in C++

you should do as:

getline(name, sizeofname, '\n');
strtok(name, " ");

This will give you the "joht" in name then to get next token,

temp = strtok(NULL, " ");

temp will get "smith" in it. then you should use string concatination to append the temp at end of name. as:

strcat(name, temp);

(you may also append space first, to obtain a space in between).

Opposite of append in jquery

Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.

GetFiles with multiple extensions

I'm not sure if that is possible. The MSDN GetFiles reference says a search pattern, not a list of search patterns.

I might be inclined to fetch each list separately and "foreach" them into a final list.

How to create a batch file to run cmd as administrator

(This is based on @DarkXphenomenon's answer, which unfortunately had some problems.)

You need to enclose your code within this wrapper:

if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload
    echo %~nx0: running payload with parameters:
    echo %*
    echo ---------------------------------------------------
    cd /d %2
    shift
    shift
    rem put your code here
    rem e.g.: perl myscript.pl %1 %2 %3 %4 %5 %6 %7 %8 %9
goto :eof

This makes batch file run itself as elevated user. It adds two parameters to the privileged code:

  • word payload, to indicate this is payload call, i.e. already elevated. Otherwise it would just open new processes over and over.

  • directory path where the main script was called. Due to the fact that Windows always starts elevated cmd.exe in "%windir%\system32", there's no easy way of knowing what the original path was (and retaining ability to copy your script around without touching code)

Note: Unfortunately, for some reason shift does not work for %*, so if you need to pass actual arguments on, you will have to resort to the ugly notation I used in the example (%1 %2 %3 %4 %5 %6 %7 %8 %9), which also brings in the limit of maximum of 9 arguments

Check whether a value exists in JSON object

I think this is the best and easy way:

$lista = @()

$lista += ('{"name": "Diego" }' | ConvertFrom-Json)
$lista += ('{"name": "Monica" }' | ConvertFrom-Json)
$lista += ('{"name": "Celia" }' | ConvertFrom-Json)
$lista += ('{"name": "Quin" }' | ConvertFrom-Json)

if ("Diego" -in $lista.name) {
    Write-Host "is in the list"
    return $true

}
else {
    Write-Host "not in the list"
    return $false
}

Excel 2007 - Compare 2 columns, find matching values

=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup) will solve this issue.

This will search for a value in the first column to the left and return the value in the same row from a specific column.

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

The idle shortcut is an "Advertised Shortcut" which breaks certain features like the "find target" button. Google for more info.

You can view the link with a hex editor or download LNK Parser to see where it points to.

In my case it runs:
..\..\..\..\..\Python27\pythonw.exe "C:\Python27\Lib\idlelib\idle.pyw"

Add padding on view programmatically

view.setPadding(0,padding,0,0);

This will set the top padding to padding-pixels.

If you want to set it in dp instead, you can do a conversion:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);

How to zip a whole folder using PHP

Use this is working fine.

$dir = '/Folder/';
$zip = new ZipArchive();
$res = $zip->open(trim($dir, "/") . '.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($res === TRUE) {
    foreach (glob($dir . '*') as $file) {
        $zip->addFile($file, basename($file));
    }
    $zip->close();
} else {
    echo 'Failed to create to zip. Error: ' . $res;
}

Error: Java: invalid target release: 11 - IntelliJ IDEA

I tried all the above and found this secret sauce

  1. make sure pom.xml specifies your desired jdk.
  2. make sure maven specifies your desired jdk.
  3. make sure Projects specifies your desired jdk.
  4. make sure Modules specifies your integer jdk AND Dependencies specifies your jdk. hth.

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

I got a better way to hide static cells and even sections dynamically without any hacks.

Setting the row height to 0 can hide a row, but that doesn't work if you want to hide an entire section which will hold some spaces even you hide all the rows.

My approach is to build a section array of static cells. Then the table view contents will be driven by the section array.

Here is some sample code:

var tableSections = [[UITableViewCell]]()

private func configTableSections() {
    // seciton A
    tableSections.append([self.cell1InSectionA, self.cell2InSectionA])

    // section B
    if shouldShowSectionB {
        tableSections.append([self.cell1InSectionB, self.cell2InSectionB])
    }

    // section C
    if shouldShowCell1InSectionC {
        tableSections.append([self.cell1InSectionC, self.cell2InSectionC, self.cell3InSectionC])
    } else {
        tableSections.append([self.cell2InSectionC, self.cell3InSectionC])
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return tableSections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableSections[section].count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return tableSections[indexPath.section][indexPath.row]
}

This way, you can put all of your configuration code together without having to write the nasty code to calculate number of rows and sections. And of course, no 0 heights anymore.

This code is also very easy maintain. For example, if you want to add/remove more cells or sections.

Similarly, you can create a section header title array and section footer title array to config your section titles dynamically.

How to error handle 1004 Error with WorksheetFunction.VLookup?

There is a way to skip the errors inside the code and go on with the loop anyway, hope it helps:

Sub new1()

Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
Dim ws As Worksheet: Set ws = Sheets(1)
Dim rngLook As Range: Set rngLook = ws.Range("A:M")

currName = "Example"
On Error Resume Next ''if error, the code will go on anyway
cellNum = wsFunc.VLookup(currName, rngLook, 13, 0)

If Err.Number <> 0 Then
''error appeared
    MsgBox "currName not found" ''optional, no need to do anything
End If

On Error GoTo 0 ''no error, coming back to default conditions

End Sub

How to List All Redis Databases?

Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli:

$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1

How can I change NULL to 0 when getting a single value from a SQL function?

You could use

SELECT ISNULL(SUM(ISNULL(Price, 0)), 0).

I'm 99% sure that will work.

@class vs. #import

Another advantage: Quick compilation

If you include a header file, any change in it causes the current file also to compile but this is not the case if the class name is included as @class name. Of course you will need to include the header in source file

CSS set li indent

padding-left is what controls the indentation of ul not margin-left.

Compare: Here's setting padding-left to 0, notice all the indentation disappears.

_x000D_
_x000D_
ul {
  padding-left: 0;
}
_x000D_
<ul>
  <li>section a
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
<ul>
  <li>section b
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
_x000D_
_x000D_
_x000D_

and here's setting margin-left to 0px. Notice the indentation does NOT change.

_x000D_
_x000D_
ul {
  margin-left: 0;
}
_x000D_
<ul>
  <li>section a
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
<ul>
  <li>section b
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
_x000D_
_x000D_
_x000D_

How to unblock with mysqladmin flush hosts

You can easily restart your MySql service. This kicks the error off.

How can I set a website image that will show as preview on Facebook?

If you're using Weebly, start by viewing the published site and right-clicking the image to Copy Image Address. Then in Weebly, go to Edit Site, Pages, click the page you wish to use, SEO Settings, under Header Code enter the code from Shef's answer:

<meta property="og:image" content="/uploads/..." />

just replacing /uploads/... with the copied image address. Click Publish to apply the change.

You can skip the part of Shef's answer about namespace, because that's already set by default in Weebly.

How to auto-size an iFrame?

In IE 5.5+, you can use the contentWindow property:

iframe.height = iframe.contentWindow.document.scrollHeight;

In Netscape 6 (assuming firefox as well), contentDocument property:

iframe.height = iframe.contentDocument.scrollHeight

python catch exception and continue try block

one way you could handle this is with a generator. Instead of calling the function, yield it; then whatever is consuming the generator can send the result of calling it back into the generator, or a sentinel if the generator failed: The trampoline that accomplishes the above might look like so:

def consume_exceptions(gen):
    action = next(gen)
    while True:
        try:
            result = action()
        except Exception:
            # if the action fails, send a sentinel
            result = None

        try:
            action = gen.send(result)
        except StopIteration:
            # if the generator is all used up, result is the return value.
            return result

a generator that would be compatible with this would look like this:

def do_smth1():
    1 / 0

def do_smth2():
    print "YAY"

def do_many_things():
    a = yield do_smth1
    b = yield do_smth2
    yield "Done"
>>> consume_exceptions(do_many_things())
YAY

Note that do_many_things() does not call do_smth*, it just yields them, and consume_exceptions calls them on its behalf

Sort a single String in Java

In Java 8 it can be done with:

String s = "edcba".chars()
    .sorted()
    .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
    .toString();

A slightly shorter alternative that works with a Stream of Strings of length one (each character in the unsorted String is converted into a String in the Stream) is:

String sorted =
    Stream.of("edcba".split(""))
        .sorted()
        .collect(Collectors.joining());

How to get first object out from List<Object> using Linq

I do so.

List<Object> list = new List<Object>();

if(list.Count>0){
  Object obj = list[0];
}

npm install error - unable to get local issuer certificate

Anyone gets this error when 'npm install' is trying to fetch a package from HTTPS server with a self-signed or invalid certificate.

Quick and insecure solution:

npm config set strict-ssl false

Why this solution is insecure? The above command tells npm to connect and fetch module from server even server do not have valid certificate and server identity is not verified. So if there is a proxy server between npm client and actual server, it provided man in middle attack opportunity to an intruder.

Secure solution:

If any module in your package.json is hosted on a server with self-signed CA certificate then npm is unable to identify that server with an available system CA certificates. So you need to provide CA certificate for server validation with the explicit configuration in .npmrc. In .npmrc you need to provide cafile, please refer more detail about cafile configuration here

cafile=./ca-certs.pem

In ca-certs file, you can add any number of CA certificates(public) that you required to identify servers. The certificate should be in “Base-64 encoded X.509 (.CER)(PEM)” format.

For example,

# cat ca-certs.pem 
DigiCert Global Root CA
=======================
-----BEGIN CERTIFICATE-----
CAUw7C29C79Fv1C5qfPrmAE.....
-----END CERTIFICATE-----

VeriSign Class 3 Public Primary Certification Authority - G5
========================================
-----BEGIN CERTIFICATE-----
MIIE0zCCA7ugAwIBAgIQ......
-----END CERTIFICATE-----

Note: once you provide cafile configuration in .npmrc, npm try to identify all server using CA certificate(s) provided in cafile only, it won't check system CA certificate bundles then. If someone wants all well-known public CA authority certificat bundle then can get from here.

One other situation when you get this error:

If you have mentioned Git URL as a dependency in package.json and git is on invalid/self-signed certificate then also npm throws a similar error. You can fix it with following configuration for git client

git config --global http.sslVerify false 

How to keep footer at bottom of screen

Perhaps the easiest is to use position: absolute to fix to the bottom, then a suitable margin/padding to make sure that the other text doesn't spill over the top of it.

css:

<style>
  body {
    margin: 0 0 20px;
  }
  .footer {
    position: absolute;
    bottom: 0;
    height: 20px;
    background: #f0f0f0;
    width: 100%;
  }
</style>

Here is the html main content.

<div class="footer"> Here is the footer. </div>

Partial Dependency (Databases)

A FD (functional dependency) that holds in a relation is partial when removing one of the determining attributes gives a FD that holds in the relation. A FD that isn't partial is full.

Eg: If {A,B} ? {C} but also {A} ? {C} then {C} is partially functionally dependent on {A,B}.

Eg: Here's a relation value where that example condition holds. (A FD holds in a relation variable when it holds in every value that can arise.)

A  B  C
1  1  1
1  2  1
2  1  1

The non-trivial FDs that hold: {A,B} determines {C}, {B,C}, {A,C} & {A,B,C}; {A}, {B} & {} also determine {C}. Of those: {A,B} ? {C} is partial per {A} ? {C}, {B} ? {C} & {} ? {C}; {A} ? {C} & {B} ? {C} are partial per {} ? {C}; the others are full.

A functional dependency X ? Y is a full functional dependency if removal of any attribute A from X means that the dependency does not hold any more; that is, for any attribute A e X, (X – {A}) does not functionally determine Y. A functional dependency X ? Y is a partial dependency if some attribute A e X can be removed from X and the dependency still holds; that is, for some A e X, (X – {A}) ? Y.

-- FUNDAMENTALS OF Database Systems SIXTH EDITION Ramez Elmasri & Navathe

Notice that whether a FD is full vs partial doesn't depend on CKs (candidate keys), let alone one CK that you might be calling the PK (primary key).

(A definition of 2NF is that every non-CK attribute is fully functionally determined by every CK. Observe that the only CK is {A,B} & the only non-CK attribute C is partially dependent on it so this value is not in 2NF & indeed it is the lossless join of components/projections onto {A,B} & {A,C}, onto {A,B} & {B,C} & onto {A,B} & {C}.)

(Beware that that textbook's definition of "transitive FD" does not define the same sort of thing as the standard definition of "transitive FD".)

How to delete Project from Google Developers Console

You can try delete project via Google Cloud Platform https://console.cloud.google.com/iam-admin/projects delete project from google cloud platform

Select required project and click DELETE PROJECT. The project will be completely deleted after 7 days

Is there a difference between x++ and ++x in java?

Yes, there is a difference, incase of x++(postincrement), value of x will be used in the expression and x will be incremented by 1 after the expression has been evaluated, on the other hand ++x(preincrement), x+1 will be used in the expression. Take an example:

public static void main(String args[])
{
    int i , j , k = 0;
    j = k++; // Value of j is 0
    i = ++j; // Value of i becomes 1
    k = i++; // Value of k is 1
    System.out.println(k);  
}

Select row on click react-table

I am not familiar with, react-table, so I do not know it has direct support for selecting and deselecting (it would be nice if it had).

If it does not, with the piece of code you already have you can install the onCLick handler. Now instead of trying to attach style directly to row, you can modify state, by for instance adding selected: true to row data. That would trigger rerender. Now you only have to override how are rows with selected === true rendered. Something along lines of:

// Any Tr element will be green if its (row.age > 20) 
<ReactTable
  getTrProps={(state, rowInfo, column) => {
    return {
      style: {
        background: rowInfo.row.selected ? 'green' : 'red'
      }
    }
  }}
/>

How to sort a dataframe by multiple column(s)

I learned about order with the following example which then confused me for a long time:

set.seed(1234)

ID        = 1:10
Age       = round(rnorm(10, 50, 1))
diag      = c("Depression", "Bipolar")
Diagnosis = sample(diag, 10, replace=TRUE)

data = data.frame(ID, Age, Diagnosis)

databyAge = data[order(Age),]
databyAge

The only reason this example works is because order is sorting by the vector Age, not by the column named Age in the data frame data.

To see this create an identical data frame using read.table with slightly different column names and without making use of any of the above vectors:

my.data <- read.table(text = '

  id age  diagnosis
   1  49 Depression
   2  50 Depression
   3  51 Depression
   4  48 Depression
   5  50 Depression
   6  51    Bipolar
   7  49    Bipolar
   8  49    Bipolar
   9  49    Bipolar
  10  49 Depression

', header = TRUE)

The above line structure for order no longer works because there is no vector named age:

databyage = my.data[order(age),]

The following line works because order sorts on the column age in my.data.

databyage = my.data[order(my.data$age),]

I thought this was worth posting given how confused I was by this example for so long. If this post is not deemed appropriate for the thread I can remove it.

EDIT: May 13, 2014

Below is a generalized way of sorting a data frame by every column without specifying column names. The code below shows how to sort from left to right or by right to left. This works if every column is numeric. I have not tried with a character column added.

I found the do.call code a month or two ago in an old post on a different site, but only after extensive and difficult searching. I am not sure I could relocate that post now. The present thread is the first hit for ordering a data.frame in R. So, I thought my expanded version of that original do.call code might be useful.

set.seed(1234)

v1  <- c(0,0,0,0, 0,0,0,0, 1,1,1,1, 1,1,1,1)
v2  <- c(0,0,0,0, 1,1,1,1, 0,0,0,0, 1,1,1,1)
v3  <- c(0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1)
v4  <- c(0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1)

df.1 <- data.frame(v1, v2, v3, v4) 
df.1

rdf.1 <- df.1[sample(nrow(df.1), nrow(df.1), replace = FALSE),]
rdf.1

order.rdf.1 <- rdf.1[do.call(order, as.list(rdf.1)),]
order.rdf.1

order.rdf.2 <- rdf.1[do.call(order, rev(as.list(rdf.1))),]
order.rdf.2

rdf.3 <- data.frame(rdf.1$v2, rdf.1$v4, rdf.1$v3, rdf.1$v1) 
rdf.3

order.rdf.3 <- rdf.1[do.call(order, as.list(rdf.3)),]
order.rdf.3

Rounding a variable to two decimal places C#

Pay attention on fact that Round rounds.

So (I don't know if it matters in your industry or not), but:

float a = 12.345f;
Math.Round(a,2);

//result:12,35, and NOT 12.34 !

To make it more precise for your case we can do something like this:

int aInt = (int)(a*100);
float aFloat= aInt /100.0f;
//result:12,34