Programs & Examples On #Pgpool

Pgpool-II is a middleware between PostgreSQL servers and clients for connection pooling, replication and load balancing

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Your Event.hbm.xml says:

<set name="attendees" cascade="all">
    <key column="attendeeId" />
    <one-to-many class="Attendee" />
</set>

In plain english, this means that the column Attendee.attendeeId is the foreign key for the association attendees and points to the primary key of Event.

When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.

Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.

Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event-end as inverse.

How to concatenate a std::string and an int?

As a one liner: name += std::to_string(age);

How do I remove the space between inline/inline-block elements?

Use flexbox and do a fallback (from suggestions above) for older browsers:

ul {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}

How to make PyCharm always show line numbers

PyCharm Version 3.4.1(For all files in the project):

File -> Preferences -> Editor (IDE Settings) -> Appearance -> mark 'Show line numbers'

PyCharm Version 3.4.1(only for existing file in the project):

View -> Active Editor -> Show Line Numbers

image

List submodules in a Git repository

If there isn't any .gitmodules file, but a submodules configuration exists in .git/modules/:

find .git/modules/ -name config -exec grep url {} \;

How do you list volumes in docker containers?

if you want to list all the containers name with the relevant volumes that attached to each container you can try this:

docker ps -q | xargs docker container inspect -f '{{ .Name }} {{ .HostConfig.Binds }}'

example output:

/opt_rundeck_1 [/opt/var/lib/mysql:/var/lib/mysql:rw /var/lib/rundeck/var/storage:/var/lib/rundeck/var/storage:rw /opt/var/rundeck/.ssh:/var/lib/rundeck/.ssh:rw /opt/etc/rundeck:/etc/rundeck:rw /var/log/rundeck:/var/log/rundeck:rw /opt/rundeck-plugins:/opt/rundeck-plugins:rw /opt/var/rundeck:/var/rundeck:rw]

/opt_rundeck_1 - container name

[..] - volumes attached to the conatiner

jQuery - hashchange event

A different approach to your problem...

There are 3 ways to bind the hashchange event to a method:

<script>
    window.onhashchange = doThisWhenTheHashChanges;
</script>

Or

<script>
    window.addEventListener("hashchange", doThisWhenTheHashChanges, false);
</script>

Or

<body onhashchange="doThisWhenTheHashChanges();">

These all work with IE 9, FF 5, Safari 5, and Chrome 12 on Win 7.

How to solve '...is a 'type', which is not valid in the given context'? (C#)

Change

private void Form1_Load(object sender, EventArgs e) 
    { 
        CERas.CERAS = new CERas.CERAS(); 
    } 

to

private void Form1_Load(object sender, EventArgs e) 
    { 
        CERas.CERAS c = new CERas.CERAS(); 
    } 

Or if you wish to use it later again

change it to

using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WinApp_WMI2 
{ 
    public partial class Form1 : Form 
    { 
        CERas.CERAS m_CERAS;

        public Form1() 
        { 
            InitializeComponent(); 
        } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
        m_CERAS = new CERas.CERAS(); 
    } 
} 


}

I want to multiply two columns in a pandas DataFrame and add the result into a new column

For me, this is the clearest and most intuitive:

values = []
for action in ['Sell','Buy']:
    amounts = orders_df['Amounts'][orders_df['Action'==action]].values
    if action == 'Sell':
        prices = orders_df['Prices'][orders_df['Action'==action]].values
    else:
        prices = -1*orders_df['Prices'][orders_df['Action'==action]].values
    values += list(amounts*prices)  
orders_df['Values'] = values

The .values method returns a numpy array allowing you to easily multiply element-wise and then you can cumulatively generate a list by 'adding' to it.

addEventListener for keydown on Canvas

Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.

In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )

Bootstrap modal link

Please remove . from your target it should be a id

<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>

Also you have to give your modal id like below

<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">

Here is the solution in a fiddle.

How do I print out the contents of a vector?

My solution is simple.h, which is part of scc package. All std containers, maps, sets, c-arrays are printable.

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

At its simplest, the difference is one of plurality:

  • Backout backs out of a single changelist (whether the most recent or not). i.e. it undoes a single changelist.
  • Rollback rolls back changes as much as it needs to in order to get to a previous changelist. i.e. it undoes multiple changelists.

I used to forget which one is which and end up having to look it up many times. To fix this problem, imagine rolling back as several rotations then hopefully the fact that rollback is plural will help you (and me!) remember which one is which. Backout sounds 'less plural' than rollback to me. Imagine backing out of a single parking space.

So, the mnemonic is:

  • Rollback → multiple rotations
  • Backout → back out of a single car parking space

I hope this helps!

Comparing Java enum members: == or equals()?

I want to complement polygenelubricants answer:

I personally prefer equals(). But it lake the type compatibility check. Which I think is an important limitation.

To have type compatibility check at compilation time, declare and use a custom function in your enum.

public boolean isEquals(enumVariable) // compare constant from left
public static boolean areEqual(enumVariable, enumVariable2) // compare two variable

With this, you got all the advantage of both solution: NPE protection, easy to read code and type compatibility check at compilation time.

I also recommend to add an UNDEFINED value for enum.

Android WebView progress bar

here is the easiest way to add progress bar in android Web View.

Add a boolean field in your activity/fragment

private boolean isRedirected;

This boolean will prevent redirection of web pages cause of dead links.Now you can just pass your WebView object and web Url into this method.

private void startWebView(WebView webView,String url) {

    webView.setWebViewClient(new WebViewClient() {
        ProgressDialog progressDialog;

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            isRedirected = true;
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            isRedirected = false;
        }

        public void onLoadResource (WebView view, String url) {
            if (!isRedirected) {
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
                    progressDialog.setMessage("Loading...");
                    progressDialog.show();
                }
            }

        }
        public void onPageFinished(WebView view, String url) {
            try{
                isRedirected=true;

                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }



            }catch(Exception exception){
                exception.printStackTrace();
            }
        }

    });

    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);
}

Here when start loading it will call onPageStarted. Here i setting Boolean field is false. But when page load finish it will come to onPageFinished method and here Boolean field is set to true. Sometimes if url is dead it will redirected and it will come to onLoadResource() before onPageFinished method. For this reason it will not hiding the progress bar. To prevent this i am checking if (!isRedirected) in onLoadResource()

in onPageFinished() method before dismissing the Progress Dialog you can write your 10 second time delay code

That's it. Happy coding :)

How to determine previous page URL in Angular?

I had some struggle to access the previous url inside a guard.
Without implementing a custom solution, this one is working for me.

public constructor(private readonly router: Router) {
};

public ngOnInit() {
   this.router.getCurrentNavigation().previousNavigation.initialUrl.toString();
}

The initial url will be the previous url page.

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

error: command 'gcc' failed with exit status 1 while installing eventlet

try this :

sudo apt-get install libblas-dev libatlas-base-dev

I had a similar issue on Ubuntu 14.04. For me the following Ubuntu packages

How do I mock a service that returns promise in AngularJS Jasmine unit test?

You can use a stubbing library like sinon to mock your service. You can then return $q.when() as your promise. If your scope object's value comes from the promise result, you will need to call scope.$root.$digest().

var scope, controller, datacontextMock, customer;
  beforeEach(function () {
        module('app');
        inject(function ($rootScope, $controller,common, datacontext) {
            scope = $rootScope.$new();
            var $q = common.$q;
            datacontextMock = sinon.stub(datacontext);
            customer = {id:1};
           datacontextMock.customer.returns($q.when(customer));

            controller = $controller('Index', { $scope: scope });

        })
    });


    it('customer id to be 1.', function () {


            scope.$root.$digest();
            expect(controller.customer.id).toBe(1);


    });

Add column with number of days between dates in DataFrame pandas

To remove the 'days' text element, you can also make use of the dt() accessor for series: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html

So,

df[['A','B']] = df[['A','B']].apply(pd.to_datetime) #if conversion required
df['C'] = (df['B'] - df['A']).dt.days

which returns:

             A          B   C
one 2014-01-01 2014-02-28  58
two 2014-02-03 2014-03-01  26

"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

From find manual:

NON-BUGS         

   Operator precedence surprises
   The command find . -name afile -o -name bfile -print will never print
   afile because this is actually equivalent to find . -name afile -o \(
   -name bfile -a -print \).  Remember that the precedence of -a is
   higher than that of -o and when there is no operator specified
   between tests, -a is assumed.

   “paths must precede expression” error message
   $ find . -name *.c -print
   find: paths must precede expression
   Usage: find [-H] [-L] [-P] [-Olevel] [-D ... [path...] [expression]

   This happens because *.c has been expanded by the shell resulting in
   find actually receiving a command line like this:
   find . -name frcode.c locate.c word_io.c -print
   That command is of course not going to work.  Instead of doing things
   this way, you should enclose the pattern in quotes or escape the
   wildcard:
   $ find . -name '*.c' -print
   $ find . -name \*.c -print

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Visual Studio popup: "the operation could not be completed"

For me, this issue was being caused by conflicting <site> configurations in the following file.

C:\Users\smunro\Documents\IISExpress\config\applicationhost.config

I edited this file to remove all of the site elements within the following element. You might want to be a little more selective and try to identify the site that is causing the conflict and remove just that.

<configuration><system.applicationHost><sites>

Note that I left the <siteDefaults>, <applicationDefaults> and <virtualDirectoryDefaults> elements there.

When I reloaded the project, a new <site> element was created automatically.

Use grep --exclude/--include syntax to not grep through certain files

In the directories are also many binary files. I can't search only certain directories (the directory structure is a big mess). Is there's a better way of grepping only in certain files?

ripgrep

This is one of the quickest tools designed to recursively search your current directory. It is written in Rust, built on top of Rust's regex engine for maximum efficiency. Check the detailed analysis here.

So you can just run:

rg "some_pattern"

It respect your .gitignore and automatically skip hidden files/directories and binary files.

You can still customize include or exclude files and directories using -g/--glob. Globbing rules match .gitignore globs. Check man rg for help.

For more examples, see: How to exclude some files not matching certain extensions with grep?

On macOS, you can install via brew install ripgrep.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

gem update --system

will update the rubygems and will fix the problem.

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

Source: CodePath - UI Testing With Espresso

  1. Finally, we need to pull in the Espresso dependencies and set the test runner in our app build.gradle:
// build.gradle
...
android {
    ...
    defaultConfig {
        ...
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

dependencies {
    ...
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
        // Necessary if your app targets Marshmallow (since Espresso
        // hasn't moved to Marshmallow yet)
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    androidTestCompile('com.android.support.test:runner:0.5') {
        // Necessary if your app targets Marshmallow (since the test runner
        // hasn't moved to Marshmallow yet)
        exclude group: 'com.android.support', module: 'support-annotations'
    }
}

I've added that to my gradle file and the warning disappeared.

Also, if you get any other dependency listed as conflicting, such as support-annotations, try excluding it too from the androidTestCompile dependencies.

Excel 2013 VBA Clear All Filters macro

This works best for me.

I usually use the following before I save and close the files.

Sub remove_filters

ActiveSheet.AutofilterMode = False

End Sub

How to make a <div> or <a href="#"> to align center

You can use the code below:

a {
display: block;
width: 113px;
margin: auto; 
}

By setting, in my case, the link to display:block, it is easier to position the link.
This works the same when you use a <div> tag/class.
You can pick any width you want.

How to run a bash script from C++ program

The only standard mandated implementation dependent way is to use the system() function from stdlib.h.

Also if you know how to make user become the super-user that would be nice also.

Do you want the script to run as super-user or do you want to elevate the privileges of the C executable? The former can be done with sudo but there are a few things you need to know before you can go off using sudo.

ios Upload Image and Text using HTTP POST

I can show you an example of uploading a .txt file to a server with NSMutableURLRequest and NSURLSessionUploadTask with help of a php script.

-(void)uploadFileToServer : (NSString *) filePath
{
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://YourURL.com/YourphpScript.php"]];
[request setHTTPMethod:@"POST"]; 
[request addValue:@"File Name" forHTTPHeaderField:@"FileName"];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject];

NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePath] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                      {
                                          NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                          if (error || [httpResponse statusCode]!=202)
                                          {

                                              //Error
                                          }
                                          else
                                          {
                                             //Success
                                          }
                                          [defaultSession invalidateAndCancel];
                                      }];
[uploadTask resume];
}

php Script

<?php 
$request_body = @file_get_contents('php://input');
foreach (getallheaders() as $name => $value) 
{
    if ($FileName=="FileName") 
    {
        $header=$value;
        break;
    }
}   
$uploadedDir = "directory/";
@mkdir($uploadedDir);
file_put_contents($uploadedDir."/".$FileName.".txt",
$request_body.PHP_EOL, FILE_APPEND);
header('X-PHP-Response-Code: 202', true, 202);  
?>       

How to capitalize the first letter of text in a TextView in an Android Application

You can add Apache Commons Lang in Gradle like compile 'org.apache.commons:commons-lang3:3.4'

And use WordUtils.capitalizeFully(name)

Auto populate columns in one sheet from another sheet

If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?

It might not be the best way but you may type the following

=IF(sheet1!A1<>"",sheet1!A1,"")

and drag it down to the maximum number of rows you expect.

Difference between Encapsulation and Abstraction

There is a great article that touches on differences between Abstraction, Encapsulation and Information hiding in depth: http://www.tonymarston.co.uk/php-mysql/abstraction.txt

