Programs & Examples On #Hidden markov models

Hidden Markov Models are a model for understanding and predicting sequential data in statistics and machine learning, commonly used in natural language processing and bioinformatics.

Cast to generic type in C#

To convert any type object to a generic type T, the trick is to first assign to an object of any higher type then cast that to the generic type.

object temp = otherTypeObject;
T result = (T)temp;

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

In the Global.asax I am using the code below. My URI to get JSON is http://www.digantakumar.com/api/values?json=true

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new  QueryStringMapping("json", "true", "application/json"));
}

Install sbt on ubuntu

The simplest way of installing SBT on ubuntu is the deb package provided by Typesafe.

Run the following shell commands:

  1. wget http://apt.typesafe.com/repo-deb-build-0002.deb
  2. sudo dpkg -i repo-deb-build-0002.deb
  3. sudo apt-get update
  4. sudo apt-get install sbt

And you're done !

CSS float right not working correctly

You have not used float:left command for your text.

jQuery/JavaScript to replace broken images

I got the same problem. This code works well on my case.

// Replace broken images by a default img
$('img').each(function(){
    if($(this).attr('src') === ''){
      this.src = '/default_feature_image.png';
    }
});

Program "make" not found in PATH

Just to clarify the details that Adel's linked eclipse forum covers, here's how I solved this (on OS X):

Note: for me, even though my personal environment (i.e. if in bash, echo $PATH) had /Developer/usr/bin in it, I still had to add it to Eclipse's Environment variables:

Go to Eclipse Preferences -> C/C++ -> Build -> Environment -> Add.. -> "${PATH}:/Developer/usr/bin"

In the case of some other OS, just use the right path where make exists.

How to INNER JOIN 3 tables using CodeIgniter

you can modiv your coding like this

 $this->db->select('a.nik,b.nama,a.inv,c.cekin,c.cekout,a.tunai,a.nontunai,a.id');
 $this->db->select('DATEDIFF (c.cekout, c.cekin) as lama');
 $this->db->select('(DATEDIFF (c.cekout, c.cekin)*c.total) as tagihan');
 $this->db->from('bayar as a');
 $this->db->join('pelanggan as b', 'a.nik = b.nik');
 $this->db->join('pesankamar_h as c', 'a.inv = c.id');
 $this->db->where('a.user_id',$id);
 $query = $this->db->get();
 return $query->result();

i hope can be resolve your SQL

Creation timestamp and last update timestamp with Hibernate and MySQL

If we are using @Transactional in our methods, @CreationTimestamp and @UpdateTimestamp will save the value in DB but will return null after using save(...).

In this situation, using saveAndFlush(...) did the trick

How to set the color of an icon in Angular Material?

<mat-icon style="-webkit-text-fill-color:blue">face</mat-icon>

Where is svcutil.exe in Windows 7?

Try to generate the proxy class via SvcUtil.exe with command

Syntax:

svcutil.exe /language:<type> /out:<name>.cs /config:<name>.config http://<host address>:<port>

Example:

svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceSamples/myService1

To check if service is available try in your IE URL from example upon without myService1 postfix

Django datetime issues (default=datetime.now())

In Django 3.0 auto_now_add seems to work with auto_now

reg_date=models.DateField(auto_now=True,blank=True)

PostgreSQL next value of the sequences?

The previously obtained value of a sequence is accessed with the currval() function.

But that will only return a value if nextval() has been called before that.

There is absolutely no way of "peeking" at the next value of a sequence without actually obtaining it.

But your question is unclear. If you call nextval() before doing the insert, you can use that value in the insert. Or even better, use currval() in your insert statement:

select nextval('my_sequence') ...

... do some stuff with the obtained value

insert into my_table(id, filename)
values (currval('my_sequence'), 'some_valid_filename');

SeekBar and media player in android

Based on previous statements, for better performance, you can also add an if condition

