Programs & Examples On #Test class

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

I faced the same Maven connection timeout issue and resolved by disabling/whitelisting the anti-virus & firewall setting.

The issue got resolved immediately:

org.apache.maven.wagon.providers.http.httpclient.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239)

specifying goal in pom.xml

You need to set the path of maven under Global setting like MAVEN_HOME

/user/share/maven

and make sure the workbench have permission of read, write and delete "777"

Resource files not found from JUnit test cases

Make 'maven.test.skip' as false in pom file, while building project test reource will come under test-classes.

<maven.test.skip>false</maven.test.skip>

Maven does not find JUnit tests to run

Here's the exact code I had to add to my pom.xml:

    <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.21.0</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.2.0-M1</version>
                </dependency>
                <dependency>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.2.0</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

And here's my dependencies:

    <dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.2.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.easytesting</groupId>
        <artifactId>fest-assert-core</artifactId>
        <version>2.0M10</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-surefire-provider</artifactId>
        <version>1.2.0-M1</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.2.0-M1</version>
    </dependency>
</dependencies>

Can I use conditional statements with EJS templates (in JMVC)?

For others that stumble on this, you can also use ejs params/props in conditional statements:

recipes.js File:

app.get("/recipes", function(req, res) {
    res.render("recipes.ejs", {
        recipes: recipes
    });
});

recipes.ejs File:

<%if (recipes.length > 0) { %>
// Do something with more than 1 recipe
<% } %>

How does Python manage int and long?

On my machine:

>>> print type(1<<30)
<type 'int'>
>>> print type(1<<31)
<type 'long'>
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'long'>

Python uses ints (32 bit signed integers, I don't know if they are C ints under the hood or not) for values that fit into 32 bit, but automatically switches to longs (arbitrarily large number of bits - i.e. bignums) for anything larger. I'm guessing this speeds things up for smaller values while avoiding any overflows with a seamless transition to bignums.

Best way to copy from one array to another

There are lots of solutions:

b = Arrays.copyOf(a, a.length);

Which allocates a new array, copies over the elements of a, and returns the new array.

Or

b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);

Which copies the source array content into a destination array that you allocate yourself.

Or

b = a.clone();

which works very much like Arrays.copyOf(). See this thread.

Or the one you posted, if you reverse the direction of the assignment in the loop:

b[i] = a[i]; // NOT a[i] = b[i];

onchange equivalent in angular2

@Mark Rajcok gave a great solution for ion projects that include a range type input.

In any other case of non ion projects I will suggest this:

HTML:

<input type="text" name="points" #points maxlength="8" [(ngModel)]="range" (ngModelChange)="range=saverange($event, points)">

Component:

    onChangeAchievement(eventStr: string, eRef): string {

      //Do something (some manipulations) on input and than return it to be saved:

       //In case you need to force of modifing the Element-Reference value on-focus of input:
       var eventStrToReplace = eventStr.replace(/[^0-9,eE\.\+]+/g, "");
       if (eventStr != eventStrToReplace) {
           eRef.value = eventStrToReplace;
       }

      return this.getNumberOnChange(eventStr);

    }

The idea here:

  1. Letting the (ngModelChange) method to do the Setter job:

    (ngModelChange)="range=saverange($event, points)

  2. Enabling direct access to the native Dom element using this call:

    eRef.value = eventStrToReplace;

A JOIN With Additional Conditions Using Query Builder or Eloquent

$results = DB::table('rooms')
                     ->distinct()
                     ->leftJoin('bookings', function($join)
                         {
                             $join->on('rooms.id', '=', 'bookings.room_type_id');
                             $join->on('arrival','>=',DB::raw("'2012-05-01'"));
                             $join->on('arrival','<=',DB::raw("'2012-05-10'"));
                             $join->on('departure','>=',DB::raw("'2012-05-01'"));
                             $join->on('departure','<=',DB::raw("'2012-05-10'"));
                         })
                     ->where('bookings.room_type_id', '=', NULL)
                     ->get();

Not quite sure if the between clause can be added to the join in laravel.

Notes:

  • DB::raw() instructs Laravel not to put back quotes.
  • By passing a closure to join methods you can add more join conditions to it, on() will add AND condition and orOn() will add OR condition.

Creating all possible k combinations of n items in C++

Behind the link below is a generic C# answer to this problem: How to format all combinations out of a list of objects. You can limit the results only to the length of k pretty easily.

https://stackoverflow.com/a/40417765/2613458

How do I convert from int to String?

It's acceptable, but I've never written anything like that. I'd prefer this:

String strI = Integer.toString(i);

Div with margin-left and width:100% overflowing on the right side

I realise this is an old post but this might benefit somebody who, like me, has come to this page from a google search and is at their wits end.

None of the other answers given here worked for me and I had already given up hope, but today I was searching for a solution to another similar problem with divs, which I found answered multiple times on SO. The accepted answer worked for my div, and I had the sudden notion to try it for my previous textbox issue - and it worked! The solution:

add box-sizing: border-box to the style of the textbox.

To add this to all multi-line textboxes using CSS, add the following to your style sheet:

textarea
{
  box-sizing: border-box;
}

Thanks to thirtydot for the solution at

width: 100%-padding?

and

Content of div is longer then div itself when width is set to 100%?

ImportError: No module named mysql.connector using Python2

In my case i already installed the package

pip install mysql-connector
pip install mysql-connector-python

It giving me the same error so, i uninstall the both package by using

pip uninstall mysql-connector
pip uninstall mysql-connector-python

and then again install the second package only

pip install mysql-connector-python

This solution worked for me.

What is the difference between a 'closure' and a 'lambda'?

A lambda is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Examples:

def func(): return h
def anotherfunc(h):
   return func()

This will cause an error, because func does not close over the environment in anotherfunc - h is undefined. func only closes over the global environment. This will work:

def anotherfunc(h):
    def func(): return h
    return func()

Because here, func is defined in anotherfunc, and in python 2.3 and greater (or some number like this) when they almost got closures correct (mutation still doesn't work), this means that it closes over anotherfunc's environment and can access variables inside of it. In Python 3.1+, mutation works too when using the nonlocal keyword.

Another important point - func will continue to close over anotherfunc's environment even when it's no longer being evaluated in anotherfunc. This code will also work:

def anotherfunc(h):
    def func(): return h
    return func

print anotherfunc(10)()

This will print 10.

This, as you notice, has nothing to do with lambdas - they are two different (although related) concepts.

Is try-catch like error handling possible in ASP Classic?

There are two approaches, you can code in JScript or VBScript which do have the construct or you can fudge it in your code.

Using JScript you'd use the following type of construct:

<script language="jscript" runat="server">
try  {
    tryStatements
}
catch(exception) {
    catchStatements
}
finally {
    finallyStatements
}
</script>

In your ASP code you fudge it by using on error resume next at the point you'd have a try and checking err.Number at the point of a catch like:

<%
' Turn off error Handling
On Error Resume Next


'Code here that you want to catch errors from

' Error Handler
If Err.Number <> 0 Then
   ' Error Occurred - Trap it
   On Error Goto 0 ' Turn error handling back on for errors in your handling block
   ' Code to cope with the error here
End If
On Error Goto 0 ' Reset error handling.

%>

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

Programmatically navigate using react router V4

I had a similar issue when migrating over to React-Router v4 so I'll try to explain my solution below.

Please do not consider this answer as the right way to solve the problem, I imagine there's a good chance something better will arise as React Router v4 becomes more mature and leaves beta (It may even already exist and I just didn't discover it).

For context, I had this problem because I occasionally use Redux-Saga to programmatically change the history object (say when a user successfully authenticates).

In the React Router docs, take a look at the <Router> component and you can see you have the ability to pass your own history object via a prop. This is the essence of the solution - we supply the history object to React-Router from a global module.