Here is the conclusion from the article:

Abstraction, information hiding, and encapsulation are very different, but highly-related, concepts. One could argue that abstraction is a technique that helps us identify which specific information should be visible, and which information should be hidden. Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible.

Keyword not supported: "data source" initializing Entity Framework Context

Make sure you have Data Source and not DataSource in your connection string. The space is important. Trust me. I'm an idiot.

How do I get an apk file from an Android device?

Steps to Download APK from Device to Desktop

A) Make sure that your running (emulator/real Device). To check use this command

adb devices

B) Select all the available package list installed in your device. You can use grep command to select the specific package you intend to download.

adb shell pm list packages
adb shell pm list packages -f -3

Output (List of available packages )

package:/data/app/com.example.mytestapplication-sOzKi5USzfbYLPNDmaaK6g==/base.apk=com.example.mytestapplication
package:/data/app/com.example.myapplication-nd1I4FGnTZnQ9PyRbPDHhw==/base.apk=com.example.myapplication

C) Copy the package (which you like to download) from the above link. Form our case I choose this (com.example.myapplication) package

Syntax : adb shell pm path [your_package_name]
Command: adb shell pm path com.example.myapplication

Output

package:/data/app/com.example.myapplication-nd1I4FGnTZnQ9PyRbPDHhw==/base.apk

D) Finally, To download APK from your (emulator/real device)

Syntax : adb pull /data/app/[your_package_name]-1/base.apk  [your_destination_path]
Command: adb pull /data/app/com.example.myapplication-3j4CVk0Tb2gysElgjz5O6A==/base.apk /Users/$(whoami)/Documents/your_apk.apk

Example: Trying to pull this CertInstaller.apk file in your local machine ( Mac )

adb pull /system/app/CertInstaller/CertInstaller.apk /Users/$(whoami)/Documents/APK/download_apk/

E) Confirm in your local directory

ls -la /Users/$(whoami)/Documents/

Reference to a non-shared member requires an object reference occurs when calling public sub

Go to the Declaration of the desired object and mark it Shared.

Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

You can define foreign key by:

public class Parent
{
   public int Id { get; set; }
   public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
   public int Id { get; set; }
   // This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
   public int ParentId { get; set; } 
   public virtual Parent Parent { get; set; }
}

Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.

If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation

Data annotation:

// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }

Fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey(c => c.ParentId);

Other types of constraints can be enforced by data annotations and model validation.

Edit:

You will get an exception if you don't set ParentId. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.

Where is a log file with logs from a container?

To see how much space each container's log is taking up, use this:

docker ps -qa | xargs docker inspect --format='{{.LogPath}}' | xargs ls -hl

(you might need a sudo before ls).

Get the current first responder without using a private API

Using Swift and with a specific UIView object this might help:

func findFirstResponder(inView view: UIView) -> UIView? {
    for subView in view.subviews as! [UIView] {
        if subView.isFirstResponder() {
            return subView
        }
        
        if let recursiveSubView = self.findFirstResponder(inView: subView) {
            return recursiveSubView
        }
    }
    
    return nil
}

Just place it in your UIViewController and use it like this:

let firstResponder = self.findFirstResponder(inView: self.view)

Take note that the result is an Optional value so it will be nil in case no firstResponder was found in the given views subview hierarchy.

Check if string is neither empty nor space in shell script