if (player.isPlaying() {
    handler.postDelayed(..., 1000);
}

CodeIgniter - Correct way to link to another page in a view

I assume you are meaning "internally" within your application.

you can create your own <a> tag and insert a url in the href like this

<a href="<?php echo site_url('controller/function/uri') ?>">Link</a>

OR you can use the URL helper this way to generate an <a> tag

anchor(uri segments, text, attributes)

So... to use it...

<?php echo anchor('controller/function/uri', 'Link', 'class="link-class"') ?>

and that will generate

<a href="http://domain.com/index.php/controller/function/uri" class="link-class">Link</a>

For the additional commented question

I would use my first example

so...

<a href="<?php echo site_url('controller/function') ?>"><img src="<?php echo base_url() ?>img/path/file.jpg" /></a>

for images (and other assets) I wouldn't put the file path within the php, I would just echo the base_url() and then add the path normally.

Why is the use of alloca() not considered good practice?

As noted in this newsgroup posting, there are a few reasons why using alloca can be considered difficult and dangerous:

  • Not all compilers support alloca.
  • Some compilers interpret the intended behaviour of alloca differently, so portability is not guaranteed even between compilers that support it.
  • Some implementations are buggy.

How to make a window always stay on top in .Net?

The way i solved this was by making a system tray icon that had a cancel option.

Remove icon/logo from action bar on android

    //disable application icon from ActionBar
    getActionBar().setDisplayShowHomeEnabled(false);

    //disable application name from ActionBar
    getActionBar().setDisplayShowTitleEnabled(false);

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.

How do I get the full path to a Perl script that is executing?

perlfaq8 answers a very similar question with using the rel2abs() function on $0. That function can be found in File::Spec.

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

How do I get the max ID with Linq to Entity?

Note that none of these answers will work if the key is a varchar since it is tempting to use MAX in a varchar column that is filled with "ints".

In a database if a column e.g. "Id" is in the database 1,2,3, 110, 112, 113, 4, 5, 6 Then all of the answers above will return 6.

So in your local database everything will work fine since while developing you will never get above 100 test records, then, at some moment during production you get a weird support ticket. Then after an hour you discover exactly this line "max" which seems to return the wrong key for some reason....

(and note that it says nowhere above that the key is INT...) (and if happens to end up in a generic library...)

So use:

Users.OrderByDescending(x=>x.Id.Length).ThenByDescending(a => a.Id).FirstOrDefault();

Bind service to activity in Android

"If you start an android Service with startService(..) that Service will remain running until you explicitly invoke stopService(..). There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the Service's IBinder). Usually the IBinder returned is for a complex interface that has been written in AIDL.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the Service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy()."

"Multiple definition", "first defined here" errors

You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123();

#endif

commands.c

#include "commands.h"

void f123()
{
    /* code */
}

MySQL DELETE FROM with subquery as condition

@CodeReaper, @BennyHill: It works as expected.

However, I wonder the time complexity for having millions of rows in the table? Apparently, it took about 5ms to execute for having 5k records on a correctly indexed table.

My Query:

SET status = '1'
WHERE id IN (
    SELECT id
    FROM (
      SELECT c2.id FROM clusters as c2
      WHERE c2.assign_to_user_id IS NOT NULL
        AND c2.id NOT IN (
         SELECT c1.id FROM clusters AS c1
           LEFT JOIN cluster_flags as cf on c1.last_flag_id = cf.id
           LEFT JOIN flag_types as ft on ft.id = cf.flag_type_id
         WHERE ft.slug = 'closed'
         )
      ) x)```

Or is there something we can improve on my query above?

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

The problem here are PHP namespaces. You need to learn how to use them. As your controller are in App\Http\Controllers namespace, if you refer any other class, you need to add leading backslash (or proper namespace) or add use statement at the beginning of file (before class definition).

So in your case you could use:

$headquote = \DB::table('quotation_texts')->find(176);
$headquote = \App\Quotation::find(176);

or add in your controller class use statement so the beginning of your controller class could look like this:

<?php

namespace App\Http\Controllers;

use DB;
use App\Quotation;

For more information about namespaces you could look at How to use objects from other namespaces and how to import namespaces in PHP or namespaces in PHP manual

Get month name from Date

You could just simply use Date.toLocaleDateString() and parse the date wanted as parameter

_x000D_
_x000D_
const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

const options = {  year: 'numeric', month: 'short', day: 'numeric' };

console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012

console.log(event.toLocaleDateString('en-US', options));
// US format 


// In case you only want the month
console.log(event.toLocaleDateString(undefined, { month: 'short'}));
console.log(event.toLocaleDateString(undefined, { month: 'long'}));
_x000D_
_x000D_
_x000D_

You can find more information in the Firefox documentation

Using json_encode on objects in PHP (regardless of scope)

Following code worked for me:

public function jsonSerialize()
{
    return get_object_vars($this);
}

How to add new line in Markdown presentation?

MarkDown file in three way to Break a Line

<br /> Tag Using

paragraph First Line <br /> Second Line

\ Using

First Line sentence \
Second Line sentence 

space keypress two times Using

First Line sentence??
Second Line sentence

Paragraphs in use <br /> tag.

Multiple sentences in using \ or two times press space key then Enter and write a new sentence.

SVN- How to commit multiple files in a single shot

Use a changeset. You can add as many files as you like to the changeset, all at once, or over several commands; and then commit them all in one go.

Regex to test if string begins with http:// or https://

(http|https)?:\/\/(\S+)

This works for me

Not a regex specialist, but i will try to explain the awnser.

(http|https) : Parenthesis indicates a capture group, "I" a OR statement.

\/\/ : "\" allows special characters, such as "/"

(\S+) : Anything that is not whitespace until the next whitespace

One line if-condition-assignment

If you wish to invoke a method if some boolean is true, you can put else None to terminate the trinary.

>>> a=1
>>> print(a) if a==1 else None
1
>>> print(a) if a==2 else None
>>> a=2
>>> print(a) if a==2 else None
2
>>> print(a) if a==1 else None
>>>

Submit form using a button outside the <form> tag

I used this way, and kind liked it , it validates the form before submit also is compatible with safari/google. no jquery n.n.

        <module-body>
            <form id="testform" method="post">
                <label>Input Title</label>
                <input name="named1" placeholder="Placeholder"  title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
                <alert>No Alerts!</alert>

                <label>Input Title</label>
                <input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
                <alert>No Alerts!</alert>

                <label>Input Title</label>
                <input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
                <alert>No Alerts!</alert>
            </form>
        </module-body>
        <module-footer>
            <input type="button" onclick='if (document.querySelector("#testform").reportValidity()) { document.querySelector("#testform").submit(); }' value="Submit">
            <input type="button" value="Reset">
        </module-footer>

Pandas dataframe fillna() only some columns in place

Or something like:

df.loc[df['a'].isnull(),'a']=0
df.loc[df['b'].isnull(),'b']=0

and if there is more:

for i in your_list:
    df.loc[df[i].isnull(),i]=0

How do I provide a username and password when running "git clone [email protected]"?

I prefer to use GIT_ASKPASS environment for providing HTTPS credentials to git.
Provided that login and password are exported in USR and PSW variables, the following script does not leave traces of password in history and disk + it is not vulnerable to special characters in the password:

GIT_ASKPASS=$(mktemp) && chmod a+rx $GIT_ASKPASS && export GIT_ASKPASS

cat > $GIT_ASKPASS <<'EOF'
#!/bin/sh
exec echo "$PSW"
EOF

git clone https://${USR}@example.com/repo.git

Note single quotes around heredoc marker 'EOF' which means that temporary script holds literally $PSW characters, not the password

Header set Access-Control-Allow-Origin in .htaccess doesn't work

Try this in the .htaccess of the external root folder

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Be careful on : Header add Access-Control-Allow-Origin "*" This is not judicious at all to grant access to everybody. I think you should user:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "http://example.com"
</IfModule>

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

How to multiply individual elements of a list with a number?

In NumPy it is quite simple

import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)

I recommend taking a look at the NumPy tutorial for an explanation of the full capabilities of NumPy's arrays:

https://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

Storing image in database directly or as base64 data?

  • Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.

  • Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.

How to extend an existing JavaScript array with another array, without creating a new array

I like the a.push.apply(a, b) method described above, and if you want you can always create a library function like this:

Array.prototype.append = function(array)
{
    this.push.apply(this, array)
}

and use it like this

a = [1,2]
b = [3,4]

a.append(b)

How to modify existing, unpushed commit messages?

Amending the most recent commit message

git commit --amend

will open your editor, allowing you to change the commit message of the most recent commit. Additionally, you can set the commit message directly in the command line with:

git commit --amend -m "New commit message"

…however, this can make multi-line commit messages or small corrections more cumbersome to enter.

Make sure you don't have any working copy changes staged before doing this or they will get committed too. (Unstaged changes will not get committed.)

Changing the message of a commit that you've already pushed to your remote branch

If you've already pushed your commit up to your remote branch, then - after amending your commit locally (as described above) - you'll also need to force push the commit with:

git push <remote> <branch> --force
# Or
git push <remote> <branch> -f

Warning: force-pushing will overwrite the remote branch with the state of your local one. If there are commits on the remote branch that you don't have in your local branch, you will lose those commits.

Warning: be cautious about amending commits that you have already shared with other people. Amending commits essentially rewrites them to have different SHA IDs, which poses a problem if other people have copies of the old commit that you've rewritten. Anyone who has a copy of the old commit will need to synchronize their work with your newly re-written commit, which can sometimes be difficult, so make sure you coordinate with others when attempting to rewrite shared commit history, or just avoid rewriting shared commits altogether.


Perform an interactive rebase

Another option is to use interactive rebase. This allows you to edit any message you want to update even if it's not the latest message.

In order to do a Git squash, follow these steps:

// n is the number of commits up to the last commit you want to be able to edit
git rebase -i HEAD~n

Once you squash your commits - choose the e/r for editing the message:

Enter image description here

Important note about interactive rebase

When you use git rebase -i HEAD~n there can be more than n commits. Git will "collect" all the commits in the last n commits, and if there was a merge somewhere in between that range you will see all the commits as well, so the outcome will be n + .

Good tip:

If you have to do it for more than a single branch and you might face conflicts when amending the content, set up git rerere and let Git resolve those conflicts automatically for you.


Documentation

Is there an embeddable Webkit component for Windows / C# development?

The Windows version of Qt 4 includes both WebKit and classes to create ActiveX components. It probably isn't an ideal solution if you aren't already using Qt though.

refresh both the External data source and pivot tables together within a time schedule

Auto Refresh Workbook for example every 5 sec. Apply to module

Public Sub Refresh()
'refresh
ActiveWorkbook.RefreshAll

alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
    Application.OnTime alertTime, "Refresh"

End Sub

Apply to Workbook on Open

Private Sub Workbook_Open()
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
Application.OnTime alertTime, "Refresh"
End Sub

:)

JSON Invalid UTF-8 middle byte

I got this exception when in the Java Client Application I was serializing a JSON like this

String json = mapper.writeValueAsString(contentBean);

and on the Server Side I was using Spring Boot as REST Endpoint. Exception was:

nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0xaa

My problem was, that I was not setting the correct encoding on the HTTP Client. This solved my problem:

updateRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity entity= new StringEntity(json, "UTF-8");
updateRequest.setEntity(entity);

Android set content type HttpPost

Simplest way to restart service on a remote computer

I believe PowerShell now trumps the "sc" command in terms of simplicity:

Restart-Service "servicename"

Difference between string and StringBuilder in C#

From the StringBuilder Class documentation:

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

how to set radio button checked in edit mode in MVC razor view

Don't do this at the view level. Just set the default value to the property in your view model's constructor. Clean and simple. In your post-backs, your selected value will automatically populate the correct selection.

For example

public class MyViewModel
{
        public MyViewModel()
        {
            Gender = "Male";
        }
}

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
 <td><label>@Html.RadioButtonFor(i => i.Gender, "Male")Male</label></td>_x000D_
 <td><label>@Html.RadioButtonFor(i => i.Gender, "Female")Female</label></td>_x000D_
  </tr>_x000D_
 </table>
_x000D_
_x000D_
_x000D_

no debugging symbols found when using gdb

Replace -ggdb with -g and make sure you aren't stripping the binary with the strip command.

Setting up maven dependency for SQL Server

<dependency>
  <groupId>com.hynnet</groupId>
  <artifactId>sqljdbc4-chs</artifactId>
  <version>4.0.2206.100</version>
</dependency>

This worked for me(if you use maven)

https://search.maven.org/artifact/com.hynnet/sqljdbc4-chs/4.0.2206.100/jar

Getting only response header from HTTP POST using curl

The Following command displays extra informations

curl -X POST http://httpbin.org/post -v > /dev/null

You can ask server to send just HEAD, instead of full response

curl -X HEAD -I http://httpbin.org/

Note: In some cases, server may send different headers for POST and HEAD. But in almost all cases headers are same.

Determine .NET Framework version for dll

The simplest way: just open the .dll in any text editor. Look at one of the last lines: enter image description here

How can I create a simple index.html file which lists all files/directories?

Did you try to allow it for this directory via .htaccess?

Options +Indexes

I use this for some of my directories where directory listing is disabled by my provider

git stash changes apply to new branch?

Is the standard procedure not working?

  • make changes
  • git stash save
  • git branch xxx HEAD
  • git checkout xxx
  • git stash pop

Shorter:

  • make changes
  • git stash
  • git checkout -b xxx
  • git stash pop

See :hover state in Chrome Developer Tools

I know that what I do is quite the workaround, however it works perfectly and that is the way I do it everytime.

Undock Chrome Developer Tools

Then, proceed like this:

  • First make sure Chrome Developer Tools is undocked.
  • Then, just move any side of the Dev Tools window to the middle of the element you want to inspect while hovered.

Hover on element

  • Finally, hover the element, right click and inspect element, move your mouse into the Dev Tools window and you will be able to play with your element:hover css.

Cheers!

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

The answers of installing pip via:

  1. curl https://bootstrap.pypa.io/get-pip.py |sudo python or
  2. curl https://bootstrap.pypa.io/get-pip.py | python

did not work for me as I kept on getting the error:

Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping
ERROR: Could not find a version that satisfies the requirement pip (from versions: none)
ERROR: No matching distribution found for pip

I had to install pip manually via:

  1. Go the pip distribution website
  2. Download the tar.gz version
  3. Unpack the file locally and cd into the directory
  4. run python setup.py install

SSL "Peer Not Authenticated" error with HttpClient 4.1

If the server's certificate is self-signed, then this is working as designed and you will have to import the server's certificate into your keystore.

Assuming the server certificate is signed by a well-known CA, this is happening because the set of CA certificates available to a modern browser is much larger than the limited set that is shipped with the JDK/JRE.

The EasySSL solution given in one of the posts you mention just buries the error, and you won't know if the server has a valid certificate.

You must import the proper Root CA into your keystore to validate the certificate. There's a reason you can't get around this with the stock SSL code, and that's to prevent you from writing programs that behave as if they are secure but are not.

Hive External Table Skip First Row

Just append below property in your query and the first header or line int the record will not load or it will be skipped.

Try this

tblproperties ("skip.header.line.count"="1");

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

This type of error also takes place because the resize is unable to get the image in simple the directory of the image may be wrong.In my case I left the forward slash during providing the location of file and this error took place after I put the slash problem was solved.

.ssh directory not being created

I am assuming that you have enough permissions to create this directory.

To fix your problem, you can either ssh to some other location:

ssh [email protected]

and accept new key - it will create directory ~/.ssh and known_hosts underneath, or simply create it manually using

mkdir ~/.ssh
chmod 700 ~/.ssh

Note that chmod 700 is an important step!

After that, ssh-keygen should work without complaints.

ios Upload Image and Text using HTTP POST

Here is a Swift version. Note that if you do not want to send form data it is still important to send the empty form boundary. Flask in particular expects form data followed by file data and will not populate request.files without the first boundary.

  let composedData = NSMutableData()

  // Set content type header
  let BoundaryConstant = "--------------------------3d74a90a3bfb8696"
  let contentType = "multipart/form-data; boundary=\(BoundaryConstant)"
  request.setValue(contentType, forHTTPHeaderField: "Content-Type")

  // Empty form boundary
  composedData.appendData("--\(BoundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

  // Build multipart form to send image
  composedData.appendData("--\(BoundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
  composedData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
  composedData.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
  composedData.appendData(rawData!)
  composedData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
  composedData.appendData("--\(BoundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

  request.HTTPBody = composedData

  // Get content length
  let length = "\(composedData.length)"
  request.setValue(length, forHTTPHeaderField: "Content-Length")

How to link C++ program with Boost using CMake

The following is my configuration:

cmake_minimum_required(VERSION 2.8)
set(Boost_INCLUDE_DIR /usr/local/src/boost_1_46_1)
set(Boost_LIBRARY_DIR /usr/local/src/boost_1_46_1/stage/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})

add_executable(main main.cpp)
target_link_libraries( main ${Boost_LIBRARIES} )

Access item in a list of lists

50 - List1[0][0] + List[0][1] - List[0][2]

List[0] gives you the first list in the list (try out print List[0]). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0].

SQL Query - Change date format in query to DD/MM/YYYY

If you have a Date (or Datetime) column, look at http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

 SELECT DATE_FORMAT(datecolumn,'%d/%m/%Y') FROM ...

Should do the job for MySQL, for SqlServer I'm sure there is an analog function. If you have a VARCHAR column, you might have at first to convert it to a date, see STR_TO_DATE for MySQL.

Eclipse - java.lang.ClassNotFoundException

Hmm, looks a little bizarre, try running it with the following annotation at the top of the class:

@RunWith(SpringJUnit4ClassRunner.class)
public class UserDaoTest {
}

and let me know how you get on with it.

Check that you have build automatically enabled as well. If you want to make sure your test classes are being compiled correctly clear out the Maven target folder (and any bin folder that Eclipse may be using). Are you using m2eclipse as well, as I find it to be a little problematic.

Matplotlib transparent line plots

After I plotted all the lines, I was able to set the transparency of all of them as follows:

for l in fig_field.gca().lines:
    l.set_alpha(.7)

EDIT: please see Joe's answer in the comments.

What are Unwind segues for and how do you use them?

Something that I didn't see mentioned in the other answers here is how you deal with unwinding when you don't know where the initial segue originated, which to me is an even more important use case. For example, say you have a help view controller (H) that you display modally from two different view controllers (A and B):

A ? H
B ? H

How do you set up the unwind segue so that you go back to the correct view controller? The answer is that you declare an unwind action in A and B with the same name, e.g.:

// put in AViewController.swift and BViewController.swift
@IBAction func unwindFromHelp(sender: UIStoryboardSegue) {
    // empty
}

This way, the unwind will find whichever view controller (A or B) initiated the segue and go back to it.

In other words, think of the unwind action as describing where the segue is coming from, rather than where it is going to.

Why doesn't JavaScript have a last method?

Yeah, or just:

var arr = [1, 2, 5];
arr.reverse()[0]

if you want the value, and not a new list.

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

It's an invisible folder. Just hit Command + Shift + G (takes you to the Go to Folder menu item) and type /etc/.

Then it will take you to inside that folder.

Convert InputStream to BufferedReader

A BufferedReader constructor takes a reader as argument, not an InputStream. You should first create a Reader from your stream, like so:

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

Preferrably, you also provide a Charset or character encoding name to the StreamReader constructor. Since a stream just provides bytes, converting these to text means the encoding must be known. If you don't specify it, the system default is assumed.

Save attachments to a folder and rename them

Public Sub Extract_Outlook_Email_Attachments()

Dim OutlookOpened As Boolean
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outFolder As Outlook.MAPIFolder
Dim outAttachment As Outlook.Attachment
Dim outItem As Object
Dim saveFolder As String
Dim outMailItem As Outlook.MailItem
Dim inputDate As String, subjectFilter As String


saveFolder = "Y:\Wingman" ' THIS IS WHERE YOU WANT TO SAVE THE ATTACHMENT TO

If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\"

subjectFilter = ("Daily Operations Custom All Req Statuses Report") ' THIS IS WHERE YOU PLACE THE EMAIL SUBJECT FOR THE CODE TO FIND

OutlookOpened = False
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
    Set outApp = New Outlook.Application
    OutlookOpened = True
End If
On Error GoTo 0

If outApp Is Nothing Then
    MsgBox "Cannot start Outlook.", vbExclamation
    Exit Sub
End If

Set outNs = outApp.GetNamespace("MAPI")
Set outFolder = outNs.GetDefaultFolder(olFolderInbox)

If Not outFolder Is Nothing Then
    For Each outItem In outFolder.Items
        If outItem.Class = Outlook.OlObjectClass.olMail Then
            Set outMailItem = outItem
                If InStr(1, outMailItem.Subject, subjectFilter) > 0 Then 'removed the quotes around subjectFilter
                    For Each outAttachment In outMailItem.Attachments
                    outAttachment.SaveAsFile saveFolder & outAttachment.filename

                    Set outAttachment = Nothing

                    Next
                End If
        End If
    Next
End If

If OutlookOpened Then outApp.Quit

Set outApp = Nothing

End Sub

NuGet behind a proxy

Apart from the suggestions from @arcain I had to add the following Windows Azure Content Delivery Network url to our proxy server's the white-list:

.msecnd.net

Change Project Namespace in Visual Studio

"Default Namespace textbox in project properties is disabled" Same with me (VS 2010). I edited the project file ("xxx.csproj") and tweaked the item. That changed the default namespace.

How to convert list to string

L = ['L','O','L']
makeitastring = ''.join(map(str, L))

Java 8 Lambda function that throws exception?

You could however create your own FunctionalInterface that throws as below..

@FunctionalInterface
public interface UseInstance<T, X extends Throwable> {
  void accept(T instance) throws X;
}

then implement it using Lambdas or references as shown below.

import java.io.FileWriter;
import java.io.IOException;

//lambda expressions and the execute around method (EAM) pattern to
//manage resources

public class FileWriterEAM  {
  private final FileWriter writer;

  private FileWriterEAM(final String fileName) throws IOException {
    writer = new FileWriter(fileName);
  }
  private void close() throws IOException {
    System.out.println("close called automatically...");
    writer.close();
  }
  public void writeStuff(final String message) throws IOException {
    writer.write(message);
  }
  //...

  public static void use(final String fileName, final UseInstance<FileWriterEAM, IOException> block) throws IOException {

    final FileWriterEAM writerEAM = new FileWriterEAM(fileName);    
    try {
      block.accept(writerEAM);
    } finally {
      writerEAM.close();
    }
  }

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

    FileWriterEAM.use("eam.txt", writerEAM -> writerEAM.writeStuff("sweet"));

    FileWriterEAM.use("eam2.txt", writerEAM -> {
        writerEAM.writeStuff("how");
        writerEAM.writeStuff("sweet");      
      });

    FileWriterEAM.use("eam3.txt", FileWriterEAM::writeIt);     

  }


 void writeIt() throws IOException{
     this.writeStuff("How ");
     this.writeStuff("sweet ");
     this.writeStuff("it is");

 }

}

Bash script to check running process

I need to do this from time to time and end up hacking the command line until it works.

For example, here I want to see if I have any SSH connections, (the 8th column returned by "ps" is the running "path-to-procname" and is filtered by "awk":

ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g'

Then I put it in a shell-script, ("eval"-ing the command line inside of backticks), like this:

#!/bin/bash

VNC_STRING=`ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g'`

if [ ! -z "$VNC_STRING" ]; then
    echo "The VNC STRING is not empty, therefore your process is running."
fi

The "sed" part trims the path to the exact token and might not be necessary for your needs.

Here's my example I used to get your answer. I wrote it to automatically create 2 SSH tunnels and launch a VNC client for each.

I run it from my Cygwin shell to do admin to my backend from my windows workstation, so I can jump to UNIX/LINUX-land with one command, (this also assumes the client rsa keys have already been "ssh-copy-id"-ed and are known to the remote host).

It's idempotent in that each proc/command only fires when their $VAR eval's to an empty string.

It appends " | wc -l" to store the number of running procs that match, (i.e., number of lines found), instead of proc-name for each $VAR to suit my needs. I keep the "echo" statements so I can re-run and diagnose the state of both connections.

#!/bin/bash

SSH_COUNT=`eval ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g' | wc -l`
VNC_COUNT=`eval ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g' | wc -l`

if  [ $SSH_COUNT = "2" ]; then
    echo "There are already 2 SSH tunnels."
elif  [ $SSH_COUNT = "1" ]; then
    echo "There is only 1 SSH tunnel."
elif [ $SSH_COUNT = "0" ]; then
    echo "connecting 2 SSH tunnels."
    ssh -L 5901:localhost:5901 -f -l USER1 HOST1 sleep 10;
    ssh -L 5904:localhost:5904 -f -l USER2 HOST2 sleep 10;
fi

if  [ $VNC_COUNT = "2" ]; then
    echo "There are already 2 VNC sessions."
elif  [ $VNC_COUNT = "1" ]; then
    echo "There is only 1 VNC session."
elif [ $VNC_COUNT = "0" ]; then
    echo "launching 2 vnc sessions."
    vncviewer.exe localhost:1 &
    vncviewer.exe localhost:4 &
fi

This is very perl-like to me and possibly more unix utils than true shell scripting. I know there are lots of "MAGIC" numbers and cheezy hard-coded values but it works, (I think I'm also in poor taste for using so much UPPERCASE too). Flexibility can be added with some cmd-line args to make this more versatile but I wanted to share what worked for me. Please improve and share. Cheers.

Twitter Bootstrap - how to center elements horizontally or vertically

From the Bootstrap documentation:

Set an element to display: block and center via margin. Available as a mixin and class.

<div class="center-block">...</div>

Tkinter: "Python may not be configured for Tk"

To anyone using Windows and Windows Subsystem for Linux, make sure that when you run the python command from the command line, it's not accidentally running the python installation from WSL! This gave me quite a headache just now. A quick check you can do for this is just
which <python command you're using>
If that prints something like /usr/bin/python2 even though you're in powershell, that's probably what's going on.

How to use enums in C++

Rather than using a bunch of if-statements, enums lend themselves well to switch statements

I use some enum/switch combinations in the level builder I am building for my game.

EDIT: Another thing, I see you want syntax similar to;

if(day == Days.Saturday)
etc

You can do this in C++:

if(day == Days::Saturday)
etc

Here is a very simple example:

EnumAppState.h

#ifndef ENUMAPPSTATE_H
#define ENUMAPPSTATE_H
enum eAppState
{
    STARTUP,
    EDIT,
    ZONECREATION,
    SHUTDOWN,
    NOCHANGE
};
#endif

Somefile.cpp

#include "EnumAppState.h"
eAppState state = eAppState::STARTUP;
switch(state)
{
case STARTUP:
    //Do stuff
    break;
case EDIT:
    //Do stuff
    break;
case ZONECREATION:
    //Do stuff
    break;
case SHUTDOWN:
    //Do stuff
    break;
case NOCHANGE:
    //Do stuff
    break;
}

Writing new lines to a text file in PowerShell

You can use the Environment class's static NewLine property to get the proper newline:

$errorMsg =  "{0} Error {1}{2} key {3} expected: {4}{5} local value is: {6}" -f `
               (Get-Date),$keyPath,$value,$key,$policyValue,([Environment]::NewLine),$localValue
Add-Content -Path $logpath $errorMsg

MySQL Query GROUP BY day / month / year

I tried using the 'WHERE' statement above, I thought its correct since nobody corrected it but I was wrong; after some searches I found out that this is the right formula for the WHERE statement so the code becomes like this:

SELECT COUNT(id)  
FROM stats  
WHERE YEAR(record_date) = 2009  
GROUP BY MONTH(record_date)

Drawing rotated text on a HTML5 canvas

Posting this in an effort to help others with similar problems. I solved this issue with a five step approach -- save the context, translate the context, rotate the context, draw the text, then restore the context to its saved state.

I think of translations and transforms to the context as manipulating the coordinate grid overlaid on the canvas. By default the origin (0,0) starts in the upper left hand corner of the canvas. X increases from left to right, Y increases from top to bottom. If you make an "L" w/ your index finger and thumb on your left hand and hold it out in front of you with your thumb down, your thumb would point in the direction of increasing Y and your index finger would point in the direction of increasing X. I know it's elementary, but I find it helpful when thinking about translations and rotations. Here's why:

When you translate the context, you move the origin of the coordinate grid to a new location on the canvas. When you rotate the context, think of rotating the "L" you made with your left hand in a clockwise direction the amount indicated by the angle you specify in radians about the origin. When you strokeText or fillText, specify your coordinates in relation to the newly aligned axes. To orient your text so it's readable from bottom to top, you would translate to a position below where you want to start your labels, rotate by -90 degrees and fill or strokeText, offsetting each label along the rotated x axis. Something like this should work:

 context.save();
 context.translate(newx, newy);
 context.rotate(-Math.PI/2);
 context.textAlign = "center";
 context.fillText("Your Label Here", labelXposition, 0);
 context.restore();

.restore() resets the context back to the state it had when you called .save() -- handy for returning things back to "normal".


Retrieving an element from array list in Android?

In arraylist you have a positional order and not a nominal order, so you need to know in advance the element position you need to select or you must loop between elements until you find the element that you need to use. To do this you can use an iterator and an if, for example:

Iterator iter = list.iterator();
while (iter.hasNext())
{
    // if here          
    System.out.println("string " + iter.next());
}

jQuery Validate Plugin - How to create a simple custom rule?

You can create a simple rule by doing something like this:

jQuery.validator.addMethod("greaterThanZero", function(value, element) {
    return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");

And then applying this like so:

$('validatorElement').validate({
    rules : {
        amount : { greaterThanZero : true }
    }
});

Just change the contents of the 'addMethod' to validate your checkboxes.

Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Import Excel to Datagridview

I used the following code, it's working!

using System.Data.OleDb;
using System.IO;
using System.Text.RegularExpressions;

private void btopen_Click(object sender, EventArgs e)
{
   try
   {
     OpenFileDialog openFileDialog1 = new OpenFileDialog();  //create openfileDialog Object
     openFileDialog1.Filter = "XML Files (*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb) |*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb";//open file format define Excel Files(.xls)|*.xls| Excel Files(.xlsx)|*.xlsx| 
     openFileDialog1.FilterIndex = 3;

     openFileDialog1.Multiselect = false;        //not allow multiline selection at the file selection level
     openFileDialog1.Title = "Open Text File-R13";   //define the name of openfileDialog
     openFileDialog1.InitialDirectory = @"Desktop"; //define the initial directory

     if (openFileDialog1.ShowDialog() == DialogResult.OK)        //executing when file open
     {
       string pathName = openFileDialog1.FileName;
       fileName = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
       DataTable tbContainer = new DataTable();
       string strConn = string.Empty;
       string sheetName = fileName;

       FileInfo file = new FileInfo(pathName);
       if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
       string extension = file.Extension;
       switch (extension)
       {
          case ".xls":
                   strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                   break;
          case ".xlsx":
                   strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                   break;
          default:
                   strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                   break;
         }
         OleDbConnection cnnxls = new OleDbConnection(strConn);
         OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
         oda.Fill(tbContainer);

         dtGrid.DataSource = tbContainer;
       }

     }
     catch (Exception)
     {
        MessageBox.Show("Error!");
     }
  }

What are callee and caller saved registers?

I'm not really sure if this adds anything but,

Caller saved means that the caller has to save the registers because they will be clobbered in the call and have no choice but to be left in a clobbered state after the call returns (for instance, the return value being in eax for cdecl. It makes no sense for the return value to be restored to the value before the call by the callee, because it is a return value).

Callee saved means that the callee has to save the registers and then restore them at the end of the call because they have the guarantee to the caller of containing the same values after the function returns, and it is possible to restore them, even if they are clobbered at some point during the call.

The issue with the above definition though is that for instance on Wikipedia cdecl, it says eax, ecx and edx are caller saved and rest are callee saved, this suggests that the caller must save all 3 of these registers, when it might not if none of these registers were used by the caller in the first place. In which case caller 'saved' becomes a misnomer, but 'call clobbered' still correctly applies. This is the same with 'the rest' being called callee saved. It implies that all other x86 registers will be saved and restored by the callee when this is not the case if some of the registers are never used in the call anyway. With cdecl, eax:edx may be used to return a 64 bit value. I'm not sure why ecx is also caller saved if needed, but it is.

Disabling Chrome Autofill

For username password combos this is an easy issue to resolve. Chrome heuristics looks for the pattern:

<input type="text">

followed by:

<input type="password">

Simply break this process by invalidating this:

<input type="text">
<input type="text" onfocus="this.type='password'">

React: why child component doesn't update when prop changes

I was encountering the same problem. I had a Tooltip component that was receiving showTooltip prop, that I was updating on Parent component based on an if condition, it was getting updated in Parent component but Tooltip component was not rendering.

const Parent = () => {
   let showTooltip = false;
   if(....){ showTooltip = true; }
   return(
      <Tooltip showTooltip={showTooltip}></Tooltip>
   )
}

The mistake I was doing is to declare showTooltip as a let.

I realized what I was doing wrong I was violating the principles of how rendering works, Replacing it with hooks did the job.

const [showTooltip, setShowTooltip] =  React.useState<boolean>(false);

html button to send email

This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto link/action is sparsely supported, but maybe this can help...

HTML:

<form id="fr1">
    <input type="text" id="tb1" />
    <input type="text" id="tb2" />
    <input type="button" id="bt1" value="click" />
</form>

JavaScript (with jQuery):

$(document).ready(function() {
    $('#bt1').click(function() {
        $('#fr1').attr('action',
                       'mailto:[email protected]?subject=' +
                       $('#tb1').val() + '&body=' + $('#tb2').val());
        $('#fr1').submit();
    });
});

Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit type, it's just a button type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.

It's working in so much as it submits the form to a mailto action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.

HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.

How to animate CSS Translate

I too was looking for a good way to do this, I found the best way was to set a transition on the "transform" property and then change the transform and then remove the transition.

I put it all together in a jQuery plugin

https://gist.github.com/dustinpoissant/8a4837c476e3939a5b3d1a2585e8d1b0

You would use the code like this:

$("#myElement").animateTransform("rotate(180deg)", 750, function(){
  console.log("animation completed after 750ms");
});

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

I had the same error. But command "FLUSH PRIVILEGES;" didn't help. I did like that:

CREATE USER 'jimmy'@'localhost' IDENTIFIED BY 'test123';
UPDATE mysql.user SET USER='jack' WHERE USER='jimmy';

SQL - using alias in Group By

SQL Server doesn't allow you to reference the alias in the GROUP BY clause because of the logical order of processing. The GROUP BY clause is processed before the SELECT clause, so the alias is not known when the GROUP BY clause is evaluated. This also explains why you can use the alias in the ORDER BY clause.

Here is one source for information on the SQL Server logical processing phases.

How to open up a form from another form in VB.NET?

You can also use showdialog

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                      Handles Button3.Click

     dim mydialogbox as new aboutbox1
     aboutbox1.showdialog()

End Sub

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

The code of Ellbar works! You need only add using.

1 - using Microsoft.AspNet.Identity;

And... the code of Ellbar:

2 - string currentUserId = User.Identity.GetUserId(); ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

With this code (in currentUser), you work the general data of the connected user, if you want extra data... see this link

How to determine one year from now in Javascript

As setYear() is deprecated, correct variant is:

// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)

All examples return Unix timestamp, if you want to get Date object - just wrap it with another new Date(...)

how to call scalar function in sql server 2008

You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.

select dbo.fun_functional_score('01091400003')

CSS display:table-row does not expand when width is set to 100%

You can nest table-cell directly within table. You muslt have a table. Starting eith table-row does not work. Try it with this HTML:

<html>
  <head>
    <style type="text/css">
.table {
  display: table;
  width: 100%;
}
.tr {
  display: table-row;
  width: 100%;
}
.td {
  display: table-cell;
}
    </style>
  </head>
  <body>

    <div class="table">
      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>
    </div>

      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>

    <div class="table">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
    </div>

  </body>
</html>

Python to print out status bar and percentage

I came upon this thread today and after having tried out this solution from Mark Rushakoff

from time import sleep
import sys

for i in range(21):
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
sys.stdout.flush()
sleep(0.25)

I can say that this works fine on W7-64 with python 3.4.3 64-bit but only in the native console. However when using the built-in console of spyder 3.0.0dev, the line breaks are still/again present. As this took me some time to figure out, I'd like to report this observation here.

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

Another reason + solution

I run into this error ("package XXX is not available for R version X.X.X") when trying to install pkgdown in my RStudio on my company's HPC.

Turns out, the CRAN snapshot they have on the HPC is from Jan. 2018 (almost 2 years old) and indeed pkgdown did not exist then. That was meant to control the source of packages for layman users, but as a developer, you can in most cases change that by:

## checking the specific repos you currently have
getOption("repos")

## updating your CRAN snapshot to a newer date
r <- getOption("repos")
r["newCRAN"] <- "https://cran.microsoft.com/snapshot/*2019-11-07*/"
options(repos = r)

## add newCRAN to repos you can use
setRepositories()

If you know what you are doing and may need more than one package that might not be available in your system's CRAN, you can set this up in your project .Rprofile.

If it's just one package, maybe just use install.packages("package name", repos = "a newer CRAN than your company's archaic CRAN snapshot").

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

My answer was different and came along with the message:

resource fork, Finder information, or similar detritus not allowed

The solution was to do with generated graphics:

Code Sign Error in macOS Sierra Xcode 8 : resource fork, Finder information, or similar detritus not allowed

Rails 4 Authenticity Token

These features were added for security and forgery protection purposes.
However, to answer your question, here are some inputs. You can add these lines after your the controller name.

Like so,

class NameController < ApplicationController
    skip_before_action :verify_authenticity_token

Here are some lines for different versions of rails.

Rails 3

skip_before_filter :verify_authenticity_token

Rails 4:

skip_before_action :verify_authenticity_token


Should you intend to disable this security feature for all controller routines, you can change the value of protect_from_forgery to :null_session on your application_controller.rb file.

Like so,

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

How to view the current heap size that an application is using?

You can use jconsole (standard with most JDKs) to check heap sizes of any java process.

How can I get date and time formats based on Culture Info?

You could take a look at the DateTimeFormat property which contains the culture specific formats.

ASP.NET MVC 3 - redirect to another action

You will need to return the result of RedirectToAction.

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

The most simple and used by everyone mostly is javascript:void(0) You can use it instead of using # to stop tag redirect to header section.

<a href="javascript:void(0)" onclick="testFunction();">Click To check Function</a>

function testFunction() {
    alert("hello world");
}

On a CSS hover event, can I change another div's styling?

The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS

$(document).ready(function(){
     $("#a").mouseover(function(){
         $("#b").css("background-color", "red");
     });
});

How I can delete in VIM all text from current line to end of file?

dG will delete from the current line to the end of file

dCtrl+End will delete from the cursor to the end of the file

But if this file is as large as you say, you may be better off reading the first few lines with head rather than editing and saving the file.

head hugefile > firstlines

(If you are on Windows you can use the Win32 port of head)

SQL Server CASE .. WHEN .. IN statement

CASE AlarmEventTransactions.DeviceID should just be CASE.

You are mixing the 2 forms of the CASE expression.

Are there any standard exit status codes in Linux?

When Linux returns 0, it means success. Anything else means failure, each program has its own exit codes, so it would been quite long to list them all... !

About the 11 error code, it's indeed the segmentation fault number, mostly meaning that the program accessed a memory location that was not assigned.

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

I did which node on my terminal: /usr/local/bin/node

and then i added "runtimeExecutable": "/usr/local/bin/node" in my json file.

MATLAB, Filling in the area between two sets of data, lines in one figure

You want to look at the patch() function, and sneak in points for the start and end of the horizontal line:

x = 0:.1:2*pi;
y = sin(x)+rand(size(x))/2;

x2 = [0 x 2*pi];
y2 = [.1 y .1];
patch(x2, y2, [.8 .8 .1]);

If you only want the filled in area for a part of the data, you'll need to truncate the x and y vectors to only include the points you need.

How to restart counting from 1 after erasing table in MS Access?

I always use below approach. I've created one table in database as Table1 with only one column i.e. Row_Id Number (Long Integer) and its value is 0

enter image description here

INSERT INTO <TABLE_NAME_TO_RESET>
SELECT Row_Id AS <COLUMN_NAME_TO_RESET>
FROM Table1;

This will insert one row with 0 value in AutoNumber column, later delete that row.

AngularJS UI Router - change url without reloading state

Ok, solved :) Angular UI Router has this new method, $urlRouterProvider.deferIntercept() https://github.com/angular-ui/ui-router/issues/64

basically it comes down to this:

angular.module('myApp', [ui.router])
  .config(['$urlRouterProvider', function ($urlRouterProvider) {
    $urlRouterProvider.deferIntercept();
  }])
  // then define the interception
  .run(['$rootScope', '$urlRouter', '$location', '$state', function ($rootScope, $urlRouter, $location, $state) {
    $rootScope.$on('$locationChangeSuccess', function(e, newUrl, oldUrl) {
      // Prevent $urlRouter's default handler from firing
      e.preventDefault();

      /** 
       * provide conditions on when to 
       * sync change in $location.path() with state reload.
       * I use $location and $state as examples, but
       * You can do any logic
       * before syncing OR stop syncing all together.
       */

      if ($state.current.name !== 'main.exampleState' || newUrl === 'http://some.url' || oldUrl !=='https://another.url') {
        // your stuff
        $urlRouter.sync();
      } else {
        // don't sync
      }
    });
    // Configures $urlRouter's listener *after* your custom listener
    $urlRouter.listen();
  }]);

I think this method is currently only included in the master version of angular ui router, the one with optional parameters (which are nice too, btw). It needs to be cloned and built from source with

grunt build

The docs are accessible from the source as well, through

grunt ngdocs

(they get built into the /site directory) // more info in README.MD

There seems to be another way to do this, by dynamic parameters (which I haven't used). Many credits to nateabele.


As a sidenote, here are optional parameters in Angular UI Router's $stateProvider, which I used in combination with the above:

angular.module('myApp').config(['$stateProvider', function ($stateProvider) {    

  $stateProvider
    .state('main.doorsList', {
      url: 'doors',
      controller: DoorsListCtrl,
      resolve: DoorsListCtrl.resolve,
      templateUrl: '/modules/doors/doors-list.html'
    })
    .state('main.doorsSingle', {
      url: 'doors/:doorsSingle/:doorsDetail',
      params: {
        // as of today, it was unclear how to define a required parameter (more below)
        doorsSingle: {value: null},
        doorsDetail: {value: null}
      },
      controller: DoorsSingleCtrl,
      resolve: DoorsSingleCtrl.resolve,
      templateUrl: '/modules/doors/doors-single.html'
    });

}]);

what that does is it allows to resolve a state, even if one of the params is missing. SEO is one purpose, readability another.

In the example above, I wanted doorsSingle to be a required parameter. It is not clear how to define those. It works ok with multiple optional parameters though, so not really a problem. The discussion is here https://github.com/angular-ui/ui-router/pull/1032#issuecomment-49196090

"Insufficient Storage Available" even there is lot of free space in device memory

The same problem was coming for my phone and this resolved the problem:

  • Go to Application Manager/ Apps from Settings.

  • Select Google Play Services.

Enter image description here

  • Click Uninstall Updates button to the right of the Force Stop button.

  • Once the updates are uninstalled, you should see Disable button which means you are done.

Enter image description here

You will see lots of free space available now.

Converting String to "Character" array in Java

One liner with :

String str = "testString";

//[t, e, s, t, S, t, r, i, n, g]
Character[] charObjectArray = 
    str.chars().mapToObj(c -> (char)c).toArray(Character[]::new); 

What it does is:

  • get an IntStream of the characters (you may want to also look at codePoints())
  • map each 'character' value to Character (you need to cast to actually say that its really a char, and then Java will box it automatically to Character)
  • get the resulting array by calling toArray()

SQL Server 2008 - Help writing simple INSERT Trigger

cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.

You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.

How to output JavaScript with PHP

Another option is to do like this:

<html>
    <body>
    <?php
    //...php code...  
    ?>
    <script type="text/javascript">
        document.write("Hello World!");
    </script>
    <?php
    //....php code...
    ?>
    </body>
</html>

and if you want to use PHP inside your JavaScript, do like this:

<html>
    <body>
    <?php
        $text = "Hello World!";
    ?>
    <script type="text/javascript">
        document.write("<?php echo $text ?>");
    </script>
    <?php
    //....php code...
    ?>
    </body>
</html>

Hope this can help.

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

How to iterate over columns of pandas dataframe to run regression

Using list comprehension, you can get all the columns names (header):

[column for column in df]

Close Window from ViewModel

it may be late, but here is my answer

foreach (Window item in Application.Current.Windows)
{
    if (item.DataContext == this) item.Close();
}

How should I pass an int into stringWithFormat?

And for comedic value:

label.text = [NSString stringWithFormat:@"%@", [NSNumber numberWithInt:count]];

(Though it could be useful if one day you're dealing with NSNumber's)

Passing data between view controllers

There are various ways by which data can be received by a different class in iOS. For example -

  1. Direct initialization after the allocation of another class.
  2. Delegation - for passing data back
  3. Notification - for broadcasting data to multiple classes at a single time
  4. Saving in NSUserDefaults - for accessing it later
  5. Singleton classes
  6. Databases and other storage mechanisms, like p-list files, etc.

But for the simple scenario of passing a value to a different class whose allocation is done in the current class, the most common and preferred method would be the direct setting of values after allocation. This is done as follows:

We can understand it using two controllers - Controller1 and Controller2

Suppose in Controller1 class you want to create the Controller2 object and push it with a String value being passed. This can be done as this:

- (void)pushToController2 {

    Controller2 *obj = [[Controller2 alloc] initWithNib:@"Controller2" bundle:nil];
    [obj passValue:@"String"];
    [self pushViewController:obj animated:YES];
}

In the implementation of the Controller2 class there will be this function as:

@interface Controller2  : NSObject

@property (nonatomic, strong) NSString* stringPassed;

@end

@implementation Controller2

@synthesize stringPassed = _stringPassed;

- (void) passValue:(NSString *)value {

    _stringPassed = value; // Or self.stringPassed = value
}

@end

You can also directly set the properties of the Controller2 class in the similar way as this:

- (void)pushToController2 {

    Controller2 *obj = [[Controller2 alloc] initWithNib:@"Controller2" bundle:nil];
    [obj setStringPassed:@"String"];
    [self pushViewController:obj animated:YES];
}

To pass multiple values, you can use the multiple parameters like:

Controller2 *obj = [[Controller2 alloc] initWithNib:@"Controller2" bundle:nil];
[obj passValue:@“String1” andValues:objArray withDate:date];

Or if you need to pass more than three parameters which are related to a common feature, you can store the values in a model class and pass that modelObject to the next class

ModelClass *modelObject = [[ModelClass alloc] init];
modelObject.property1 = _property1;
modelObject.property2 = _property2;
modelObject.property3 = _property3;

Controller2 *obj = [[Controller2 alloc] initWithNib:@"Controller2" bundle:nil];
[obj passmodel: modelObject];

So in short, if you want to -

  1. set the private variables of the second class initialise the values by calling a custom function and passing the values.
  2. setProperties do it by directlyInitialising it using the setter method.
  3. pass more that 3-4 values related to each other in some manner, then create a model class and set values to its object and pass the object using any of the above process.

What is the meaning of Bus: error 10 in C

There is no space allocated for the strings. use array (or) pointers with malloc() and free()

Other than that

#import <stdio.h>
#import <string.h>

should be

#include <stdio.h>
#include <string.h>

NOTE:

  • anything that is malloc()ed must be free()'ed
  • you need to allocate n + 1 bytes for a string which is of length n (the last byte is for \0)

Please you the following code as a reference

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    //char *str1 = "First string";
    char *str1 = "First string is a big string";
    char *str2 = NULL;

    if ((str2 = (char *) malloc(sizeof(char) * strlen(str1) + 1)) == NULL) {
        printf("unable to allocate memory \n");
        return -1; 
    }   

    strcpy(str2, str1);

    printf("str1 : %s \n", str1);
    printf("str2 : %s \n", str2);

    free(str2);
    return 0;
}

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

ArrayList of int array in java

In java, an array is an object. Therefore the call to arl.get(0) returns a primitive int[] object which appears as ascii in your call to System.out.

The answer to your first question is therefore

System.out.println("Arraylist contains:"+Arrays.toString( arl.get( 0 ) ) );

If you're looking for particular elements, the returned int[] object must be referenced as such. The answer to your second question would be something like

    int[] contentFromList = arl.get(0);
    for (int i = 0; i < contentFromList.length; i++) {
        int j = contentFromList[i];
        System.out.println("Value at index - "+i+" is :"+j);
    }

Making RGB color in Xcode

Yeah.ios supports RGB valur to range between 0 and 1 only..its close Range [0,1]

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

My first post... UDF I managed quickly to compile. Usage: Select 3D range as normal and enclose is into quotation marks like below...

=CountIf3D("'StartSheet:EndSheet'!G16:G878";"Criteria")

Advisably sheets to be adjacent to avoid unanticipated results.

Public Function CountIf3D(SheetstoCount As String, CriteriaToUse As Variant)

     Dim sStarSheet As String, sEndSheet As String, sAddress As String
     Dim lColonPos As Long, lExclaPos As Long, cnt As Long

    lColonPos = InStr(SheetstoCount, ":") 'Finding ':' separating sheets
    lExclaPos = InStr(SheetstoCount, "!") 'Finding '!' separating address from the sheets

    sStarSheet = Mid(SheetstoCount, 2, lColonPos - 2) 'Getting first sheet's name
    sEndSheet = Mid(SheetstoCount, lColonPos + 1, lExclaPos - lColonPos - 2) 'Getting last sheet's name

    sAddress = Mid(SheetstoCount, lExclaPos + 1, Len(SheetstoCount) - lExclaPos) 'Getting address

        cnt = 0
   For i = Sheets(sStarSheet).Index To Sheets(sEndSheet).Index
        cnt = cnt + Application.CountIf(Sheets(i).Range(sAddress), CriteriaToUse)
   Next

   CountIf3D = cnt

End Function

Set select option 'selected', by value

To select an option with value 'val2':

$('.id_100 option[value=val2]').attr('selected','selected');

Binding arrow keys in JS/jQuery

You can use jQuery bind:

$(window).bind('keydown', function(e){
    if (e.keyCode == 37) {
        console.log('left');
    } else if (e.keyCode == 38) {
        console.log('up');
    } else if (e.keyCode == 39) {
        console.log('right');
    } else if (e.keyCode == 40) {
        console.log('down');
    }
});

Can angularjs routes have optional parameter values?

It looks like Angular has support for this now.

From the latest (v1.2.0) docs for $routeProvider.when(path, route):

path can contain optional named groups with a question mark (:name?)

how to sort pandas dataframe from one column

Here is template of sort_values according to pandas documentation.

DataFrame.sort_values(by, axis=0,
                          ascending=True,
                          inplace=False,
                          kind='quicksort',
                          na_position='last',
                          ignore_index=False, key=None)[source]

In this case it will be like this.

df.sort_values(by=['2'])

API Reference pandas.DataFrame.sort_values

How to replace specific values in a oracle database column?

In Oracle, there is the concept of schema name, so try using this

update schemname.tablename t
set t.columnname = replace(t.columnname, t.oldvalue, t.newvalue);

Create JSON object dynamically via JavaScript (Without concate strings)

This is what you need!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

It seems that you can transfer your Certificates and Provisioning profiles from one machine to the other, so if you are having issues in setting up your certificate and/or profiles because you migrated your Dev machine, have a look at this:

how to transfer xcode certificates between macs

Handle ModelState Validation in ASP.NET Web API

Maybe not what you were looking for, but perhaps nice for someone to know:

If you are using .net Web Api 2 you could just do the following:

if (!ModelState.IsValid)
     return BadRequest(ModelState);

Depending on the model errors, you get this result:

{
   Message: "The request is invalid."
   ModelState: {
       model.PropertyA: [
            "The PropertyA field is required."
       ],
       model.PropertyB: [
             "The PropertyB field is required."
       ]
   }
}

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

Calendar Recurring/Repeating Events - Best Storage Method

Why not use a mechanism similar to Apache cron jobs? http://en.wikipedia.org/wiki/Cron

For calendar\scheduling I'd use slightly different values for "bits" to accommodate standard calendar reoccurence events - instead of [day of week (0 - 7), month (1 - 12), day of month (1 - 31), hour (0 - 23), min (0 - 59)]

-- I'd use something like [Year (repeat every N years), month (1 - 12), day of month (1 - 31), week of month (1-5), day of week (0 - 7)]

Hope this helps.

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

Easiest way to read from and write to files

     class Program
    { 
         public static void Main()
        { 
            //To write in a txt file
             File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome");

           //To Read from a txt file & print on console
             string  copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt");
             Console.Out.WriteLine("{0}",copyTxt);
        }      
    }

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

This error also happens when you try to save an entity that has validation errors. A good way to cause this is to forget to check ModelState.IsValid before saving to your DB.

Logging in Scala

This is how I got Scala Logging working for me:

Put this in your build.sbt:

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.7.2",
libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.3"

Then, after doing an sbt update, this prints out a friendly log message:

import com.typesafe.scalalogging._
object MyApp extends App with LazyLogging {
  logger.info("Hello there")
}

If you are using Play, you can of course simply import play.api.Logger for writing log messages: Logger.debug("Hi").

See the docs for more info.

What is 'PermSize' in Java?

This blog post gives a nice explanation and some background. Basically, the "permanent generation" (whose size is given by PermSize) is used to store things that the JVM has to allocate space for, but which will not (normally) be garbage-collected (hence "permanent") (+). That means for example loaded classes and static fields.

There is also a FAQ on garbage collection directly from Sun, which answers some questions about the permanent generation. Finally, here's a blog post with a lot of technical detail.

(+) Actually parts of the permanent generation will be GCed, e.g. class objects will be removed when a class is unloaded. But that was uncommon when the permanent generation was introduced into the JVM, hence the name.

Handling click events on a drawable within an EditText

Its very simple. Lets say you have a drawable on left side of your EditText 'txtsearch'. Following will do the trick.

EditText txtsearch = (EditText) findViewById(R.id.txtsearch);
txtsearch.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_UP) {
            if(event.getRawX() <= txtsearch.getTotalPaddingLeft()) {
                // your action for drawable click event

             return true;
            }
        }
        return false;
    }
});

If you want for right drawable change the if statement to:

if(event.getRawX() >= txtsearch.getRight() - txtsearch.getTotalPaddingRight())

Similarly, you can do it for all compound drawables.

txtsearch.getTotalPaddingTop()
txtsearch.getTotalPaddingBottom()

This method call returns all the padding on that side including any drawables. You can use this even for TextView, Button etc.

Click here for reference from android developer site.

C++ Best way to get integer division and remainder

Sample code testing div() and combined division & mod. I compiled these with gcc -O3, I had to add the call to doNothing to stop the compiler from optimising everything out (output would be 0 for the division + mod solution).

Take it with a grain of salt:

#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>

extern doNothing(int,int); // Empty function in another compilation unit

int main() {
    int i;
    struct timeval timeval;
    struct timeval timeval2;
    div_t result;
    gettimeofday(&timeval,NULL);
    for (i = 0; i < 1000; ++i) {
        result = div(i,3);
        doNothing(result.quot,result.rem);
    }
    gettimeofday(&timeval2,NULL);
    printf("%d",timeval2.tv_usec - timeval.tv_usec);
}

Outputs: 150

#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>

extern doNothing(int,int); // Empty function in another compilation unit

int main() {
    int i;
    struct timeval timeval;
    struct timeval timeval2;
    int dividend;
    int rem;
    gettimeofday(&timeval,NULL);
    for (i = 0; i < 1000; ++i) {
        dividend = i / 3;
        rem = i % 3;
        doNothing(dividend,rem);
    }
    gettimeofday(&timeval2,NULL);
    printf("%d",timeval2.tv_usec - timeval.tv_usec);
}

Outputs: 25

Chrome javascript debugger breakpoints don't do anything?

Pretty late answer but none of the above helped my case and was something different

while referring the javascript file type="text/javascript" was missing in the legacy application i was working

<script  src="ab.js" ></script>

below one worked and breakpoints were hitting as expected

 <script  src="ab.js" type="text/javascript"></script>

Java - get index of key in HashMap?

Not sure if this is any "cleaner", but:

List keys = new ArrayList(map.keySet());
for (int i = 0; i < keys.size(); i++) {
    Object obj = keys.get(i);
    // do stuff here
}

How to enumerate an enum

I think this is more efficient than other suggestions because GetValues() is not called each time you have a loop. It is also more concise. And you get a compile-time error, not a runtime exception if Suit is not an enum.

EnumLoop<Suit>.ForEach((suit) => {
    DoSomethingWith(suit);
});

EnumLoop has this completely generic definition:

class EnumLoop<Key> where Key : struct, IConvertible {
    static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
    static internal void ForEach(Action<Key> act) {
        for (int i = 0; i < arr.Length; i++) {
            act(arr[i]);
        }
    }
}

Quoting backslashes in Python string literals

You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)

>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

Incidentally, there's another string form which might be a bit clearer:

>>> print(r'baz "\"')
baz "\"

Why is quicksort better than mergesort?

In c/c++ land, when not using stl containers, I tend to use quicksort, because it is built into the run time, while mergesort is not.

So I believe that in many cases, it is simply the path of least resistance.

In addition performance can be much higher with quick sort, for cases where the entire dataset does not fit into the working set.

Sql Server string to date conversion

For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.

Undo a git stash

This will also restore the staging directory:

git stash apply --index

Password masking console application

I have updated Ronnie's version after spending way too much time trying to enter a password only to find out that I had my CAPS LOCK on!

With this version what ever the message is in _CapsLockMessage will "float" at the end of the typing area and will be displayed in red.

This version takes a bit more code and does require a polling loop. On my computer CPU usage about 3% to 4%, but one could always add a small Sleep() value to decrease CPU usage if needed.

    private const string _CapsLockMessage = " CAPS LOCK";

    /// <summary>
    /// Like System.Console.ReadLine(), only with a mask.
    /// </summary>
    /// <param name="mask">a <c>char</c> representing your choice of console mask</param>
    /// <returns>the string the user typed in</returns>
    public static string ReadLineMasked(char mask = '*')
    {
        // Taken from http://stackoverflow.com/a/19770778/486660
        var consoleLine = new StringBuilder();
        ConsoleKeyInfo keyInfo;
        bool isDone;
        bool isAlreadyLocked;
        bool isCapsLockOn;
        int cursorLeft;
        int cursorTop;
        ConsoleColor originalForegroundColor;

        isDone = false;
        isAlreadyLocked = Console.CapsLock;

        while (isDone == false)
        {
            isCapsLockOn = Console.CapsLock;
            if (isCapsLockOn != isAlreadyLocked)
            {
                if (isCapsLockOn)
                {
                    cursorLeft = Console.CursorLeft;
                    cursorTop = Console.CursorTop;
                    originalForegroundColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("{0}", _CapsLockMessage);
                    Console.SetCursorPosition(cursorLeft, cursorTop);
                    Console.ForegroundColor = originalForegroundColor;
                }
                else
                {
                    cursorLeft = Console.CursorLeft;
                    cursorTop = Console.CursorTop;
                    Console.Write("{0}", string.Empty.PadRight(_CapsLockMessage.Length));
                    Console.SetCursorPosition(cursorLeft, cursorTop);
                }
                isAlreadyLocked = isCapsLockOn;
            }

            if (Console.KeyAvailable)
            {
                keyInfo = Console.ReadKey(intercept: true);

                if (keyInfo.Key == ConsoleKey.Enter)
                {
                    isDone = true;
                    continue;
                }

                if (!char.IsControl(keyInfo.KeyChar))
                {
                    consoleLine.Append(keyInfo.KeyChar);
                    Console.Write(mask);
                }
                else if (keyInfo.Key == ConsoleKey.Backspace && consoleLine.Length > 0)
                {
                    consoleLine.Remove(consoleLine.Length - 1, 1);

                    if (Console.CursorLeft == 0)
                    {
                        Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
                        Console.Write(' ');
                        Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
                    }
                    else
                    {
                        Console.Write("\b \b");
                    }
                }

                if (isCapsLockOn)
                {
                    cursorLeft = Console.CursorLeft;
                    cursorTop = Console.CursorTop;
                    originalForegroundColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("{0}", _CapsLockMessage);
                    Console.CursorLeft = cursorLeft;
                    Console.CursorTop = cursorTop;
                    Console.ForegroundColor = originalForegroundColor;
                }
            }
        }

        Console.WriteLine();

        return consoleLine.ToString();
    }

background: fixed no repeat not working on mobile

I found maybe best solution for parallax effect which work on all devices.

Main thing is to set all sections with z-index greater than parallax section.

And parallax image element to set fixed with max width and height

_x000D_
_x000D_
body, html { margin: 0px; }_x000D_
section {_x000D_
  position: relative; /* Important */_x000D_
  z-index: 1; /* Important */_x000D_
  width: 100%;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
section.blue { background-color: blue; }_x000D_
section.red { background-color: red; }_x000D_
_x000D_
section.parallax {_x000D_
  z-index: 0; /* Important */_x000D_
}_x000D_
_x000D_
section.parallax .image {_x000D_
  position: fixed; /* Important */_x000D_
  top: 0; /* Important */_x000D_
  left: 0; /* Important */_x000D_
  width: 100%; /* Important */_x000D_
  height: 100%; /* Important */_x000D_
  background-image: url(https://www.w3schools.com/css/img_fjords.jpg);_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center;_x000D_
  -webkit-background-size: cover;_x000D_
  -moz-background-size: cover;_x000D_
  -o-background-size: cover;_x000D_
  background-size: cover;_x000D_
}
_x000D_
<section class="blue"></section>_x000D_
<section class="parallax">_x000D_
  <div class="image"></div>_x000D_
</section>_x000D_
<section class="red"></section>
_x000D_
_x000D_
_x000D_

Is the Javascript date object always one day off?

The following worked for me -

    var doo = new Date("2011-09-24").format("m/d/yyyy");

Is it still valid to use IE=edge,chrome=1?

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> serves two purposes.

  1. IE=edge: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.
  2. chrome=1: specifies that Google Chrome frame should start if the user has it installed

The IE=edge flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.

As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1 will do nothing more than consume a few bytes of bandwidth.

I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.

Note, the W3C validator will flag chrome=1 as an error:

Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.

Convert character to ASCII numeric value in java

Convert the char to int.

    String name = "admin";
    int ascii = name.toCharArray()[0];

Also :

int ascii = name.charAt(0);

Adding a favicon to a static HTML page

If you add the favicon into the root/images folder with the name favicon.ico browser will automatically understand and get it as favicon.I tested and worked. your link must be www.website.com/images/favicon.ico

For more information look this answer:

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

How to get SQL from Hibernate Criteria API (*not* for logging)

For anyone wishing to do this in a single line (e.g in the Display/Immediate window, a watch expression or similar in a debug session), the following will do so and "pretty print" the SQL:

new org.hibernate.jdbc.util.BasicFormatterImpl().format((new org.hibernate.loader.criteria.CriteriaJoinWalker((org.hibernate.persister.entity.OuterJoinLoadable)((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),new org.hibernate.loader.criteria.CriteriaQueryTranslator(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),((org.hibernate.impl.CriteriaImpl)crit),((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),(org.hibernate.impl.CriteriaImpl)crit,((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters())).getSQLString());

...or here's an easier to read version:

new org.hibernate.jdbc.util.BasicFormatterImpl().format(
  (new org.hibernate.loader.criteria.CriteriaJoinWalker(
     (org.hibernate.persister.entity.OuterJoinLoadable)
      ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(
        ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(
          ((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),
     new org.hibernate.loader.criteria.CriteriaQueryTranslator(
          ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
          ((org.hibernate.impl.CriteriaImpl)crit),
          ((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
          org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),
     ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
     (org.hibernate.impl.CriteriaImpl)crit,
     ((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
     ((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters()
   )
  ).getSQLString()
);

Notes:

  1. The answer is based on the solution posted by ramdane.i.
  2. It assumes the Criteria object is named crit. If named differently, do a search and replace.
  3. It assumes the Hibernate version is later than 3.3.2.GA but earlier than 4.0 in order to use BasicFormatterImpl to "pretty print" the HQL. If using a different version, see this answer for how to modify. Or perhaps just remove the pretty printing entirely as it's just a "nice to have".
  4. It's using getEnabledFilters rather than getLoadQueryInfluencers() for backwards compatibility since the latter was introduced in a later version of Hibernate (3.5???)
  5. It doesn't output the actual parameter values used if the query is parameterized.

What is username and password when starting Spring Boot with Tomcat?

Try to take username and password from below code snipet in your project and login and hope this will work.

@Override
    @Bean
    public UserDetailsService userDetailsService() {
        List<UserDetails> users= new ArrayList<UserDetails>();
        users.add(User.withDefaultPasswordEncoder().username("admin").password("admin").roles("USER","ADMIN").build());
        users.add(User.withDefaultPasswordEncoder().username("spring").password("spring").roles("USER").build());
        return new UserDetailsManager(users);
    }

Using Razor within JavaScript

You're trying to jam a square peg in a round hole.

Razor was intended as an HTML-generating template language. You may very well get it to generate JavaScript code, but it wasn't designed for that.

For instance: What if Model.Title contains an apostrophe? That would break your JavaScript code, and Razor won't escape it correctly by default.

It would probably be more appropriate to use a String generator in a helper function. There will likely be fewer unintended consequences of that approach.

How to detect my browser version and operating system using JavaScript?

I'm sad to say: We are sh*t out of luck on this one.

I'd like to refer you to the author of WhichBrowser: Everybody lies.

Basically, no browser is being honest. No matter if you use Chrome or IE, they both will tell you that they are "Mozilla Netscape" with Gecko and Safari support. Try it yourself on any of the fiddles flying around in this thread:

hims056's fiddle

Hariharan's fiddle

or any other... Try it with Chrome (which might still succeed), then try it with a recent version of IE, and you will cry. Of course, there are heuristics, to get it all right, but it will be tedious to grasp all the edge cases, and they will very likely not work anymore in a year's time.

Take your code, for example:

<div id="example"></div>
<script type="text/javascript">
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>

Chrome says:

Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36

Cookies Enabled: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36

IE says:

Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko

Cookies Enabled: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko

At least Chrome still has a string that contains "Chrome" with the exact version number. But, for IE you must extrapolate from the things it supports to actually figure it out (who else would boast that they support .NET or Media Center :P), and then match it against the rv: at the very end to get the version number. Of course, even such sophisticated heuristics might very likely fail as soon as IE 12 (or whatever they want to call it) comes out.

Should I learn C before learning C++?

I think you should learn C first, because I learned C first. C gave me a good grasp of the syntax and gotchas with things like pointers, all of which flow into C++.

I think C++ makes it easy to wrap up all those gotchas (need an array that won't overflow when you use the [] operator and a dodgy index? Sure, make an array class that does bounds checking) but you need to know what they are and get bitten by them before you understand why things are done in certain ways.

When all is said and done, the way C++ is usually taught is "C++ is C with objects, here's the C stuff and here's how all this OO stuff works", so you're likely to learn basic C before any real C++ if you follow most texts anyway.

Add views in UIStackView programmatically

In my case the thing that was messing with I would expect was that I was missing this line:

stackView.translatesAutoresizingMaskIntoConstraints = false;

After that no need to set constraints to my arranged subviews whatsoever, the stackview is taking care of that.

Spring Boot - Loading Initial Data

Spring Boot allows you to use a simple script to initialize your database, using Spring Batch.

Still, if you want to use something a bit more elaborated to manage DB versions and so on, Spring Boot integrates well with Flyway.

See also:

Scaling an image to fit on canvas

You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

Rendering an array.map() in React

You are not returning. Change to

this.state.data.map(function(item, i){
  console.log('test');
  return <li>Test</li>;
})

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

I faced this issue because of lower version of Jdk. Previously I installed Jdk 1.7 and Android Studio 1.5.1, I got this issue. If you install Android Studio 1.5.1 or above JDK 1.8 required

So Installing JDK 1.8 solved this issue.

how to concat two columns into one with the existing column name in mysql?

You can try this simple way for combining columns:

select some_other_column,first_name || ' ' || last_name AS First_name from customer;

How can I pass an Integer class correctly by reference?

1 ) Only the copy of reference is sent as a value to the formal parameter. When the formal parameter variable is assigned other value ,the formal parameter's reference changes but the actual parameter's reference remain the same incase of this integer object.

public class UnderstandingObjects {

public static void main(String[] args) {

    Integer actualParam = new Integer(10);

    changeValue(actualParam);

    System.out.println("Output " + actualParam); // o/p =10

    IntObj obj = new IntObj();

    obj.setVal(20);

    changeValue(obj);

    System.out.println(obj.a); // o/p =200

}

private static void changeValue(Integer formalParam) {

    formalParam = 100;

    // Only the copy of reference is set to the formal parameter
    // this is something like => Integer formalParam =new Integer(100);
    // Here we are changing the reference of formalParam itself not just the
    // reference value

}

private static void changeValue(IntObj obj) {
    obj.setVal(200);

    /*
     * obj = new IntObj(); obj.setVal(200);
     */
    // Here we are not changing the reference of obj. we are just changing the
    // reference obj's value

    // we are not doing obj = new IntObj() ; obj.setValue(200); which has happend
    // with the Integer

}

}

class IntObj { Integer a;

public void setVal(int a) {
    this.a = a;
}

}

How can I profile C++ code running on Linux?

If your goal is to use a profiler, use one of the suggested ones.

However, if you're in a hurry and you can manually interrupt your program under the debugger while it's being subjectively slow, there's a simple way to find performance problems.

Just halt it several times, and each time look at the call stack. If there is some code that is wasting some percentage of the time, 20% or 50% or whatever, that is the probability that you will catch it in the act on each sample. So, that is roughly the percentage of samples on which you will see it. There is no educated guesswork required. If you do have a guess as to what the problem is, this will prove or disprove it.

You may have multiple performance problems of different sizes. If you clean out any one of them, the remaining ones will take a larger percentage, and be easier to spot, on subsequent passes. This magnification effect, when compounded over multiple problems, can lead to truly massive speedup factors.

Caveat: Programmers tend to be skeptical of this technique unless they've used it themselves. They will say that profilers give you this information, but that is only true if they sample the entire call stack, and then let you examine a random set of samples. (The summaries are where the insight is lost.) Call graphs don't give you the same information, because

  1. They don't summarize at the instruction level, and
  2. They give confusing summaries in the presence of recursion.

They will also say it only works on toy programs, when actually it works on any program, and it seems to work better on bigger programs, because they tend to have more problems to find. They will say it sometimes finds things that aren't problems, but that is only true if you see something once. If you see a problem on more than one sample, it is real.

P.S. This can also be done on multi-thread programs if there is a way to collect call-stack samples of the thread pool at a point in time, as there is in Java.

P.P.S As a rough generality, the more layers of abstraction you have in your software, the more likely you are to find that that is the cause of performance problems (and the opportunity to get speedup).

Added: It might not be obvious, but the stack sampling technique works equally well in the presence of recursion. The reason is that the time that would be saved by removal of an instruction is approximated by the fraction of samples containing it, regardless of the number of times it may occur within a sample.

Another objection I often hear is: "It will stop someplace random, and it will miss the real problem". This comes from having a prior concept of what the real problem is. A key property of performance problems is that they defy expectations. Sampling tells you something is a problem, and your first reaction is disbelief. That is natural, but you can be sure if it finds a problem it is real, and vice-versa.

Added: Let me make a Bayesian explanation of how it works. Suppose there is some instruction I (call or otherwise) which is on the call stack some fraction f of the time (and thus costs that much). For simplicity, suppose we don't know what f is, but assume it is either 0.1, 0.2, 0.3, ... 0.9, 1.0, and the prior probability of each of these possibilities is 0.1, so all of these costs are equally likely a-priori.

Then suppose we take just 2 stack samples, and we see instruction I on both samples, designated observation o=2/2. This gives us new estimates of the frequency f of I, according to this:

Prior                                    
P(f=x) x  P(o=2/2|f=x) P(o=2/2&&f=x)  P(o=2/2&&f >= x)  P(f >= x | o=2/2)

0.1    1     1             0.1          0.1            0.25974026
0.1    0.9   0.81          0.081        0.181          0.47012987
0.1    0.8   0.64          0.064        0.245          0.636363636
0.1    0.7   0.49          0.049        0.294          0.763636364
0.1    0.6   0.36          0.036        0.33           0.857142857
0.1    0.5   0.25          0.025        0.355          0.922077922
0.1    0.4   0.16          0.016        0.371          0.963636364
0.1    0.3   0.09          0.009        0.38           0.987012987
0.1    0.2   0.04          0.004        0.384          0.997402597
0.1    0.1   0.01          0.001        0.385          1

                  P(o=2/2) 0.385                

The last column says that, for example, the probability that f >= 0.5 is 92%, up from the prior assumption of 60%.

Suppose the prior assumptions are different. Suppose we assume P(f=0.1) is .991 (nearly certain), and all the other possibilities are almost impossible (0.001). In other words, our prior certainty is that I is cheap. Then we get:

Prior                                    
P(f=x) x  P(o=2/2|f=x) P(o=2/2&& f=x)  P(o=2/2&&f >= x)  P(f >= x | o=2/2)

0.001  1    1              0.001        0.001          0.072727273
0.001  0.9  0.81           0.00081      0.00181        0.131636364
0.001  0.8  0.64           0.00064      0.00245        0.178181818
0.001  0.7  0.49           0.00049      0.00294        0.213818182
0.001  0.6  0.36           0.00036      0.0033         0.24
0.001  0.5  0.25           0.00025      0.00355        0.258181818
0.001  0.4  0.16           0.00016      0.00371        0.269818182
0.001  0.3  0.09           0.00009      0.0038         0.276363636
0.001  0.2  0.04           0.00004      0.00384        0.279272727
0.991  0.1  0.01           0.00991      0.01375        1

                  P(o=2/2) 0.01375                

Now it says P(f >= 0.5) is 26%, up from the prior assumption of 0.6%. So Bayes allows us to update our estimate of the probable cost of I. If the amount of data is small, it doesn't tell us accurately what the cost is, only that it is big enough to be worth fixing.

Yet another way to look at it is called the Rule Of Succession. If you flip a coin 2 times, and it comes up heads both times, what does that tell you about the probable weighting of the coin? The respected way to answer is to say that it's a Beta distribution, with average value (number of hits + 1) / (number of tries + 2) = (2+1)/(2+2) = 75%.

(The key is that we see I more than once. If we only see it once, that doesn't tell us much except that f > 0.)

So, even a very small number of samples can tell us a lot about the cost of instructions that it sees. (And it will see them with a frequency, on average, proportional to their cost. If n samples are taken, and f is the cost, then I will appear on nf+/-sqrt(nf(1-f)) samples. Example, n=10, f=0.3, that is 3+/-1.4 samples.)


Added: To give an intuitive feel for the difference between measuring and random stack sampling:
There are profilers now that sample the stack, even on wall-clock time, but what comes out is measurements (or hot path, or hot spot, from which a "bottleneck" can easily hide). What they don't show you (and they easily could) is the actual samples themselves. And if your goal is to find the bottleneck, the number of them you need to see is, on average, 2 divided by the fraction of time it takes. So if it takes 30% of time, 2/.3 = 6.7 samples, on average, will show it, and the chance that 20 samples will show it is 99.2%.

Here is an off-the-cuff illustration of the difference between examining measurements and examining stack samples. The bottleneck could be one big blob like this, or numerous small ones, it makes no difference.

enter image description here

Measurement is horizontal; it tells you what fraction of time specific routines take. Sampling is vertical. If there is any way to avoid what the whole program is doing at that moment, and if you see it on a second sample, you've found the bottleneck. That's what makes the difference - seeing the whole reason for the time being spent, not just how much.

how to bind datatable to datagridview in c#

On the DataGridView, set the DataPropertyName of the columns to your column names of your DataTable.

Git: "please tell me who you are" error

Have a look at the config file.

Repository > Repository Settings > Edit config file.

Check if the [user] section exists. If the user section is missing, add it.

Example:

[user]
name = "your name"
email = "your email"

How to convert 1 to true or 0 to false upon model fetch

All you need is convert string to int with + and convert the result to boolean with !!:

var response = {"isChecked":"1"};
response.isChecked = !!+response.isChecked

You can do this manipulation in the parse method:

parse: function (response) {
  response.isChecked = !!+response.isChecked;
  return response;
}

UPDATE: 7 years later, I find Number(string) conversion more elegant. Also mutating an object is not the best idea. That being said:

parse: function (response) {
  return Object.assign({}, response, {
    isChecked: !!Number(response.isChecked), // OR
    isChecked: Boolean(Number(response.isChecked))
  });
}

Should I use the Reply-To header when sending emails as a service to others?

After reading all of this, I might just embed a hyperlink in the email body like this:

To reply to this email, click here <a href="mailto:...">[email protected]</a>

How to upload a file and JSON data in Postman?

If somebody needed:

body -> form-data

Add field name as array

enter image description here

Spring 3 MVC accessing HttpRequest from controller

I know that is a old question, but...

You can also use this in your class:

@Autowired
private HttpServletRequest context;

And this will provide the current instance of HttpServletRequest for you use on your method.

CSS image resize percentage of itself?

HTML:

<span>
    <img src="example.png"/>
</span>

CSS:

span {
    display: inline-block;
}
img {
    width: 50%;
}

This has got to be one of the simplest solutions using the container element approach.

When using the container element approach, this question is a variation of this question. The trick is to let the container element shrinkwrap the child image, so it will have a size equal to that of the unsized image. Thus, when setting width property of the image as a percentage value, the image is scaled relative to its original scale.

Some of the other shrinkwrapping-enabling properties and property values are: float: left/right, position: fixed and min/max-width, as mentioned in the linked question. Each has its own side-effects, but display: inline-block would be a safer choice. Matt has mentioned float: left/right in his answer, but he wrongly attributed it to overflow: hidden.

Demo on jsfiddle


Edit: As mentioned by trojan, you can also take advantage of the newly introduced CSS3 intrinsic & extrinsic sizing module:

HTML:

<figure>
    <img src="example.png"/>
</figure>

CSS:

figure {
    width: intrinsic;
}
img {
    width: 50%;
}

However, not all popular browser versions support it at the time of writing.

How do I count a JavaScript object's attributes?

Although it wouldn't be a "true object", you could always do something like this:

var foo = [
  {Key1: "key1"},
  {Key2: "key2"},
  {Key3: "key3"}
];

alert(foo.length); // === 3

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

Generally, the answer to your question is no, you cannot define more than one externally visible function per file. You can return function handles to local functions, though, and a convenient way to do so is to make them fields of a struct. Here is an example:

function funs = makefuns
  funs.fun1=@fun1;
  funs.fun2=@fun2;
end

function y=fun1(x)
  y=x;
end

function z=fun2
  z=1;
end

And here is how it could be used:

>> myfuns = makefuns;
>> myfuns.fun1(5)    
ans =
     5
>> myfuns.fun2()     
ans =
     1

CASE WHEN statement for ORDER BY clause

declare @OrderByCmd  nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'    
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd 

Using OpenGl with C#?

OpenTK is an improvement over the Tao API, as it uses idiomatic C# style with overloading, strongly-typed enums, exceptions, and standard .NET types:

GL.Begin(BeginMode.Points);
GL.Color3(Color.Yellow);
GL.Vertex3(Vector3.Up);

as opposed to Tao which merely mirrors the C API:

Gl.glBegin(Gl.GL_POINTS);   // double "gl" prefix
Gl.glColor3ub(255, 255, 0); // have to pass RGB values as separate args
Gl.glVertex3f(0, 1, 0);     // explicit "f" qualifier

This makes for harder porting but is incredibly nice to use.

As a bonus it provides font rendering, texture loading, input handling, audio, math...

Update 18th January 2016: Today the OpenTK maintainer has stepped away from the project, leaving its future uncertain. The forums are filled with spam. The maintainer recommends moving to MonoGame or SDL2#.

Update 30th June 2020: OpenTK has had new maintainers for a while now and has an active discord community. So the previous recommendation of using another library isn't necessarily true.

Convert js Array() to JSon object for use with JQuery .ajax

You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:

var a = [];
for (key in saveData) {
    a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

In bash, how to store a return value in a variable?

It's due to the echo statements. You could switch your echos to prints and return with an echo. Below works

#!/bin/bash

set -x
echo "enter: "
read input

function password_formula
{
        length=${#input}
        last_two=${input:length-2:length}
        first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
        second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
        let sum=$first+$second
        sum_len=${#sum}
        print $second
        print $sum

        if [ $sum -gt 9 ]
        then
           sum=${sum:1}
        fi

        value=$second$sum$first
        echo $value
}
result=$(password_formula)
echo $result

No resource found that matches the given name '@style/Theme.AppCompat.Light'

Below are the steps you can try it out to resolve the issue: -

  1. Provide reference of AppCompat Library into your project.
  2. If option 1 doesn't solve the issue then you can try to change the style.xml file to below code.
 parent="android:Theme.Holo.Light"  

instead.

 parent="android:Theme.AppCompat.Light"  

But option 2 will require minimum sdk version 14.

Hope this will help !

Summved

How to trigger checkbox click event even if it's checked through Javascript code?

Getting check status

var checked = $("#selectall").is(":checked");

Then for setting

$("input:checkbox").attr("checked",checked);

Create view with primary key?

You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also. Applications requiring a primary key may accept the view as it is the case with Lightswitch.

Do you know the Maven profile for mvnrepository.com?

mvnrepository.com isn't a repository. It's a search engine. It might or might not tell you what repository it found stuff in if it's not central; since you didn't post an example, I can't help you read the output.

Keras, How to get the output of each layer?

I wrote this function for myself (in Jupyter) and it was inspired by indraforyou's answer. It will plot all the layer outputs automatically. Your images must have a (x, y, 1) shape where 1 stands for 1 channel. You just call plot_layer_outputs(...) to plot.

%matplotlib inline
import matplotlib.pyplot as plt
from keras import backend as K

def get_layer_outputs():
    test_image = YOUR IMAGE GOES HERE!!!
    outputs    = [layer.output for layer in model.layers]          # all layer outputs
    comp_graph = [K.function([model.input]+ [K.learning_phase()], [output]) for output in outputs]  # evaluation functions

    # Testing
    layer_outputs_list = [op([test_image, 1.]) for op in comp_graph]
    layer_outputs = []

    for layer_output in layer_outputs_list:
        print(layer_output[0][0].shape, end='\n-------------------\n')
        layer_outputs.append(layer_output[0][0])

    return layer_outputs

def plot_layer_outputs(layer_number):    
    layer_outputs = get_layer_outputs()

    x_max = layer_outputs[layer_number].shape[0]
    y_max = layer_outputs[layer_number].shape[1]
    n     = layer_outputs[layer_number].shape[2]

    L = []
    for i in range(n):
        L.append(np.zeros((x_max, y_max)))

    for i in range(n):
        for x in range(x_max):
            for y in range(y_max):
                L[i][x][y] = layer_outputs[layer_number][x][y][i]


    for img in L:
        plt.figure()
        plt.imshow(img, interpolation='nearest')

python 2 instead of python 3 as the (temporary) default python?

You don't want a "temporary default Python"

You want the 2.7 scripts to start with

/usr/bin/env python2.7

And you want the 3.2 scripts to begin with

/usr/bin/env python3.2

There's really no use for a "default" Python. And the idea of a "temporary default" is just a road to absolute confusion.

Remember.

Explicit is better than Implicit.

incompatible character encodings: ASCII-8BIT and UTF-8

I had the same problem when parsing CSV files on Ruby 1.9.2 that were correctly parsed on Ruby 1.8. I found the answer here. When opening the CSV file with Ruby CSV module it is necessary to specify UTF-8 enconding as following:

CSV.foreach("file.txt", encoding: "UTF-8") do |row|
   # foo and bar correctly encoded
   foo, bar, ... = row
end

React-Router: No Not Found Route?

I just had a quick look at your example, but if i understood it the right way you're trying to add 404 routes to dynamic segments. I had the same issue a couple of days ago, found #458 and #1103 and ended up with a hand made check within the render function:

if (!place) return <NotFound />;

hope that helps!

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I believe the id accessors don't match the bean naming conventions and that's why the exception is thrown. They should be as follows:

public Integer getId() { return id; }    
public void setId(Integer i){ id= i; }

Rails 4: List of available datatypes

Rails4 has some added datatypes for Postgres.

For example, railscast #400 names two of them:

Rails 4 has support for native datatypes in Postgres and we’ll show two of these here, although a lot more are supported: array and hstore. We can store arrays in a string-type column and specify the type for hstore.

Besides, you can also use cidr, inet and macaddr. For more information:

https://blog.engineyard.com/2013/new-in-rails-4

Change One Cell's Data in mysql

You probably need to specify which rows you want to update...

UPDATE 
    mytable
SET 
    column1 = value1,
    column2 = value2
WHERE 
    key_value = some_value;