Steps:

  1. Install the history npm module - yarn add history or npm install history --save
  2. create a file called history.js in your App.js level folder (this was my preference)

    // src/history.js
    
    import createHistory from 'history/createBrowserHistory';
    export default createHistory();`
    
  3. Add this history object to your Router component like so

    // src/App.js
    
    import history from '../your/path/to/history.js;'
    <Router history={history}>
    // Route tags here
    </Router>
    
  4. Adjust the URL just like before by importing your global history object:

    import history from '../your/path/to/history.js;'
    history.push('new/path/here/');
    

Everything should stay synced up now, and you also have access to a way of setting the history object programmatically and not via a component/container.

Reloading/refreshing Kendo Grid

$("#grd").data("kendoGrid").dataSource.read();

Safe width in pixels for printing web pages?

It's not as straightforward as looks. I just run into a similar question, and here is what I got: First, a little background on wikipedia.

Next, in CSS, for paper, they have pt, which is point, or 1/72 inch. So if you want to have the same size of image as on the monitor, first you have to know the DPI/PPI of your monitor (usually 96, as mentioned on the wikipedia article), then convert it to inches, then convert it to points (divide by 72).

But then again, the browsers have all sorts of problems with printable content, for example, if you try to use float css tags, the Gecko-based browsers will cut your images mid page, even if you use page-break-inside: avoid; on your images (see here, in the Mozilla bug tracking system).

There is (much) more about printing from a browser in this article on A List Apart.

Furthermore, you have to deal width "Shrink to Fit" in the print preview, and the various paper sizes and orientations.

So either you just figure out a good image size in inches, I mean points, (7.1" * 72 = 511.2 so width: 511pt; would work for the letter sized paper) regardless of the pixel sizes, or go width percentage widths, and base your image widths on the paper size.

Good luck...

How to import component into another root component in Angular 2

above answers In simple words, you have to register under @NgModule's

declarations: [
    AppComponent, YourNewComponentHere
  ] 

of app.module.ts

do not forget to import that component.

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

Yes, it's definitely possible, although I am struggling with the same issue at the moment. I've managed to get the cells to hide and everything works ok, but I cannot currently make the thing animate neatly. Here is what I have found:

I am hiding rows based on the state of an ON / OFF switch in the first row of the first section. If the switch is ON there is 1 row beneath it in the same section, otherwise there are 2 different rows.

I have a selector called when the switch is toggled, and I set a variable to indicate which state I am in. Then I call:

[[self tableView] reloadData];

I override the tableView:willDisplayCell:forRowAtIndexPath: function and if the cell is supposed to be hidden I do this:

[cell setHidden:YES];

That hides the cell and its contents, but does not remove the space it occupies.

To remove the space, override the tableView:heightForRowAtIndexPath: function and return 0 for rows that should be hidden.

You also need to override tableView:numberOfRowsInSection: and return the number of rows in that section. You have to do something strange here so that if your table is a grouped style the rounded corners occur on the correct cells. In my static table there is the full set of cells for the section, so there is the first cell containing the option, then 1 cell for the ON state options and 2 more cells for the OFF state options, a total of 4 cells. When the option is ON, I have to return 4, this includes the hidden option so that the last option displayed has a rounded box. When the option is off, the last two options are not displayed so I return 2. This all feels clunky. Sorry if this isn't very clear, its tricky to describe. Just to illustrate the setup, this is the construction of the table section in IB:

  • Row 0: Option with ON / OFF switch
  • Row 1: Displayed when option is ON
  • Row 2: Displayed when option is OFF
  • Row 3: Displayed when option is OFF

So when the option is ON the table reports two rows which are:

  • Row 0: Option with ON / OFF switch
  • Row 1: Displayed when option is ON

When the option is OFF the table reports four rows which are:

  • Row 0: Option with ON / OFF switch
  • Row 1: Displayed when option is ON
  • Row 2: Displayed when option is OFF
  • Row 3: Displayed when option is OFF

This approach doesn't feel correct for several reasons, its just as far as I have got with my experimentation so far, so please let me know if you find a better way. The problems I have observed so far are:

  • It feels wrong to be telling the table the number of rows is different to what is presumably contained in the underlying data.

  • I can't seem to animate the change. I've tried using tableView:reloadSections:withRowAnimation: instead of reloadData and the results don't seem to make sense, I'm still trying to get this working. Currently what seems to happen is the tableView does not update the correct rows so one remains hidden that should be displayed and a void is left under the first row. I think this might be related to the first point about the underlying data.

Hopefully someone will be able to suggest alternative methods or perhaps how to extend with animation, but maybe this will get you started. My apologies for the lack of hyperlinks to functions, I put them in but they were rejected by the spam filter because I am a fairly new user.

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

Div Scrollbar - Any way to style it?

Using javascript you can style the scroll bars. Which works fine in IE as well as FF.

Check the below links

From Twinhelix , Example 2 , Example 3 [or] you can find some 30 type of scroll style types by click the below link 30 scrolling techniques

Build error: You must add a reference to System.Runtime

On our Tfs 2013 build server I had the same error, in a test project. with the main web project running on .Net 4.5.1.

I installed a nuGet package of System Runtime and added the reference from packages\System.Runtime.4.3.0\ref\net462\System.Runtime.dll

That solved it for me.

How to save and load cookies using Python + Selenium WebDriver

You can save the current cookies as a Python object using pickle. For example:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

And later to add them back:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

Rounding a double value to x number of decimal places in swift

var n = 123.111222333
n = Double(Int(n * 10.0)) / 10.0

Result: n = 123.1

Change 10.0 (1 decimal place) to any of 100.0 (2 decimal place), 1000.0 (3 decimal place) and so on, for the number of digits you want after decimal..

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

Since this is the first result of google this error, I want to remind that simply click the bottom window error message blue link "Fix Gradle wrapper and re-import project Gradle settings" will auto fix for you now.

enter image description here

Bootstrap 3: Offset isn't working?

If I get you right, you want something that seems to be the opposite of what is desired normally: you want a horizontal layout for small screens and vertically stacked elements on large screens. You may achieve this in a way like this:

<div class="container">
    <div class="row">
        <div class="hidden-md hidden-lg col-xs-3 col-xs-offset-6">a</div>
        <div class="hidden-md hidden-lg col-xs-3">b</div>
    </div>
    <div class="row">
        <div class="hidden-xs hidden-sm">c</div>

    </div>
</div>

On small screens, i.e. xs and sm, this generates one row with two columns with an offset of 6. On larger screens, i.e. md and lg, it generates two vertically stacked elements in full width (12 columns).

ant build.xml file doesn't exist

Using ant debug after building build.xml file :

in your cmd your root should be your project at first then use the ant debug command e.g:

c:\testApp>ant debug 

How to specify in crontab by what user to run script?

EDIT: Note that this method won't work with crontab -e, but only works if you edit /etc/crontab directly. Otherwise, you may get an error like /bin/sh: www-data: command not found

Just before the program name:

*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1

Insert a new row into DataTable

@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.

//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);

DataRow dr = dt.NewRow();

dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";

dt.Rows.Add(dr);//this will add the row at the end of the datatable
//OR
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);

Get the short Git version hash

what about this :

git log --pretty="%h %cD %cn %s"  

it shows someting like :

674cd0d Wed, 20 Nov 2019 12:15:38 +0000 Bob commit message

see the pretty format documentation enter link description here

CSS: fixed to bottom and centered

The problem lies in position: static. Static means don't do anyting at all with the position. position: absolute is what you want. Centering the element is still tricky though. The following should work:

#whatever {
  position: absolute;
  bottom: 0px;
  margin-right: auto;
  margin-left: auto;
  left: 0px;
  right: 0px;
}

or

#whatever {
  position: absolute;
  bottom: 0px;
  margin-right: auto;
  margin-left: auto;
  left: 50%;
  transform: translate(-50%, 0);
}

But I recommend the first method. I used centering techniques from this answer: How to center absolutely positioned element in div?

Using Java to pull data from a webpage?

The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.

For example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class DownloadPage {

    public static void main(String[] args) throws IOException {

        // Make a URL to the web page
        URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

        // Get the input stream through URL Connection
        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();

        // Once you have the Input Stream, it's just plain old Java IO stuff.

        // For this case, since you are interested in getting plain-text web page
        // I'll use a reader and output the text content to System.out.

        // For binary content, it's better to directly read the bytes from stream and write
        // to the target file.


        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Hope this helps.

How do I obtain a list of all schemas in a Sql Server database

SELECT s.name + '.' + ao.name
       , s.name
FROM sys.all_objects ao
INNER JOIN sys.schemas s ON s.schema_id = ao.schema_id
WHERE ao.type='u';

Changing Font Size For UITableView Section Headers

This is my solution with swift 5.

To fully control the header section view, you need to use the tableView(:viewForHeaderInsection::) method in your controller, as the previous post showed. However, there is a further step: to improve performance, apple recommend not generate a new view every time but to re-use the header view, just like reuse table cell. This is by method tableView.dequeueReusableHeaderFooterView(withIdentifier: ). But the problem I had is once you start to use this re-use function, the font won't function as expected. Other things like color, alignment all fine but just font. There are some discussions but I made it work like the following.

The problem is tableView.dequeueReusableHeaderFooterView(withIdentifier:) is not like tableView.dequeneReuseCell(:) which always returns a cell. The former will return a nil if no one available. Even if it returns a reuse header view, it is not your original class type, but a UITableHeaderFooterView. So you need to do the judgement and act according in your own code. Basically, if it is nil, get a brand new header view. If not nil, force to cast so you can control.

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let reuse_header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "yourHeaderID")
        if (reuse_header == nil) {
            let new_sec_header = YourTableHeaderViewClass(reuseIdentifier:"yourHeaderID")
            new_section_header.label.text="yourHeaderString"
            //do whatever to set color. alignment, etc to the label view property
            //note: the label property here should be your custom label view. Not the build-in labelView. This way you have total control.
            return new_section_header
        }
        else {
            let new_section_header = reuse_section_header as! yourTableHeaderViewClass
            new_sec_header.label.text="yourHeaderString"
            //do whatever color, alignment, etc to the label property
            return new_sec_header}

    }

jQuery disable a link

unbind() was deprecated in jQuery 3, use the off() method instead:

$("a").off("click");

What is the best way to test for an empty string with jquery-out-of-the-box?

Try executing this in your browser console or in a node.js repl.

var string = ' ';
string ? true : false;
//-> true

string = '';
string ? true : false;
//-> false

Therefore, a simple branching construct will suffice for the test.

if(string) {
    // string is not empty
}

Sequence contains more than one element

FYI you can also get this error if EF Migrations tries to run with no Db configured, for example in a Test Project.

Chased this for hours before I figured out that it was erroring on a query, but, not because of the query but because it was when Migrations kicked in to try to create the Db.

Can regular JavaScript be mixed with jQuery?

Of course you can, but why do this? You have to include a <script></script>pair of tags that link to the jQuery web page, i.e.: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> . Then you will load the whole jQuery object just to use one single function, and because jQuery is a JavaScript library which will take time for the computer to upload, it will execute slower than just JavaScript.

PHP Unset Session Variable

You can unset session variable using:

  1. session_unset - Frees all session variables (It is equal to using: $_SESSION = array(); for older deprecated code)
  2. unset($_SESSION['Products']); - Unset only Products index in session variable. (Remember: You have to use like a function, not as you used)
  3. session_destroy — Destroys all data registered to a session

To know the difference between using session_unset and session_destroy, read this SO answer. That helps.

How can I search sub-folders using glob.glob module?

There's a lot of confusion on this topic. Let me see if I can clarify it (Python 3.7):

  1. glob.glob('*.txt') :matches all files ending in '.txt' in current directory
  2. glob.glob('*/*.txt') :same as 1
  3. glob.glob('**/*.txt') :matches all files ending in '.txt' in the immediate subdirectories only, but not in the current directory
  4. glob.glob('*.txt',recursive=True) :same as 1
  5. glob.glob('*/*.txt',recursive=True) :same as 3
  6. glob.glob('**/*.txt',recursive=True):matches all files ending in '.txt' in the current directory and in all subdirectories

So it's best to always specify recursive=True.

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

string requestUri = _apiURL + "?e=" + OperationURL[0] + ((OperationURL[1] == "GET") ? GetRequestSignature() : "");

can be translated to:

string requestUri="";
if ((OperationURL[1] == "GET")
{
    requestUri = _apiURL + "?e=" + GetRequestSignature();
}
else
{
   requestUri = _apiURL + "?e=";
}

An array of List in c#

// The letter "t" is usually letter "i"//

    for(t=0;t<x[t];t++)
    {

         printf(" %2d          || %7d \n ",t,x[t]);
    }

document.createElement("script") synchronously

The answers above pointed me in the right direction. Here is a generic version of what I got working:

  var script = document.createElement('script');
  script.src = 'http://' + location.hostname + '/module';
  script.addEventListener('load', postLoadFunction);
  document.head.appendChild(script);

  function postLoadFunction() {
     // add module dependent code here
  }      

SQL query for getting data for last 3 months

Latest Versions of mysql don't support DATEADD instead use the syntax

DATE_ADD(date,INTERVAL expr type)

To get the last 3 months data use,

DATE_ADD(NOW(),INTERVAL -90 DAY) 
DATE_ADD(NOW(), INTERVAL -3 MONTH)

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

You will get the following error message too when you provide undefined or so to an operator which expects an Observable, eg. takeUntil.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable 

Java serialization - java.io.InvalidClassException local class incompatible

@DanielChapman gives a good explanation of serialVersionUID, but no solution. the solution is this: run the serialver program on all your old classes. put these serialVersionUID values in your current versions of the classes. as long as the current classes are serial compatible with the old versions, you should be fine. (note for future code: you should always have a serialVersionUID on all Serializable classes)

if the new versions are not serial compatible, then you need to do some magic with a custom readObject implementation (you would only need a custom writeObject if you were trying to write new class data which would be compatible with old code). generally speaking adding or removing class fields does not make a class serial incompatible. changing the type of existing fields usually will.

Of course, even if the new class is serial compatible, you may still want a custom readObject implementation. you may want this if you want to fill in any new fields which are missing from data saved from old versions of the class (e.g. you have a new List field which you want to initialize to an empty list when loading old class data).

Call asynchronous method in constructor?

You could put the async calls in a separate method and call that method in the constructor. Although, this may lead to a situation where some variable values not being available at the time you expect them.

 public NewTravelPageVM(){
   GetVenues();              
 }

 async void  GetVenues(){
   var locator = CrossGeolocator.Current;
   var position = await locator.GetPositionAsync();
   Venues = await Venue.GetVenues(position.Latitude, position.Longitude);
 }

How to use find command to find all files with extensions from list?

In supplement to @Dennis Williamson 's response above, if you want the same regex to be case-insensitive to the file extensions, use -iregex :

find /path/to -iregex ".*\.\(jpg\|gif\|png\|jpeg\)" > log

varbinary to string on SQL Server

"Converting a varbinary to a varchar" can mean different things.

If the varbinary is the binary representation of a string in SQL Server (for example returned by casting to varbinary directly or from the DecryptByPassPhrase or DECOMPRESS functions) you can just CAST it

declare @b varbinary(max)
set @b = 0x5468697320697320612074657374

select cast(@b as varchar(max)) /*Returns "This is a test"*/

This is the equivalent of using CONVERT with a style parameter of 0.

CONVERT(varchar(max), @b, 0)

Other style parameters are available with CONVERT for different requirements as noted in other answers.

Asynchronous Process inside a javascript for loop

async await is here (ES7), so you can do this kind of things very easily now.

  var i;
  var j = 10;
  for (i = 0; i < j; i++) {
    await asycronouseProcess();
    alert(i);
  }

Remember, this works only if asycronouseProcess is returning a Promise

If asycronouseProcess is not in your control then you can make it return a Promise by yourself like this

function asyncProcess() {
  return new Promise((resolve, reject) => {
    asycronouseProcess(()=>{
      resolve();
    })
  })
}

Then replace this line await asycronouseProcess(); by await asyncProcess();

Understanding Promises before even looking into async await is must (Also read about support for async await)

How can I get column names from a table in SQL Server?

It will check whether the given the table is Base Table.

SELECT 
    T.TABLE_NAME AS 'TABLE NAME',
    C.COLUMN_NAME AS 'COLUMN NAME'
FROM INFORMATION_SCHEMA.TABLES T
INNER JOIN INFORMATION_SCHEMA.COLUMNS C ON T.TABLE_NAME=C.TABLE_NAME
    WHERE   T.TABLE_TYPE='BASE TABLE'
            AND T.TABLE_NAME LIKE 'Your Table Name'

How to print a number with commas as thousands separators in JavaScript

The following code uses char scan, so there's no regex.

function commafy( num){
  var parts = (''+(num<0?-num:num)).split("."), s=parts[0], L, i=L= s.length, o='';
  while(i--){ o = (i===0?'':((L-i)%3?'':',')) 
                  +s.charAt(i) +o }
  return (num<0?'-':'') + o + (parts[1] ? '.' + parts[1] : ''); 
}

It shows promising performance: http://jsperf.com/number-formatting-with-commas/5

2015.4.26: Minor fix to resolve issue when num<0. See https://jsfiddle.net/runsun/p5tqqvs3/

JPA: unidirectional many-to-one and cascading delete

@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)

Given annotation worked for me. Can have a try

For Example :-

     public class Parent{
            @Id
            @GeneratedValue(strategy=GenerationType.AUTO)
            @Column(name="cct_id")
            private Integer cct_id;
            @OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER,mappedBy="clinicalCareTeam", orphanRemoval=true)
            @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
            private List<Child> childs;
        }
            public class Child{
            @ManyToOne(fetch=FetchType.EAGER)
            @JoinColumn(name="cct_id")
            private Parent parent;
    }

Best /Fastest way to read an Excel Sheet into a DataTable?

Here is another way of doing it

public DataSet CreateTable(string source)
{
    using (var connection = new OleDbConnection(GetConnectionString(source, true)))
    {
        var dataSet = new DataSet();
        connection.Open();
        var schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        if (schemaTable == null)
            return dataSet;

        var sheetName = "";
        foreach (DataRow row in schemaTable.Rows)
        {
            sheetName = row["TABLE_NAME"].ToString();
            break;
        }

        var command = string.Format("SELECT * FROM [{0}$]", sheetName);
        var adapter = new OleDbDataAdapter(command, connection);
        adapter.TableMappings.Add("TABLE", "TestTable");
        adapter.Fill(dataSet);
        connection.Close();

        return dataSet;
    }
}

//

private string GetConnectionString(string source, bool hasHeader)
{
    return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
    Extended Properties=\"Excel 12.0;HDR={1};IMEX=1\"", source, (hasHeader ? "YES" : "NO"));
}

Why are there no ++ and --? operators in Python?

This original answer I wrote is a myth from the folklore of computing: debunked by Dennis Ritchie as "historically impossible" as noted in the letters to the editors of Communications of the ACM July 2012 doi:10.1145/2209249.2209251


The C increment/decrement operators were invented at a time when the C compiler wasn't very smart and the authors wanted to be able to specify the direct intent that a machine language operator should be used which saved a handful of cycles for a compiler which might do a

load memory
load 1
add
store memory

instead of

inc memory 

and the PDP-11 even supported "autoincrement" and "autoincrement deferred" instructions corresponding to *++p and *p++, respectively. See section 5.3 of the manual if horribly curious.

As compilers are smart enough to handle the high-level optimization tricks built into the syntax of C, they are just a syntactic convenience now.

Python doesn't have tricks to convey intentions to the assembler because it doesn't use one.

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

This might not work for everyone, but I updated node and it fixed the issue for me when none of the above did

JavaScript: set dropdown selected item based on option text

You can loop through the select_obj.options. There's a #text method in each of the option object, which you can use to compare to what you want and set the selectedIndex of the select_obj.

How to stop INFO messages displaying on spark console?

Another way of stopping logs completely is:

    import org.apache.log4j.Appender;
    import org.apache.log4j.BasicConfigurator;
    import org.apache.log4j.varia.NullAppender;

    public class SomeClass {

        public static void main(String[] args) {
            Appender nullAppender = new NullAppender();
            BasicConfigurator.configure(nullAppender);

            {...more code here...}

        }
    }

This worked for me. An NullAppender is

An Appender that ignores log events. (https://logging.apache.org/log4j/2.x/log4j-core/apidocs/org/apache/logging/log4j/core/appender/NullAppender.html)

Temporarily change current working directory in bash to run a command

Something like this should work:

sh -c 'cd /tmp && exec pwd'

Select where count of one field is greater than one

One way

SELECT t1.* 
FROM db.table t1
WHERE exists 
      (SELECT *
      FROM db.table t2 
      where t1.pk != t2.pk 
      and t1.someField = t2.someField)

Turning multi-line string into single comma-separated

With perl:

fg@erwin ~ $ perl -ne 'push @l, (split(/\s+/))[1]; END { print join(",", @l) . "\n" }' <<EOF
something1:    +12.0   (some unnecessary trailing data (this must go))
something2:    +15.5   (some more unnecessary trailing data)
something4:    +9.0   (some other unnecessary data)
something1:    +13.5  (blah blah blah)
EOF

+12.0,+15.5,+9.0,+13.5

Margin on child element moves parent element

interestingly my favorite solution to this problem isn't yet mentioned here: using floats.

html:

<div class="parent">
    <div class="child"></div>
</div>

css:

.parent{width:100px; height:100px;}
.child{float:left; margin-top:20px; width:50px; height:50px;}

see it here: http://codepen.io/anon/pen/Iphol

note that in case you need dynamic height on the parent, it also has to float, so simply replace height:100px; by float:left;

how to clear JTable

((DefaultTableModel)jTable3.getModel()).setNumRows(0); // delet all table row

Try This:

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

Stop absolutely positioned div from overlapping text

_x000D_
_x000D_
<div style="position: relative; width:600px;">_x000D_
        <p>Content of unknown length</p>_x000D_
        <div>Content of unknown height</div>_x000D_
        <div id="spacer" style="width: 200px; height: 100px; float:left; display:inline-block"></div>_x000D_
        <div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;"></div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

This should be a comment but I don't have enough reputation yet. The solution works, but visual studio code told me the following putting it into a css sheet:

inline-block is ignored due to the float. If 'float' has a value other than 'none', the box is floated and 'display' is treated as 'block'

So I did it like this

.spacer {
    float: left;
    height: 20px;
    width: 200px;
}

And it works just as well.

What is the best Java email address validation method?

Another option is use the Hibernate email validator, using the annotation @Email or using the validator class programatically, like:

import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; 

class Validator {
    // code
    private boolean isValidEmail(String email) {
        EmailValidator emailValidator = new EmailValidator();
        return emailValidator.isValid(email, null);
    }

}

How to fill background image of an UIView

Swift 4 Solution :

@IBInspectable var backgroundImage: UIImage? {
    didSet {
        UIGraphicsBeginImageContext(self.frame.size)
        backgroundImage?.draw(in: self.bounds)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        if let image = image{
            self.backgroundColor = UIColor(patternImage: image)
        }
    }
}

How do I POST an array of objects with $.ajax (jQuery or Zepto)

Try the following:

$.ajax({
  url: _saveDeviceUrl
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: {'myArray': postData}
, success: _madeSave.bind(this)
//, processData: false //Doesn't help
});

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html

The correct way to use LOCK TABLES and UNLOCK TABLES with transactional tables, such as InnoDB tables, is to begin a transaction with SET autocommit = 0 (not START TRANSACTION) followed by LOCK TABLES, and to not call UNLOCK TABLES until you commit the transaction explicitly. For example, if you need to write to table t1 and read from table t2, you can do this:

SET autocommit=0;
LOCK TABLES t1 WRITE, t2 READ, ...;... do something with tables t1 and t2 here ...
COMMIT;
UNLOCK TABLES;

Rails: Can't verify CSRF token authenticity when making a POST request

Cross site request forgery (CSRF/XSRF) is when a malicious web page tricks users into performing a request that is not intended for example by using bookmarklets, iframes or just by creating a page which is visually similar enough to fool users.

The Rails CSRF protection is made for "classical" web apps - it simply gives a degree of assurance that the request originated from your own web app. A CSRF token works like a secret that only your server knows - Rails generates a random token and stores it in the session. Your forms send the token via a hidden input and Rails verifies that any non GET request includes a token that matches what is stored in the session.

However an API is usually by definition cross site and meant to be used in more than your web app, which means that the whole concept of CSRF does not quite apply.

Instead you should use a token based strategy of authenticating API requests with an API key and secret since you are verifying that the request comes from an approved API client - not from your own app.

You can deactivate CSRF as pointed out by @dcestari:

class ApiController < ActionController::Base
  protect_from_forgery with: :null_session
end

Updated. In Rails 5 you can generate API only applications by using the --api option:

rails new appname --api

They do not include the CSRF middleware and many other components that are superflouus.

Create boolean column in MySQL with false as default value?

You can set a default value at creation time like:

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
Married boolean DEFAULT false);

How to plot a function curve in R

As sjdh also mentioned, ggplot2 comes to the rescue. A more intuitive way without making a dummy data set is to use xlim:

library(ggplot2)
eq <- function(x){sin(x)}
base <- ggplot() + xlim(0, 30)
base + geom_function(fun=eq)

Additionally, for a smoother graph we can set the number of points over which the graph is interpolated using n:

base + geom_function(fun=eq, n=10000)

Multiple lines of text in UILabel

I found a solution.

One just has to add the following code:

// Swift
textLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
textLabel.numberOfLines = 0 

// For Swift >= 3
textLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
textLabel.numberOfLines = 0

// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;  

Restored old answer (for reference and devs willing to support iOS below 6.0):

textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

On the side: both enum values yield to 0 anyway.

process.env.NODE_ENV is undefined

If you faced this probem in React, you need [email protected] and higher. Also for other environment variables than NODE_ENV to work in React, they need to be prefixed with REACT_APP_.

C# - using List<T>.Find() with custom objects

You can use find with a Predicate as follows:

list.Find(x => x.Id == IdToFind);

This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).

Android Studio AVD - Emulator: Process finished with exit code 1

This can be solved by the following step:

Please ensure "Windows Hypervisor Platform" is installed. If it's not installed, install it, restart your computer and you will be good to go.

enter image description here

React - How to get parameter value from query string?

I used an external package called query-string to parse url parameter like so.

import React, {Component} from 'react'
import { parse } from 'query-string';

resetPass() {
    const {password} = this.state;
    this.setState({fetching: true, error: undefined});
    const query = parse(location.search);
    return fetch(settings.urls.update_password, {
        method: 'POST',
        headers: {'Content-Type': 'application/json', 'Authorization': query.token},
        mode: 'cors',
        body: JSON.stringify({password})
    })
        .then(response=>response.json())
        .then(json=>{
            if (json.error)
                throw Error(json.error.message || 'Unknown fetch error');
            this.setState({fetching: false, error: undefined, changePassword: true});
        })
        .catch(error=>this.setState({fetching: false, error: error.message}));
}

Run a shell script with an html button

As stated by Luke you need to use a server side language, like php. This is a really simple php example:

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  exec("/path/to/name.sh");
}
?>

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>

Save this as myfilename.php and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

How to use curl in a shell script?

url=”http://shahkrunalm.wordpress.com“
content=”$(curl -sLI “$url” | grep HTTP/1.1 | tail -1 | awk {‘print $2'})”
if [ ! -z $content ] && [ $content -eq 200 ]
then
echo “valid url”
else
echo “invalid url”
fi

UIButton action in table view cell

We can create a closure for the button and use that in cellForRowAtIndexPath

class ClosureSleeve {
  let closure: () -> ()

  init(attachTo: AnyObject, closure: @escaping () -> ()) {
    self.closure = closure
    objc_setAssociatedObject(attachTo, "[\(arc4random())]", self,.OBJC_ASSOCIATION_RETAIN)
}

@objc func invoke() {
   closure()
 }
}

extension UIControl {
func addAction(for controlEvents: UIControlEvents = .primaryActionTriggered, action: @escaping () -> ()) {
  let sleeve = ClosureSleeve(attachTo: self, closure: action)
 addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
 }
}

And then in cellForRowAtIndexPath

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = youtableview.dequeueReusableCellWithIdentifier(identifier) as? youCell
    cell?.selectionStyle = UITableViewCell.SelectionStyle.none//swift 4 style

      button.addAction {
       //Do whatever you want to do when the button is tapped here
        print("button pressed")
      }

    return cell
 }

\r\n, \r and \n what is the difference between them?

A carriage return (\r) makes the cursor jump to the first column (begin of the line) while the newline (\n) jumps to the next line and eventually to the beginning of that line. So to be sure to be at the first position within the next line one uses both.

"You tried to execute a query that does not include the specified aggregate function"

The error is because fName is included in the SELECT list, but is not included in a GROUP BY clause and is not part of an aggregate function (Count(), Min(), Max(), Sum(), etc.)

You can fix that problem by including fName in a GROUP BY. But then you will face the same issue with surname. So put both in the GROUP BY:

SELECT
    fName,
    surname,
    Count(*) AS num_rows
FROM
    author
    INNER JOIN book
    ON author.aID = book.authorID;
GROUP BY
    fName,
    surname

Note I used Count(*) where you wanted SUM(orders.quantity). However, orders isn't included in the FROM section of your query, so you must include it before you can Sum() one of its fields.

If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.

How to make a round button?

I went through all the answers. But none of them is beginner friendly. So here I have given a very detailed answers fully explained with pictures.

Open Android Studio. Go to Project Window and scroll to drawable folder under res folder

enter image description here

Right click, select New --> drawable resource folder

enter image description here

In the window that appears, name the file rounded_corners and click on OK

enter image description here

A new file rounded_corners.xml gets created

Open the file. You are presented with the following code -->

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://android.com/apk/res/android">

</selector>

enter image description here

Replace it with the following code -->

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="8dp" />
    <solid android:color="#66b3ff" />
</shape>

enter image description here

Here the design view can be seen on the right side

Adjust the value in android:radius to make the button more or less rounded.

Then go to activity_main.xml

Put the following code -->

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:padding="10dp">

    <Button
        android:id="@+id/_1"
        android:text="1"
        android:textSize="25dp"
        android:textColor="#ffffff"
        android:background="@drawable/rounded_corners"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"/>

</RelativeLayout> 

Here I have placed the Button inside a RelativeLayout. You can use any Layout you want.

For reference purpose MainActivity.java code is as follows -->

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

I have a Pixel 4 API 30 avd installed. After running the code in the avd the display is as follows -->

enter image description here

How do you Make A Repeat-Until Loop in C++?

When you want to check the condition at the beginning of the loop, simply negate the condition on a standard while loop:

while(!cond) { ... }

If you need it at the end, use a do ... while loop and negate the condition:

do { ... } while(!cond);

notifyDataSetChanged not working on RecyclerView

I had same problem. I just solved it with declaring adapter public before onCreate of class.

PostAdapter postAdapter;

after that

postAdapter = new PostAdapter(getActivity(), posts);
recList.setAdapter(postAdapter);

at last I have called:

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    // Display the size of your ArrayList
    Log.i("TAG", "Size : " + posts.size());
    progressBar.setVisibility(View.GONE);
    postAdapter.notifyDataSetChanged();
}

May this will helps you.

How to read the value of a private field from a different class in Java?

Just an additional note about reflection: I have observed in some special cases, when several classes with the same name exist in different packages, that reflection as used in the top answer may fail to pick the correct class from the object. So if you know what is the package.class of the object, then it's better to access its private field values as follows:

org.deeplearning4j.nn.layers.BaseOutputLayer ll = (org.deeplearning4j.nn.layers.BaseOutputLayer) model.getLayer(0);
Field f = Class.forName("org.deeplearning4j.nn.layers.BaseOutputLayer").getDeclaredField("solver");
f.setAccessible(true);
Solver s = (Solver) f.get(ll);

(This is the example class that was not working for me)

How to redirect single url in nginx?

If you need to duplicate more than a few redirects, you might consider using a map:

# map is outside of server block
map $uri $redirect_uri {
    ~^/issue1/?$    http://example.com/shop/issues/custom_isse_name1;
    ~^/issue2/?$    http://example.com/shop/issues/custom_isse_name2;
    ~^/issue3/?$    http://example.com/shop/issues/custom_isse_name3;
    # ... or put these in an included file
}

location / {
    try_files $uri $uri/ @redirect-map;
}

location @redirect-map {
    if ($redirect_uri) {  # redirect if the variable is defined
        return 301 $redirect_uri;
    }
}

How to insert a large block of HTML in JavaScript?

If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:

var x =
    "<div> \
    <span> \
    <p> \
    some text \
    </p> \
    </div>";

How to uncompress a tar.gz in another directory

You can use for loop to untar multiple .tar.gz files to another folder. The following code will take /destination/folder/path as an argument to the script and untar all .tar.gz files present at the current location in /destination/folder/path.

if [ $# -ne 1 ];
 then
 echo "invalid argument/s"
 echo "Usage: ./script-file-name.sh /target/directory"
 exit 0
fi
for file in *.tar.gz
do
    tar -zxvf "$file" --directory $1
done

Regex number between 1 and 100

There are many options how to write a regex pattern for that

  • ^(?:(?!0)\d{1,2}|100)$
  • ^(?:[1-9]\d?|100)$
  • ^(?!0)(?=100$|..$|.$)\d+$

Make EditText ReadOnly

Please use this code..

Edittext.setEnabled(false);

Why std::cout instead of simply cout?

In the C++ standard, cout is defined in the std namespace, so you need to either say std::cout or put

using namespace std;

in your code in order to get at it.

However, this was not always the case, and in the past cout was just in the global namespace (or, later on, in both global and std). I would therefore conclude that your classes used an older C++ compiler.

How does one reorder columns in a data frame?

The only one I have seen work well is from here.

 shuffle_columns <- function (invec, movecommand) {
      movecommand <- lapply(strsplit(strsplit(movecommand, ";")[[1]],
                                 ",|\\s+"), function(x) x[x != ""])
  movelist <- lapply(movecommand, function(x) {
    Where <- x[which(x %in% c("before", "after", "first",
                              "last")):length(x)]
    ToMove <- setdiff(x, Where)
    list(ToMove, Where)
  })
  myVec <- invec
  for (i in seq_along(movelist)) {
    temp <- setdiff(myVec, movelist[[i]][[1]])
    A <- movelist[[i]][[2]][1]
    if (A %in% c("before", "after")) {
      ba <- movelist[[i]][[2]][2]
      if (A == "before") {
        after <- match(ba, temp) - 1
      }
      else if (A == "after") {
        after <- match(ba, temp)
      }
    }
    else if (A == "first") {
      after <- 0
    }
    else if (A == "last") {
      after <- length(myVec)
    }
    myVec <- append(temp, values = movelist[[i]][[1]], after = after)
  }
  myVec
}

Use like this:

new_df <- iris[shuffle_columns(names(iris), "Sepal.Width before Sepal.Length")]

Works like a charm.

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

You can use tuples like this: SELECT * FROM table WHERE (Col, 1) IN ((123,1),(123,1),(222,1),....)

There are no restrictions on number of these. It compares pairs.

How to write to file in Ruby?

To destroy the previous contents of the file, then write a new string to the file:

open('myfile.txt', 'w') { |f| f << "some text or data structures..." } 

To append to a file without overwriting its old contents:

open('myfile.txt', "a") { |f| f << 'I am appended string' } 

How to ignore deprecation warnings in Python

If you are using logging (https://docs.python.org/3/library/logging.html) to format or redirect your ERROR, NOTICE, and DEBUG messages, you can redirect the WARNINGS from the warning system to the logging system:

logging.captureWarnings(True)

See https://docs.python.org/3/library/warnings.html and https://docs.python.org/3/library/logging.html#logging.captureWarnings

In my case, I was formatting all the exceptions with the logging system, but warnings (e.g. scikit-learn) were not affected.

Mercurial — revert back to old version and continue from there

The answers above were most useful and I learned a lot. However, for my needs the succinct answer is:

hg revert --all --rev ${1}

hg commit -m "Restoring branch ${1} as default"

where ${1} is the number of the revision or the name of the branch. These two lines are actually part of a bash script, but they work fine on their own if you want to do it manually.

This is useful if you need to add a hot fix to a release branch, but need to build from default (until we get our CI tools right and able to build from branches and later do away with release branches as well).

AngularJS - How to use $routeParams in generating the templateUrl?

I was having a similar issue and used $stateParams instead of routeParam

async for loop in node.js

You've correctly diagnosed your problem, so good job. Once you call into your search code, the for loop just keeps right on going.

I'm a big fan of https://github.com/caolan/async, and it serves me well. Basically with it you'd end up with something like:

var async = require('async')
async.eachSeries(Object.keys(config), function (key, next){ 
  search(config[key].query, function(err, result) { // <----- I added an err here
    if (err) return next(err)  // <---- don't keep going if there was an error

    var json = JSON.stringify({
      "result": result
    });
    results[key] = {
      "result": result
    }
    next()    /* <---- critical piece.  This is how the forEach knows to continue to
                       the next loop.  Must be called inside search's callback so that
                       it doesn't loop prematurely.*/
  })
}, function(err) {
  console.log('iterating done');
}); 

I hope that helps!

React - uncaught TypeError: Cannot read property 'setState' of undefined

In ES7+ (ES2016) you can use the experimental function bind syntax operator :: to bind. It is a syntactic sugar and will do the same as Davin Tryon's answer.

You can then rewrite this.delta = this.delta.bind(this); to this.delta = ::this.delta;


For ES6+ (ES2015) you can also use the ES6+ arrow function (=>) to be able to use this.

delta = () => {
    this.setState({
        count : this.state.count + 1
    });
}

Why ? From the Mozilla doc :

Until arrow functions, every new function defined its own this value [...]. This proved to be annoying with an object-oriented style of programming.

Arrow functions capture the this value of the enclosing context [...]

How can I simulate a print statement in MySQL?

This is an old post, but thanks to this post I have found this:

\! echo 'some text';

Tested with MySQL 8 and working correctly. Cool right? :)

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

After searching and browsing all day, the only one works is adding

android.injected.testOnly=false

to the gradle.properties file

Makefile to compile multiple C programs?

Do it like so

all: program1 program2

program1: program1.c
    gcc -o program1 program1.c

program2: program2.c
    gcc -o program2 program2.c

You said you don't want advanced stuff, but you could also shorten it like this based on some default rules.

all: program1 program2

program1: program1.c
program2: program2.c

How to change the font color of a disabled TextBox?

NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor of the TextBox.


I think what you really want to do is enable the TextBox and set the ReadOnly property to true.

It's a bit tricky to change the color of the text in a disabled TextBox. I think you'd probably have to subclass and override the OnPaint event.

ReadOnly though should give you the same result as !Enabled and allow you to maintain control of the color and formatting of the TextBox. I think it will also still support selecting and copying text from the TextBox which is not possible with a disabled TextBox.

Another simple alternative is to use a Label instead of a TextBox.

Difference between request.getSession() and request.getSession(true)

request.getSession(true) and request.getSession() both do the same thing, but if we use request.getSession(false) it will return null if session object not created yet.

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

I had the same issue (but on my local) when I was trying to add Entity Framework migration with Package Manager Console.

The way I solved it was by creating a console application where Main() had the following code:

 var dbConfig = new Configuration();
 var dbMigrator = new DbMigrator(dbConfig);
 dbMigrator.Update();

Make sure the Configuration class is the migration Configuration of your failing project. You will need System.Data.Entity.Migrations to use DbMigrator.

Set a breakpoint in your application, and run it. The exception should be caught by Visual Studio (unless you have that exception type set to not break the debug session), and you should be able to find the info you are looking for.

The missing reference in my case was EFProviderWrapperToolkit.

How to read from input until newline is found using scanf()?

#include <stdio.h>
int main()
{
    char a[5],b[10];
    scanf("%2000s %2000[^\n]s",a,b);
    printf("a=%s b=%s",a,b);
}

Just write s in place of \n :)

String.equals versus ==

Use the string.equals(Object other) function to compare strings, not the == operator.

The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

if (usuario.equals(datos[0])) {
    ...
}

NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.

Adding JPanel to JFrame

Your Test2 class is not a Component, it has a Component which is a difference.

Either you do something like

frame.add(test.getPanel() );

after you introduced a getter for the panel in your class, or you make sure your Test2 class becomes a Component (e.g. by extending a JPanel)

Python: import module from another directory at the same level in project hierarchy

From Python 2.5 onwards, you can use

from ..Modules import LDAPManager

The leading period takes you "up" a level in your heirarchy.

See the Python docs on intra-package references for imports.

How can I get column names from a table in Oracle?

select column_name,* from information_schema.columns
 where table_name = 'YourTableName'
order by ordinal_position

Working with Enums in android

There has been some debate around this point of contention, but even in the most recent documents android suggests that it's not such a good idea to use enums in an android application. The reason why is because they use up more memory than a static constants variable. Here is a document from a page of 2014 that advises against the use of enums in an android application. http://developer.android.com/training/articles/memory.html#Overhead

I quote:

Be aware of memory overhead

Be knowledgeable about the cost and overhead of the language and libraries you are using, and keep this information in mind when you design your app, from start to finish. Often, things on the surface that look innocuous may in fact have a large amount of overhead. Examples include:

  • Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.

  • Every class instance has 12-16 bytes of RAM overhead.

  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes (see the previous section about optimized data containers).

A few bytes here and there quickly add up—app designs that are class- or object-heavy will suffer from this overhead. That can leave you in the difficult position of looking at a heap analysis and realizing your problem is a lot of small objects using up your RAM.

There has been some places where they say that these tips are outdated and no longer valuable, but the reason they keep repeating it, must be there is some truth to it. Writing an android application is something you should keep as lightweight as possible for a smooth user experience. And every little inch of performance counts!

Rails formatting date

Create an initializer for it:

# config/initializers/time_formats.rb

Add something like this to it:

Time::DATE_FORMATS[:custom_datetime] = "%d.%m.%Y"

And then use it the following way:

post.updated_at.to_s(:custom_datetime)

?? Your have to restart rails server for this to work.

Check the documentation for more information: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s

Get current controller in view

Create base class for all controllers and put here name attribute:

public abstract class MyBaseController : Controller
{
    public abstract string Name { get; }
}

In view

@{
    var controller = ViewContext.Controller as MyBaseController;
    if (controller != null)
    {
       @controller.Name
    }
}

Controller example

 public class SampleController: MyBaseController 
    { 
      public override string Name { get { return "Sample"; } 
    }

How to add hours to current date in SQL Server?

declare @hours int = 5;

select dateadd(hour,@hours,getdate())

How to cancel an $http request in AngularJS?

here is a version that handles multiple requests, also checks for cancelled status in callback to suppress errors in error block. (in Typescript)

controller level:

    requests = new Map<string, ng.IDeferred<{}>>();

in my http get:

    getSomething(): void {
        let url = '/api/someaction';
        this.cancel(url); // cancel if this url is in progress

        var req = this.$q.defer();
        this.requests.set(url, req);
        let config: ng.IRequestShortcutConfig = {
            params: { id: someId}
            , timeout: req.promise   // <--- promise to trigger cancellation
        };

        this.$http.post(url, this.getPayload(), config).then(
            promiseValue => this.updateEditor(promiseValue.data as IEditor),
            reason => {
                // if legitimate exception, show error in UI
                if (!this.isCancelled(req)) {
                    this.showError(url, reason)
                }
            },
        ).finally(() => { });
    }

helper methods

    cancel(url: string) {
        this.requests.forEach((req,key) => {
            if (key == url)
                req.resolve('cancelled');
        });
        this.requests.delete(url);
    }

    isCancelled(req: ng.IDeferred<{}>) {
        var p = req.promise as any; // as any because typings are missing $$state
        return p.$$state && p.$$state.value == 'cancelled';
    }

now looking at the network tab, i see that it works beatuifully. i called the method 4 times and only the last one went through.

enter image description here

Remove first 4 characters of a string with PHP

$num = "+918883967576";

$str = substr($num, 3);

echo $str;

Output:8883967576

Is Unit Testing worth the effort?

Just today, I had to change a class for which a unit test has been written previously.
The test itself was well written and included test scenarios that I hadn't even thought about.
Luckily all of the tests passed, and my change was quickly verified and put into the test environment with confidence.

bind/unbind service example (android)

Add these methods to your Activity:

private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder binder) {
        myServiceBinder = ((MyService.MyBinder) binder).getService();
        Log.d("ServiceConnection","connected");
        showServiceData();
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
};

public Handler myHandler = new Handler() {
    public void handleMessage(Message message) {
        Bundle data = message.getData();
    }
};

public void doBindService() {
    Intent intent = null;
    intent = new Intent(this, BTService.class);
    // Create a new Messenger for the communication back
    // From the Service to the Activity
    Messenger messenger = new Messenger(myHandler);
    intent.putExtra("MESSENGER", messenger);

    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}

And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.

@Override
protected void onResume() {

    Log.d("activity", "onResume");
    if (myService == null) {
        doBindService();
    }
    super.onResume();
}

@Override
protected void onPause() {
    //FIXME put back

    Log.d("activity", "onPause");
    if (myService != null) {
        unbindService(myConnection);
        myService = null;
    }
    super.onPause();
}

Note, that when binding to a service only the onCreate() method is called in the service class. In your Service class you need to define the myBinder method:

private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;

@Override
public IBinder onBind(Intent arg0) {
    Bundle extras = arg0.getExtras();
    Log.d("service","onBind");
    // Get messager from the Activity
    if (extras != null) {
        Log.d("service","onBind with extra");
        outMessenger = (Messenger) extras.get("MESSENGER");
    }
    return mBinder;
}

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

After you defined these methods you can reach the methods of your service at your Activity:

private void showServiceData() {  
    myServiceBinder.myMethod();
}

and finally you can start your service when some event occurs like _BOOT_COMPLETED_

public class MyReciever  extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("android.intent.action.BOOT_COMPLETED")) {
            Intent service = new Intent(context, myService.class);
            context.startService(service);
        }
    }
}

note that when starting a service the onCreate() and onStartCommand() is called in service class and you can stop your service when another event occurs by stopService() note that your event listener should be registerd in your Android manifest file:

<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

Delegates in swift?

The solutions above seemed a little coupled and at the same time avoid reuse the same protocol in other controllers, that's why I've come with the solution that is more strong typed using generic type-erasure.

@noreturn public func notImplemented(){
    fatalError("not implemented yet")
}


public protocol DataChangedProtocol: class{
    typealias DataType

    func onChange(t:DataType)
}

class AbstractDataChangedWrapper<DataType> : DataChangedProtocol{

    func onChange(t: DataType) {
        notImplemented()
    }
}


class AnyDataChangedWrapper<T: DataChangedProtocol> : AbstractDataChangedWrapper<T.DataType>{

    var base: T

    init(_ base: T ){
        self.base = base
    }

    override func onChange(t: T.DataType) {
        base.onChange(t)
    }
}


class AnyDataChangedProtocol<DataType> : DataChangedProtocol{

    var base: AbstractDataChangedWrapper<DataType>

    init<S: DataChangedProtocol where S.DataType == DataType>(_ s: S){
        self.base = AnyDataChangedWrapper(s)
    }

    func onChange(t: DataType) {
        base.onChange(t)
    }
}



class Source : DataChangedProtocol {
    func onChange(data: String) {
        print( "got new value \(data)" )
    }
}


class Target {
    var delegate: AnyDataChangedProtocol<String>?

    func reportChange(data:String ){
        delegate?.onChange(data)
    }
}


var source = Source()
var target = Target()

target.delegate = AnyDataChangedProtocol(source)
target.reportChange("newValue")    

output: got new value newValue

EOL conversion in notepad ++

In Notepad++, use replace all with regular expression. This has advantage over conversion command in menu that you can operate on entire folder w/o having to open each file or drag n drop (on several hundred files it will noticeably become slower) plus you can also set filename wildcard filter.

(\r?\n)|(\r\n?)

to

\n

This will match every possible line ending pattern (single \r, \n or \r\n) back to \n. (Or \r\n if you are converting to windows-style)

To operate on multiple files, either:

  • Use "Replace All in all opened document" in "Replace" tab. You will have to drag and drop all files into Notepad++ first. It's good that you will have control over which file to operate on but can be slow if there several hundreds or thousands files.
  • "Replace in files" in "Find in files" tab, by file filter of you choice, e.g., *.cpp *.cs under one specified directory.

How to run PowerShell in CMD

You need to separate the arguments from the file path:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"

Another option that may ease the syntax using the File parameter and positional parameters:

powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"

PHP and MySQL Select a Single Value

You do this by using mysqli_fetch_field method.

session_start();
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' limit 1";
$result = mysqli_query($link, $sql);
if ($result !== false) {
    $value = mysqli_fetch_field($result);
    $_SESSION['myid'] = $value;
}

Note: you can do that by using mysql_fetch_field() method as well, but it will be deprecated in php v5.5

how to run two commands in sudo?

I usually do:

sudo bash -c 'whoami; whoami'

How to show all shared libraries used by executables in Linux?

If you don't care about the path to the executable file -

ldd `which <executable>` # back quotes, not single quotes

What's the difference between utf8_general_ci and utf8_unicode_ci?

This post describes it very nicely.

In short: utf8_unicode_ci uses the Unicode Collation Algorithm as defined in the Unicode standards, whereas utf8_general_ci is a more simple sort order which results in "less accurate" sorting results.

How to Auto-start an Android Application?

If by autostart you mean auto start on phone bootup then you should register a BroadcastReceiver for the BOOT_COMPLETED Intent. Android systems broadcasts that intent once boot is completed.

Once you receive that intent you can launch a Service that can do whatever you want to do.

Keep note though that having a Service running all the time on the phone is generally a bad idea as it eats up system resources even when it is idle. You should launch your Service / application only when needed and then stop it when not required.

React Native add bold or italics to single words in <Text> field

<Text>
    <Text style={{fontWeight: "bold"}}>bold</Text>
    normal text
    <Text style={{fontStyle: "italic"}}> italic</Text>
</Text>

Eclipse C++: Symbol 'std' could not be resolved

I was having this problem using Eclipse Neon on Kubuntu with a 16.04 kernel, I had to change my #include <stdlib.h> to #include <cstdlib> this made the std namespace "visible" to Eclipse and removed the error.

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

Here is how I fixed this issue:

Open the nuget package manager console and install the below nuget packages:

Install-Package WebMatrix.Data
Install-Package Microsoft.AspNet.WebHelpers
Update-Package

Clean the solution, rebuild and my asp.net web app starts working!

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

Clearing NSUserDefaults

Try This, It's working for me .

Single line of code

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];

Unresolved reference issue in PyCharm

Done in PyCharm 2019.3.1 Right-click on your src folder -> "Mark Directory as" -> Click-on "Excluded" and your src folder should be blue.

Help with packages in java - import does not work

It sounds like you are on the right track with your directory structure. When you compile the dependent code, specify the -classpath argument of javac. Use the parent directory of the com directory, where com, in turn, contains company/thing/YourClass.class

So, when you do this:

javac -classpath <parent> client.java

The <parent> should be referring to the parent of com. If you are in com, it would be ../.

HTML.ActionLink method

I think that Joseph flipped controller and action. First comes the action then the controller. This is somewhat strange, but the way the signature looks.

Just to clarify things, this is the version that works (adaption of Joseph's example):

Html.ActionLink(article.Title, 
    "Login",  // <-- ActionMethod
    "Item",   // <-- Controller Name
    new { id = article.ArticleID }, // <-- Route arguments.
    null  // <-- htmlArguments .. which are none
    )

Spring MVC - How to get all request params in a map in Spring controller?

Here is the simple example of getting request params in a Map.

 @RequestMapping(value="submitForm.html", method=RequestMethod.POST)
     public ModelAndView submitForm(@RequestParam Map<String, String> reqParam) 
       {
          String name  = reqParam.get("studentName");
          String email = reqParam.get("studentEmail");

          ModelAndView model = new ModelAndView("AdmissionSuccess");
          model.addObject("msg", "Details submitted by you::
          Name: " + name + ", Email: " + email );
       }

In this case, it will bind the value of studentName and studentEmail with name and email variables respectively.

How to declare a global variable in php?

If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:

$variable = 5;

function name()
{
    global $variable;

    $value = $variable + 5;

    return $value;  

}

Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.

config.php

global $variable;

$variable = 5;

other.php

function name()
{
    require_once __DIR__ . '/config.php';
}

You can use $GLOBALS as well. It's a superglobal so it has access everywhere.

$GLOBALS['variable'] = 5;

function name()
{
    echo $GLOBALS['variable'];
}

Depending on your choice you can choose either.

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

To summarize:

Step1

Project Properties 
   -> Configuration Properties 
       -> Linker (General) 
          -> Enable Incremental Linking -> "No (/INCREMENTAL:NO)"

if step1 not work, do Step2

Project Properties 
   -> Configuration Properties 
       -> Manifest Tool (Input and Output) 
          -> Enable Incremental Linking -> "No"

if step2 not work, do Step3 Copy file one of:

  1. C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\cvtres.exe
  2. C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\cvtres.exe
  3. C:\Program Files (x86)\Microsoft Visual Studio 13.0\VC\bin\cvtres.exe

    Then, replace to C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe With me, do 3 step it work

What is the difference between GitHub and gist?

GISTS The Gist is an outstanding service provided by GitHub. Using this service, you can share your work publically or privately. You can share a single file, articles, full applications or source code etc.

The GitHub is much more than just Gists. It provides immense services to group together a project or programs digital resources in a centralized location called repository and share among stakeholder. The GitHub repository will hold or maintain the multiple version of the files or history of changes and you can retrieve a specific version of a file when you want. Whereas gist will create each post as a new repository and will maintain the history of the file.

How can I pretty-print JSON using Go?

//You can do it with json.MarshalIndent(data, "", "  ")

package main

import(
  "fmt"
  "encoding/json" //Import package
)

//Create struct
type Users struct {
    ID   int
    NAME string
}

//Asign struct
var user []Users
func main() {
 //Append data to variable user
 user = append(user, Users{1, "Saturn Rings"})
 //Use json package the blank spaces are for the indent
 data, _ := json.MarshalIndent(user, "", "  ")
 //Print json formatted
 fmt.Println(string(data))
}

How do I update the password for Git?

There is such a confusion on this question, as there is way too much complexity in this question. First MacOS vs. Win10. Then the different auth mechanisms.

I will start a consolidated answer here and probably need some help, if I do not get help, I will keep working on the answer until it is complete, but that will take time.

Windows 10: |

|-- Run this command. You will be prompted on next push/pull to enter username and password:
|      git config --global credential.helper wincred (Thanks to @Andrew Pye)

` MacOS:

|
|-- Using git config to store username and password:
|  git config --global --add user.password
|
|---- first time entry
|  git config --global --add user.password <new_pass>
|
|---- password update
|  git config --global --unset user.password
|  git config --global --add user.password <new_pass>
|
|-- Using keychain:
|  git config --global credential.helper osxkeychain
|
|---- first time entry
|  Terminal will ask you for the username and password. Just enter it, it will be 
|  stored in keychain from then on.
|
|---- password update
|  Open keychain, delete the entry for the repository you are trying to use. 
|  (git remote -v will show you)
|  On next use of git push or something that needs permissions, git will ask for 
|  the credentials, as it can not find them in the keychain anymore.
`

No signing certificate "iOS Distribution" found

I got the "No signing certificate" error when running Xcode 11.3 on macOS 10.14.x Mojave. (but after Xcode 12 was released.)

I was also using Fastlane. My fix was to set generate_apple_certs to false when running Match. This seemed to generate signing certificates that were backwards-compatible with Xcode 11.3

Match documentation - https://docs.fastlane.tools/actions/match/

This is the relevant section of my Fastfile:

platform :ios do
  lane :certs do
    force = false
    match(type: "development", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.dev")
    match(type: "adhoc",       generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.beta")
    match(type: "appstore",    generate_apple_certs: false, force: force, app_identifier: "your.app.identifier")
  end

  ...

How to list running screen sessions?

So you're using screen to keep the experiments running in the background, or what? If so, why not just start it in the background?

./experiment &

And if you're asking how to get notification the job i done, how about stringing the experiment together with a mail command?

./experiment && echo "the deed is done" | mail youruser@yourlocalworkstation -s "job on server $HOSTNAME is done"

Sending and receiving data over a network using TcpClient

I've developed a dotnet library that might come in useful. I have fixed the problem of never getting all of the data if it exceeds the buffer, which many posts have discounted. Still some problems with the solution but works descently well https://github.com/NicholasLKSharp/DotNet-TCP-Communication

convert iso date to milliseconds in javascript

if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);

How to make a vertical line in HTML

Put a <div> around the markup where you want the line to appear to next, and use CSS to style it:

_x000D_
_x000D_
.verticalLine {_x000D_
  border-left: thick solid #ff0000;_x000D_
}
_x000D_
<div class="verticalLine">_x000D_
  some other content_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert string to long

Do this:

long l = Long.parseLong(str);

However, always check that str contains digits to prevent throwing exceptions. For instance:

String str="ABCDE";
long l = Long.parseLong(str);

would throw an exception but this

String str="1234567";
long l = Long.parseLong(str);

won't.

Concat strings by & and + in VB.Net

You've probably got Option Strict turned on (which is a good thing), and the compiler is telling you that you can't add a string and an int. Try this:

t = s1 & i.ToString()

HQL "is null" And "!= null" on an Oracle column

No. See also this link Handle conditional null in HQL for tips and tricks on how to handle comparisons with both null and non-null values.

How to increase editor font size?

In my case it was because of my 4K screen too thin to read. Then u need to change from monospace In my case it was because of my 4K screen too thin to read. Then u need to change from Monospaced to Consolas.

Settings --> Color Scheme Font --> Font --> Consolas

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

'M' (Capital) represent month & 'm' (Simple) represent minutes

Some example for months

'M' -> 7  (without prefix 0 if it is single digit)
'M' -> 12

'MM' -> 07 (with prefix 0 if it is single digit)
'MM' -> 12

'MMM' -> Jul (display with 3 character)

'MMMM' -> December (display with full name)

Some example for minutes

'm' -> 3  (without prefix 0 if it is single digit)
'm' -> 19
'mm' -> 03 (with prefix 0 if it is single digit)
'mm' -> 19

How to get share counts using graph API

After August 7, 2016 you can still make your call like this:

http://graph.facebook.com/?id=https://www.apple.com/

but the response format is going to be different: it won't be

{
  "id": "http://www.apple.com",
  "shares": 1146997
}

but instead it will be

{
   "og_object": {
      "id": "388265801869",
      "description": "Get a first look at iPhone 7, Apple Watch Series 2, and the new AirPods \u2014 the future of wireless headphones. Visit the site to learn more.",
      "title": "Apple",
      "type": "website",
      "updated_time": "2016-09-20T08:21:03+0000"
   },
   "share": {
      "comment_count": 1,
      "share_count": 1094227
   },
   "id": "https://www.apple.com"
}

So you will have to process the response like this:

reponse_variable.share.share_count

How to change the datetime format in pandas

You can try this it'll convert the date format to DD-MM-YYYY:

df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)

Adb Devices can't find my phone

I just spent half a day trying to connect my various Android devices to my MacBook Pro (running 10.8.2). It turns out to have been a Micro USB cable problem. I have many Micro USB cables, but only the one that came packaged with my Galaxy Nexus works to connect the phones to my computer. I don't know if this is due to damage, or some proprietary manufacturing, but please remember to try connecting the phone with the cable that was packaged with it.

Android: I lost my android key store, what should I do?

You can create a new keystore, but the Android Market wont allow you to upload the apk as an update - worse still, if you try uploading the apk as a new app it will not allow it either as it knows there is a 'different' version of the same apk already in the market even if you delete your previous version from the market

Do your absolute best to find that keystore!!

When you find it, email it to yourself so you have a copy on your gmail that you can go and get in the case you loose it from your hard drive!

Passing an array of data as an input parameter to an Oracle procedure

This is one way to do it:

SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
  2  /

Type created

SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
  2  BEGIN
  3    FOR i IN 1..t_in.count LOOP
  4      dbms_output.put_line(t_in(i));
  5    END LOOP;
  6  END;
  7  /

Procedure created

SQL> DECLARE
  2    v_t MyType;
  3  BEGIN
  4    v_t := MyType();
  5    v_t.EXTEND(10);
  6    v_t(1) := 'this is a test';
  7    v_t(2) := 'A second test line';
  8    testing(v_t);
  9  END;
 10  /

this is a test
A second test line

To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:

SQL> CREATE OR REPLACE PACKAGE p IS
  2    TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
  3  
  4    PROCEDURE pp (inp p_type);
  5  END p;
  6  /

Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
  2    PROCEDURE pp (inp p_type) IS
  3    BEGIN
  4      FOR i IN 1..inp.count LOOP
  5        dbms_output.put_line(inp(i));
  6      END LOOP;
  7    END pp;
  8  END p;
  9  /

Package body created
SQL> DECLARE
  2    v_t p.p_type;
  3  BEGIN
  4    v_t(1) := 'this is a test of p';
  5    v_t(2) := 'A second test line for p';
  6    p.pp(v_t);
  7  END;
  8  /

this is a test of p
A second test line for p

PL/SQL procedure successfully completed

SQL> 

This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.

List comprehension vs. lambda + filter

I find the second way more readable. It tells you exactly what the intention is: filter the list.
PS: do not use 'list' as a variable name

How to multiply all integers inside list

Try a list comprehension:

l = [x * 2 for x in l]

This goes through l, multiplying each element by two.

Of course, there's more than one way to do it. If you're into lambda functions and map, you can even do

l = map(lambda x: x * 2, l)

to apply the function lambda x: x * 2 to each element in l. This is equivalent to:

def timesTwo(x):
    return x * 2

l = map(timesTwo, l)

Note that map() returns a map object, not a list, so if you really need a list afterwards you can use the list() function afterwards, for instance:

l = list(map(timesTwo, l))

Thanks to Minyc510 in the comments for this clarification.

Parameterize an SQL IN clause

This is a reusable variation of the solution in Mark Bracket's excellent answer.

Extension Method:

public static class ParameterExtensions
{
    public static Tuple<string, SqlParameter[]> ToParameterTuple<T>(this IEnumerable<T> values)
    {
        var createName = new Func<int, string>(index => "@value" + index.ToString());
        var paramTuples = values.Select((value, index) => 
        new Tuple<string, SqlParameter>(createName(index), new SqlParameter(createName(index), value))).ToArray();
        var inClause = string.Join(",", paramTuples.Select(t => t.Item1));
        var parameters = paramTuples.Select(t => t.Item2).ToArray();
        return new Tuple<string, SqlParameter[]>(inClause, parameters);
    }
}

Usage:

        string[] tags = {"ruby", "rails", "scruffy", "rubyonrails"};
        var paramTuple = tags.ToParameterTuple();
        var cmdText = $"SELECT * FROM Tags WHERE Name IN ({paramTuple.Item1})";

        using (var cmd = new SqlCommand(cmdText))
        {
            cmd.Parameters.AddRange(paramTuple.Item2);
        }

CSS Animation onClick

_x000D_
_x000D_
var  abox = document.getElementsByClassName("box")[0];_x000D_
function allmove(){_x000D_
        abox.classList.remove("move-ltr");_x000D_
        abox.classList.remove("move-ttb");_x000D_
       abox.classList.toggle("move");_x000D_
}_x000D_
function ltr(){_x000D_
        abox.classList.remove("move");_x000D_
        abox.classList.remove("move-ttb");_x000D_
       abox.classList.toggle("move-ltr");_x000D_
}_x000D_
function ttb(){_x000D_
       abox.classList.remove("move-ltr");_x000D_
       abox.classList.remove("move");_x000D_
       abox.classList.toggle("move-ttb");_x000D_
}
_x000D_
.box {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  position: relative;_x000D_
}_x000D_
.move{_x000D_
  -webkit-animation: moveall 5s;_x000D_
  animation: moveall 5s;_x000D_
}_x000D_
.move-ltr{_x000D_
   -webkit-animation: moveltr 5s;_x000D_
  animation: moveltr 5s;_x000D_
}_x000D_
.move-ttb{_x000D_
    -webkit-animation: movettb 5s;_x000D_
  animation: movettb 5s;_x000D_
}_x000D_
@keyframes moveall {_x000D_
  0%   {left: 0px; top: 0px;}_x000D_
  25%  {left: 200px; top: 0px;}_x000D_
  50%  {left: 200px; top: 200px;}_x000D_
  75%  {left: 0px; top: 200px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}_x000D_
@keyframes moveltr {_x000D_
  0%   { left: 0px; top: 0px;}_x000D_
  50%  {left: 200px; top: 0px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}_x000D_
@keyframes movettb {_x000D_
  0%   {left: 0px; top: 0px;}_x000D_
  50%  {top: 200px;left: 0px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}
_x000D_
<div class="box"></div>_x000D_
<button onclick="allmove()">click</button>_x000D_
<button onclick="ltr()">click</button>_x000D_
<button onclick="ttb()">click</button>
_x000D_
_x000D_
_x000D_

Auto populate columns in one sheet from another sheet

Use the 'EntireColumn' property, that's what it is there for. C# snippet, but should give you a good indication of how to do this:

string rangeQuery = "A1:A1";

Range range = workSheet.get_Range(rangeQuery, Type.Missing);

range = range.EntireColumn;

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

If you'd like to use C# 6.0:

  1. Make sure your project's .NET version is higher than 4.5.2.
  2. And then check your .config file to perform the following modifications.

Look for the system.codedom and modify it so that it will look as shown below:

<system.codedom>
 <compilers>
  <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
 </compilers>
</system.codedom>

How to redirect DNS to different ports

(It's been a while since I did this stuff. Please don't blindly assume that all the details below are correct. But I hope I'm not too embarrassingly wrong. :))


As the previous answer stated, the Minecraft client (as of 1.3.1) supports SRV record lookup using the service name _minecraft and the protocol name _tcp, which means that if your zone file looks like this...

arboristal.com.                 86400 IN A   <your IP address>
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 20 25565 arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25566 arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25567 arboristal.com.

...then Minecraft clients who perform SRV record lookup as hinted in the changelog will use ports 25566 and 25567 with preference (40% of the time each) over port 25565 (20% of the time). We can assume that Minecraft clients who do not find and respect these SRV records will use port 25565 as usual.


However, I would argue that it would actually be more "clean and professional" to do it using a load balancer such as Nginx. (I pick Nginx just because I've used it before. I'm not claiming it's uniquely suited to this task. It might even be a bad choice for some reason.) Then you don't have to mess with your DNS, and you can use the same approach to load-balance any service, not just ones like Minecraft which happen to have done the hard client-side work to look up and respect SRV records. To do it the Nginx way, you'd run Nginx on the arboristal.com machine with something like the following in /etc/nginx/sites-enabled/arboristal.com:

upstream minecraft_servers {
    ip_hash;
    server 127.0.0.1:25566 weight=1;
    server 127.0.0.1:25567 weight=1;
    server 127.0.0.1:25568 weight=1;
}
server {
    listen 25565;
    proxy_pass minecraft_servers;
}

Here we are controlling the load-balancing ourselves on the server side (via Nginx), so we no longer need to worry that badly behaved clients might prefer port 25565 to the other two ports. In fact, now all clients will talk to arboristal.com:25565! But the listener on that port is no longer a Minecraft server; it's Nginx, secretly proxying all the traffic onto three other ports on the same machine.

We load-balance based on a hash of the client's IP address (ip_hash), so that if a client disconnects and then reconnects later, there's a good chance that it'll get reconnected to the same Minecraft server it had before. (I don't know how much this matters to Minecraft, or how SRV-enabled clients are programmed to deal with this aspect.)

Notice that we used to run a Minecraft server on port 25565; I've moved it to port 25568 so that we can use port 25565 for the load-balancer.

A possible disadvantage of the Nginx method is that it makes Nginx a bottleneck in your system. If Nginx goes down, then all three servers become unreachable. If some part of your system can't keep up with the volume of traffic on that single port, 25565, all three servers become flaky. And not to mention, Nginx is a big new dependency in your ecosystem. Maybe you don't want to introduce yet another massive piece of software with a complicated config language and a huge attack surface. I can respect that.

A possible advantage of the Nginx method is... that it makes Nginx a bottleneck in your system! You can apply global policies via Nginx, such as rejecting packets above a certain size, or responding with a static web page to HTTP connections on port 80. You can also firewall off ports 25566, 25567, and 25568 from the Internet, since now they should be talked to only by Nginx over the loopback interface. This reduces your attack surface somewhat.

Nginx also makes it easier to add new Minecraft servers to your backend; now you can just add a server line to your config and service nginx reload. Using the old port-based approach, you'd have to add a new SRV record with your DNS provider (and it could take up to 86400 seconds for clients to notice the change) and then also remember to edit your firewall (e.g. /etc/iptables.rules) to permit external traffic over that new port.

Nginx also frees you from having to think about DNS TTLs when making ops changes. Suppose you decide to split up your three Minecraft servers onto three different physical machines with different IP addresses. Using Nginx, you can do that completely via config changes to your server lines, and you can keep those new machines inside your firewall (connected only to Nginx over a private interface), and the changes will take effect immediately, by definition. Whereas, using SRV records, you'll have to rewrite your zone file to something like this...

arboristal.com.                 86400 IN CNAME mc1.arboristal.com.
mc1.arboristal.com.             86400 IN A   <a new machine's IP address>
mc2.arboristal.com.             86400 IN A   <a new machine's IP address>
mc3.arboristal.com.             86400 IN A   <a new machine's IP address>
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 20 25565 mc1.arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc2.arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc3.arboristal.com.

...and you'll have to leave all three new machines poking outside your firewall so that they can receive connections from the Internet. And you'll have to wait up to 86400 seconds for your clients to notice the change, which could affect the complexity of your rollout plan. And if you were running any other services (such as an HTTP server) on arboristal.com, now you have to move them to the mc1.arboristal.com machine because of how I did that CNAME. I did that only for the benefit of those hypothetical Minecraft clients who don't respect SRV records and will still be trying to connect to arboristal.com:25565.


So, I think both ways (SRV records and Nginx load-balancing) are reasonable, and your choice will depend on your personal preferences. I caricature the options as:

  • SRV records: "I just need it to work. I don't want complexity. And I know and trust my DNS provider."
  • Nginx: "I foresee arboristal.com taking over the world, or at least moving to a bigger machine someday. I'm not scared of learning a new tool. What's a zone file?"

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

It is not always about the compilation flags, I have the same error on gentoo when using distcc.

The reason is that on distcc server is using a not-hardened profile and on client the profile is hardened. Check this discussion: https://forums.gentoo.org/viewtopic-p-7463994.html

Iterating through a golang map

For example,

package main

import "fmt"

func main() {
    type Map1 map[string]interface{}
    type Map2 map[string]int
    m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}
    //m = map[foo:map[first: 1] boo: map[second: 2]]
    fmt.Println("m:", m)
    for k, v := range m {
        fmt.Println("k:", k, "v:", v)
    }
}

Output:

m: map[boo:map[second:2] foo:map[first:1]]
k: boo v: map[second:2]
k: foo v: map[first:1]

What is move semantics?

To illustrate the need for move semantics, let's consider this example without move semantics:

Here's a function that takes an object of type T and returns an object of the same type T:

T f(T o) { return o; }
  //^^^ new object constructed

The above function uses call by value which means that when this function is called an object must be constructed to be used by the function.
Because the function also returns by value, another new object is constructed for the return value:

T b = f(a);
  //^ new object constructed

Two new objects have been constructed, one of which is a temporary object that's only used for the duration of the function.

When the new object is created from the return value, the copy constructor is called to copy the contents of the temporary object to the new object b. After the function completes, the temporary object used in the function goes out of scope and is destroyed.


Now, let's consider what a copy constructor does.

It must first initialize the object, then copy all the relevant data from the old object to the new one.
Depending on the class, maybe its a container with very much data, then that could represent much time and memory usage

// Copy constructor
T::T(T &old) {
    copy_data(m_a, old.m_a);
    copy_data(m_b, old.m_b);
    copy_data(m_c, old.m_c);
}

With move semantics it's now possible to make most of this work less unpleasant by simply moving the data rather than copying.

// Move constructor
T::T(T &&old) noexcept {
    m_a = std::move(old.m_a);
    m_b = std::move(old.m_b);
    m_c = std::move(old.m_c);
}

Moving the data involves re-associating the data with the new object. And no copy takes place at all.

This is accomplished with an rvalue reference.
An rvalue reference works pretty much like an lvalue reference with one important difference:
an rvalue reference can be moved and an lvalue cannot.

From cppreference.com:

To make strong exception guarantee possible, user-defined move constructors should not throw exceptions. In fact, standard containers typically rely on std::move_if_noexcept to choose between move and copy when container elements need to be relocated. If both copy and move constructors are provided, overload resolution selects the move constructor if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move), and selects the copy constructor if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy constructor is provided, all argument categories select it (as long as it takes a reference to const, since rvalues can bind to const references), which makes copying the fallback for moving, when moving is unavailable. In many situations, move constructors are optimized out even if they would produce observable side-effects, see copy elision. A constructor is called a 'move constructor' when it takes an rvalue reference as a parameter. It is not obligated to move anything, the class is not required to have a resource to be moved and a 'move constructor' may not be able to move a resource as in the allowable (but maybe not sensible) case where the parameter is a const rvalue reference (const T&&).

Adding value labels on a matplotlib bar chart

Firstly freq_series.plot returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax rather than fig to be more consistent with other code examples.

You can get the list of the bars produced in the plot from the ax.patches member. Then you can use the technique demonstrated in this matplotlib gallery example to add the labels using the ax.text method.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that, 
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)

x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)

rects = ax.patches

# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]

for rect, label in zip(rects, labels):
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
            ha='center', va='bottom')

This produces a labeled plot that looks like:

enter image description here

scp from remote host to local host

You need the ip of the other pc and do:

scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop

it will ask you for 'user's password on the other pc.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

R: invalid multibyte string

If you want an R solution, here's a small convenience function I sometimes use to find where the offending (multiByte) character is lurking. Note that it is the next character to what gets printed. This works because print will work fine, but substr throws an error when multibyte characters are present.

find_offending_character <- function(x, maxStringLength=256){  
  print(x)
  for (c in 1:maxStringLength){
    offendingChar <- substr(x,c,c)
    #print(offendingChar) #uncomment if you want the indiv characters printed
    #the next character is the offending multibyte Character
  }    
}

string_vector <- c("test", "Se\x96ora", "works fine")

lapply(string_vector, find_offending_character)

I fix that character and run this again. Hope that helps someone who encounters the invalid multibyte string error.

How to add a filter class in Spring Boot?

There are three ways to add your filter,

  1. Annotate your filter with one of the Spring stereotypes such as @Component
  2. Register a @Bean with Filter type in Spring @Configuration
  3. Register a @Bean with FilterRegistrationBean type in Spring @Configuration

Either #1 or #2 will do if you want your filter applies to all requests without customization, use #3 otherwise. You don't need to specify component scan for #1 to work as long as you place your filter class in the same or sub-package of your SpringApplication class. For #3, use along with #2 is only necessary when you want Spring to manage your filter class such as have it auto wired dependencies. It works just fine for me to new my filter which doesn't need any dependency autowiring/injection.

Although combining #2 and #3 works fine, I was surprised it doesn't end up with two filters applying twice. My guess is that Spring combines the two beans as one when it calls the same method to create both of them. In case you want to use #3 alone with authowiring, you can AutowireCapableBeanFactory. The following is an example,

private @Autowired AutowireCapableBeanFactory beanFactory;

    @Bean
    public FilterRegistrationBean myFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        Filter myFilter = new MyFilter();
        beanFactory.autowireBean(myFilter);
        registration.setFilter(myFilter);
        registration.addUrlPatterns("/myfilterpath/*");
        return registration;
    }

How to cat <<EOF >> a file containing code?

I know this is a two year old question, but this is a quick answer for those searching for a 'how to'.

If you don't want to have to put quotes around anything you can simply write a block of text to a file, and escape variables you want to export as text (for instance for use in a script) and not escape one's you want to export as the value of the variable.

#!/bin/bash

FILE_NAME="test.txt"
VAR_EXAMPLE="\"string\""

cat > ${FILE_NAME} << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} in ${FILE_NAME}  
EOF

Will write "${VAR_EXAMPLE}="string" in test.txt" into test.txt

This can also be used to output blocks of text to the console with the same rules by omitting the file name

#!/bin/bash

VAR_EXAMPLE="\"string\""

cat << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} to console 
EOF

Will output "${VAR_EXAMPLE}="string" to console" to the console

What is a StackOverflowError?

Stack overflow means exactly that: a stack overflows. Usually there's a one stack in the program that contains local-scope variables and addresses where to return when execution of a routine ends. That stack tends to be a fixed memory range somewhere in the memory, therefore it's limited how much it can contain values.

If the stack is empty you can't pop, if you do you'll get stack underflow error.

If the stack is full you can't push, if you do you'll get stack overflow error.

So stack overflow appears where you allocate too much into the stack. For instance, in the mentioned recursion.

Some implementations optimize out some forms of recursions. Tail recursion in particular. Tail recursive routines are form of routines where the recursive call appears as a final thing what the routine does. Such routine call gets simply reduced into a jump.

Some implementations go so far as implement their own stacks for recursion, therefore they allow the recursion to continue until the system runs out of memory.

Easiest thing you could try would be to increase your stack size if you can. If you can't do that though, the second best thing would be to look whether there's something that clearly causes the stack overflow. Try it by printing something before and after the call into routine. This helps you to find out the failing routine.

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

This one really sucked.

I tried all of the solutions suggested here but the only thing that worked was to

  • create a new database
  • run ALTER TABLE old_db.{table_name} RENAME new_db.{table_name} on all of the functioning tables
  • run DROP old_db
  • create old_db again
  • run ALTER TABLE new_db.{table_name} RENAME old_db.{table_name} on all the tables in new_db

Once you have done that you can finally just create the table again that you previously had.

HAX kernel module is not installed

Actual error

enter image description here

follow bellow two simple steps to fix.

Step 1:- update "Intel x86 Emulator Accelerator (HAXM installer)" Ref. bellow img enter image description here

Step2:-

After installing the installer, you have to run it to install it on your system. Open the directory where your Android SDK is located. Go inside the extras\Intel\Hardware_Accelerated_Execution_Manager directory and you should see the intelhaxm-android.exe file.

enter image description here

If you got the error "This computer meets requirements for HAXM, but VT-x is not turned on..." during installation try to turn it on in your BIOS and check your antivirus software settings also. (Check this stackoverflow post). Thats it! its working for me.

Git diff says subproject is dirty

Also removing the submodule and then running git submodule init and git submodule update will obviously do the trick, but may not always be appropriate or possible.

Should I Dispose() DataSet and DataTable?

Datasets implement IDisposable thorough MarshalByValueComponent, which implements IDisposable. Since datasets are managed there is no real benefit to calling dispose.

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

Lea's converter is no longer available. I just used this converter

Steps:

  1. Enter the Unicode decimal version such as 8226 in the tool's green input field.
  2. Press Dec code points
  3. See the result in the box Unicode U+hex notation (eg U+2022)
  4. Use it in your CSS. Eg content: '\2022'

ps. I have no connection with the web site.

Format SQL in SQL Server Management Studio

There is a special trick I discovered by accident.

  1. Select the query you wish to format.
  2. Ctrl+Shift+Q (This will open your query in the query designer)
  3. Then just go OK Voila! Query designer will format your query for you. Caveat is that you can only do this for statements and not procedural code, but its better than nothing.

How do I connect to mongodb with node.js (and authenticate)?

Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:

   var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
    assert = require('assert');

var user = 'user';
var password = 'password';

MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
    if(err){
        console.log("Auth Failed");
        return;
    }
    console.log("Connected");
    db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
        docs.each(function(err, doc) {
          if(doc) {
            console.log(doc['_id']);
          }
        });
    });

    db.close();

}); 

Count the items from a IEnumerable<T> without iterating?

Alternatively you can do the following:

Tables.ToList<string>().Count;

python pip: force install ignoring dependencies

When I were trying install librosa package with pip (pip install librosa), this error were appeared:

ERROR: Cannot uninstall 'llvmlite'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

I tried to remove llvmlite, but pip uninstall could not remove it. So, I used capability of ignore of pip by this code:

pip install librosa --ignore-installed llvmlite

Indeed, you can use this rule for ignoring a package you don't want to consider:

pip install {package you want to install} --ignore-installed {installed package you don't want to consider}

ImportError: DLL load failed: %1 is not a valid Win32 application

You could try installing the 32 bit version of opencv

How can I cast int to enum?

Below is a nice utility class for Enums

public static class EnumHelper
{
    public static int[] ToIntArray<T>(T[] value)
    {
        int[] result = new int[value.Length];
        for (int i = 0; i < value.Length; i++)
            result[i] = Convert.ToInt32(value[i]);
        return result;
    }

    public static T[] FromIntArray<T>(int[] value) 
    {
        T[] result = new T[value.Length];
        for (int i = 0; i < value.Length; i++)
            result[i] = (T)Enum.ToObject(typeof(T),value[i]);
        return result;
    }


    internal static T Parse<T>(string value, T defaultValue)
    {
        if (Enum.IsDefined(typeof(T), value))
            return (T) Enum.Parse(typeof (T), value);

        int num;
        if(int.TryParse(value,out num))
        {
            if (Enum.IsDefined(typeof(T), num))
                return (T)Enum.ToObject(typeof(T), num);
        }

        return defaultValue;
    }
}

Difference in make_shared and normal shared_ptr in C++

There is another case where the two possibilities differ, on top of those already mentioned: if you need to call a non-public constructor (protected or private), make_shared might not be able to access it, while the variant with the new works fine.

class A
{
public:

    A(): val(0){}

    std::shared_ptr<A> createNext(){ return std::make_shared<A>(val+1); }
    // Invalid because make_shared needs to call A(int) **internally**

    std::shared_ptr<A> createNext(){ return std::shared_ptr<A>(new A(val+1)); }
    // Works fine because A(int) is called explicitly

private:

    int val;

    A(int v): val(v){}
};

Disable XML validation in Eclipse

In JBoss Developer 4.0 and above (Eclipse-based), this is a tad easier. Just right-click on your file or folder that contains xml-based files, choose "Exclude Validation", then click "Yes" to confirm. Then right-click the same files/folder again and click on "Validate", which will remove the errors with a confirmation.

How to resolve cURL Error (7): couldn't connect to host?

you can also get this if you are trying to hit the same URL with multiple HTTP request at the same time.Many curl requests wont be able to connect and so return with error

Postgresql Select rows where column = array

In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])

I spent almost 6 hours before I stumble on the post.

Socket send and receive byte array

You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.

This is the easiest case for a known size (100 bytes):

in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);

In this case DataInputStream makes sense as it offers readFully(). If you don't use it, you need to loop yourself until the expected number of bytes is read.

Android Canvas: drawing too large bitmap

In my case I had to remove the android platform and add it again. Something got stuck and copying all my code into another app worked like a charm - hence my idea of cleaning up the build for android by removing the platform.

cordova platform remove android
cordova platform add android

I guess it's some kind of cleanup that you have to do from time to time :-(

Android: Flush DNS

You have a few options:

  • Release an update for your app that uses a different hostname that isn't in anyone's cache.
  • Same thing, but using the IP address of your server
  • Have your users go into settings -> applications -> Network Location -> Clear data.

You may want to check that last step because i don't know for a fact that this is the appropriate service. I can't really test that right now. Good luck!

Replace new line/return with space using regex

The new line separator is different for different OS-es - '\r\n' for Windows and '\n' for Linux.

To be safe, you can use regex pattern \R - the linebreak matcher introduced with Java 8:

String inlinedText = text.replaceAll("\\R", " ");

Strip out HTML and Special Characters

Probably better here for a regex replace

// Strip HTML Tags
$clear = strip_tags($des);
// Clean up things like &amp;
$clear = html_entity_decode($clear);
// Strip out any url-encoded stuff
$clear = urldecode($clear);
// Replace non-AlNum characters with space
$clear = preg_replace('/[^A-Za-z0-9]/', ' ', $clear);
// Replace Multiple spaces with single space
$clear = preg_replace('/ +/', ' ', $clear);
// Trim the string of leading/trailing space
$clear = trim($clear);

Or, in one go

$clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($des))))));

How to get a list of current open windows/process with Java?

For windows I use following:

Process process = new ProcessBuilder("tasklist.exe", "/fo", "csv", "/nh").start();
new Thread(() -> {
    Scanner sc = new Scanner(process.getInputStream());
    if (sc.hasNextLine()) sc.nextLine();
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        String[] parts = line.split(",");
        String unq = parts[0].substring(1).replaceFirst(".$", "");
        String pid = parts[1].substring(1).replaceFirst(".$", "");
        System.out.println(unq + " " + pid);
    }
}).start();
process.waitFor();
System.out.println("Done");

What is the fastest way to send 100,000 HTTP requests in Python?

Create epoll object,
open many client TCP sockets,
adjust their send buffers to be a bit more than request header,
send a request header — it should be immediate, just placing into a buffer, register socket in epoll object,
do .poll on epoll obect,
read first 3 bytes from each socket from .poll,
write them to sys.stdout followed by \n (don't flush), close the client socket.

Limit number of sockets opened simultaneously — handle errors when sockets are created. Create a new socket only if another is closed.
Adjust OS limits.
Try forking into a few (not many) processes: this may help to use CPU a bit more effectively.