[ $(echo $variable_to_test | sed s/\n// | sed s/\ //) == "" ] && echo "String is empty"

Stripping all newlines and spaces from the string will cause a blank one to be reduced to nothing which can be tested and acted upon

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Use content="IE=edge,chrome=1"   Skip other X-UA-Compatible modes

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
                                   -------------------------- 
  • No compatibility icon
    The IE9 Address bar does not show up the Compatibility View button
    and the page does not also show up a jumble of out-of-place menus, images, and text boxes.

  • Features
    This meta tag is required to enable javascript::JSON.parse() on IE8
    (even when <!DOCTYPE html> is present)

  • Correctness
    Rendering/Execution of modern HTML/CSS/JavaScript is more valid (nicer).

  • Performance
    The Trident rendering engine should run faster in its edge mode.


Usage

In your HTML

<!DOCTYPE html> 
<html> 
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Or better in the configuration of your web server:
(see also the RiaD's answer)

  • Apache as proposed by pixeline

    <IfModule mod_setenvif.c>
      <IfModule mod_headers.c>
        BrowserMatch MSIE ie
        Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie
      </IfModule>
    </IfModule>
    <IfModule mod_headers.c>
      Header append Vary User-Agent
    </IfModule>
    
  • Nginx as proposed by Stef Pause

    server {
      #...
      add_header X-UA-Compatible "IE=Edge,chrome=1";
    }
    
  • Varnish proxy as proposed by Lucas Riutzel

    sub vcl_deliver {
      if( resp.http.Content-Type ~ "text/html" ) {
        set resp.http.X-UA-Compatible = "IE=edge,chrome=1";
      }
    }
    
  • IIS (since v7)

    <configuration>
      <system.webServer>
         <httpProtocol>
            <customHeaders>
               <add name="X-UA-Compatible" value="IE=edge,chrome=1" />
            </customHeaders>
         </httpProtocol>
      </system.webServer>
    </configuration>
    

Microsoft recommends Edge mode since IE11

As noticed by Lynda (see comments), the Compatibility changes in IE11 recommends Edge mode:

Starting with IE11, edge mode is the preferred document mode; it represents the highest support for modern standards available to the browser.

But the position of Microsoft was not clear. Another MSDN page did not recommend Edge mode:

Because Edge mode forces all pages to be opened in standards mode, regardless of the version of Internet Explorer, you might be tempted to use this for all pages viewed with Internet Explorer. Don't do this, as the X-UA-Compatible header is only supported starting with Windows Internet Explorer 8.

Instead, Microsoft recommended using <!DOCTYPE html>:

If you want all supported versions of Internet Explorer to open your pages in standards mode, use the HTML5 document type declaration [...]

As Ricardo explains (in the comments below) any DOCTYPE (HTML4, XHTML1...) can be used to trigger Standards Mode, not only HTML5's DOCTYPE. The important thing is to always have a DOCTYPE in the page.

Clara Onager has even noticed in an older version of Specifying legacy document modes:

Edge mode is intended for testing purposes only; do not use it in a production environment.

It is so confusing that Usman Y thought Clara Onager was speaking about:

The [...] example is provided for illustrative purposes only; don't use it in a production environment.

<meta http-equiv="X-UA-Compatible" content="IE=7,9,10" >

Well... In the rest of this answer I give more explanations why using content="IE=edge,chrome=1" is a good practice in production.


History

For many years (2000 to 2008), IE market share was more than 80%. And IE v6 was considered as a de facto standard (80% to 97% market share in 2003, 2004, 2005 and 2006 for IE6 only, more market share with all IE versions).

As IE6 was not respecting Web standards, developers had to test their website using IE6. That situation was great for Microsoft (MS) as web developers had to buy MS products (e.g. IE cannot be used without buying Windows), and it was more profit-making to stay non-compliant (i.e. Microsoft wanted to become the standard excluding other companies).

Therefore many many sites were IE6 compliant only, and as IE was not compliant with web standard, all these web sites was not well rendered on standards compliant browsers. Even worse, many sites required only IE.

However, at this time, Mozilla started Firefox development respecting as much as possible all the web standards (other browser were implemented to render pages as done by IE6). As more and more web developers wanted to use the new web standards features, more and more websites were more supported by Firefox than IE.

When IE market sharing was decreasing, MS realized staying standard incompatible was not a good idea. Therefore MS started to release new IE version (IE8/IE9/IE10) respecting more and more the web standards.


The web-incompatible issue

But the issue is all the websites designed for IE6: Microsoft could not release new IE versions incompatible with these old IE6-designed websites. Instead of deducing the IE version a website has been designed, MS requested developers to add extra data (X-UA-Compatible) in their pages.

IE6 is still used in 2016

Nowadays, IE6 is still used (0.7% in 2016) (4.5% in January 2014), and some internet websites are still IE6-only-compliant. Some intranet website/applications are tested using IE6. Some intranet website are 100% functional only on IE6. These companies/departments prefer to postpone the migration cost: other priorities, nobody no longer knows how the website/application has been implemented, the owner of the legacy website/application went bankrupt...

China represents 50% of IE6 usage in 2013, but it may change in the next years as Chinese Linux distribution is being broadcast.

Be confident with your web skills

If you (try to) respect web standard, you can simply always use http-equiv="X-UA-Compatible" content="IE=edge,chrome=1". To keep compatibility with old browsers, just avoid using latest web features: use the subset supported by the oldest browser you want to support. Or If you want to go further, you may adopt concepts as Graceful degradation, Progressive enhancement and Unobtrusive JavaScript. (You may also be pleased to read What should a web developer consider?.)

Do do not care about the best IE version rendering: this is not your job as browsers have to be compliant with web standards. If your site is standard compliant and use moderately latest features, therefore browsers have to be compliant with your website.

Moreover, as there are many campaigns to kill IE6 (IE6 no more, MS campaign), nowadays you may avoid wasting time with IE testing!

Personal IE6 experience

In 2009-2012, I worked for a company using IE6 as the official single browser allowed. I had to implement an intranet website for IE6 only. I decided to respect web standard but using the IE6-capable subset (HTML/CSS/JS).

It was hard, but when the company switched to IE8, the website was still well rendered because I had used Firefox and firebug to check the web-standard compatibility ;)

On delete cascade with doctrine2

There are two kinds of cascades in Doctrine:

1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.

2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:

@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")

I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.

Resolve Git merge conflicts in favor of their changes during a pull

from https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging

This will basically do a fake merge. It will record a new merge commit with both branches as parents, but it will not even look at the branch you’re merging in. It will simply record as the result of the merge the exact code in your current branch.

$ git merge -s ours mundo

Merge made by the 'ours' strategy.

$ git diff HEAD HEAD~

You can see that there is no difference between the branch we were on and the result of the merge.

This can often be useful to basically trick Git into thinking that a branch is already merged when doing a merge later on. For example, say you branched off a release branch and have done some work on it that you will want to merge back into your master branch at some point. In the meantime some bugfix on master needs to be backported into your release branch. You can merge the bugfix branch into the release branch and also merge -s ours the same branch into your master branch (even though the fix is already there) so when you later merge the release branch again, there are no conflicts from the bugfix.

A situation I've found to be useful if I want master to reflect the changes of a new topic branch. I've noticed that -Xtheirs doesn't merge without conflicts in some circumstances... e.g.

$ git merge -Xtheirs topicFoo 

CONFLICT (modify/delete): js/search.js deleted in HEAD and modified in topicFoo. Version topicFoo of js/search.js left in tree.

In this case the solution I found was

$ git checkout topicFoo

from topicFoo, first merge in master using the -s ours strategy, this will create the fake commit that is just the state of topicFoo. $ git merge -s ours master

check the created merge commit

$ git log

now checkout the master branch

$ git checkout master

merge the topic branch back but this time use the -Xtheirs recursive strategy, this will now present you with a master branch with the state of topicFoo.

$ git merge -X theirs topicFoo

C# importing class into another class doesn't work

namespace MyNamespace
{
    public class MyMainClass
    {
        static void Main()
        {
            MyClass test = new MyClass();
        }
    }

    public class MyClass
    {
        void Stuff()
        {

        }
    }
}

You have no need for using a namespace then because it is all encompased in the same namespace.

If you are unsure of what namespace your class is located, type the class (case sensitive you wish to use) then with your cursor on the class, use CTRL + . and it will offer you a manual import.

500 internal server error at GetResponse()

For me this error occurred because I had 2 web API actions that had the exact same signatures and both had the same verbs, HttpPost, what I did was change one of the verbs (the one used for updating) to PUT and the error was removed. The following in my catch statement helped in getting to the root of the problem:

catch (WebException webex)
{
                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string text = reader.ReadToEnd();
                }
}

static const vs #define

Please see here: static const vs define

usually a const declaration (notice it doesn't need to be static) is the way to go

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

How to build x86 and/or x64 on Windows from command line with CMAKE?

Besides CMAKE_GENERATOR_PLATFORM variable, there is also the -A switch

cmake -G "Visual Studio 16 2019" -A Win32
cmake -G "Visual Studio 16 2019" -A x64

https://cmake.org/cmake/help/v3.16/generator/Visual%20Studio%2016%202019.html#platform-selection

  -A <platform-name>           = Specify platform name if supported by
                                 generator.

Send a ping to each IP on a subnet

#!/bin/sh

COUNTER=$1

while [ $COUNTER -lt 254 ]
do
 echo $COUNTER
 ping -c 1 192.168.1.$COUNTER | grep 'ms'
 COUNTER=$(( $COUNTER + 1 ))
done

#specify start number like this: ./ping.sh 1
#then run another few instances to cover more ground
#aka one at 1, another at 100, another at 200
#this just finds addresses quicker. will only print ttl info when an address resolves

mysql select from n last rows

Might be a very late answer, but this is good and simple.

select * from table_name order by id desc limit 5

This query will return a set of last 5 values(last 5 rows) you 've inserted in your table

What is the canonical way to check for errors using the CUDA runtime API?

The C++-canonical way: Don't check for errors...use the C++ bindings which throw exceptions.

I used to be irked by this problem; and I used to have a macro-cum-wrapper-function solution just like in Talonmies and Jared's answers, but, honestly? It makes using the CUDA Runtime API even more ugly and C-like.

So I've approached this in a different and more fundamental way. For a sample of the result, here's part of the CUDA vectorAdd sample - with complete error checking of every runtime API call:

// (... prepare host-side buffers here ...)

auto current_device = cuda::device::current::get();
auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements);

cuda::memory::copy(d_A.get(), h_A.get(), size);
cuda::memory::copy(d_B.get(), h_B.get(), size);

// (... prepare a launch configuration here... )

cuda::launch(vectorAdd, launch_config,
    d_A.get(), d_B.get(), d_C.get(), numElements
);    
cuda::memory::copy(h_C.get(), d_C.get(), size);

// (... verify results here...)

Again - all potential errors are checked , and an exception if an error occurred (caveat: If the kernel caused some error after launch, it will be caught after the attempt to copy the result, not before; to ensure the kernel was successful you would need to check for error between the launch and the copy with a cuda::outstanding_error::ensure_none() command).

The code above uses my

Thin Modern-C++ wrappers for the CUDA Runtime API library (Github)

Note that the exceptions carry both a string explanation and the CUDA runtime API status code after the failing call.

A few links to how CUDA errors are automagically checked with these wrappers:

Update multiple columns in SQL

Syntax

UPDATE table-name 
SET column-name = value, column-name = value, ...
WHERE condition

Example

UPDATE school
SET course = 'mysqli', teacher = 'Tanzania', student = 'you'
WHERE id = 6

Node.js spawn child process and get terminal output live

It's much easier now (6 years later)!

Spawn returns a childObject, which you can then listen for events with. The events are:

  • Class: ChildProcess
    • Event: 'error'
    • Event: 'exit'
    • Event: 'close'
    • Event: 'disconnect'
    • Event: 'message'

There are also a bunch of objects from childObject, they are:

  • Class: ChildProcess
    • child.stdin
    • child.stdout
    • child.stderr
    • child.stdio
    • child.pid
    • child.connected
    • child.kill([signal])
    • child.send(message[, sendHandle][, callback])
    • child.disconnect()

See more information here about childObject: https://nodejs.org/api/child_process.html

Asynchronous

If you want to run your process in the background while node is still able to continue to execute, use the asynchronous method. You can still choose to perform actions after your process completes, and when the process has any output (for example if you want to send a script's output to the client).

child_process.spawn(...); (Node v0.1.90)

var spawn = require('child_process').spawn;
var child = spawn('node ./commands/server.js');

// You can also use a variable to save the output 
// for when the script closes later
var scriptOutput = "";

child.stdout.setEncoding('utf8');
child.stdout.on('data', function(data) {
    //Here is where the output goes

    console.log('stdout: ' + data);

    data=data.toString();
    scriptOutput+=data;
});

child.stderr.setEncoding('utf8');
child.stderr.on('data', function(data) {
    //Here is where the error output goes

    console.log('stderr: ' + data);

    data=data.toString();
    scriptOutput+=data;
});

child.on('close', function(code) {
    //Here you can get the exit code of the script

    console.log('closing code: ' + code);

    console.log('Full output of script: ',scriptOutput);
});

Here's how you would use a callback + asynchronous method:

var child_process = require('child_process');

console.log("Node Version: ", process.version);

run_script("ls", ["-l", "/home"], function(output, exit_code) {
    console.log("Process Finished.");
    console.log('closing code: ' + exit_code);
    console.log('Full output of script: ',output);
});

console.log ("Continuing to do node things while the process runs at the same time...");

// This function will output the lines from the script 
// AS is runs, AND will return the full combined output
// as well as exit code when it's done (using the callback).
function run_script(command, args, callback) {
    console.log("Starting Process.");
    var child = child_process.spawn(command, args);

    var scriptOutput = "";

    child.stdout.setEncoding('utf8');
    child.stdout.on('data', function(data) {
        console.log('stdout: ' + data);

        data=data.toString();
        scriptOutput+=data;
    });

    child.stderr.setEncoding('utf8');
    child.stderr.on('data', function(data) {
        console.log('stderr: ' + data);

        data=data.toString();
        scriptOutput+=data;
    });

    child.on('close', function(code) {
        callback(scriptOutput,code);
    });
}

Using the method above, you can send every line of output from the script to the client (for example using Socket.io to send each line when you receive events on stdout or stderr).

Synchronous

If you want node to stop what it's doing and wait until the script completes, you can use the synchronous version:

child_process.spawnSync(...); (Node v0.11.12+)

Issues with this method:

  • If the script takes a while to complete, your server will hang for that amount of time!
  • The stdout will only be returned once the script has finished running. Because it's synchronous, it cannot continue until the current line has finished. Therefore it's unable to capture the 'stdout' event until the spawn line has finished.

How to use it:

var child_process = require('child_process');

var child = child_process.spawnSync("ls", ["-l", "/home"], { encoding : 'utf8' });
console.log("Process finished.");
if(child.error) {
    console.log("ERROR: ",child.error);
}
console.log("stdout: ",child.stdout);
console.log("stderr: ",child.stderr);
console.log("exist code: ",child.status);

Why should I use a pointer rather than the object itself?

But I can't figure out why should we use it like this?

I will compare how it works inside the function body if you use:

Object myObject;

Inside the function, your myObject will get destroyed once this function returns. So this is useful if you don't need your object outside your function. This object will be put on current thread stack.

If you write inside function body:

 Object *myObject = new Object;

then Object class instance pointed by myObject will not get destroyed once the function ends, and allocation is on the heap.

Now if you are Java programmer, then the second example is closer to how object allocation works under java. This line: Object *myObject = new Object; is equivalent to java: Object myObject = new Object();. The difference is that under java myObject will get garbage collected, while under c++ it will not get freed, you must somewhere explicitly call `delete myObject;' otherwise you will introduce memory leaks.

Since c++11 you can use safe ways of dynamic allocations: new Object, by storing values in shared_ptr/unique_ptr.

std::shared_ptr<std::string> safe_str = make_shared<std::string>("make_shared");

// since c++14
std::unique_ptr<std::string> safe_str = make_unique<std::string>("make_shared"); 

also, objects are very often stored in containers, like map-s or vector-s, they will automatically manage a lifetime of your objects.

What is function overloading and overriding in php?

Method overloading occurs when two or more methods with same method name but different number of parameters in single class. PHP does not support method overloading. Method overriding means two methods with same method name and same number of parameters in two different classes means parent class and child class.

Simulate delayed and dropped packets on Linux

You can try http://snad.ncsl.nist.gov/nistnet/ https://www-x.antd.nist.gov/nistnet/ It's quite old NIST project (last release 2005), but it works for me.

Using pointer to char array, values in that array can be accessed?

Most people responding don't even seem to know what an array pointer is...

The problem is that you do pointer arithmetics with an array pointer: ptr + 1 will mean "jump 5 bytes ahead since ptr points at a 5 byte array".

Do like this instead:

#include <stdio.h>

int main()
{
  char (*ptr)[5];
  char arr[5] = {'a','b','c','d','e'};
  int i;

  ptr = &arr;
  for(i=0; i<5; i++)
  {
    printf("\nvalue: %c", (*ptr)[i]);
  }
}

Take the contents of what the array pointer points at and you get an array. So they work just like any pointer in C.

c# datatable insert column at position 0

You can use the following code to add column to Datatable at postion 0:

    DataColumn Col   = datatable.Columns.Add("Column Name", System.Type.GetType("System.Boolean"));
    Col.SetOrdinal(0);// to put the column in position 0;

Append values to a set in Python

This question is the first one that shows up on Google when one looks up "Python how to add elements to set", so it's worth noting explicitly that, if you want to add a whole string to a set, it should be added with .add(), not .update().

Say you have a string foo_str whose contents are 'this is a sentence', and you have some set bar_set equal to set().

If you do bar_set.update(foo_str), the contents of your set will be {'t', 'a', ' ', 'e', 's', 'n', 'h', 'c', 'i'}.

If you do bar_set.add(foo_str), the contents of your set will be {'this is a sentence'}.

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

Took me a while to find this out but if you a number stored in a variable, say x and you want to select it, use

document.querySelector('a[data-a= + CSS.escape(x) + ']'). 

This is due to some attribute naming specifications that I'm not yet very familiar with. Hope this will help someone.

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.

the thing you have to do is to change your insertion query as below

INSERT INTO  `abuses` (  `user_id` ,  `abuser_username` ,  `comment` ,  `reg_date` , `auction_id` ) 
VALUES ( 100020,  'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I     thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;

How do I return multiple values from a function in C?

Create a struct and set two values inside and return the struct variable.

struct result {
    int a;
    char *string;
}

You have to allocate space for the char * in your program.

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

Android Studio: Module won't show up in "Edit Configuration"

In my case the problem was with SDK license acceptance. The problem was solved by downloading proper SDK version and license acceptance via SDK Manager.

Creating a new column based on if-elif-else condition

enter image description here

Lets say above one is your original dataframe and you want to add a new column 'old'

If age greater than 50 then we consider as older=yes otherwise False

step 1: Get the indexes of rows whose age greater than 50

row_indexes=df[df['age']>=50].index

step 2: Using .loc we can assign a new value to column

df.loc[row_indexes,'elderly']="yes"

same for age below less than 50

row_indexes=df[df['age']<50].index

df[row_indexes,'elderly']="no"

Datetime current year and month in Python

Late answer, but you can also use:

import time
ym = time.strftime("%Y-%m")

Datatables - Search Box outside datatable

More recent versions have a different syntax:

var table = $('#example').DataTable();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Note that this example uses the variable table assigned when datatables is first initialised. If you don't have this variable available, simply use:

var table = $('#example').dataTable().api();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Since: DataTables 1.10

– Source: https://datatables.net/reference/api/search()

How to check heap usage of a running JVM from the command line?

If you start execution with gc logging turned on you get the info on file. Otherwise 'jmap -heap ' will give you what you want. See the jmap doc page for more.

Please note that jmap should not be used in a production environment unless absolutely needed as the tool halts the application to be able to determine actual heap usage. Usually this is not desired in a production environment.

Java - checking if parseInt throws exception

You could try

NumberUtils.isParsable(yourInput)

It is part of org/apache/commons/lang3/math/NumberUtils and it checks whether the string can be parsed by Integer.parseInt(String), Long.parseLong(String), Float.parseFloat(String) or Double.parseDouble(String).

See below:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isParsable-java.lang.String-

What is a raw type and why shouldn't we use it?

 private static List<String> list = new ArrayList<String>();

You should specify the type-parameter.

The warning advises that types that are defined to support generics should be parameterized, rather than using their raw form.

List is defined to support generics: public class List<E>. This allows many type-safe operations, that are checked compile-time.

How to condense if/else into one line in Python?

Python's if can be used as a ternary operator:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

In which conda environment is Jupyter executing?

which environment is jupyter executing:

import sys
print(sys.executable)

create kernel for jupyter notebook

source activate myenv
python -m ipykernel install --user --name myenv --display-name "Python (myenv)"
source activate other-env
python -m ipykernel install --user --name other-env --display-name "Python (other-env)"

http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernel-install

Any way to clear python's IDLE window?

Most of the answers, here do clearing the DOS prompt screen, with clearing commands, which is not the question. Other answers here, were printing blank lines to show a clearing effect of the screen.

The simplest answer of this question is

It is not possible to clear python IDLE shell without some external module integration. If you really want to get a blank pure fresh shell just close the previous shell and run it again

JavaScript: SyntaxError: missing ) after argument list

just posting in case anyone else has the same error...

I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.

The solution was to make the function asynchronous

function functionName(args) {}

becomes

async function functionName(args) {}

Best way to find the months between two dates

Start by defining some test cases, then you will see that the function is very simple and needs no loops

from datetime import datetime

def diff_month(d1, d2):
    return (d1.year - d2.year) * 12 + d1.month - d2.month

assert diff_month(datetime(2010,10,1), datetime(2010,9,1)) == 1
assert diff_month(datetime(2010,10,1), datetime(2009,10,1)) == 12
assert diff_month(datetime(2010,10,1), datetime(2009,11,1)) == 11
assert diff_month(datetime(2010,10,1), datetime(2009,8,1)) == 14

You should add some test cases to your question, as there are lots of potential corner cases to cover - there is more than one way to define the number of months between two dates.

Node.js - Find home directory in platform agnostic way

Use osenv.home(). It's maintained by isaacs and I believe is used by npm itself.

https://github.com/isaacs/osenv

Where does this come from: -*- coding: utf-8 -*-

In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.

Default port for SQL Server

If you have access to the server then you can use

select local_tcp_port from sys.dm_exec_connections where local_tcp_port is not null

For full details see port number of SQL Server

Most recent previous business day in Python

 def getNthBusinessDay(startDate, businessDaysInBetween):
    currentDate = startDate
    daysToAdd = businessDaysInBetween
    while daysToAdd > 0:
        currentDate += relativedelta(days=1)
        day = currentDate.weekday()
        if day < 5:
            daysToAdd -= 1

    return currentDate 

Plotting a fast Fourier transform in Python

I write this additional answer to explain the origins of the diffusion of the spikes when using FFT and especially discuss the scipy.fftpack tutorial with which I disagree at some point.

In this example, the recording time tmax=N*T=0.75. The signal is sin(50*2*pi*x) + 0.5*sin(80*2*pi*x). The frequency signal should contain two spikes at frequencies 50 and 80 with amplitudes 1 and 0.5. However, if the analysed signal does not have a integer number of periods diffusion can appear due to the truncation of the signal:

  • Pike 1: 50*tmax=37.5 => frequency 50 is not a multiple of 1/tmax => Presence of diffusion due to signal truncation at this frequency.
  • Pike 2: 80*tmax=60 => frequency 80 is a multiple of 1/tmax => No diffusion due to signal truncation at this frequency.

Here is a code that analyses the same signal as in the tutorial (sin(50*2*pi*x) + 0.5*sin(80*2*pi*x)), but with the slight differences:

  1. The original scipy.fftpack example.
  2. The original scipy.fftpack example with an integer number of signal periods (tmax=1.0 instead of 0.75 to avoid truncation diffusion).
  3. The original scipy.fftpack example with an integer number of signal periods and where the dates and frequencies are taken from the FFT theory.

The code:

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

# 1. Linspace
N = 600
# Sample spacing
tmax = 3/4
T = tmax / N # =1.0 / 800.0
x1 = np.linspace(0.0, N*T, N)
y1 = np.sin(50.0 * 2.0*np.pi*x1) + 0.5*np.sin(80.0 * 2.0*np.pi*x1)
yf1 = scipy.fftpack.fft(y1)
xf1 = np.linspace(0.0, 1.0/(2.0*T), N//2)

# 2. Integer number of periods
tmax = 1
T = tmax / N # Sample spacing
x2 = np.linspace(0.0, N*T, N)
y2 = np.sin(50.0 * 2.0*np.pi*x2) + 0.5*np.sin(80.0 * 2.0*np.pi*x2)
yf2 = scipy.fftpack.fft(y2)
xf2 = np.linspace(0.0, 1.0/(2.0*T), N//2)

# 3. Correct positioning of dates relatively to FFT theory ('arange' instead of 'linspace')
tmax = 1
T = tmax / N # Sample spacing
x3 = T * np.arange(N)
y3 = np.sin(50.0 * 2.0*np.pi*x3) + 0.5*np.sin(80.0 * 2.0*np.pi*x3)
yf3 = scipy.fftpack.fft(y3)
xf3 = 1/(N*T) * np.arange(N)[:N//2]

fig, ax = plt.subplots()
# Plotting only the left part of the spectrum to not show aliasing
ax.plot(xf1, 2.0/N * np.abs(yf1[:N//2]), label='fftpack tutorial')
ax.plot(xf2, 2.0/N * np.abs(yf2[:N//2]), label='Integer number of periods')
ax.plot(xf3, 2.0/N * np.abs(yf3[:N//2]), label='Correct positioning of dates')
plt.legend()
plt.grid()
plt.show()

Output:

As it can be here, even with using an integer number of periods some diffusion still remains. This behaviour is due to a bad positioning of dates and frequencies in the scipy.fftpack tutorial. Hence, in the theory of discrete Fourier transforms:

  • the signal should be evaluated at dates t=0,T,...,(N-1)*T where T is the sampling period and the total duration of the signal is tmax=N*T. Note that we stop at tmax-T.
  • the associated frequencies are f=0,df,...,(N-1)*df where df=1/tmax=1/(N*T) is the sampling frequency. All harmonics of the signal should be multiple of the sampling frequency to avoid diffusion.

In the example above, you can see that the use of arange instead of linspace enables to avoid additional diffusion in the frequency spectrum. Moreover, using the linspace version also leads to an offset of the spikes that are located at slightly higher frequencies than what they should be as it can be seen in the first picture where the spikes are a little bit at the right of the frequencies 50 and 80.

I'll just conclude that the example of usage should be replace by the following code (which is less misleading in my opinion):

import numpy as np
from scipy.fftpack import fft

# Number of sample points
N = 600
T = 1.0 / 800.0
x = T*np.arange(N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = fft(y)
xf = 1/(N*T)*np.arange(N//2)
import matplotlib.pyplot as plt
plt.plot(xf, 2.0/N * np.abs(yf[0:N//2]))
plt.grid()
plt.show()

Output (the second spike is not diffused anymore):

I think this answer still bring some additional explanations on how to apply correctly discrete Fourier transform. Obviously, my answer is too long and there is always additional things to say (ewerlopes talked briefly about aliasing for instance and a lot can be said about windowing), so I'll stop.

I think that it is very important to understand deeply the principles of discrete Fourier transform when applying it because we all know so much people adding factors here and there when applying it in order to obtain what they want.

How to close the current fragment by using Button like the back button?

From Fragment A, to go to B, replace A with B and use addToBackstack() before commit().

Now From Fragment B, to go to C, first use popBackStackImmediate(), this will bring back A. Now replace A with C, just like the first transaction.

Which MySQL datatype to use for an IP address?

For IPv4 addresses, you can use VARCHAR to store them as strings, but also look into storing them as long integesrs INT(11) UNSIGNED. You can use MySQL's INET_ATON() function to convert them to integer representation. The benefit of this is it allows you to do easy comparisons on them, like BETWEEN queries

INET_ATON() MySQL function

Relative frequencies / proportions with dplyr

This answer is based upon Matifou's answer.

First I modified it to ensure that I don't get the freq column returned as a scientific notation column by using the scipen option.

Then I multiple the answer by 100 to get a percent rather than decimal to make the freq column easier to read as a percentage.

getOption("scipen") 
options("scipen"=10) 
mtcars %>%
count(am, gear) %>% 
mutate(freq = (n / sum(n)) * 100)

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Based on Jakub's answer you can configure the following git aliases for convenience:

accept-ours = "!f() { git checkout --ours -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"
accept-theirs = "!f() { git checkout --theirs -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"

They optionally take one or several paths of files to resolve and default to resolving everything under the current directory if none are given.

Add them to the [alias] section of your ~/.gitconfig or run

git config --global alias.accept-ours '!f() { git checkout --ours -- "${@:-.}"; git add -u "${@:-.}"; }; f'
git config --global alias.accept-theirs '!f() { git checkout --theirs -- "${@:-.}"; git add -u "${@:-.}"; }; f'

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

Simply switch to the Design View, and locate the concerned widget. Grab the one of the dots on the boundary of the widget and join it to an appropriate edge of the screen (or to a dot on some other widget).

For instance, if the widget is a toolbar, just grab the top-most dot and join it to the top-most edge of the phone screen as shown in the image.

Design View

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

find . -type f | 
sed -n "s/\(.*\)factory\.py$/& \1service\.py/p" | 
xargs -p -n 2 mv

eg will rename all files in the cwd with names ending in "factory.py" to be replaced with names ending in "service.py"

explanation:

1) in the sed cmd, the -n flag will suppress normal behavior of echoing input to output after the s/// command is applied, and the p option on s/// will force writing to output if a substitution is made. since a sub will only be made on match, sed will only have output for files ending in "factory.py"

2) in the s/// replacement string, we use "& " to interpolate the entire matching string, followed by a space character, into the replacement. because of this, it's vital that our RE matches the entire filename. after the space char, we use "\1service.py" to interpolate the string we gulped before "factory.py", followed by "service.py", replacing it. So for more complex transformations youll have to change the args to s/// (with an re still matching the entire filename)

example output:

foo_factory.py foo_service.py
bar_factory.py bar_service.py

3) we use xargs with -n 2 to consume the output of sed 2 delimited strings at a time, passing these to mv (i also put the -p option in there so you can feel safe when running this). voila.

What is a callback?

Definition

A callback is executable code that is passed as an argument to other code.

Implementation

// Parent can Read
public class Parent
{
    public string Read(){ /*reads here*/ };
}

// Child need Info
public class Child
{
    private string information;
    // declare a Delegate
    delegate string GetInfo();
    // use an instance of the declared Delegate
    public GetInfo GetMeInformation;

    public void ObtainInfo()
    {
        // Child will use the Parent capabilities via the Delegate
        information = GetMeInformation();
    }
}

Usage

Parent Peter = new Parent();
Child Johny = new Child();

// Tell Johny from where to obtain info
Johny.GetMeInformation = Peter.Read;

Johny.ObtainInfo(); // here Johny 'asks' Peter to read

Links

Remove an array element and shift the remaining ones

You just need to overwrite what you're deleting with the next value in the array, propagate that change, and then keep in mind where the new end is:

int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

// delete 3 (index 2)
for (int i = 2; i < 8; ++i)
    array[i] = array[i + 1]; // copy next element left

Now your array is {1, 2, 4, 5, 6, 7, 8, 9, 9}. You cannot delete the extra 9 since this is a statically-sized array, you just have to ignore it. This can be done with std::copy:

std::copy(array + 3, // copy everything starting here
          array + 9, // and ending here, not including it,
          array + 2) // to this destination

In C++11, use can use std::move (the algorithm overload, not the utility overload) instead.

More generally, use std::remove to remove elements matching a value:

// remove *all* 3's, return new ending (remaining elements unspecified)
auto arrayEnd = std::remove(std::begin(array), std::end(array), 3);

Even more generally, there is std::remove_if.

Note that the use of std::vector<int> may be more appropriate here, as its a "true" dynamically-allocated resizing array. (In the sense that asking for its size() reflects removed elements.)

How can I install a previous version of Python 3 in macOS using homebrew?

To solve this with homebrew, you can temporarily backdate homebrew-core and set the HOMEBREW_NO_AUTO_UPDATE variable to hold it in place:

cd `brew --repo homebrew/core`
git checkout f2a764ef944b1080be64bd88dca9a1d80130c558
export HOMEBREW_NO_AUTO_UPDATE=1
brew install python

I don't recommend permanently backdating homebrew-core, as you will miss out on security patches, but it is useful for testing purposes.

You can also extract old versions of homebrew formulae into your own tap (tap_owner/tap_name) using the brew extract command:

brew extract python tap_owner/tap_name --version=3.6.5

How to pad a string with leading zeros in Python 3

Make use of the zfill() helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.x and Python 3.x.

Sample usage:

print str(1).zfill(3);
# Expected output: 001

Description:

When applied to a value, zfill() returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.

Syntax:

str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.

How to index into a dictionary?

If anybody still looking at this question, the currently accepted answer is now outdated:

Since Python 3.7* the dictionaries are order-preserving, that is they now behave exactly as collections.OrderedDicts used to. Unfortunately, there is still no dedicated method to index into keys() / values() of the dictionary, so getting the first key / value in the dictionary can be done as

first_key = list(colors)[0]
first_val = list(colors.values())[0]

or alternatively (this avoids instantiating the keys view into a list):

def get_first_key(dictionary):
    for key in dictionary:
        return key
    raise IndexError

first_key = get_first_key(colors)
first_val = colors[first_key]

If you need an n-th key, then similarly

def get_nth_key(dictionary, n=0):
    if n < 0:
        n += len(dictionary)
    for i, key in enumerate(dictionary.keys()):
        if i == n:
            return key
    raise IndexError("dictionary index out of range") 

(*CPython 3.6 already included ordered dicts, but this was only an implementation detail. The language specification includes ordered dicts from 3.7 onwards.)

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

How to submit a form when the return key is pressed?

Use the <button> tag. From the W3C standard:

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.

Basically there is another tag, <button>, which requires no javascript, that also can submit a form. It can be styled much in the way of a <div> tag (including <img /> inside the button tag). The buttons from the <input /> tag are not nearly as flexible.

<button type="submit">
    <img src="my-icon.png" />
    Clicking will submit the form
</button>

There are three types to set on the <button>; they map to the <input> button types.

<button type="submit">Will submit the form</button>
<button type="reset">Will reset the form</button>
<button type="button">Will do nothing; add javascript onclick hooks</button>

Standards

I use <button> tags with and a bit of styling to get colorful and functional form buttons. Note that it's possible to write css for, for example, <a class="button"> links share to styling with the <button> element.

How to put a horizontal divisor line between edit text's in a activity

Use This..... You will love it

 <TextView
    android:layout_width="fill_parent"
    android:layout_height="1px"
    android:text=" "
    android:background="#anycolor"
    android:id="@+id/textView"/>

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

axios post request to send form data

Using application/x-www-form-urlencoded format in axios

By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

Browser

In a browser, you can use the URLSearchParams API as follows:

const params = new URLSearchParams();

params.append('param1', 'value1');

params.append('param2', 'value2');

axios.post('/foo', params);

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

Alternatively, you can encode data using the qs library:

const qs = require('qs');

axios.post('/foo', qs.stringify({ 'bar': 123 }));

Or in another way (ES6),

import qs from 'qs';

const data = { 'bar': 123 };

const options = {

method: 'POST',

headers: { 'content-type': 'application/x-www-form-urlencoded' },

data: qs.stringify(data),

url, };

axios(options);

How can I run dos2unix on an entire directory?

It's probably best to skip hidden files and folders, such as .git. So instead of using find, if your bash version is recent enough or if you're using zsh, just do:

dos2unix **

Note that for Bash, this will require:

shopt -s globstar

....but this is a useful enough feature that you should honestly just put it in your .bashrc anyway.

If you don't want to skip hidden files and folders, but you still don't want to mess with find (and I wouldn't blame you), you can provide a second recursive-glob argument to match only hidden entries:

dos2unix ** **/.*

Note that in both cases, the glob will expand to include directories, so you will see the following warning (potentially many times over): Skipping <dir>, not a regular file.

How to access single elements in a table in R

Maybe not so perfect as above ones, but I guess this is what you were looking for.

data[1:1,3:3]    #works with positive integers
data[1:1, -3:-3] #does not work, gives the entire 1st row without the 3rd element
data[i:i,j:j]    #given that i and j are positive integers

Here indexing will work from 1, i.e,

data[1:1,1:1]    #means the top-leftmost element

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

How to redirect output to a file and stdout

Bonus answer since this use-case brought me here:

In the case where you need to do this as some other user

echo "some output" | sudo -u some_user tee /some/path/some_file

Note that the echo will happen as you and the file write will happen as "some_user" what will NOT work is if you were to run the echo as "some_user" and redirect the output with >> "some_file" because the file redirect will happen as you.

Hint: tee also supports append with the -a flag, if you need to replace a line in a file as another user you could execute sed as the desired user.

How to parse JSON string in Typescript

Yes it's a little tricky in TypeScript but you can do the below example like this

_x000D_
_x000D_
let decodeData  =  JSON.parse(`${jsonResponse}`);
_x000D_
_x000D_
_x000D_

How can I compare two ordered lists in python?

The expression a == b should do the job.

What is the difference between Google App Engine and Google Compute Engine?

The cloud services provides a range of options from fully managed to less managed services. Less managed services gives more control to the developers. The same is the difference in Compute and App engine also. The below image elaborate more on this point enter image description here

Creating a jQuery object from a big HTML-string

As of jQuery 1.8 you can just use parseHtml to create your jQuery object:

var myString = "<div>Some stuff<div>Some more stuff<span id='theAnswer'>The stuff I am looking for</span></div></div>";
var $jQueryObject = $($.parseHTML(myString));

I've created a JSFidle that demonstrates this: http://jsfiddle.net/MCSyr/2/

It parses the arbitrary HTML string into a jQuery object, and uses find to display the result in a div.

Letsencrypt add domain to existing certificate

This is how i registered my domain:

sudo letsencrypt --apache -d mydomain.com

Then it was possible to use the same command with additional domains and follow the instructions:

sudo letsencrypt --apache -d mydomain.com,x.mydomain.com,y.mydomain.com

How do I convert a Python program to a runnable .exe Windows program?

py2exe works with Python 2.7 (as well as other versions). You just need the MSVCR90.dll

http://www.py2exe.org/index.cgi/Tutorial

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Bootstrap 3: Keep selected tab on page refresh

A mix between others answers:

  • No jump on click
  • Save on location hash
  • Save on localStorage (e.g: for form submit)
  • Just copy&paste ;)

    if (location.hash) {
      $('a[href=\'' + location.hash + '\']').tab('show');
    }
    var activeTab = localStorage.getItem('activeTab');
    if (activeTab) {
      $('a[href="' + activeTab + '"]').tab('show');
    }
    
    $('body').on('click', 'a[data-toggle=\'tab\']', function (e) {
      e.preventDefault()
      var tab_name = this.getAttribute('href')
      if (history.pushState) {
        history.pushState(null, null, tab_name)
      }
      else {
        location.hash = tab_name
      }
      localStorage.setItem('activeTab', tab_name)
    
      $(this).tab('show');
      return false;
    });
    $(window).on('popstate', function () {
      var anchor = location.hash ||
        $('a[data-toggle=\'tab\']').first().attr('href');
      $('a[href=\'' + anchor + '\']').tab('show');
    });
    

django order_by query set, ascending and descending

Reserved.objects.filter(client=client_id).order_by('-check_in')

A hyphen "-" in front of "check_in" indicates descending order. Ascending order is implied.

We don't have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.

More on this here: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters

Meaning of 'const' last in a function declaration of a class?

when you use const in the method signature (like your said: const char* foo() const;) you are telling the compiler that memory pointed to by this can't be changed by this method (which is foo here).

How to convert date format to milliseconds?

beginupd.getTime() will give you time in milliseconds since January 1, 1970, 00:00:00 GMT till the time you have specified in Date object

Delete a row from a table by id

Something quick and dirty:

<script type='text/javascript'>
function del_tr(remtr)  
{   
    while((remtr.nodeName.toLowerCase())!='tr')
        remtr = remtr.parentNode;

    remtr.parentNode.removeChild(remtr);
}
function del_id(id)  
{   
        del_tr(document.getElementById(id));
}
</script>

if you place

<a href='' onclick='del_tr(this);return false;'>x</a>

anywhere within the row you want to delete, than its even working without any ids

Restart node upon changing a file

You should look at something like nodemon.

Nodemon will watch the files in the directory in which nodemon was started, and if they change, it will automatically restart your node application.

Example:

nodemon ./server.js localhost 8080

or simply

nodemon server

How to manually set REFERER header in Javascript?

You can change the value of the referrer in the HTTP header using the Web Request API.

It requires a background js script for it's use. You can use the onBeforeSendHeaders as it modifies the header before the request is sent.

Your code will be something like this :

    chrome.webRequest.onBeforeSendHeaders.addEventListener(function(details){
    var newRef = "http://new-referer/path";
    var hasRef = false;
    for(var n in details.requestHeaders){
        hasRef = details.requestHeaders[n].name == "Referer";
        if(hasRef){
            details.requestHeaders[n].value = newRef;
         break;
        }
    }
    if(!hasRef){
        details.requestHeaders.push({name:"Referer",value:newRef});
    }
    return {requestHeaders:details.requestHeaders};
},
{
    urls:["http://target/*"]
},
[
    "requestHeaders",
    "blocking"
]);

urls : It acts as a request filter, and invokes the listener only for certain requests.

For more info: https://developer.chrome.com/extensions/webRequest

How to launch multiple Internet Explorer windows/tabs from batch file?

Thanks Marcelo. This worked for me. I wanted to open a new IE Window and open two tabs in that so I modified the code:

start iexplore.exe website
PING 1.1.1.1 -n 1 -w 2000 >NUL 
START /d iexplore.exe website

Get drop down value

Use the value property of the <select> element. For example:

var value = document.getElementById('your_select_id').value;
alert(value);

How to copy to clipboard in Vim?

I've been struggling with this for months till now on MacOsX using keyboard shortcuts. I know question isn't about using keyboard shorts. But this might help someone with the same concern.

I found that if you uncheck:

View -> Allow Mouse Reporting

from Terminal menu, you'll be able to copy to clipboard using

command + c

again.

When should I use "this" in a class?

To make sure that the current object's members are used. Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used.

If your object is not concerned with thread safety then there is no reason to specify which object member's value is used.

unknown type name 'uint8_t', MinGW

EDIT:

To Be Clear: If the order of your #includes matters and it is not part of your design pattern (read: you don't know why), then you need to rethink your design. Most likely, this just means you need to add the #include to the header file causing problems.

At this point, I have little interest in discussing/defending the merits of the example but will leave it up as it illustrates some nuances in the compilation process and why they result in errors.

END EDIT

You need to #include the stdint.h BEFORE you #include any other library interfaces that need it.

Example:

My LCD library uses uint8_t types. I wrote my library with an interface (Display.h) and an implementation (Display.c)

In display.c, I have the following includes.

#include <stdint.h>
#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>

And this works.

However, if I re-arrange them like so:

#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>
#include <stdint.h>

I get the error you describe. This is because Display.h needs things from stdint.h but can't access it because that information is compiled AFTER Display.h is compiled.

So move stdint.h above any library that need it and you shouldn't get the error anymore.

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

forEach() in React JSX does not output any HTML

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So it's better to use map because map returns an array:

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.map((answer, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Answer key={answer} answer={answer} />) 
        })}
}

export default QuestionSet;

How to add chmod permissions to file in Git?

According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index sub-command.

To set the flag, use following command:

git update-index --chmod=+x path/to/file

To remove it, use:

git update-index --chmod=-x path/to/file

Under the hood

While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:

  • 100644 for regular files
  • 100755 for executable ones

You can visualize it using ls-file subcommand, with --stage option:

$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0       .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0       my_executable_script.sh

By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode option to false:

git config core.fileMode false

Troubleshooting

If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:

git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file

Bonus

Starting with Git 2.9, you can stage a file AND set the flag in one command:

git add --chmod=+x path/to/file

Popup Message boxes

javax.swing.JOptionPane

Here is the code to a method I call whenever I want an information box to pop up, it hogs the screen until it is accepted:

import javax.swing.JOptionPane;

public class ClassNameHere
{

    public static void infoBox(String infoMessage, String titleBar)
    {
        JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
    }
}

The first JOptionPane parameter (null in this example) is used to align the dialog. null causes it to center itself on the screen, however any java.awt.Component can be specified and the dialog will appear in the center of that Component instead.

I tend to use the titleBar String to describe where in the code the box is being called from, that way if it gets annoying I can easily track down and delete the code responsible for spamming my screen with infoBoxes.

To use this method call:

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");

javafx.scene.control.Alert

For a an in depth description of how to use JavaFX dialogs see: JavaFX Dialogs (official) by code.makery. They are much more powerful and flexible than Swing dialogs and capable of far more than just popping up messages.

As above I'll post a small example of how you could use JavaFX dialogs to achieve the same result

import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;

public class ClassNameHere
{

    public static void infoBox(String infoMessage, String titleBar)
    {
        /* By specifying a null headerMessage String, we cause the dialog to
           not have a header */
        infoBox(infoMessage, titleBar, null);
    }

    public static void infoBox(String infoMessage, String titleBar, String headerMessage)
    {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle(titleBar);
        alert.setHeaderText(headerMessage);
        alert.setContentText(infoMessage);
        alert.showAndWait();
    }
}

One thing to keep in mind is that JavaFX is a single threaded GUI toolkit, which means this method should be called directly from the JavaFX application thread. If you have another thread doing work, which needs a dialog then see these SO Q&As: JavaFX2: Can I pause a background Task / Service? and Platform.Runlater and Task Javafx.

To use this method call:

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");

or

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE", "HEADER MESSAGE");

Filter Excel pivot table using VBA

Configure the pivot table so that it is like this:

enter image description here

Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode

Sub FilterPivotTable()
Application.ScreenUpdating = False
    ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub

Laravel Eloquent - Get one Row

Laravel 5.2

$sql = "SELECT * FROM users WHERE email = $email";

$user = collect(\User::select($sql))->first();

or

$user = User::table('users')->where('email', $email)->pluck();

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

How can I find the link URL by link text with XPath?

Too late for you, but for anyone else with the same question...

//a[contains(text(), 'programming')]/@href

Of course, 'programming' can be any text fragment.

Import python package from local directory into interpreter

Using sys.path should include current directory already.

Try:

import .

or:

from . import sth

however it may be not a good practice, so why not just use:

import mypackage

Interview Question: Merge two sorted singly linked lists without creating new nodes

Node MergeLists(Node node1, Node node2)
{
   if(node1 == null)
      return node2;
   else (node2 == null)
      return node1;

   Node head;
   if(node1.data < node2.data)
   {
      head = node1;
      node1 = node1.next;
   else
   {
      head = node2;
      node2 = node2.next;
   }

   Node current = head;
   while((node1 != null) ||( node2 != null))
   {
      if (node1 == null) {
         current.next = node2;
         return head;
      }
      else if (node2 == null) {
         current.next = node1;
         return head;
      }

      if (node1.data < node2.data)
      {
          current.next = node1;
          current = current.next;

          node1 = node1.next;
      }
      else
      {
          current.next = node2;
          current = current.next;

          node2 = node2.next;
      }
   }
   current.next = NULL // needed to complete the tail of the merged list
   return head;

}

c# write text on bitmap

You need to use the Graphics class in order to write on the bitmap.

Specifically, one of the DrawString methods.

Bitmap a = new Bitmap(@"path\picture.bmp");

using(Graphics g = Graphics.FromImage(a))
{
  g.DrawString(....); // requires font, brush etc
}

pictuteBox1.Image = a;

How can I remove duplicate rows?

Use this

WITH tblTemp as
(
SELECT ROW_NUMBER() Over(PARTITION BY Name,Department ORDER BY Name)
   As RowNumber,* FROM <table_name>
)
DELETE FROM tblTemp where RowNumber >1

How can I switch to another branch in git?

Switching to another branch in git. Straightforward answer,

git-checkout - Switch branches or restore working tree files

git fetch origin         <----this will fetch the branch
git checkout branch_name <--- Switching the branch

Before switching the branch make sure you don't have any modified files, in that case, you can commit the changes or you can stash it.

Make anchor link go some pixels above where it's linked to

To link to an element, and then 'position' that element an arbitrary distance from the top of the page, using pure CSS, you'd have to use padding-top, that way the element is still positioned at the top of the window, but it appears, visibly, to be positioned some distance from the top of the view-port, for example:

<a href="#link1">Link one</a>
<a href="#link2">Link two</a>

<div id="link1">
    The first.
</div>

<div id="link2">
    The second.
</div>

CSS:

div {
    /* just to force height, and window-scrolling to get to the elements.
       Irrelevant to the demo, really */
    margin-top: 1000px;
    height: 1000px;
}

#link2 {
    /* places the contents of the element 100px from the top of the view-port */
    padding-top: 100px;
}

JS Fiddle demo.

To use a plain JavaScript approach:

function addMargin() {
    window.scrollTo(0, window.pageYOffset - 100);
}

window.addEventListener('hashchange', addMargin);

JS Fiddle demo.

Maven Out of Memory Build Failure

What kind of 'web' module are you talking about? Is it a simple war and has packaging type war?

If you are not using Google's web toolkit (GWT) then you don't need to provide any gwt.extraJvmArgs

Forking the compile process might be not the best idea, because it starts a second process which ignores MAVEN_OPTS altogether, thus making analysis more difficult.

So I would try to increase the Xmx by setting the MAVEN_OPTS

export MAVEN_OPTS="-Xmx3000m"

And don't fork the compiler to a different process

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.5</source>
        <target>1.5</target>
   </configuration>
</plugin>

Increasing -XX:MaxPermSize=512m should not be required because if perm size is the reason of the problem, then I would expect the error java.lang.OutOfMemoryError: PermGen space

If that does not solve your problem, then you can create heap dumps for further analysis by adding -XX:+HeapDumpOnOutOfMemoryError. Additionally, you can use jconsole.exe in your java bin directory to connect to the jvm while the compilation is running and see what is going on inside the jvm's heap.

Another Idea (may be a stupid one) which came up to me, do you have enough RAM inside your machine? Defining the memory size is nice, but if your host has only 4GB and then you might have the problem that Java is not able to use the defined Memory because it is already used by the OS, Java, MS-Office...

How to switch between hide and view password

Try this:

First define a flag as global like this:

private boolean isShowPassword = false;

And set listener to handle tap on show and hide password button:

imgPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowPassword) {
                    etPassword.setTransformationMethod(new PasswordTransformationMethod());
                    imgPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_hide));
                    isShowPassword = false;
                }else{
                    etPassword.setTransformationMethod(null);
                    imgPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_show));
                    isShowPassword = true;
                }
            }
        });

ScalaTest in sbt: is there a way to run a single test without tags?

Just to simplify the example of Tyler.

test:-prefix is not needed.

So according to his example:

In the sbt-console:

testOnly *LoginServiceSpec

And in the terminal:

sbt "testOnly *LoginServiceSpec"

How to apply color in Markdown?

I like the idea of redefining existing tags if they're unused due to the fact that the text is cleaner, at the expense of existing tags. The inline styling works but creates a lot of noise when reading the raw text.

Using VSCode I've found that custom single-letter tags, supported by a small <style> section at the top, works well with a minimum of noise, especially for spot colour, e.g.

<style>
r { color: Red }
o { color: Orange }
g { color: Green }
</style>

# TODOs:

- <r>TODO:</r> Important thing to do
- <o>TODO:</o> Less important thing to do
- <g>DONE:</g> Breath deeply and improve karma

My use-case is orgmode-ish in-app note taking during development but I guess it might work elsewhere?

Undefined reference to vtable

What is a vtable?

It might be useful to know what the error message is talking about before trying to fix it. I'll start at a high level, then work down to some more details. That way people can skip ahead once they are comfortable with their understanding of vtables. …and there goes a bunch of people skipping ahead right now. :) For those sticking around:

A vtable is basically the most common implementation of polymorphism in C++. When vtables are used, every polymorphic class has a vtable somewhere in the program; you can think of it as a (hidden) static data member of the class. Every object of a polymorphic class is associated with the vtable for its most-derived class. By checking this association, the program can work its polymorphic magic. Important caveat: a vtable is an implementation detail. It is not mandated by the C++ standard, even though most (all?) C++ compilers use vtables to implement polymorphic behavior. The details I am presenting are either typical or reasonable approaches. Compilers are allowed to deviate from this!

Each polymorphic object has a (hidden) pointer to the vtable for the object's most-derived class (possibly multiple pointers, in the more complex cases). By looking at the pointer, the program can tell what the "real" type of an object is (except during construction, but let's skip that special case). For example, if an object of type A does not point to the vtable of A, then that object is actually a sub-object of something derived from A.

The name "vtable" comes from "virtual function table". It is a table that stores pointers to (virtual) functions. A compiler chooses its convention for how the table is laid out; a simple approach is to go through the virtual functions in the order they are declared within class definitions. When a virtual function is called, the program follows the object's pointer to a vtable, goes to the entry associated with the desired function, then uses the stored function pointer to invoke the correct function. There are various tricks for making this work, but I won't go into those here.

Where/when is a vtable generated?

A vtable is automatically generated (sometimes called "emitted") by the compiler. A compiler could emit a vtable in every translation unit that sees a polymorphic class definition, but that would usually be unnecessary overkill. An alternative (used by gcc, and probably by others) is to pick a single translation unit in which to place the vtable, similar to how you would pick a single source file in which to put a class' static data members. If this selection process fails to pick any translation units, then the vtable becomes an undefined reference. Hence the error, whose message is admittedly not particularly clear.

Similarly, if the selection process does pick a translation unit, but that object file is not provided to the linker, then the vtable becomes an undefined reference. Unfortunately, the error message can be even less clear in this case than in the case where the selection process failed. (Thanks to the answerers who mentioned this possibility. I probably would have forgotten it otherwise.)

The selection process used by gcc makes sense if we start with the tradition of devoting a (single) source file to each class that needs one for its implementation. It would be nice to emit the vtable when compiling that source file. Let's call that our goal. However, the selection process needs to work even if this tradition is not followed. So instead of looking for the implementation of the entire class, let's look for the implementation of a specific member of the class. If tradition is followed – and if that member is in fact implemented – then this achieves the goal.

The member selected by gcc (and potentially by other compilers) is the first non-inline virtual function that is not pure virtual. If you are part of the crowd that declares constructors and destructors before other member functions, then that destructor has a good chance of being selected. (You did remember to make the destructor virtual, right?) There are exceptions; I'd expect that the most common exceptions are when an inline definition is provided for the destructor and when the default destructor is requested (using "= default").

The astute might notice that a polymorphic class is allowed to provide inline definitions for all of its virtual functions. Doesn't that cause the selection process to fail? It does in older compilers. I've read that the latest compilers have addressed this situation, but I do not know relevant version numbers. I could try looking this up, but it's easier to either code around it or wait for the compiler to complain.

In summary, there are three key causes of the "undefined reference to vtable" error:

  1. A member function is missing its definition.
  2. An object file is not being linked.
  3. All virtual functions have inline definitions.

These causes are by themselves insufficient to cause the error on their own. Rather, these are what you would address to resolve the error. Do not expect that intentionally creating one of these situations will definitely produce this error; there are other requirements. Do expect that resolving these situations will resolve this error.

(OK, number 3 might have been sufficient when this question was asked.)

How to fix the error?

Welcome back people skipping ahead! :)

  1. Look at your class definition. Find the first non-inline virtual function that is not pure virtual (not "= 0") and whose definition you provide (not "= default").
    • If there is no such function, try modifying your class so there is one. (Error possibly resolved.)
    • See also the answer by Philip Thomas for a caveat.
  2. Find the definition for that function. If it is missing, add it! (Error possibly resolved.)
  3. Check your link command. If it does not mention the object file with that function's definition, fix that! (Error possibly resolved.)
  4. Repeat steps 2 and 3 for each virtual function, then for each non-virtual function, until the error is resolved. If you're still stuck, repeat for each static data member.

Example
The details of what to do can vary, and sometimes branch off into separate questions (like What is an undefined reference/unresolved external symbol error and how do I fix it?). I will, though, provide an example of what to do in a specific case that might befuddle newer programmers.

Step 1 mentions modifying your class so that it has a function of a certain type. If the description of that function went over your head, you might be in the situation I intend to address. Keep in mind that this is a way to accomplish the goal; it is not the only way, and there easily could be better ways in your specific situation. Let's call your class A. Is your destructor declared (in your class definition) as either

virtual ~A() = default;

or

virtual ~A() {}

? If so, two steps will change your destructor into the type of function we want. First, change that line to

virtual ~A();

Second, put the following line in a source file that is part of your project (preferably the file with the class implementation, if you have one):

A::~A() {}

That makes your (virtual) destructor non-inline and not generated by the compiler. (Feel free to modify things to better match your code formatting style, such as adding a header comment to the function definition.)

How to read all files in a folder from Java?

import java.io.File;


public class ReadFilesFromFolder {
  public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
  static String temp = "";

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
    listFilesForFolder(folder);
  }

  public static void listFilesForFolder(final File folder) {

    for (final File fileEntry : folder.listFiles()) {
      if (fileEntry.isDirectory()) {
        // System.out.println("Reading files under the folder "+folder.getAbsolutePath());
        listFilesForFolder(fileEntry);
      } else {
        if (fileEntry.isFile()) {
          temp = fileEntry.getName();
          if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt"))
            System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
        }

      }
    }
  }
}

Get first and last day of month using threeten, LocalDate

Just use withDayOfMonth, and lengthOfMonth():

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.withDayOfMonth(initial.lengthOfMonth());

Returning JSON object from an ASP.NET page

If you get code behind, use some like this

        MyCustomObject myObject = new MyCustomObject();
        myObject.name='try';
        //OBJECT -> JSON
        var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string myObjectJson = javaScriptSerializer.Serialize(myObject);
        //return JSON   
        Response.Clear();     
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(myObjectJson );
        Response.End();

So you return a json object serialized with all attributes of MyCustomObject.

Changing one character in a string

Don't modify strings.

Work with them as lists; turn them into strings only when needed.

>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'

Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings.

How can one see the structure of a table in SQLite?

You can use the Firefox add-on called SQLite Manager to view the database's structure clearly.

What is the difference between a mutable and immutable string in C#?

String is immutable

i.e. strings cannot be altered. When you alter a string (by adding to it for example), you are actually creating a new string.

But StringBuilder is not immutable (rather, it is mutable)

so if you have to alter a string many times, such as multiple concatenations, then use StringBuilder.

Parse large JSON file in Nodejs

Just as I was thinking that it would be fun to write a streaming JSON parser, I also thought that maybe I should do a quick search to see if there's one already available.

Turns out there is.

Since I just found it, I've obviously not used it, so I can't comment on its quality, but I'll be interested to hear if it works.

It does work consider the following Javascript and _.isString:

stream.pipe(JSONStream.parse('*'))
  .on('data', (d) => {
    console.log(typeof d);
    console.log("isString: " + _.isString(d))
  });

This will log objects as they come in if the stream is an array of objects. Therefore the only thing being buffered is one object at a time.

VBA Excel Provide current Date in Text box

Here's a more simple version. In the cell you want the date to show up just type

=Today()      

Format the cell to the date format you want and Bob's your uncle. :)

How do you set, clear, and toggle a single bit?

If you want to perform this all operation with C programming in the Linux kernel then I suggest to use standard APIs of the Linux kernel.

See https://www.kernel.org/doc/htmldocs/kernel-api/ch02s03.html

set_bit  Atomically set a bit in memory
clear_bit  Clears a bit in memory
change_bit  Toggle a bit in memory
test_and_set_bit  Set a bit and return its old value
test_and_clear_bit  Clear a bit and return its old value
test_and_change_bit  Change a bit and return its old value
test_bit  Determine whether a bit is set

Note: Here the whole operation happens in a single step. So these all are guaranteed to be atomic even on SMP computers and are useful to keep coherence across processors.

#1292 - Incorrect date value: '0000-00-00'

You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.

Don't reload application when orientation changes

There are generally three ways to do this:

  1. As some of the answers suggested, you could distinguish the cases of your activity being created for the first time and being restored from savedInstanceState. This is done by overriding onSaveInstanceState and checking the parameter of onCreate.

  2. You could lock the activity in one orientation by adding android:screenOrientation="portrait" (or "landscape") to <activity> in your manifest.

  3. You could tell the system that you meant to handle screen changes for yourself by specifying android:configChanges="orientation|screenSize" in the <activity> tag. This way the activity will not be recreated, but will receive a callback instead (which you can ignore as it's not useful for you).

Personally I'd go with (3). Of course if locking the app to one of the orientations is fine with you, you can also go with (2).

justify-content property isn't working

I was having a lot of problems with justify-content, and I figured out the problem was "margin: 0 auto"

The auto part overrides the justify-content so its always displayed according to the margin and not to the justify-content.

Running a command in a new Mac OS X Terminal window

A colleague asked me how to open A LOT of ssh sessions at once. I used cobbal's answer to write this script:

tmpdir=$( mktemp -d )
trap '$DEBUG rm -rf $tmpdir ' EXIT
index=1

{
cat <<COMMANDS
ssh user1@host1
ssh user2@host2
COMMANDS
} | while read command
do 
  COMMAND_FILE=$tmpdir/$index.command
  index=$(( index + 1 ))
  echo $command > $COMMAND_FILE
  chmod +x  $COMMAND_FILE
  open $COMMAND_FILE
done
sleep 60

By updating the list of commands ( they don't have to be ssh invocations ), you will get an additional open window for every command executed. The sleep 60 at the end is there to keep the .command files around while they are being executed. Otherwise, the shell completes too quickly, executing the trap to delete the temp directory ( created by mktemp ) before the launched sessions have an opportunity to read the files.

OSError: [Errno 8] Exec format error

OSError: [Errno 8] Exec format error can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:

>>> with open('a','w') as f: f.write('exit 0') # create the script
... 
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable                       
>>> os.execl('./a', './a')     # execute it                                            
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/os.py", line 312, in execl
    execv(file, args)
OSError: [Errno 8] Exec format error

To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh at the top of your script:

>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
... 
>>> os.execl('./a', './a')

It executes exit 0 without any errors.


On POSIX systems, shell parses the command line i.e., your script won't see spaces around = e.g., if script is:

#!/usr/bin/env python
import sys
print(sys.argv)

then running it in the shell:

$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST

produces:

['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no spaces around '='. I've added quotes around <hostname> to escape the redirection metacharacters <>.

To emulate the shell command in Python, run:

from subprocess import check_call

cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)

Note: no shell=True. And you don't need to escape <> because no shell is run.

"Exec format error" might indicate that your script has invalid format, run:

$ file /usr/local/bin/script

to find out what it is. Compare the architecture with the output of:

$ uname -m

Best way to test for a variable's existence in PHP; isset() is clearly broken

If the variable you are checking would be in the global scope you could do:

array_key_exists('v', $GLOBALS) 

Angular 4 - Observable catch error

You should be using below

return Observable.throw(error || 'Internal Server error');

Import the throw operator using the below line

import 'rxjs/add/observable/throw';

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

Checking oracle sid and database name

Type on sqlplus command prompt

SQL> select * from global_name;

then u will be see result on command prompt

SQL ORCL.REGRESS.RDBMS.DEV.US.ORACLE.COM

Here first one "ORCL" is database name,may be your system "XE" and other what was given on oracle downloading time.

How can a windows service programmatically restart itself?

Dim proc As New Process()
Dim psi As New ProcessStartInfo()

psi.CreateNoWindow = True
psi.FileName = "cmd.exe"
psi.Arguments = "/C net stop YOURSERVICENAMEHERE && net start YOURSERVICENAMEHERE"
psi.LoadUserProfile = False
psi.UseShellExecute = False
psi.WindowStyle = ProcessWindowStyle.Hidden
proc.StartInfo = psi
proc.Start()

What are type hints in Python 3.5?

I would suggest reading PEP 483 and PEP 484 and watching this presentation by Guido on type hinting.

In a nutshell: Type hinting is literally what the words mean. You hint the type of the object(s) you're using.

Due to the dynamic nature of Python, inferring or checking the type of an object being used is especially hard. This fact makes it hard for developers to understand what exactly is going on in code they haven't written and, most importantly, for type checking tools found in many IDEs (PyCharm and PyDev come to mind) that are limited due to the fact that they don't have any indicator of what type the objects are. As a result they resort to trying to infer the type with (as mentioned in the presentation) around 50% success rate.


To take two important slides from the type hinting presentation:

Why type hints?

  1. Helps type checkers: By hinting at what type you want the object to be the type checker can easily detect if, for instance, you're passing an object with a type that isn't expected.
  2. Helps with documentation: A third person viewing your code will know what is expected where, ergo, how to use it without getting them TypeErrors.
  3. Helps IDEs develop more accurate and robust tools: Development Environments will be better suited at suggesting appropriate methods when know what type your object is. You have probably experienced this with some IDE at some point, hitting the . and having methods/attributes pop up which aren't defined for an object.

Why use static type checkers?

  • Find bugs sooner: This is self-evident, I believe.
  • The larger your project the more you need it: Again, makes sense. Static languages offer a robustness and control that dynamic languages lack. The bigger and more complex your application becomes the more control and predictability (from a behavioral aspect) you require.
  • Large teams are already running static analysis: I'm guessing this verifies the first two points.

As a closing note for this small introduction: This is an optional feature and, from what I understand, it has been introduced in order to reap some of the benefits of static typing.

You generally do not need to worry about it and definitely don't need to use it (especially in cases where you use Python as an auxiliary scripting language). It should be helpful when developing large projects as it offers much needed robustness, control and additional debugging capabilities.


Type hinting with mypy:

In order to make this answer more complete, I think a little demonstration would be suitable. I'll be using mypy, the library which inspired Type Hints as they are presented in the PEP. This is mainly written for anybody bumping into this question and wondering where to begin.

Before I do that let me reiterate the following: PEP 484 doesn't enforce anything; it is simply setting a direction for function annotations and proposing guidelines for how type checking can/should be performed. You can annotate your functions and hint as many things as you want; your scripts will still run regardless of the presence of annotations because Python itself doesn't use them.

Anyways, as noted in the PEP, hinting types should generally take three forms:

  • Function annotations (PEP 3107).
  • Stub files for built-in/user modules.
  • Special # type: type comments that complement the first two forms. (See: What are variable annotations? for a Python 3.6 update for # type: type comments)

Additionally, you'll want to use type hints in conjunction with the new typing module introduced in Py3.5. In it, many (additional) ABCs (abstract base classes) are defined along with helper functions and decorators for use in static checking. Most ABCs in collections.abc are included, but in a generic form in order to allow subscription (by defining a __getitem__() method).

For anyone interested in a more in-depth explanation of these, the mypy documentation is written very nicely and has a lot of code samples demonstrating/describing the functionality of their checker; it is definitely worth a read.

Function annotations and special comments:

First, it's interesting to observe some of the behavior we can get when using special comments. Special # type: type comments can be added during variable assignments to indicate the type of an object if one cannot be directly inferred. Simple assignments are generally easily inferred but others, like lists (with regard to their contents), cannot.

Note: If we want to use any derivative of containers and need to specify the contents for that container we must use the generic types from the typing module. These support indexing.

# Generic List, supports indexing.
from typing import List

# In this case, the type is easily inferred as type: int.
i = 0

# Even though the type can be inferred as of type list
# there is no way to know the contents of this list.
# By using type: List[str] we indicate we want to use a list of strings.
a = []  # type: List[str]

# Appending an int to our list
# is statically not correct.
a.append(i)

# Appending a string is fine.
a.append("i")

print(a)  # [0, 'i']

If we add these commands to a file and execute them with our interpreter, everything works just fine and print(a) just prints the contents of list a. The # type comments have been discarded, treated as plain comments which have no additional semantic meaning.

By running this with mypy, on the other hand, we get the following response:

(Python3)jimmi@jim: mypy typeHintsCode.py
typesInline.py:14: error: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"

Indicating that a list of str objects cannot contain an int, which, statically speaking, is sound. This can be fixed by either abiding to the type of a and only appending str objects or by changing the type of the contents of a to indicate that any value is acceptable (Intuitively performed with List[Any] after Any has been imported from typing).

Function annotations are added in the form param_name : type after each parameter in your function signature and a return type is specified using the -> type notation before the ending function colon; all annotations are stored in the __annotations__ attribute for that function in a handy dictionary form. Using a trivial example (which doesn't require extra types from the typing module):

def annotated(x: int, y: str) -> bool:
    return x < y

The annotated.__annotations__ attribute now has the following values:

{'y': <class 'str'>, 'return': <class 'bool'>, 'x': <class 'int'>}

If we're a complete newbie, or we are familiar with Python 2.7 concepts and are consequently unaware of the TypeError lurking in the comparison of annotated, we can perform another static check, catch the error and save us some trouble:

(Python3)jimmi@jim: mypy typeHintsCode.py
typeFunction.py: note: In function "annotated":
typeFunction.py:2: error: Unsupported operand types for > ("str" and "int")

Among other things, calling the function with invalid arguments will also get caught:

annotated(20, 20)

# mypy complains:
typeHintsCode.py:4: error: Argument 2 to "annotated" has incompatible type "int"; expected "str"

These can be extended to basically any use case and the errors caught extend further than basic calls and operations. The types you can check for are really flexible and I have merely given a small sneak peak of its potential. A look in the typing module, the PEPs or the mypy documentation will give you a more comprehensive idea of the capabilities offered.

Stub files:

Stub files can be used in two different non mutually exclusive cases:

  • You need to type check a module for which you do not want to directly alter the function signatures
  • You want to write modules and have type-checking but additionally want to separate annotations from content.

What stub files (with an extension of .pyi) are is an annotated interface of the module you are making/want to use. They contain the signatures of the functions you want to type-check with the body of the functions discarded. To get a feel of this, given a set of three random functions in a module named randfunc.py:

def message(s):
    print(s)

def alterContents(myIterable):
    return [i for i in myIterable if i % 2 == 0]

def combine(messageFunc, itFunc):
    messageFunc("Printing the Iterable")
    a = alterContents(range(1, 20))
    return set(a)

We can create a stub file randfunc.pyi, in which we can place some restrictions if we wish to do so. The downside is that somebody viewing the source without the stub won't really get that annotation assistance when trying to understand what is supposed to be passed where.

Anyway, the structure of a stub file is pretty simplistic: Add all function definitions with empty bodies (pass filled) and supply the annotations based on your requirements. Here, let's assume we only want to work with int types for our Containers.

# Stub for randfucn.py
from typing import Iterable, List, Set, Callable

def message(s: str) -> None: pass

def alterContents(myIterable: Iterable[int])-> List[int]: pass

def combine(
    messageFunc: Callable[[str], Any],
    itFunc: Callable[[Iterable[int]], List[int]]
)-> Set[int]: pass

The combine function gives an indication of why you might want to use annotations in a different file, they some times clutter up the code and reduce readability (big no-no for Python). You could of course use type aliases but that sometime confuses more than it helps (so use them wisely).


This should get you familiarized with the basic concepts of type hints in Python. Even though the type checker used has been mypy you should gradually start to see more of them pop-up, some internally in IDEs (PyCharm,) and others as standard Python modules.

I'll try and add additional checkers/related packages in the following list when and if I find them (or if suggested).

Checkers I know of:

  • Mypy: as described here.
  • PyType: By Google, uses different notation from what I gather, probably worth a look.

Related Packages/Projects:

  • typeshed: Official Python repository housing an assortment of stub files for the standard library.

The typeshed project is actually one of the best places you can look to see how type hinting might be used in a project of your own. Let's take as an example the __init__ dunders of the Counter class in the corresponding .pyi file:

class Counter(Dict[_T, int], Generic[_T]):
        @overload
        def __init__(self) -> None: ...
        @overload
        def __init__(self, Mapping: Mapping[_T, int]) -> None: ...
        @overload
        def __init__(self, iterable: Iterable[_T]) -> None: ...

Where _T = TypeVar('_T') is used to define generic classes. For the Counter class we can see that it can either take no arguments in its initializer, get a single Mapping from any type to an int or take an Iterable of any type.


Notice: One thing I forgot to mention was that the typing module has been introduced on a provisional basis. From PEP 411:

A provisional package may have its API modified prior to "graduating" into a "stable" state. On one hand, this state provides the package with the benefits of being formally part of the Python distribution. On the other hand, the core development team explicitly states that no promises are made with regards to the the stability of the package's API, which may change for the next release. While it is considered an unlikely outcome, such packages may even be removed from the standard library without a deprecation period if the concerns regarding their API or maintenance prove well-founded.

So take things here with a pinch of salt; I'm doubtful it will be removed or altered in significant ways, but one can never know.


** Another topic altogether, but valid in the scope of type-hints: PEP 526: Syntax for Variable Annotations is an effort to replace # type comments by introducing new syntax which allows users to annotate the type of variables in simple varname: type statements.

See What are variable annotations?, as previously mentioned, for a small introduction to these.

How to compare two dates along with time in java

The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.

    String dateTimeString = "2014-01-16T10:25:00";
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
    LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());

    if (dateTime.isBefore(now)) {
        System.out.println(dateTimeString + " is in the past");
    } else if (dateTime.isAfter(now)) {
        System.out.println(dateTimeString + " is in the future");
    } else {
        System.out.println(dateTimeString + " is now");
    }

When running in 2020 output from this snippet is:

2014-01-16T10:25:00 is in the past

Since your string doesn’t inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device’ time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar"). For UTC specify ZoneOffset.UTC.

I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.

Question: For Android development doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Any way to Invoke a private method?

You can use Manifold's @Jailbreak for direct, type-safe Java reflection:

@Jailbreak Foo foo = new Foo();
foo.callMe();

public class Foo {
    private void callMe();
}

@Jailbreak unlocks the foo local variable in the compiler for direct access to all the members in Foo's hierarchy.

Similarly you can use the jailbreak() extension method for one-off use:

foo.jailbreak().callMe();

Through the jailbreak() method you can access any member in Foo's hierarchy.

In both cases the compiler resolves the method call for you type-safely, as if a public method, while Manifold generates efficient reflection code for you under the hood.

Alternatively, if the type is not known statically, you can use Structural Typing to define an interface a type can satisfy without having to declare its implementation. This strategy maintains type-safety and avoids performance and identity issues associated with reflection and proxy code.

Discover more about Manifold.

How do I search a Perl array for a matching string?

I guess

@foo = ("aAa", "bbb");
@bar = grep(/^aaa/i, @foo);
print join ",",@bar;

would do the trick.

iOS download and save image inside app

You cannot save anything inside the app's bundle, but you can use +[NSData dataWithContentsOfURL:] to store the image in your app's documents directory, e.g.:

NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];

Not exactly permanent, but it stays there at least until the user deletes the app.

Failed to resolve version for org.apache.maven.archetypes

I had the same problem. I fixed it by adding the maven archetype catalog to eclipse. Steps are provided below:

  1. Open Window > Preferences
  2. Open Maven > Archetypes
  3. Click 'Add Remote Catalog' and add the following:

css with background image without repeating the image

body {
    background: url(images/image_name.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Here is a good solution to get your image to cover the full area of the web app perfectly

Replace only text inside a div using jquery

You need to set the text to something other than an empty string. In addition, the .html() function should do it while preserving the HTML structure of the div.

$('#one').html($('#one').html().replace('text','replace'));

Opposite of append in jquery

You could use remove(). More information on jQuery remove().

$(this).children("ul").remove();

Note that this will remove all ul elements that are children.

How to edit HTML input value colour?

Please try this:

<input class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2" type="text" name="name" value="" placeholder="Your Name" style="background-color:blue;"/>

You basically put all the CSS inside the style part of the input tag and it works.

Where do I call the BatchNormalization function in Keras?

It is another type of layer, so you should add it as a layer in an appropriate place of your model

model.add(keras.layers.normalization.BatchNormalization())

See an example here: https://github.com/fchollet/keras/blob/master/examples/kaggle_otto_nn.py

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

Additionally, if you can't see the "Provide Export Compliance Information" button make sure you have the right role in your App Store Connect or talk to the right person (Account Holder, Admin, or App Manager).

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

Confirmation dialog on ng-click - AngularJS

Confirmation dialog can implemented using AngularJS Material:

$mdDialog opens a dialog over the app to inform users about critical information or require them to make decisions. There are two approaches for setup: a simple promise API and regular object syntax.

Implementation example: Angular Material - Dialogs

Reverse each individual word of "Hello World" string with Java

public String reverse(String arg) {
    char[] s = arg.toCharArray();
    StringBuilder sb = new StringBuilder();
    boolean reverse = false;
    boolean isChar = false;
    int insertPos = 0;

    for (int i = 0; i < s.length; i++) {
        isChar = Character.isAlphabetic(s[i]);
        if (!reverse && isChar) {
            sb.append(s[i]);
            insertPos = i;
            reverse = true;
        } else if (reverse && isChar) {
            sb.insert(insertPos, s[i]);
        } else if (!reverse && !isChar) {
            sb.append(s[i]);
        } else if (reverse && !isChar) {
            reverse = false;
            sb.append(s[i]);
        }
    }

    return sb.toString();
}

How to get xdebug var_dump to show full object/array

I know this is a super old post, but I figured this may still be helpful.

If you're comfortable with reading json format you could replace your var_dump with:

return json_encode($myvar);

I've been using this to help troubleshoot a service I've been building that has some deeply nested arrays. This will return every level of your array without truncating anything or requiring you to change your php.ini file.

Also, because the json_encoded data is a string it means you can write it to the error log easily

error_log(json_encode($myvar));

It probably isn't the best choice for every situation, but it's a choice!

What is the difference between dynamic programming and greedy approach?

Difference between greedy method and dynamic programming are given below :

  1. Greedy method never reconsiders its choices whereas Dynamic programming may consider the previous state.

  2. Greedy algorithm is less efficient whereas Dynamic programming is more efficient.

  3. Greedy algorithm have a local choice of the sub-problems whereas Dynamic programming would solve the all sub-problems and then select one that would lead to an optimal solution.

  4. Greedy algorithm take decision in one time whereas Dynamic programming take decision at every stage.

How to change default text color using custom theme?

You can't use @android:style/TextAppearance as the parent for the whole app's theme; that's why koopaking3's solution seems quite broken.

To change default text colour everywhere in your app using a custom theme, try something like this. Works at least on Android 4.0+ (API level 14+).

res/values/themes.xml:

<resources>    
    <style name="MyAppTheme" parent="android:Theme.Holo.Light">
        <!-- Change default text colour from dark grey to black -->
        <item name="android:textColor">@android:color/black</item>
    </style>
</resources>

Manifest:

<application
    ...
    android:theme="@style/MyAppTheme">

Update

A shortcoming with the above is that also disabled Action Bar overflow menu items use the default colour, instead of being greyed out. (Of course, if you don't use disabled menu items anywhere in your app, this may not matter.)

As I learned by asking this question, a better way is to define the colour using a drawable:

<item name="android:textColor">@drawable/default_text_color</item>

...with res/drawable/default_text_color.xml specifying separate state_enabled="false" colour:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@android:color/darker_gray"/>
    <item android:color="@android:color/black"/>
</selector>

Angular2 - Focusing a textbox on component load

Using simple autofocus HTML5 attribute works for 'on load' scenario

 <input autofocus placeholder="enter text" [(ngModel)]="test">

or

<button autofocus (click)="submit()">Submit</button>

http://www.w3schools.com/TAgs/att_input_autofocus.asp

Composer Warning: openssl extension is missing. How to enable in WAMP

WAMP uses different php.ini files in the CLI and for Apache. when you enable php_openssl through the WAMP UI, you enable it for Apache, not for the CLI. You need to modify C:\wamp\bin\php\php-5.4.3\php.ini to enable it for the CLI.

'Must Override a Superclass Method' Errors after importing a project into Eclipse

This happens when your maven project uses different Compiler Compliance level and Eclipse IDE uses different Compiler Compliance level. In order to fix this we need to change the Compiler Compliance level of Maven project to the level IDE uses.

1) To See Java Compiler Compliance level uses in Eclipse IDE

*) Window -> Preferences -> Compiler -> Compiler Compliance level : 1.8 (or 1.7, 1.6 ,, ect)

2) To Change Java Compiler Compliance level of Maven project

*) Go to "Project" -> "Properties" -> Select "Java Compiler" -> Change the Compiler Compliance level : 1.8 (or 1.7, 1.6 ,, ect)

How to get past the login page with Wget?

I wanted a one-liner that didn't download any files; here is an example of piping the cookie output into the next request. I only tested the following on Gentoo, but it should work in most *nix environments:

wget -q -O /dev/null --save-cookies /dev/stdout --post-data 'u=user&p=pass' 'http://example.com/login' | wget -q -O - --load-cookies /dev/stdin 'http://example.com/private/page'

(This is one line, though it likely wraps on your browser)

If you want the output saved to a file, change -O - to -O /some/file/name.ext

How to uncheck a radio button?

Thanks Patrick, you made my day! It's mousedown you have to use. However I've improved the code so you can handle a group of radio buttons.

//We need to bind click handler as well
//as FF sets button checked after mousedown, but before click
$('input:radio').bind('click mousedown', (function() {
    //Capture radio button status within its handler scope,
    //so we do not use any global vars and every radio button keeps its own status.
    //This required to uncheck them later.
    //We need to store status separately as browser updates checked status before click handler called,
    //so radio button will always be checked.
    var isChecked;

    return function(event) {
        //console.log(event.type + ": " + this.checked);

        if(event.type == 'click') {
            //console.log(isChecked);

            if(isChecked) {
                //Uncheck and update status
                isChecked = this.checked = false;
            } else {
                //Update status
                //Browser will check the button by itself
                isChecked = true;

                //Do something else if radio button selected
                /*
                if(this.value == 'somevalue') {
                    doSomething();
                } else {
                    doSomethingElse();
                }
                */
            }
    } else {
        //Get the right status before browser sets it
        //We need to use onmousedown event here, as it is the only cross-browser compatible event for radio buttons
        isChecked = this.checked;
    }
}})());

Bootstrap - Removing padding or margin when screen size is smaller

The problem here is much more complex than removing the container padding since the grid structure relies on this padding when applying negative margins for the enclosed rows.

Removing the container padding in this case will cause an x-axis overflow caused by all the rows inside of this container class, this is one of the most stupid things about the Bootstrap Grid.

Logically it should be approached by

  1. Never using the .container class for anything other than rows
  2. Make a clone of the .container class that has no padding for use with non-grid html
  3. For removing the .container padding on mobile you can manually remove it with media queries then overflow-x: hidden; which is not very reliable but works in most cases.

If you are using LESS the end result will look like this

@media (max-width: @screen-md-max) {
    .container{
        padding: 0;
        overflow-x: hidden;
    }
}

Change the media query to whatever size you want to target.

Final thoughts, I would highly recommend using the Foundation Framework Grid as its way more advanced

TypeError: a bytes-like object is required, not 'str'

This code is probably good for Python 2. But in Python 3, this will cause an issue, something related to bit encoding. I was trying to make a simple TCP server and encountered the same problem. Encoding worked for me. Try this with sendto command.

clientSocket.sendto(message.encode(),(serverName, serverPort))

Similarly you would use .decode() to receive the data on the UDP server side, if you want to print it exactly as it was sent.

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

jsPDF multi page PDF with HTML renderer

Below is my code but the problem is that the document doesn't split to display the other part of the document in a new page.

Please improve this code.

<script type='text/javascript'>
$(document).on("click", "#btnExportToPDF", function () {
    var table1 =
    tableToJson($('#table1')[0]),
    cellWidth =42,
    rowCount = 0,
    cellContents,
    leftMargin = 2,
    topMargin = 12,
    topMarginTable =5,
    headerRowHeight = 13,
    rowHeight = 12,
    l = {
        orientation: 'p',
        unit: 'mm',
        format: 'a3',
        compress: true,
        fontSize: 11,
        lineHeight: 1,
        autoSize: false,
        printHeaders: true
    };

    var doc = new jsPDF(l,'pt', 'letter');

    doc.setProperties({
        title: 'Test PDF Document',
        subject: 'This is the subject',
        author: 'author',
        keywords: 'generated, javascript, web 2.0, ajax',
        creator: 'author'
    });
    doc.cellInitialize();

    $.each(table1, function (i, row)
    {
        rowCount++;

        $.each(row, function (j, cellContent) {

            if (rowCount == 1) {
                doc.margins = 1;
                doc.setFont("Times New Roman");
                doc.setFontType("bold");
                doc.setFontSize(11);

                doc.cell(leftMargin, topMargin, cellWidth, headerRowHeight, cellContent, i)
            }
            else if (rowCount == 2) {

                doc.margins = 1;
                doc.setFont("Times ");
                doc.setFontType("normal");
                // or for normal font type use ------ doc.setFontType("normal");

                doc.setFontSize(11);

                doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
            }
            else {

                doc.margins = 1;
                doc.setFont("Times  ");
                doc.setFontType("normal ");
                doc.setFontSize(11);
                doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
                // 1st=left margin    2nd parameter=top margin,     3rd=row cell width      4th=Row height
            }
        })
    })
    doc.save('sample Report.pdf');
});

function tableToJson(table) {

    var data = [];

    // first row needs to be headers
    var headers = [];

    for (var i=0; i<table.rows[0].cells.length; i++) {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }

    // go through cells
    for (var i=1; i<table.rows.length; i++) {

        var tableRow = table.rows[i];

        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {
            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
        }

        data.push(rowData);
    }

    return data;
}
</script>

close fxml window by code, javafx

  1. give your close button an fx:id, if you haven't yet: <Button fx:id="closeButton" onAction="#closeButtonAction">
  2. In your controller class:

    @FXML private javafx.scene.control.Button closeButton;
    
    @FXML
    private void closeButtonAction(){
        // get a handle to the stage
        Stage stage = (Stage) closeButton.getScene().getWindow();
        // do what you have to do
        stage.close();
    }
    

MySql Inner Join with WHERE clause

You are using two WHERE clauses but only one is allowed. Use it like this:

SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
WHERE
  table1.f_com_id = '430'
  AND table1.f_status = 'Submitted'
  AND table2.f_type = 'InProcess'

Change onclick action with a Javascript function

Do not invoke the method when assigning the new onclick handler.

Simply remove the parenthesis:

document.getElementById("a").onclick = Foo;

UPDATE (due to new information):

document.getElementById("a").onclick = function () { Foo(param); };

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

String replace a Backslash

sSource = sSource.replace("\\/", "/");
  • String is immutable - each method you invoke on it does not change its state. It returns a new instance holding the new state instead. So you have to assign the new value to a variable (it can be the same variable)
  • replaceAll(..) uses regex. You don't need that.

"Javac" doesn't work correctly on Windows 10

just add C:\Program Files\Java\jdk1.7.0_80\bin as the path in environmental variables. no need to add java.exe and javac.exe to that path. IT WORKS

pip install returning invalid syntax

You need to be in the specific folder where pip.exe exists, then do the following steps:

  1. open cmd.exe
  2. write the following command:
    cd "The path to the python folder"

or in my case, i wrote

    cd C:\Users\username\AppData\Local\Programs\Python\Python37-32\Scripts
  1. then write the following command
    pip install *anypackage*

git push says "everything up-to-date" even though I have local changes

See VonC's answer above - I needed an extra step:

$ git log -1
- note the SHA-1 of latest commit
$ git checkout master
- reset your branch head to your previously detached commit
$ git reset --hard <commit-id>

I did this, but when I then tried to git push remoterepo master, it said "error: failed to push some refs. To prevent you from losing history, non-fast-forward updates were rejected, Merge the remote changes (e.g. 'git pull') before pushing again."

So I did 'git pull remoterepo master', and it found a conflict. I did git reset --hard <commit-id> again, copied the conflicted files to a backup folder, did git pull remoterepo master again, copied the conflicted files back into my project, did git commit, then git push remoterepo master, and this time it worked.

Git stopped saying 'everything is up to date' - and it stopped complaining about 'fast forwards'.

Check if user is using IE

This is how the Angularjs team is doing it (v 1.6.5):

var msie, // holds major version number for IE, or NaN if UA is not IE.

// Support: IE 9-11 only
/**
 * documentMode is an IE-only property
 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
 */
msie = window.document.documentMode;

Then there are several lines of code scattered throughout using it as a number such as

if (event === 'input' && msie <= 11) return false;

and

if (enabled && msie < 8) {