Programs & Examples On #Launchpad

Launchpad is a unique collaboration and hosting platform for software projects.

Issue in installing php7.2-mcrypt

Mcrypt PECL extenstion

 sudo apt-get -y install gcc make autoconf libc-dev pkg-config
 sudo apt-get -y install libmcrypt-dev
 sudo pecl install mcrypt-1.0.1

When you are shown the prompt

 libmcrypt prefix? [autodetect] :

Press [Enter] to autodetect.

After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.

The output will look like this:

...
Build process completed successfully
Installing '/usr/lib/php/20170718/mcrypt.so'    ---->   this is our path to mcrypt extension lib
install ok: channel://pecl.php.net/mcrypt-1.0.1
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini

Grab installing path and add to cli and apache2 php.ini configuration.

sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"

Verify that the extension was installed

Run command:

php -i | grep "mcrypt"

The output will look like this:

/etc/php/7.2/cli/conf.d/mcrypt.ini
Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value

PHP 7 RC3: How to install missing MySQL PDO

Had the same issue, resolved by actually enabling the extension in the php.ini with the right file name. It was listed as php_pdo_mysql.so but the module name in /lib/php/modules was called just pdo_mysql.so

So just remove the "php_" prefix from the php.ini file and then restart the httpd service and it worked like a charm.

Please note that I'm using Arch and thus path names and services may be different depending on your distrubution.

How to decode a QR-code image in (preferably pure) Python?

I'm answering only the part of the question about zbar installation.

I spent nearly half an hour a few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:

PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.

PS2: I just tested pyzbar with pip install pyzbar and it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

While ln -s is the obvious easiest fix, a piece of explanation:

Because of a conflict with another package, the executable from the Ubuntu repositories is called nodejs instead of node. Keep this in mind as you are running software.

This advice comes up, when installing sudo apt-get install nodejs.

So some other known tool (I don't know what it does. While being known to ubuntu repositories, it is not installed by default in 16.04) occupies that namespace.

Would have been nice, if Ubuntu had offered an advice how to fix this 'cleanly', if not by doing by hand what otherwise the package would do. (a collision remains a collision... if+when it would occur)

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

In GNU/Linux you can use this command

 /etc/init.d/virtualbox

Options

  • start
  • stop
  • stop_vms
  • restart
  • force-reload
  • status

for example

 /etc/init.d/virtualbox force-reload

Good Luck

Font is not available to the JVM with Jasper Reports

JasperReports raises a JRFontNotFoundException in the case where the font used inside a report template is not available to the JVM as either as a system font or a font coming from a JR font extension. This ensure that all problems caused by font metrics mismatches are avoided and we have an early warning about the inconsistency.

Jasper reports is trying to help you in your report development, stating that it can not export your report correctly since it can not find the font defined in TextField or StaticText

<font fontName="Arial"/>

Yes you can disable this by setting net.sf.jasperreports.awt.ignore.missing.font to true but you will have export inconsistencies.

Yes you can install the font as JVM system font (but you need to do it on every PC used that may generate report and you can still have encoding problems).

The correct way!

Use Font Extensions!, if you like to create your own (see link below), jasper reports also distributes a default font-extension jar (jasperreports-fonts-x.x.x.jar), that supports fontName DejaVu Sans, DejaVu Serif and DejaVu Sans Mono

<font fontName="DejaVu Sans"/>

From the JasperReport Ultimate Guide:

We strongly encourage people to use only fonts derived from font extensions, because this is the only way to make sure that the fonts will be available to the application when the reports are executed at runtime. Using system fonts always brings the risk for the reports not to work properly when deployed on a new machine that might not have those fonts installed

Links on StackOverflow on how to render fonts correctly in pdf

Checklist on how to render font correctly in pdf

Generate font-extensions with JasperSoft Studio

Generate font-extensions with iReport

Compare two MySQL databases

For the first part of the question, I just do a dump of both and diff them. Not sure about mysql, but postgres pg_dump has a command to just dump the schema without the table contents, so you can see if you've changed the schema any.

How to create a RelativeLayout programmatically with two buttons one on top of the other?

public class AndroidWalkthroughApp1 extends Activity implements View.OnClickListener {

    final int TOP_ID = 3;
    final int BOTTOM_ID = 4;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // create two layouts to hold buttons
        RelativeLayout top = new RelativeLayout(this);
        top.setId(TOP_ID);
        RelativeLayout bottom = new RelativeLayout(this);
        bottom.setId(BOTTOM_ID);

        // create buttons in a loop
        for (int i = 0; i < 2; i++) {
            Button button = new Button(this);
            button.setText("Button " + i);
            // R.id won't be generated for us, so we need to create one
            button.setId(i);

            // add our event handler (less memory than an anonymous inner class)
            button.setOnClickListener(this);

            // add generated button to view
            if (i == 0) {
                top.addView(button);
            }
            else {
                bottom.addView(button);
            }
        }

        RelativeLayout root = (RelativeLayout) findViewById(R.id.root_layout);

        // add generated layouts to root layout view
       // LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);

        root.addView(top);
        root.addView(bottom);
    }

    @Override
    public void onClick(View v) {
        // show a message with the button's ID
        Toast toast = Toast.makeText(AndroidWalkthroughApp1.this, "You clicked button " + v.getId(), Toast.LENGTH_LONG);
        toast.show();

        // get the parent layout and remove the clicked button
        RelativeLayout parentLayout = (RelativeLayout)v.getParent();
        parentLayout.removeView(v);



    }
}

Finding non-numeric rows in dataframe in pandas?

# Original code
df = pd.DataFrame({'a': [1, 2, 3, 'bad', 5],
                   'b': [0.1, 0.2, 0.3, 0.4, 0.5],
                   'item': ['a', 'b', 'c', 'd', 'e']})
df = df.set_index('item')

Convert to numeric using 'coerce' which fills bad values with 'nan'

a = pd.to_numeric(df.a, errors='coerce')

Use isna to return a boolean index:

idx = a.isna()

Apply that index to the data frame:

df[idx]

output

Returns the row with the bad data in it:

        a    b
item          
d     bad  0.4

Why use #define instead of a variable

I got in trouble at work one time. I was accused of using "magic numbers" in array declarations.

Like this:

int Marylyn[256], Ann[1024];

The company policy was to avoid these magic numbers because, it was explained to me, that these numbers were not portable; that they impeded easy maintenance. I argued that when I am reading the code, I want to know exactly how big the array is. I lost the argument and so, on a Friday afternoon I replaced the offending "magic numbers" with #defines, like this:

 #define TWO_FIFTY_SIX 256
 #define TEN_TWENTY_FOUR 1024

 int Marylyn[TWO_FIFTY_SIX], Ann[TEN_TWENTY_FOUR];

On the following Monday afternoon I was called in and accused of having passive defiant tendencies.

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

Convert a space delimited string to list

try

states.split()

it returns the list

['Alaska',
 'Alabama',
 'Arkansas',
 'American',
 'Samoa',
 'Arizona',
 'California',
 'Colorado']

and this returns the random element of the list

import random
random.choice(states.split())

split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example

states.split('Ari')

returns

['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']

Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here

I see you are probably new to python, so I'd give you some advice how to use python's great documentation

Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language

I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this

How do I manually configure a DataSource in Java?

use MYSQL as Example: 1) use database connection pools: for Example: Apache Commons DBCP , also, you need basicDataSource jar package in your classpath

@Bean
public BasicDataSource dataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/gene");
    ds.setUsername("root");
    ds.setPassword("root");
    return ds;
}

2)use JDBC-based Driver it is usually used if you don't consider connection pool:

@Bean
public DataSource dataSource(){
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/gene");
    ds.setUsername("root");
    ds.setPassword("root");
    return ds;
}

How to concatenate strings in a Windows batch file?

Note that the variables @fname or @ext can be simply concatenated. This:

forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"

renames all PDF files to "filename_old.pdf"

Sqlite in chrome

You might be able to make use of sql.js.

sql.js is a port of SQLite to JavaScript, by compiling the SQLite C code with Emscripten. no C bindings or node-gyp compilation here.

<script src='js/sql.js'></script>
<script>
    //Create the database
    var db = new SQL.Database();
    // Run a query without reading the results
    db.run("CREATE TABLE test (col1, col2);");
    // Insert two rows: (1,111) and (2,222)
    db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]);

    // Prepare a statement
    var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
    stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}

    // Bind new values
    stmt.bind({$start:1, $end:2});
    while(stmt.step()) { //
        var row = stmt.getAsObject();
        // [...] do something with the row of result
    }
</script>

sql.js is a single JavaScript file and is about 1.5MiB in size currently. While this could be a problem in a web-page, the size is probably acceptable for an extension.

Grant SELECT on multiple tables oracle

This worked for me on my Oracle database:

SELECT   'GRANT SELECT, insert, update, delete ON mySchema.' || TABLE_NAME || ' to myUser;'
FROM     user_tables
where table_name like 'myTblPrefix%'

Then, copy the results, paste them into your editor, then run them like a script.

You could also write a script and use "Execute Immediate" to run the generated SQL if you don't want the extra copy/paste steps.

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.

To fix it you just need to make your GetRandomBits() method static as well.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

In my case I was launching a WKWebView and displaying a website. Then (within 25 seconds) I deallocated the WKWebView. But 25-60 seconds after launching the WKWebView I received this "113" error message. I assume the system was trying to signal something to the WKWebView and couldn't find it because it was deallocated.

The fix was simply to leave the WKWebView allocated.

Overloading and overriding

I want to share an example which made a lot sense to me when I was learning:

This is just an example which does not include the virtual method or the base class. Just to give a hint regarding the main idea.

Let's say there is a Vehicle washing machine and it has a function called as "Wash" and accepts Car as a type.

Gets the Car input and washes the Car.

public void Wash(Car anyCar){
       //wash the car
}

Let's overload Wash() function

Overloading:

public void Wash(Truck anyTruck){
   //wash the Truck  
}

Wash function was only washing a Car before, but now its overloaded to wash a Truck as well.

  • If the provided input object is a Car, it will execute Wash(Car anyCar)
  • If the provided input object is a Truck, then it will execute Wash(Truck anyTruck)

Let's override Wash() function

Overriding:

public override void Wash(Car anyCar){
   //check if the car has already cleaned
   if(anyCar.Clean){ 
       //wax the car
   }
   else{
       //wash the car
       //dry the car
       //wax the car
   }     
}

Wash function now has a condition to check if the Car is already clean and not need to be washed again.

  • If the Car is clean, then just wax it.

  • If not clean, then first wash the car, then dry it and then wax it

.

So the functionality has been overridden by adding a new functionality or do something totally different.

PHP preg_match - only allow alphanumeric strings and - _ characters

\w\- is probably the best but here just another alternative
Use [:alnum:]

if(!preg_match("/[^[:alnum:]\-_]/",$str)) echo "valid";

demo1 | demo2

Finding multiple occurrences of a string within a string in Python

A simple iterative code which returns a list of indices where the substring occurs.

        def allindices(string, sub):
           l=[]
           i = string.find(sub)
           while i >= 0:
              l.append(i)
              i = string.find(sub, i + 1)
           return l

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

The active firewall on the server might be causing this. You can try to (temporarily) turn it off and see if it resolves the issue.

If it is indeed caused by the firewall, you should allegedly be able to resolve it by adding an inbound rule for TCP port 1433 set to allowed, but I personally haven't been able to connect this way.

Compare a string using sh shell

eq is used to compare integers use equal '=' instead , example:

if [ 'AAA' = 'ABC' ];
then 
    echo "the same" 
else 
    echo "not the same"
fi

good luck

Disabling and enabling a html input button

Without jQuery disable input will be simpler

Button.disabled=1;

_x000D_
_x000D_
function dis() {_x000D_
  Button.disabled= !Button.disabled;_x000D_
}
_x000D_
<input id="Button" type="button" value="+" style="background-color:grey" onclick="Me();"/>_x000D_
_x000D_
<button onclick="dis()">Toggle disable</button>
_x000D_
_x000D_
_x000D_

How to get local server host and port in Spring Boot?

I have just found a way to get server ip and port easily by using Eureka client library. As I am using it anyway for service registration, it is not an additional lib for me just for this purpose.

You need to add the maven dependency first:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

Then you can use the ApplicationInfoManager service in any of your Spring beans.

@Autowired
private ApplicationInfoManager applicationInfoManager;
...

InstanceInfo applicationInfo = applicationInfoManager.getInfo();

The InstanceInfo object contains all important information about your service, like IP address, port, hostname, etc.

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

If you want the editor to work with git operations, setting the $EDITOR environment variable may not be enough, at least not in the case of Sublime - e.g. if you want to rebase, it will just say that the rebase was successful, but you won't have a chance to edit the file in any way, git will just close it straight away:

git rebase -i HEAD~
Successfully rebased and updated refs/heads/master.

If you want Sublime to work correctly with git, you should configure it using:

git config --global core.editor "sublime -n -w"

I came here looking for this and found the solution in this gist on github.

Password encryption at client side

This won't be secure, and it's simple to explain why:

If you hash the password on the client side and use that token instead of the password, then an attacker will be unlikely to find out what the password is.

But, the attacker doesn't need to find out what the password is, because your server isn't expecting the password any more - it's expecting the token. And the attacker does know the token because it's being sent over unencrypted HTTP!

Now, it might be possible to hack together some kind of challenge/response form of encryption which means that the same password will produce a different token each request. However, this will require that the password is stored in a decryptable format on the server, something which isn't ideal, but might be a suitable compromise.

And finally, do you really want to require users to have javascript turned on before they can log into your website?

In any case, SSL is neither an expensive or especially difficult to set up solution any more

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

One more method is to Define the Layout inside the View:

   @{
    Layout = "~/Views/Shared/_MyAdminLayout.cshtml";
    }

More Ways to do, can be found here, hope this helps someone.

SimpleDateFormat and locale based format string

Use the style + locale: DateFormat.getDateInstance(int style, Locale locale)

Check http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html

Run the following example to see the differences:

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

public class DateFormatDemoSO {
  public static void main(String args[]) {
    int style = DateFormat.MEDIUM;
    //Also try with style = DateFormat.FULL and DateFormat.SHORT
    Date date = new Date();
    DateFormat df;
    df = DateFormat.getDateInstance(style, Locale.UK);
    System.out.println("United Kingdom: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.US);
    System.out.println("USA: " + df.format(date));   
    df = DateFormat.getDateInstance(style, Locale.FRANCE);
    System.out.println("France: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.ITALY);
    System.out.println("Italy: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.JAPAN);
    System.out.println("Japan: " + df.format(date));
  }
}

Output:

United Kingdom: 25-Sep-2017
USA: Sep 25, 2017
France: 25 sept. 2017
Italy: 25-set-2017
Japan: 2017/09/25

Displaying the Indian currency symbol on a website

best way copy the ? symbol and paste it.

Getting full JS autocompletion under Sublime Text

As of today (November 2019), Microsoft's TypeScript plugin does what the OP required: https://packagecontrol.io/packages/TypeScript.

Calculate difference between two datetimes in MySQL

If your start and end datetimes are on different days use TIMEDIFF.

SELECT TIMEDIFF(datetime1,datetime2)

if datetime1 > datetime2 then

SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")

gives: 24:01:00

and datetime1 < datetime2

SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")

gives: -24:01:00

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

you don't - not like this. give an id to your tag , lets say it looks like this now :

<h3 id="myHeader"></h3>

then set the value like that :

myHeader.innerText = "public offers";

Vim: faster way to select blocks of text in visual mode

} means move cursor to next paragraph. so, use v} to select entire paragraph.

Git: How configure KDiff3 as merge tool and diff tool

I needed to add the command line parameters or KDiff3 would only open without files and prompt me for base, local and remote. I used the version supplied with TortoiseHg.

Additionally, I needed to resort to the good old DOS 8.3 file names.

[merge]
    tool = kdiff3

[mergetool "kdiff3"]
    cmd = /c/Progra~1/TortoiseHg/lib/kdiff3.exe $BASE $LOCAL $REMOTE -o $MERGED

However, it works correctly now.

CSS body background image fixed to full screen even when zooming in/out

Add this in your css file:

.custom_class
 {
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
 }

and then, in your .html (or .php) file call this class like that:

<div class="custom_class">
   ...
</div>

Javascript to display the current date and time

To return the client side date you can use the following javascript:

var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;

or in jQuery:

var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
$('#date').html(date);

equivalent to following PHP:

<?php date("j.n.Y"); ?>

To get equivalent to the following PHP (i.e. leading 0's):

<?php date("d.m.Y"); ?>

JavaScript:

var d = new Date();
var day = d.getDate();
var month = d.getMonth()+1;

if(day < 10){
    day = "0"+d.getDate();
}

if(month < 10){
    month = "0"+eval(d.getMonth()+1);
}

var date = day+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;

jQuery:

var d = new Date();
var day = d.getDate();
var month = d.getMonth()+1;

if(day < 10){
    day = "0"+d.getDate();
}

if(month < 10){
    month = "0"+eval(d.getMonth()+1);
}

var date = day+"."+month+"."+d.getFullYear();
$('#date').html(date);

Best way to do multi-row insert in Oracle?

Cursors may also be used, although it is inefficient. The following stackoverflow post discusses the usage of cursors :

INSERT and UPDATE a record using cursors in oracle

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I had a same issue. It was working fine on the local machine but it had issues on the server. I have changed the SMTP setting. It works fine for me.

If you're using GoDaddy Plesk Hosting, use the following SMTP details.

Host = relay-hosting.secureserver.net
Port = 25 

How can I pair socks from a pile efficiently?

I've finished pairing my socks just right now, and I found that the best way to do it is the following:

  • Choose one of the socks and put it away (create a 'bucket' for that pair)
  • If the next one is the pair of the previous one, then put it to the existing bucket, otherwise create a new one.

In the worst case it means that you will have n/2 different buckets, and you will have n-2 determinations about that which bucket contains the pair of the current sock. Obviously, this algorithm works well if you have just a few pairs; I did it with 12 pairs.

It is not so scientific, but it works well:)

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

That information is stored in the ALL_TAB_COLUMNS system table:

SQL> select column_name from all_tab_columns where table_name = 'DUAL';

DUMMY

Or you could DESCRIBE the table if you are using SQL*PLUS:

SQL> desc dual
Name                               Null?    Type
----------------------------------------------------- -------- ---------------------- -------------
DUMMY                               VARCHAR2(1)

C# nullable string error

string cannot be the parameter to Nullable because string is not a value type. String is a reference type.

string s = null; 

is a very valid statement and there is not need to make it nullable.

private string typeOfContract
    {
      get { return ViewState["typeOfContract"] as string; }
      set { ViewState["typeOfContract"] = value; }
    }

should work because of the as keyword.

Fastest way to count exact number of rows in a very large table?

If SQL Server edition is 2005/2008, you can use DMVs to calculate the row count in a table:

-- Shows all user tables and row counts for the current database 
-- Remove is_ms_shipped = 0 check to include system objects 
-- i.index_id < 2 indicates clustered index (1) or hash table (0) 
SELECT o.name, 
 ddps.row_count 
FROM sys.indexes AS i 
 INNER JOIN sys.objects AS o ON i.OBJECT_ID = o.OBJECT_ID 
 INNER JOIN sys.dm_db_partition_stats AS ddps ON i.OBJECT_ID = ddps.OBJECT_ID 
 AND i.index_id = ddps.index_id 
WHERE i.index_id < 2 
 AND o.is_ms_shipped = 0 
ORDER BY o.NAME 

For SQL Server 2000 database engine, sysindexes will work, but it is strongly advised to avoid using it in future editions of SQL Server as it may be removed in the near future.

Sample code taken from: How To Get Table Row Counts Quickly And Painlessly

How to use UIVisualEffectView to Blur Image?

Just put this blur view on the imageView. Here is an example in Objective-C:

UIVisualEffect *blurEffect;
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];

UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];

visualEffectView.frame = imageView.bounds;
[imageView addSubview:visualEffectView];

and Swift:

var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))    

visualEffectView.frame = imageView.bounds

imageView.addSubview(visualEffectView)

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

How to force Chrome's script debugger to reload javascript?

If you're running a local server on Apache, you can get what look like caching problems. This happened to me when I had a Apache server running under Vagrant (in virtualbox).

Just add the following lines to your config file (/etc/httpd/conf/httpd.conf or equivalent):

#Disable image serving for network mounted drive
EnableSendfile off

Note that it's worth searching through the config file to see if EnableSendfile is set to on anywhere else.

Why can't I define a static method in a Java interface?

Well, without generics, static interfaces are useless because all static method calls are resolved at compile time. So, there's no real use for them.

With generics, they have use -- with or without a default implementation. Obviously there would need to be overriding and so on. However, my guess is that such usage wasn't very OO (as the other answers point out obtusely) and hence wasn't considered worth the effort they'd require to implement usefully.

How do I reset a sequence in Oracle?

Altering the sequence's INCREMENT value, incrementing it, and then altering it back is pretty painless, plus you have the added benefit of not having to re-establish all of the grants as you would had you dropped/recreated the sequence.

Difference between DataFrame, Dataset, and RDD in Spark

Because DataFrame is weakly typed and developers aren't getting the benefits of the type system. For example, lets say you want to read something from SQL and run some aggregation on it:

val people = sqlContext.read.parquet("...")
val department = sqlContext.read.parquet("...")

people.filter("age > 30")
  .join(department, people("deptId") === department("id"))
  .groupBy(department("name"), "gender")
  .agg(avg(people("salary")), max(people("age")))

When you say people("deptId"), you're not getting back an Int, or a Long, you're getting back a Column object which you need to operate on. In languages with a rich type systems such as Scala, you end up losing all the type safety which increases the number of run-time errors for things that could be discovered at compile time.

On the contrary, DataSet[T] is typed. when you do:

val people: People = val people = sqlContext.read.parquet("...").as[People]

You're actually getting back a People object, where deptId is an actual integral type and not a column type, thus taking advantage of the type system.

As of Spark 2.0, the DataFrame and DataSet APIs will be unified, where DataFrame will be a type alias for DataSet[Row].

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I am using apache (xampp) on my dev environment and apache on the production, add:

errorDocument 404 /index.html

to the .htaccess solve for me this issue.

git-diff to ignore ^M

Why do you get these ^M in your git diff?

In my case I was working on a project which was developed in Windows and I used OS X. When I changed some code, I saw ^M at the end of the lines I added in git diff. I think the ^M were showing up because they were different line endings than the rest of the file. Because the rest of the file was developed in Windows it used CR line endings, and in OS X it uses LF line endings.

Apparently, the Windows developer didn't use the option "Checkout Windows-style, commit Unix-style line endings" during the installation of Git.

So what should we do about this?

You can have the Windows users reinstall git and use the "Checkout Windows-style, commit Unix-style line endings" option. This is what I would prefer, because I see Windows as an exception in its line ending characters and Windows fixes its own issue this way.

If you go for this option, you should however fix the current files (because they're still using the CR line endings). I did this by following these steps:

  1. Remove all files from the repository, but not from your filesystem.

    git rm --cached -r .
    
  2. Add a .gitattributes file that enforces certain files to use a LF as line endings. Put this in the file:

    *.ext text eol=crlf
    

    Replace .ext with the file extensions you want to match.

  3. Add all the files again.

    git add .
    

    This will show messages like this:

    warning: CRLF will be replaced by LF in <filename>.
    The file will have its original line endings in your working directory.
    
  4. You could remove the .gitattributes file unless you have stubborn Windows users that don't want to use the "Checkout Windows-style, commit Unix-style line endings" option.

  5. Commit and push it all.

  6. Remove and checkout the applicable files on all the systems where they're used. On the Windows systems, make sure they now use the "Checkout Windows-style, commit Unix-style line endings" option. You should also do this on the system where you executed these tasks because when you added the files git said:

    The file will have its original line endings in your working directory.
    

    You can do something like this to remove the files:

    git ls | grep ".ext$" | xargs rm -f
    

    And then this to get them back with the correct line endings:

    git ls | grep ".ext$" | xargs git checkout
    

    Of course replacing .ext with the extension you want.

Now your project only uses LF characters for the line endings, and the nasty CR characters won't ever come back :).

The other option is to enforce windows style line endings. You can also use the .gitattributes file for this.

More info: https://help.github.com/articles/dealing-with-line-endings/#platform-all

How to set the height of table header in UITableView?

It works with me only if I set the footer/header of the tableview to nil first:

self.footer = self.searchTableView.tableFooterView;
CGRect frame = self.footer.frame;
frame.size.height = 200;
self.footer.frame = frame;
self.searchTableView.tableFooterView = nil;
self.searchTableView.tableFooterView = self.footer;

Make sure that self.footer is a strong reference to prevent the footer view from being deallocated

Can iterators be reset in Python?

Problem

I've had the same issue before. After analyzing my code, I realized that attempting to reset the iterator inside of loops slightly increases the time complexity and it also makes the code a bit ugly.

Solution

Open the file and save the rows to a variable in memory.

# initialize list of rows
rows = []

# open the file and temporarily name it as 'my_file'
with open('myfile.csv', 'rb') as my_file:

    # set up the reader using the opened file
    myfilereader = csv.DictReader(my_file)

    # loop through each row of the reader
    for row in myfilereader:
        # add the row to the list of rows
        rows.append(row)

Now you can loop through rows anywhere in your scope without dealing with an iterator.

Python, how to check if a result set is empty?

I had a similar problem when I needed to make multiple sql queries. The problem was that some queries did not return the result and I wanted to print that result. And there was a mistake. As already written, there are several solutions.

if cursor.description is None:
    # No recordset for INSERT, UPDATE, CREATE, etc
    pass
else:
    # Recordset for SELECT

As well as:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists

One of the solutions is:

The try and except block lets you handle the error/exceptions. The finally block lets you execute code, regardless of the result of the try and except blocks. So the presented problem can be solved by using it.

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))

output:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************

The example above only presents a simple use as an idea that could help with your solution. Of course, you should also pay attention to other errors, such as the correctness of the query, etc.

How do you find out the caller function in JavaScript?

2018 Update

caller is forbidden in strict mode. Here is an alternative using the (non-standard) Error stack.

The following function seems to do the job in Firefox 52 and Chrome 61-71 though its implementation makes a lot of assumptions about the logging format of the two browsers and should be used with caution, given that it throws an exception and possibly executes two regex matchings before being done.

_x000D_
_x000D_
'use strict';_x000D_
const fnNameMatcher = /([^(]+)@|at ([^(]+) \(/;_x000D_
_x000D_
function fnName(str) {_x000D_
  const regexResult = fnNameMatcher.exec(str);_x000D_
  return regexResult[1] || regexResult[2];_x000D_
}_x000D_
_x000D_
function log(...messages) {_x000D_
  const logLines = (new Error().stack).split('\n');_x000D_
  const callerName = fnName(logLines[1]);_x000D_
_x000D_
  if (callerName !== null) {_x000D_
    if (callerName !== 'log') {_x000D_
      console.log(callerName, 'called log with:', ...messages);_x000D_
    } else {_x000D_
      console.log(fnName(logLines[2]), 'called log with:', ...messages);_x000D_
    }_x000D_
  } else {_x000D_
    console.log(...messages);_x000D_
  }_x000D_
}_x000D_
_x000D_
function foo() {_x000D_
  log('hi', 'there');_x000D_
}_x000D_
_x000D_
(function main() {_x000D_
  foo();_x000D_
}());
_x000D_
_x000D_
_x000D_

Can I add a custom attribute to an HTML tag?

The jQuery data() function allows you to associate arbitrary data with DOM elements. Here's an example.

PHP - cannot use a scalar as an array warning

The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:

$data = [
"rs" => null
]

this above will work absolutely fine when used like:

$data["rs"] =  5;

But the below will throw a warning ::

$data = [
    "rs" => [
       "rs1" => null;
       ]
    ]
..

$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array

Convert NSDate to String in iOS Swift

DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:

extension Date {  
  func asString(style: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = style
    return dateFormatter.string(from: self)
  }
}

This gives you the following styles:

short, medium, long, full

Example usage:

let myDate = Date()
myDate.asString(style: .full)   // Wednesday, January 10, 2018
myDate.asString(style: .long)   // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short)  // 1/10/18

Table Height 100% inside Div element

to set height of table to its container I must do:

1) set "position: absolute"

2) remove redundant contents of cells (!)

The service cannot accept control messages at this time

I kept having this problem whenever I tried to start an app pool more than once. Rather than rebooting, I simply run the Application Information Service. (Note: This service is set to run manually on my system, which may be the reason for the problem.) From its description, it seems obvious that it is somehow involved:

Facilitates the running of interactive applications with additional administrative privileges. If this service is stopped, users will be unable to launch applications with the additional administrative privileges they may require to perform desired user tasks.

Presumably, IIS manager (as well as most other processes running as an administrator) does not maintain admin privileges throughout the life of the process, but instead request admin rights from the Application Information service on a case-by-case basis.

Source: social.technech.microsoft.com

Eclipse: How do you change the highlight color of the currently selected method/expression?

After running around in the Preferences dialog, the following is the location at which the highlight color for "occurrences" can be changed:

General -> Editors -> Text Editors -> Annotations

Look for Occurences from the Annotation types list.

Then, be sure that Text as highlighted is selected, then choose the desired color.


And, a picture is worth a thousand words...

Preferences dialog
(source: coobird.net)

Image showing occurences highlighted in orange.
(source: coobird.net)

What does -> mean in Python function definitions?

def f(x) -> 123:
    return x

My summary:

  1. Simply -> is introduced to get developers to optionally specify the return type of the function. See Python Enhancement Proposal 3107

  2. This is an indication of how things may develop in future as Python is adopted extensively - an indication towards strong typing - this is my personal observation.

  3. You can specify types for arguments as well. Specifying return type of the functions and arguments will help in reducing logical errors and improving code enhancements.

  4. You can have expressions as return type (for both at function and parameter level) and the result of the expressions can be accessed via annotations object's 'return' attribute. annotations will be empty for the expression/return value for lambda inline functions.

What does the star operator mean, in a function call?

One small point: these are not operators. Operators are used in expressions to create new values from existing values (1+2 becomes 3, for example. The * and ** here are part of the syntax of function declarations and calls.

Fastest way to zero out a 2d array in C?

You can try this

int array[20,30] = {{0}};

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

Only for using as a value:

x = 3 if a==2 else 0

or

return 3 if a==2 else 0

including parameters in OPENQUERY

Combine Dynamic SQL with OpenQuery. (This goes to a Teradata server)

DECLARE 
    @dayOfWk    TINYINT = DATEPART(DW, GETDATE()),
    @qSQL       NVARCHAR(MAX) = '';

SET @qSQL = '
SELECT
    *
FROM
    OPENQUERY(TERASERVER,''
        SELECT DISTINCT
            CASE
                WHEN ' + CAST(@dayOfWk AS NCHAR(1)) + ' = 2
                THEN ''''Monday''''
                ELSE ''''Not Monday''''
            END
        '');';

EXEC sp_executesql @qSQL;

List vs tuple, when to use each?

The first thing you need to decide is whether the data structure needs to be mutable or not. As has been mentioned, lists are mutable, tuples are not. This also means that tuples can be used for dictionary keys, wheres lists cannot.

In my experience, tuples are generally used where order and position is meaningful and consistant. For example, in creating a data structure for a choose your own adventure game, I chose to use tuples instead of lists because the position in the tuple was meaningful. Here is one example from that data structure:

pages = {'foyer': {'text' : "some text", 
          'choices' : [('open the door', 'rainbow'),
                     ('go left into the kitchen', 'bottomless pit'),
                     ('stay put','foyer2')]},}

The first position in the tuple is the choice displayed to the user when they play the game and the second position is the key of the page that choice goes to and this is consistent for all pages.

Tuples are also more memory efficient than lists, though I'm not sure when that benefit becomes apparent.

Also check out the chapters on lists and tuples in Think Python.

For Restful API, can GET method use json data?

In theory, there's nothing preventing you from sending a request body in a GET request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.

However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.

The simple option is to use POST instead of GET as recommended by other answers. Since POST is not standardized by HTTP, you'll have to document how exactly that's supposed to work.

Another option, which I prefer, is to implement your application assuming the GET payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override, which is a popular convention for clients to emulate HTTP methods with POST. So, if a client has a broken implementation, it can write the GET request as a POST, sending the X-HTTP-Method-Override: GET method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.

How do I declare an array of undefined or no initial size?

One way I can imagine is to use a linked list to implement such a scenario, if you need all the numbers entered before the user enters something which indicates the loop termination. (posting as the first option, because have never done this for user input, it just seemed to be interesting. Wasteful but artistic)

Another way is to do buffered input. Allocate a buffer, fill it, re-allocate, if the loop continues (not elegant, but the most rational for the given use-case).

I don't consider the described to be elegant though. Probably, I would change the use-case (the most rational).

"Javac" doesn't work correctly on Windows 10

Maybe a bit late, but i had same problem.

Click on "Move up" button for Java path and move it at top.

It fixed problem for me

Deleting DataFrame row in Pandas based on column value

If you want to delete rows based on multiple values of the column, you could use:

df[(df.line_race != 0) & (df.line_race != 10)]

To drop all rows with values 0 and 10 for line_race.

Generating HTML email body in C#

I use dotLiquid for exactly this task.

It takes a template, and fills special identifiers with the content of an anonymous object.

//define template
String templateSource = "<h1>{{Heading}}</h1>Dear {{UserName}},<br/><p>First part of the email body goes here");
Template bodyTemplate = Template.Parse(templateSource); // Parses and compiles the template source

//Create DTO for the renderer
var bodyDto = new {
    Heading = "Heading Here",
    UserName = userName
};
String bodyText = bodyTemplate.Render(Hash.FromAnonymousObject(bodyDto));

It also works with collections, see some online examples.

What is the (function() { } )() construct in JavaScript?

That construct is called an Immediately Invoked Function Expression (IIFE) which means it gets executed immediately. Think of it as a function getting called automatically when the interpreter reaches that function.

Most Common Use-case:

One of its most common use cases is to limit the scope of a variable made via var. Variables created via var have a scope limited to a function so this construct (which is a function wrapper around certain code) will make sure that your variable scope doesn't leak out of that function.

In following example, count will not be available outside the immediately invoked function i.e. the scope of count will not leak out of the function. You should get a ReferenceError, should you try to access it outside of the immediately invoked function anyway.

(function () { 
    var count = 10;
})();
console.log(count);  // Reference Error: count is not defined

ES6 Alternative (Recommended)

In ES6, we now can have variables created via let and const. Both of them are block-scoped (unlike var which is function-scoped).

Therefore, instead of using that complex construct of IIFE for the use case I mentioned above, you can now write much simpler code to make sure that a variable's scope does not leak out of your desired block.

{ 
    let count = 10;
}
console.log(count);  // ReferenceError: count is not defined

In this example, we used let to define count variable which makes count limited to the block of code, we created with the curly brackets {...}.

I call it a “Curly Jail”.

How should I do integer division in Perl?

int(x+.5) will round positive values toward the nearest integer. Rounding up is harder.

To round toward zero:

int($x)

For the solutions below, include the following statement:

use POSIX;

To round down: POSIX::floor($x)

To round up: POSIX::ceil($x)

To round away from zero: POSIX::floor($x) - int($x) + POSIX::ceil($x)

To round off to the nearest integer: POSIX::floor($x+.5)

Note that int($x+.5) fails badly for negative values. int(-2.1+.5) is int(-1.6), which is -1.

Showing the stack trace from a running Python application

It can be done with excellent py-spy. It's a sampling profiler for Python programs, so its job is to attach to a Python processes and sample their call stacks. Hence, py-spy dump --pid $SOME_PID is all you need to do to dump call stacks of all threads in the $SOME_PID process. Typically it needs escalated privileges (to read the target process' memory).

Here's an example of how it looks like for a threaded Python application.

$ sudo py-spy dump --pid 31080
Process 31080: python3.7 -m chronologer -e production serve -u www-data -m
Python v3.7.1 (/usr/local/bin/python3.7)

Thread 0x7FEF5E410400 (active): "MainThread"
    _wait (cherrypy/process/wspbus.py:370)
    wait (cherrypy/process/wspbus.py:384)
    block (cherrypy/process/wspbus.py:321)
    start (cherrypy/daemon.py:72)
    serve (chronologer/cli.py:27)
    main (chronologer/cli.py:84)
    <module> (chronologer/__main__.py:5)
    _run_code (runpy.py:85)
    _run_module_as_main (runpy.py:193)
Thread 0x7FEF55636700 (active): "_TimeoutMonitor"
    run (cherrypy/process/plugins.py:518)
    _bootstrap_inner (threading.py:917)
    _bootstrap (threading.py:885)
Thread 0x7FEF54B35700 (active): "HTTPServer Thread-2"
    accept (socket.py:212)
    tick (cherrypy/wsgiserver/__init__.py:2075)
    start (cherrypy/wsgiserver/__init__.py:2021)
    _start_http_thread (cherrypy/process/servers.py:217)
    run (threading.py:865)
    _bootstrap_inner (threading.py:917)
    _bootstrap (threading.py:885)
...
Thread 0x7FEF2BFFF700 (idle): "CP Server Thread-10"
    wait (threading.py:296)
    get (queue.py:170)
    run (cherrypy/wsgiserver/__init__.py:1586)
    _bootstrap_inner (threading.py:917)
    _bootstrap (threading.py:885)  

Place API key in Headers or URL

It should be put in the HTTP Authorization header. The spec is here https://tools.ietf.org/html/rfc7235

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

Structure of a PDF file?

If You want to parse PDF using Python please have a look at PDFMINER. This is the best library to parse PDF files till date.

Disable Input fields in reactive form

enter image description here

lastName: new FormControl({value: '', disabled: true}, Validators.compose([Validators.required])),

How to pre-populate the sms body text via an html link

For using Android you use below code

<a href="sms:+32665?body=reg fb1>Send SMS</a>

For iOS you can use below code

<a href="sms:+32665&body=reg fb1>Send SMS</a>

below code working for both iOs and Android

<a href="sms:+32665?&body=reg fb1>Send SMS</a>

static function in C

Making a function static hides it from other translation units, which helps provide encapsulation.

helper_file.c

int f1(int);        /* prototype */
static int f2(int); /* prototype */

int f1(int foo) {
    return f2(foo); /* ok, f2 is in the same translation unit */
                    /* (basically same .c file) as f1         */
}

int f2(int foo) {
    return 42 + foo;
}

main.c:

int f1(int); /* prototype */
int f2(int); /* prototype */

int main(void) {
    f1(10); /* ok, f1 is visible to the linker */
    f2(12); /* nope, f2 is not visible to the linker */
    return 0;
}

Setting a system environment variable from a Windows batch file?

SetX is the command that you'll need in most of the cases.Though its possible to use REG or REGEDIT

Using registry editing commands you can avoid some of the restrictions of the SetX command - different data types, variables containing = in their name and so on.

@echo off

:: requires admin elevated permissions
::setting system variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v MyVar /D MyVal
::expandable variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /T REG_EXPAND_SZ /v MyVar /D MyVal


:: does not require admin permissions
::setting user variable
REG ADD "HKEY_CURRENT_USER\Environment" /v =C: /D "C:\\test"

REG is the pure registry client but its possible also to import the data with REGEDIT though it allows using only hard coded values (or generation of a temp files). The example here is a hybrid file that contains both batch code and registry data (should be saved as .bat - mind that in batch ; are ignored as delimiters while they are used as comments in .reg files):

REGEDIT4

; @ECHO OFF
; CLS
; REGEDIT.EXE /S "%~f0"
; EXIT

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
"SystemVariable"="GlobalValue"

[HKEY_CURRENT_USER\Environment]
"UserVariable"="SomeValue"

Vertically aligning CSS :before and :after content

Messing around with the line-height attribute should do the trick. I haven't tested this, so the exact value may not be right, but start with 1.5em, and tweak it in 0.1 increments until it lines up.

.pdf{ line-height:1.5em; }

How can I bind a background color in WPF/XAML?

The Background property expects a Brush object, not a string. Change the type of the property to Brush and initialize it thus:

Background = new SolidColorBrush(Colors.Red);

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

The following works for me. Add the following method to the entity that is not the owner of the relationship (Group)

@PreRemove
private void removeGroupsFromUsers() {
    for (User u : users) {
        u.getGroups().remove(this);
    }
}

Keep in mind that for this to work, the Group must have an updated list of Users (which is not done automatically). so everytime you add a Group to the group list in User entity, you should also add a User to the user list in the Group entity.

How should I escape commas and speech marks in CSV files so they work in Excel?

We eventually found the answer to this.

Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...

Reference,Title,Description
1,"My little title","My description, which may contain ""speech marks"" and commas."
2,"My other little title","My other description, which may also contain ""speech marks"" and commas."

... fixed the problem. Hope this helps someone!

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

in FF use inline style i.e.

<img src="..." class="img-responsive" style="width:100%; height:auto;" />

It rocks :)

How can one create an overlay in css?

Here is an overlay using a pseudo-element (eg: no need to add more markup to do it)

_x000D_
_x000D_
.box {_x000D_
  background: 0 0 url(http://ianfarb.com/wp-content/uploads/2013/10/nicholas-hodag.jpg);_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: rgba(0, 0, 0, 0.4);_x000D_
}
_x000D_
  <div class="box"></div>
_x000D_
_x000D_
_x000D_

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/ directory, or Scripts\ on Windows).

The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.

How can you sort an array without mutating the original array?

Just copy the array. There are many ways to do that:

function sort(arr) {
  return arr.concat().sort();
}

// Or:
return Array.prototype.slice.call(arr).sort(); // For array-like objects

Difference between del, remove, and pop on lists

The effects of the three different methods to remove an element from a list:

remove removes the first matching value, not a specific index:

>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]

del removes the item at a specific index:

>>> a = [9, 8, 7, 6]
>>> del a[1]
>>> a
[9, 7, 6]

and pop removes the item at a specific index and returns it.

>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]

Their error modes are different too:

>>> a = [4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range

Find html label associated with a given input

with jquery you could do something like

var nameOfLabel = someInput.attr('id');
var label = $("label[for='" + nameOfLabel + "']");

Test if element is present using Selenium WebDriver?

Personally, I always go for a mixture of the above answers and create a re-usable static Utility method that uses the size() > 0 suggestion:

public Class Utility {
   ...
   public static boolean isElementExist(WebDriver driver, By by) {
      return driver.findElements(by).size() > 0;
   ...
}

This is neat, re-usable, maintainable ... all that good stuff ;-)

How can I find out a file's MIME type (Content-Type)?

file --mime works, but not --mime-type. at least for my RHEL 5.

CSS :: child set to change color on parent hover, but changes also when hovered itself

If you don't care about supporting old browsers, you can use :not() to exclude that element:

.parent:hover span:not(:hover) {
    border: 10px solid red;
}

Demo: http://jsfiddle.net/vz9A9/1/

If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:

.parent span:hover {
    border: 10px solid green;
}

Can you autoplay HTML5 videos on the iPad?

Let video muted first to ensure autoplay in ios, then unmute it if you want.

<video autoplay loop muted playsinline>
  <source src="video.mp4?123" type="video/mp4">
</video>

<script type="text/javascript">
$(function () {
  if (!navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
    $("video").prop('muted', false);
  }
});
</script>

Server is already running in Rails

kill -9 $(lsof -i tcp:3000 -t)

How to uncompress a tar.gz in another directory

Extracts myArchive.tar to /destinationDirectory

Commands:

cd /destinationDirectory
pax -rv -f myArchive.tar -s ',^/,,'

Request string without GET arguments

$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$request_uri = $uri_parts[0];
echo $request_uri;

How do I install Maven with Yum?

Icarus answered a very similar question for me. Its not using "yum", but should still work for your purposes. Try,

wget http://mirror.olnevhost.net/pub/apache/maven/maven-3/3.0.5/binaries/apache-maven-3.0.5-bin.tar.gz

basically just go to the maven site. Find the version of maven you want. The file type and use the mirror for the wget statement above.

Afterwards the process is easy

  1. Run the wget command from the dir you want to extract maven too.
  2. run the following to extract the tar,

    tar xvf apache-maven-3.0.5-bin.tar.gz
    
  3. move maven to /usr/local/apache-maven

    mv apache-maven-3.0.5  /usr/local/apache-maven
    
  4. Next add the env variables to your ~/.bashrc file

    export M2_HOME=/usr/local/apache-maven
    export M2=$M2_HOME/bin 
    export PATH=$M2:$PATH
    
  5. Execute these commands

    source ~/.bashrc

6:. Verify everything is working with the following command

    mvn -version

Send file via cURL from form POST in PHP

This should work:

$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);

$data = array(
    'uploaded_file' => '@'.$tmpfile.';filename='.$filename,
);

$ch = curl_init();   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set your other cURL options here (url, etc.)

curl_exec($ch);

In the receiving script, you would have:

print_r($_FILES);
/* which would output something like
     Array (
        [uploaded_file] => Array (
            [tmp_name] => /tmp/f87453hf
            [name] => myimage.jpg
            [error] => 0
            [size] => 12345
            [type] => image/jpeg
        )
     )
*/

Then, if you want to properly handle the file upload, you would do something like this:

if (move_uploaded_file($_FILES['uploaded_file'], '/path/to/destination/file.zip')) {
   // do stuff
}

How to get the number of characters in a string

There is a way to get count of runes without any packages by converting string to []rune as len([]rune(YOUR_STRING)):

package main

import "fmt"

func main() {
    russian := "??????? ? ??????"
    english := "Sputnik & pogrom"

    fmt.Println("count of bytes:",
        len(russian),
        len(english))

    fmt.Println("count of runes:",
        len([]rune(russian)),
        len([]rune(english)))

}

count of bytes 30 16

count of runes 16 16

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

This error you are receiving :

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

is because the number of elements in $values & $matches is not the same or $matches contains more than 1 element.

If $matches contains more than 1 element, than the insert will fail, because there is only 1 column name referenced in the query(hash)

If $values & $matches do not contain the same number of elements then the insert will also fail, due to the query expecting x params but it is receiving y data $matches.

I believe you will also need to ensure the column hash has a unique index on it as well.

Try the code here:

<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }


$matches = array('1');
$count = count($matches);
for($i = 0; $i < $count; ++$i) {
    $values[] = '?';
}

// INSERT INTO DATABASE
$sql = "INSERT INTO hashes (hash) VALUES (" . implode(', ', $values) . ") ON DUPLICATE KEY UPDATE hash='hash'";
$stmt = $dbh->prepare($sql);
$data = $stmt->execute($matches);

//Error reporting if something went wrong...
var_dump($dbh->errorInfo());

?>

You will need to adapt it a little.

Table structure I used is here:

CREATE TABLE IF NOT EXISTS `hashes` (
  `hashid` int(11) NOT NULL AUTO_INCREMENT,
  `hash` varchar(250) NOT NULL,
  PRIMARY KEY (`hashid`),
  UNIQUE KEY `hash1` (`hash`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Code was run on my XAMPP Server which is using PHP 5.3.8 with MySQL 5.5.16.

I hope this helps.

PHP, MySQL error: Column count doesn't match value count at row 1

You have 9 fields listed, but only 8 values. Try adding the method.

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

many other people answered your question above. This problen arises when your script don't find the jQuery script and if you are using other framework or cms then maybe there is a conflict between jQuery and other libraries. In my case i used as following- `

<script src="js_directory/jquery.1.7.min.js"></script>
    <script>
    jQuery.noConflict();
    jQuery(document).ready(
    function($){
    //your other code here
    });</script>

`

here might be some syntax error. Please forgive me because i'm writing from my cell phone. Thanks

How to upgrade Angular CLI to the latest version

This command works fine:

npm upgrade -g @angular/cli

Concatenating strings in Razor

the plus works just fine, i personally prefer using the concat function.

var s = string.Concat(string 1, string 2, string, 3, etc)

Calling a Sub in VBA

Try -

Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)

As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

IF statement: how to leave cell blank if condition is false ("" does not work)

The formula in C1

=IF(A1=1,B1,"")

is either giving an answer of "" (which isn't treated as blank) or the contents of B1.

If you want the formula in D1 to show TRUE if C1 is "" and FALSE if C1 has something else in then use the formula

=IF(C2="",TRUE,FALSE)

instead of ISBLANK

How can I get device ID for Admob

To get the device id, connect your phone to USB and open logcat in android studio Use the code below (make sure you have USB debugging enabled in your device). Then open any app (download any random app from play store) which has google Ad. In the Logcat type "set" as shown in the image. Your device id is shown highlighted in the image as

setTestDeviceIds(Arrays.asList("CC9DW7W7R4H0NM3LT9OLOF7455F8800D")).

enter image description here

Use the Test Device in your code as shown

val adRequest = AdRequest
        .Builder()
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("CC9DW7W7R4H0NM3LT9OLOF7455F8800D")
        .build()

Select last row in MySQL

SELECT * FROM adds where id=(select max(id) from adds);

This query used to fetch the last record in your table.

How to create cron job using PHP?

why you not use curl? logically, if you execute php file, you will execute that by url on your browser. its very simple if you run curl

while(true)
{
    sleep(60); // sleep for 60 sec = 1 minute

    $s = curl_init();
    curl_setopt($s,CURLOPT_URL, $your_php_url_to_cron); 
    curl_exec($s); 
    curl_getinfo($s,CURLINFO_HTTP_CODE); 
    curl_close($s);
}

Equivalent of varchar(max) in MySQL?

The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):

VARCHAR(65535)

However, note that the limit is lower if you use a multi-byte character set:

VARCHAR(21844) CHARACTER SET utf8

Here are some examples:

The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table.

mysql> CREATE TABLE foo ( v VARCHAR(65534) );
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

But if we try decreasing lengths, we find the greatest length that works:

mysql> CREATE TABLE foo ( v VARCHAR(65532) );
Query OK, 0 rows affected (0.01 sec)

Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't necessarily use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters.

mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8;
ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead

In spite of what the last error told us, InnoDB still doesn't like a length of 21845.

mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.

mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;
Query OK, 0 rows affected (0.32 sec)

What is the idiomatic Go equivalent of C's ternary operator?

No Go doesn't have a ternary operator, using if/else syntax is the idiomatic way.

Why does Go not have the ?: operator?

There is no ternary testing operation in Go. You may use the following to achieve the same result:

if expr {
    n = trueVal
} else {
    n = falseVal
}

The reason ?: is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. The if-else form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.

— Frequently Asked Questions (FAQ) - The Go Programming Language

How can I quantify difference between two images?

Another nice, simple way to measure the similarity between two images:

import sys
from skimage.measure import compare_ssim
from skimage.transform import resize
from scipy.ndimage import imread

# get two images - resize both to 1024 x 1024
img_a = resize(imread(sys.argv[1]), (2**10, 2**10))
img_b = resize(imread(sys.argv[2]), (2**10, 2**10))

# score: {-1:1} measure of the structural similarity between the images
score, diff = compare_ssim(img_a, img_b, full=True)
print(score)

If others are interested in a more powerful way to compare image similarity, I put together a tutorial and web app for measuring and visualizing similar images using Tensorflow.

How does one remove a Docker image?

Docker provides some command to remove images.

Show/Remove Images:

docker images
docker images -a # All images
docker images --no-trunc # List the full length image IDs

docker images --filter "dangling=true" // Show unstage images
docker rmi $(docker images -f "dangling=true" -q) # Remove on unstages images

docker rmi <REPOSITORY> or <Image ID> # Remove a single image

docker image prune # Interactively remove dangling images
docker image prune -a # Remove all images

or 

docker rmi -f $(sudo docker images -a -q)

Also, you can also use filter parameters to remove set of images at once:

Example:

$docker images --filter "before=<hello-world>" // It will all images before hello-world

$docker images --filter "since=<hello-world>" // It will all images since hello-world

So you can delete that filter images like this:

docker rmi $(docker images --filter "since=<hello-world>")
docker rmi $(docker images --filter "before=<hello-world>")

how to specify local modules as npm package dependencies

After struggling much with the npm link command (suggested solution for developing local modules without publishing them to a registry or maintaining a separate copy in the node_modules folder), I built a small npm module to help with this issue.

The fix requires two easy steps.

First:

npm install lib-manager --save-dev

Second, add this to your package.json:

{  
  "name": "yourModuleName",  
  // ...
  "scripts": {
    "postinstall": "./node_modules/.bin/local-link"
  }
}

More details at https://www.npmjs.com/package/lib-manager. Hope it helps someone.

How can we programmatically detect which iOS version is device running on?

[[[UIDevice currentDevice] systemVersion] floatValue]

How to run SUDO command in WinSCP to transfer files from Windows to linux

I know this is old, but it is actually very possible.

  • Go to your WinSCP profile (Session > Sites > Site Manager)

  • Click on Edit > Advanced... > Environment > SFTP

  • Insert sudo su -c /usr/lib/sftp-server in "SFTP Server" (note this path might be different in your system)

  • Save and connect

Source

AWS Ubuntu 18.04: enter image description here

Generating an array of letters in the alphabet

C# 3.0 :

char[] az = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToArray();
foreach (var c in az)
{
    Console.WriteLine(c);
}

yes it does work even if the only overload of Enumerable.Range accepts int parameters ;-)

How to convert a 3D point into 2D perspective projection?

All of the answers address the question posed in the title. However, I would like to add a caveat that is implicit in the text. Bézier patches are used to represent the surface, but you cannot just transform the points of the patch and tessellate the patch into polygons, because this will result in distorted geometry. You can, however, tessellate the patch first into polygons using a transformed screen tolerance and then transform the polygons, or you can convert the Bézier patches to rational Bézier patches, then tessellate those using a screen-space tolerance. The former is easier, but the latter is better for a production system.

I suspect that you want the easier way. For this, you would scale the screen tolerance by the norm of the Jacobian of the inverse perspective transformation and use that to determine the amount of tessellation that you need in model space (it might be easier to compute the forward Jacobian, invert that, then take the norm). Note that this norm is position-dependent, and you may want to evaluate this at several locations, depending on the perspective. Also remember that since the projective transformation is rational, you need to apply the quotient rule to compute the derivatives.

How to add one column into existing SQL Table

What about something like:

Alter Table Products
Add LastUpdate varchar(200) null

Do you need something more complex than this?

How to convert a List<String> into a comma separated string without iterating List explicitly

With Java 8:

String csv = String.join(",", ids);

With Java 7-, there is a dirty way (note: it works only if you don't insert strings which contain ", " in your list) - obviously, List#toString will perform a loop to create idList but it does not appear in your code:

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String idList = ids.toString();
String csv = idList.substring(1, idList.length() - 1).replace(", ", ",");

Spring MVC @PathVariable with dot (.) is getting truncated

Update for Spring 4: since 4.0.1 you can use PathMatchConfigurer (via your WebMvcConfigurer), e.g.

@Configuration
protected static class AllResources extends WebMvcConfigurerAdapter {

    @Override
    public void configurePathMatch(PathMatchConfigurer matcher) {
        matcher.setUseRegisteredSuffixPatternMatch(true);
    }

}


@Configuration
public class WebConfig implements WebMvcConfigurer {

   @Override
   public void configurePathMatch(PathMatchConfigurer configurer) {
       configurer.setUseSuffixPatternMatch(false);
   }
}

In xml, it would be (https://jira.spring.io/browse/SPR-10163):

<mvc:annotation-driven>
    [...]
    <mvc:path-matching registered-suffixes-only="true"/>
</mvc:annotation-driven>

How can I check if my python object is a number?

That's not really how python works. Just use it like you would a number, and if someone passes you something that's not a number, fail. It's the programmer's responsibility to pass in the correct types.

Naming convention - underscore in C++ and C# variables

It's simply means that it's a member field in the class.

Viewing all defined variables

This has to be defined in the interactive shell:

def MyWho():
    print [v for v in globals().keys() if not v.startswith('_')]

Then the following code can be used as an example:

>>> import os
>>> import sys
>>> a = 10 
>>> MyWho()
['a', 'MyWho', 'sys', 'os']

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

Simply creating a filter will do the trick. (Answered for Angular 1.6)

.filter('trustHtml', [
        '$sce',
        function($sce) {
            return function(value) {
                return $sce.trustAs('html', value);
            }
        }
    ]);

And use this as follow in the html.

<h2 ng-bind-html="someScopeValue | trustHtml"></h2>

Copying an array of objects into another array in javascript

A great way for cloning an array is with an array literal and the spread syntax. This is made possible by ES2015.

const objArray = [{name:'first'}, {name:'second'}, {name:'third'}, {name:'fourth'}];

const clonedArr = [...objArray];

console.log(clonedArr) // [Object, Object, Object, Object]

You can find this copy option in MDN's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Copy_an_array

It is also an Airbnb's best practice. https://github.com/airbnb/javascript#es6-array-spreads

Note: The spread syntax in ES2015 goes one level deep while copying an array. Therefore, they are unsuitable for copying multidimensional arrays.

How to get the selected date value while using Bootstrap Datepicker?

Generally speaking,

$('#startdate').data('date') 

is best because

$('#startdate').val()

not work if you have a datepicker "inline"

Getting the IP address of the current machine using Java

Since my system (like so many other systems) had various network interfaces.InetAddress.getLocalHost() or Inet4Address.getLocalHost() simply returned one that I did not desire. Therefore I had to use this naive approach.

InetAddress[] allAddresses = Inet4Address.getAllByName("YourComputerHostName");
        InetAddress desiredAddress;
        //In order to find the desired Ip to be routed by other modules (WiFi adapter)
        for (InetAddress address :
                allAddresses) {
            if (address.getHostAddress().startsWith("192.168.2")) {
                desiredAddress = address;
            }
        }
// Use the desired address for whatever purpose.

Just be careful that in this approach I already knew that my desired IP address is in 192.168.2 subnet.

How do I upgrade PHP in Mac OS X?

Option #1

As recommended here, this site provides a convenient, up-to-date one liner.

This doesn't overwrite the base version of PHP on your system, but instead installs it cleanly in /usr/local/php5.

Option #2

My preferred method is to just install via Homebrew.

Getting an attribute value in xml element

I think I got it. I have to use org.w3c.dom.Element explicitly. I had a different Element field too.

How to get the server path to the web directory in Symfony2 from inside the controller?

There's actually no direct way to get path to webdir in Symfony2 as the framework is completely independent of the webdir.

You can use getRootDir() on instance of kernel class, just as you write. If you consider renaming /web dir in future, you should make it configurable. For example AsseticBundle has such an option in its DI configuration (see here and here).

Validate email with a regex in jQuery

This regex can help you to check your email-address according to all the criteria which gmail.com used.

var re = /^\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;

var emailFormat = re.test($("#email").val()); // This return result in Boolean type

if (emailFormat) {}

How to convert HTML to PDF using iTextSharp

I use the following code to create PDF

protected void CreatePDF(Stream stream)
        {
            using (var document = new Document(PageSize.A4, 40, 40, 40, 30))
            {
                var writer = PdfWriter.GetInstance(document, stream);
                writer.PageEvent = new ITextEvents();
                document.Open();

                // instantiate custom tag processor and add to `HtmlPipelineContext`.
                var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
                tagProcessorFactory.AddProcessor(
                    new TableProcessor(),
                    new string[] { HTML.Tag.TABLE }
                );

                //Register Fonts.
                XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
                fontProvider.Register(HttpContext.Current.Server.MapPath("~/Content/Fonts/GothamRounded-Medium.ttf"), "Gotham Rounded Medium");
                CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);

                var htmlPipelineContext = new HtmlPipelineContext(cssAppliers);
                htmlPipelineContext.SetTagFactory(tagProcessorFactory);

                var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
                var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);

                // get an ICssResolver and add the custom CSS
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                cssResolver.AddCss(CSSSource, "utf-8", true);
                var cssResolverPipeline = new CssResolverPipeline(
                    cssResolver, htmlPipeline
                );

                var worker = new XMLWorker(cssResolverPipeline, true);
                var parser = new XMLParser(worker);
                using (var stringReader = new StringReader(HTMLSource))
                {
                    parser.Parse(stringReader);
                    document.Close();
                    HttpContext.Current.Response.ContentType = "application /pdf";
                    if (base.View)
                        HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=\"" + OutputFileName + ".pdf\"");
                    else
                        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + OutputFileName + ".pdf\"");
                    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    HttpContext.Current.Response.WriteFile(OutputPath);
                    HttpContext.Current.Response.End();
                }
            }
        }

How can I escape latex code received through user input?

When you read the string from the GUI control, it is already a "raw" string. If you print out the string you might see the backslashes doubled up, but that's an artifact of how Python displays strings; internally there's still only a single backslash.

>>> a='\nu + \lambda + \theta'
>>> a
'\nu + \\lambda + \theta'
>>> len(a)
20
>>> b=r'\nu + \lambda + \theta'
>>> b
'\\nu + \\lambda + \\theta'
>>> len(b)
22
>>> b[0]
'\\'
>>> print b
\nu + \lambda + \theta

How to send parameters from a notification-click to an activity?

G'day, I too can say that I tried everything mentioned in these posts and a few more from elsewhere. The #1 problem for me was that the new Intent always had a null bundle. My issue was in focusing too much on the details of "have I included .this or .that". My solution was in taking a step back from the detail and looking at the overall structure of the notification. When I did that I managed to place the key parts of the code in the correct sequence. So, if you're having similar issues check for:

1. Intent notificationIntent = new Intent(MainActivity.this, NotificationActivity.class);

2a. Bundle bundle = new Bundle();

//I like specifying the data type much better. eg bundle.putInt

2b. notificationIntent.putExtras(bundle);
3. PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, WIZARD_NOTIFICATION_ID, notificationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
4. NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
5.          NotificationCompat.Builder nBuilder =
                    new NotificationCompat.Builder(this)
                            .setSmallIcon(R.drawable.ic_notify)
                            .setContentTitle(title)
                            .setContentText(content)
                            .setContentIntent(contentIntent)
                            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                            .setAutoCancel(false)//false is standard. true == automatically removes the notification when the user taps it.
                            .setColor(getResources().getColor(R.color.colorPrimary))
                            .setCategory(Notification.CATEGORY_REMINDER)
                            .setPriority(Notification.PRIORITY_HIGH)
                            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            notificationManager.notify(WIZARD_NOTIFICATION_ID, nBuilder.build());

With this sequence I get a valid bundle.

How to delete projects in Intellij IDEA 14?

You will have to manually delete from the project explorer (your local machine hard drive), then delete the project in IntelliJ when it asks to re-open recent projects.

Passing a variable to a powershell script via command line

Here's a good tutorial on Powershell params:

PowerShell ABC's - P is for Parameters

Basically, you should use a param statement on the first line of the script

param([type]$p1 = , [type]$p2 = , ...)

or use the $args built-in variable, which is auto-populated with all of the args.

how to add a jpg image in Latex

if you add a jpg,png,pdf picture, you should use pdflatex to compile it.

Converting newline formatting from Mac to Windows

The following is a complete script based on the above answers along with sanity checking and works on Mac OS X and should work on other Linux / Unix systems as well (although this has not been tested).

#!/bin/bash

# http://stackoverflow.com/questions/6373888/converting-newline-formatting-from-mac-to-windows

# =============================================================================
# =
# = FIXTEXT.SH by ECJB
# =
# = USAGE:  SCRIPT [ MODE ] FILENAME
# =
# = MODE is one of unix2dos, dos2unix, tounix, todos, tomac
# = FILENAME is modified in-place
# = If SCRIPT is one of the modes (with or without .sh extension), then MODE
# =   can be omitted - it is inferred from the script name.
# = The script does use the file command to test if it is a text file or not,
# =   but this is not a guarantee.
# =
# =============================================================================

clear
script="$0"
modes="unix2dos dos2unix todos tounix tomac"

usage() {
    echo "USAGE:  $script [ mode ] filename"
    echo
    echo "MODE is one of:"
    echo $modes
    echo "NOTE:  The tomac mode is intended for old Mac OS versions and should not be"
    echo "used without good reason."
    echo
    echo "The file is modified in-place so there is no output filename."
    echo "USE AT YOUR OWN RISK."
    echo
    echo "The script does try to check if it's a binary or text file for sanity, but"
    echo "this is not guaranteed."
    echo
    echo "Symbolic links to this script may use the above names and be recognized as"
    echo "mode operators."
    echo
    echo "Press RETURN to exit."
    read answer
    exit
}

# -- Look for the mode as the scriptname
mode="`basename "$0" .sh`"
fname="$1"

# -- If 2 arguments use as mode and filename
if [ ! -z "$2" ] ; then mode="$1"; fname="$2"; fi

# -- Check there are 1 or 2 arguments or print usage.
if [ ! -z "$3" -o -z "$1" ] ; then usage; fi

# -- Check if the mode found is valid.
validmode=no
for checkmode in $modes; do if [ $mode = $checkmode ] ; then validmode=yes; fi; done
# -- If not a valid mode, abort.
if [ $validmode = no ] ; then echo Invalid mode $mode...aborting.; echo; usage; fi

# -- If the file doesn't exist, abort.
if [ ! -e "$fname" ] ; then echo Input file $fname does not exist...aborting.; echo; usage; fi

# -- If the OS thinks it's a binary file, abort, displaying file information.
if [ -z "`file "$fname" | grep text`" ] ; then echo Input file $fname may be a binary file...aborting.; echo; file "$fname"; echo; usage; fi

# -- Do the in-place conversion.
case "$mode" in
#   unix2dos ) # sed does not behave on Mac - replace w/ "todos" and "tounix"
#       # Plus, these variants are more universal and assume less.
#       sed -e 's/$/\r/' -i '' "$fname"             # UNIX to DOS  (adding CRs)
#       ;;
#   dos2unix )
#       sed -e 's/\r$//' -i '' "$fname"             # DOS  to UNIX (removing CRs)
#           ;;
    "unix2dos" | "todos" )
        perl -pi -e 's/\r\n|\n|\r/\r\n/g' "$fname"  # Convert to DOS
        ;;
    "dos2unix" | "tounix" )
        perl -pi -e 's/\r\n|\n|\r/\n/g'   "$fname"  # Convert to UNIX
        ;;
    "tomac" )
        perl -pi -e 's/\r\n|\n|\r/\r/g'   "$fname"  # Convert to old Mac
        ;;
    * ) # -- Not strictly needed since mode is checked first.
        echo Invalid mode $mode...aborting.; echo; usage
        ;;
esac

# -- Display result.
if [ "$?" = "0" ] ; then echo "File $fname updated with mode $mode."; else echo "Conversion failed return code $?."; echo; usage; fi

How to disable a link using only CSS?

Demo here
Try this one

$('html').on('click', 'a.Link', function(event){
    event.preventDefault();
});

Ubuntu: Using curl to download an image

If you want to keep the original name — use uppercase -O

curl -O https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

If you want to save remote file with a different name — use lowercase -o

curl -o myPic.png https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

What is the difference between DTR/DSR and RTS/CTS flow control?

The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.

How to get memory available or used in C#

You might want to check the GC.GetTotalMemory method.

It retrieves the number of bytes currently thought to be allocated by the garbage collector.

Can I recover a branch after its deletion in Git?

First go to git batch the move to your project like :

cd android studio project
cd Myproject
then type :
git reflog

You all have a list of the changes and the reference number take the ref number then checkout
from android studio or from the git betcha. another solution take the ref number and go to android studio click on git branches down then click on checkout tag or revision past the reference number then lol you have the branches.

jQuery Date Picker - disable past dates

Use the "minDate" option to restrict the earliest allowed date. The value "0" means today (0 days from today):

    $(document).ready(function () {
        $("#txtdate").datepicker({
            minDate: 0,
            // ...
        });
    });

Docs here: http://api.jqueryui.com/datepicker/#option-minDate

Is there a way to iterate over a range of integers?

The problem is not the range, the problem is how the end of slice is calculated. with a fixed number 10 the simple for loop is ok but with a calculated size like bfl.Size() you get a function-call on every iteration. A simple range over int32 would help because this evaluate the bfl.Size() only once.

type BFLT PerfServer   
  func (this *BFLT) Call() {
    bfl := MqBufferLCreateTLS(0)                                                                                   
    for this.ReadItemExists() {                                                                                    
      bfl.AppendU(this.ReadU())                                                                                    
    }
    this.SendSTART()
    // size := bfl.Size() 
    for i := int32(0); i < bfl.Size() /* size */; i++ {                                                                             
      this.SendU(bfl.IndexGet(i))                                                                                  
    }
    this.SendRETURN()
  }

How do I write JSON data to a file?

I would answer with slight modification with aforementioned answers and that is to write a prettified JSON file which human eyes can read better. For this, pass sort_keys as True and indent with 4 space characters and you are good to go. Also take care of ensuring that the ascii codes will not be written in your JSON file:

with open('data.txt', 'w') as outfile:
     json.dump(jsonData, outfile, sort_keys = True, indent = 4,
               ensure_ascii = False)

Android Paint: .measureText() vs .getTextBounds()

There is another way to measure the text bounds precisely, first you should get the path for the current Paint and text. In your case it should be like this:

p.getTextPath(someText, 0, someText.length(), 0.0f, 0.0f, mPath);

After that you can call:

mPath.computeBounds(mBoundsPath, true);

In my code it always returns correct and expected values. But, not sure if it works faster than your approach.

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

My issue was a bit stupid. I had two copy of my project and I mixed files in visual studio.

Let s say you have projectX and projectY. These projects both contain myFile.cs. I opened projectX and edited myFile.cs. But this myFile.cs was belong to projectY . (It s possible to open files from different projects in visual studio) So in that case as warning says source code will be different than original.

What is the difference between a symbolic link and a hard link?

Hard links are useful when the original file is getting moved around. For example, moving a file from /bin to /usr/bin or to /usr/local/bin. Any symlink to the file in /bin would be broken by this, but a hardlink, being a link directly to the inode for the file, wouldn't care.

Hard links may take less disk space as they only take up a directory entry, whereas a symlink needs its own inode to store the name it points to.

Hard links also take less time to resolve - symlinks can point to other symlinks that are in symlinked directories. And some of these could be on NFS or other high-latency file systems, and so could result in network traffic to resolve. Hard links, being always on the same file system, are always resolved in a single look-up, and never involve network latency (if it's a hardlink on an NFS filesystem, the NFS server would do the resolution, and it would be invisible to the client system). Sometimes this is important. Not for me, but I can imagine high-performance systems where this might be important.

I also think things like mmap(2) and even open(2) use the same functionality as hardlinks to keep a file's inode active so that even if the file gets unlink(2)ed, the inode remains to allow the process continued access, and only once the process closes it does the file really go away. This allows for much safer temporary files (if you can get the open and unlink to happen atomically, which there may be a POSIX API for that I'm not remembering, then you really have a safe temporary file) where you can read/write your data without anyone being able to access it. Well, that was true before /proc gave everyone the ability to look at your file descriptors, but that's another story.

Speaking of which, recovering a file that is open in process A, but unlinked on the file system revolves around using hardlinks to recreate the inode links so the file doesn't go away when the process which has it open closes it or goes away.

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

say you define the static getFactorial function inside a CodeController

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

CodeController::getFactorial($index);

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

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

to do that

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

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

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

then files inside lib will autoloaded.

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

inside that define the function.

if ( ! function_exists('getFactorial'))
{

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

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

        return $fact;

     }
}

and call it anywhere within the app as

$fatorial_value = getFactorial(225);

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

You should simply create your own folder in htdocs and save your .html and .php files in it. An example is create a folder called myNewFolder directly in htdocs. Don't put it in index.html. Then save all your.html and .php files in it like this-> "localhost/myNewFolder/myFilename.html" or "localhost/myNewFolder/myFilename.php" I hope this helps.

Is there any WinSCP equivalent for linux?

scp file user@host:/path/on/host

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

Here is some SQL that actually make sense:

SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL

Simple is always better.

Update built-in vim on Mac OS X

A note to romainl's answer: aliases don't work together with sudo because only the first word is checked on aliases. To change this add another alias to your .profile / .bashrc:

alias sudo='sudo '

With this change sudo vim will behave as expected!

Ignore cells on Excel line graph

There are many cases in which gaps are desired in a chart.

I am currently trying to make a plot of flow rate in a heating system vs. the time of day. I have data for two months. I want to plot only vs. the time of day from 00:00 to 23:59, which causes lines to be drawn between 23:59 and 00:01 of the next day which extend across the chart and disturb the otherwise regular daily variation.

Using the NA() formula (in German NV()) causes Excel to ignore the cells, but instead the previous and following points are simply connected, which has the same problem with lines across the chart.

The only solution I have been able to find is to delete the formulas from the cells which should create the gaps.

Using an IF formula with "" as its value for the gaps makes Excel interpret the X-values as string labels (shudder) for the chart instead of numbers (and makes me swear about the people who wrote that requirement).

How can I uninstall Ruby on ubuntu?

Uninstall the make install software when make uninstall invalid.

  • make install will create file '.installed.list'
  • Choose to clean up the files described in .installed.list (need to be careful if you have multiple versions)
  • Case: ruby2.4 switch to ruby2.3, thinking directly delete all ruby software, and then re-make install 2.3, see: Ruby # Installation Guide
  • make install -> .installed.list
  • see .installed.list file, delete all install files.

rm -rf /usr/local/include/ruby-*
rm -rf /usr/local/lib/ruby
rm /usr/local/bin/erb /usr/local/bin/gem /usr/local/bin/irb /usr/local/bin/rdoc /usr/local/bin/ri /usr/local/bin/ruby
rm /usr/local/share/man/man1/erb.1 /usr/local/share/man/man1/irb.1 /usr/local/share/man/man1/ri.1 /usr/local/share/man/man1/ruby.1
rm /usr/local/lib/libruby-static.a
rm -rf /usr/local/lib/pkgconfig/ruby-*
which ruby
pkg-config --list-all|grep ruby

CSS: How can I set image size relative to parent height?

Change your code:

a.image_container img {
    width: 100%;
}

To this:

a.image_container img {
    width: auto; // to maintain aspect ratio. You can use 100% if you don't care about that
    height: 100%;
}

http://jsfiddle.net/f9krj/5/

Creating a script for a Telnet session?

Write the telnet session inside a BAT Dos file and execute.

How do you test to see if a double is equal to NaN?

You might want to consider also checking if a value is finite via Double.isFinite(value). Since Java 8 there is a new method in Double class where you can check at once if a value is not NaN and infinity.

/**
 * Returns {@code true} if the argument is a finite floating-point
 * value; returns {@code false} otherwise (for NaN and infinity
 * arguments).
 *
 * @param d the {@code double} value to be tested
 * @return {@code true} if the argument is a finite
 * floating-point value, {@code false} otherwise.
 * @since 1.8
 */
public static boolean isFinite(double d)

How to read from standard input in the console?

Try this code:-

var input string
func main() {
      fmt.Print("Enter Your Name=")
      fmt.Scanf("%s",&input)
      fmt.Println("Hello "+input)
      }

Get Row Index on Asp.net Rowcommand event

If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:

int index = Convert.ToInt32(e.CommandArgument);

In a custom command, you can set the command argument to yourRow.RowIndex.ToString() and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.

Merge 2 DataTables and store in a new one

DataTable dtAll = new DataTable();
DataTable dt= new DataTable();
foreach (int id in lst)
{
    dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable
}
dtAll = dt;

Installing Python 2.7 on Windows 8

Type this in Windows PowerShell or CMD:

"[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")"

After running the command, please restart PowerShell or CMD. If it still doesn't work, restart your PC.

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

Just turn the LINQ to Entity query into a LINQ to Objects query (e.g. call ToArray) anytime you need to use a method call in your LINQ query.

How to convert HTML file to word?

Other Alternatives from just renaming the file to .doc.....

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(office.11).aspx

Here is a good place to start. You can also try using this Office Open XML.

http://www.ecma-international.org/publications/standards/Ecma-376.htm

Could not find module FindOpenCV.cmake ( Error in configuration process)

I am using Windows and get the same error message. I find another problem which is relevant. I defined OpenCV_DIR in my path at the end of the line. However when I typed "path" in the command line, my OpenCV_DIR was not shown. I found because Windows probably has a limit on how long the path can be, it cut my OpenCV_DIR to be only part of what I defined. So I removed some other part of the path, now it works.

wildcard * in CSS for classes

What you need is called attribute selector. An example, using your html structure, is the following:

div[class^="tocolor-"], div[class*=" tocolor-"] {
    color:red 
}

In the place of div you can add any element or remove it altogether, and in the place of class you can add any attribute of the specified element.

[class^="tocolor-"] — starts with "tocolor-".
[class*=" tocolor-"] — contains the substring "tocolor-" occurring directly after a space character.

Demo: http://jsfiddle.net/K3693/1/

More information on CSS attribute selectors, you can find here and here. And from MDN Docs MDN Docs

Is it possible to interactively delete matching search pattern in Vim?

http://vim.wikia.com/wiki/Search_and_replace

Try this search and replace:

:%s/foo/bar/gc

Change each 'foo' to 'bar', but ask for confirmation first.

Press y or n to change or keep your text.

How to establish ssh key pair when "Host key verification failed"

First you should remove existing key. SSH keys in most of Linux-based OS will be saved this file "/root/.ssh/known_hosts", so in order to remove the key related to host the following command will be used:

ssh-keygen -f "/root/.ssh/known_hosts" -R [Hostname]

Regards K1

C++ compiling on Windows and Linux: ifdef switch

You can do:

#if MACRO0
    //code...
#elif MACRO1
    //code...
#endif

…where the identifier can be:

    __linux__       Defined on Linux
    __sun           Defined on Solaris
    __FreeBSD__     Defined on FreeBSD
    __NetBSD__      Defined on NetBSD
    __OpenBSD__     Defined on OpenBSD
    __APPLE__       Defined on Mac OS X
    __hpux          Defined on HP-UX
    __osf__         Defined on Tru64 UNIX (formerly DEC OSF1)
    __sgi           Defined on Irix
    _AIX            Defined on AIX
    _WIN32          Defined on Windows

async await return Task

This is a Task that is returning a Task of type String (C# anonymous function or in other word a delegation is used 'Func')

    public static async Task<string> MyTask()
    {
        //C# anonymous AsyncTask
        return await Task.FromResult<string>(((Func<string>)(() =>
        {
            // your code here
            return  "string result here";

        }))());
    }

Why is using onClick() in HTML a bad practice?

Two more reasons not to use inline handlers:

They can require tedious quote escaping issues

Given an arbitrary string, if you want to be able to construct an inline handler that calls a function with that string, for the general solution, you'll have to escape the attribute delimiters (with the associated HTML entity), and you'll have to escape the delimiter used for the string inside the attribute, like the following:

_x000D_
_x000D_
const str = prompt('What string to display on click?', 'foo\'"bar');
const escapedStr = str
  // since the attribute value is going to be using " delimiters,
  // replace "s with their corresponding HTML entity:
  .replace(/"/g, '&quot;')
  // since the string literal inside the attribute is going to delimited with 's,
  // escape 's:
  .replace(/'/g, "\\'");
  
document.body.insertAdjacentHTML(
  'beforeend',
  '<button onclick="alert(\'' + escapedStr + '\')">click</button>'
);
_x000D_
_x000D_
_x000D_

That's incredibly ugly. From the above example, if you didn't replace the 's, a SyntaxError would result, because alert('foo'"bar') is not valid syntax. If you didn't replace the "s, then the browser would interpret it as an end to the onclick attribute (delimited with "s above), which would also be incorrect.

If one habitually uses inline handlers, one would have to make sure to remember do something similar to the above (and do it right) every time, which is tedious and hard to understand at a glance. Better to avoid inline handlers entirely so that the arbitrary string can be used in a simple closure:

_x000D_
_x000D_
const str = prompt('What string to display on click?', 'foo\'"bar');
const button = document.body.appendChild(document.createElement('button'));
button.textContent = 'click';
button.onclick = () => alert(str);
_x000D_
_x000D_
_x000D_

Isn't that so much nicer?


The scope chain of an inline handler is extremely peculiar

What do you think the following code will log?

_x000D_
_x000D_
let disabled = true;
_x000D_
<form>
  <button onclick="console.log(disabled);">click</button>
</form>
_x000D_
_x000D_
_x000D_

Try it, run the snippet. It's probably not what you were expecting. Why does it produce what it does? Because inline handlers run inside with blocks. The above code is inside three with blocks: one for the document, one for the <form>, and one for the <button>:

_x000D_
_x000D_
let disabled = true;
_x000D_
<form>
  <button onclick="console.log(disabled);">click</button>
</form>
_x000D_
_x000D_
_x000D_

enter image description here

Since disabled is a property of the button, referencing disabled inside the inline handler refers to the button's property, not the outer disabled variable. This is quite counter-intuitive. with has many problems: it can be the source of confusing bugs and significantly slows down code. It isn't even permitted at all in strict mode. But with inline handlers, you're forced to run the code through withs - and not just through one with, but through multiple nested withs. It's crazy.

with should never be used in code. Because inline handlers implicitly require with along with all its confusing behavior, inline handlers should be avoided as well.

How to get directory size in PHP

I found this approach to be shorter and more compatible. The Mac OS X version of "du" doesn't support the -b (or --bytes) option for some reason, so this sticks to the more-compatible -k option.

$file_directory = './directory/path';
$output = exec('du -sk ' . $file_directory);
$filesize = trim(str_replace($file_directory, '', $output)) * 1024;

Returns the $filesize in bytes.

trigger body click with jQuery

You should have something like this:

$('body').click(function() {
   // do something here
});

The callback function will be called when the user clicks somewhere on the web page. You can trigger the callback programmatically with:

$('body').trigger('click');

Android Layout Animations from bottom to top and top to bottom on ImageView click

Try this :

Create anim folder inside your res folder and copy this four files :

slide_in_bottom.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="100%p"
android:duration="@android:integer/config_longAnimTime"/>  

slide_out_bottom.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0" 
android:duration="@android:integer/config_longAnimTime" /> 

slide_in_top.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
 android:toYDelta="0%p"
android:duration="@android:integer/config_longAnimTime" />

slide_out_top.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="100%p"
android:duration="@android:integer/config_longAnimTime" />

When you click on image view call:

overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);

When you click on original place call:

overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);

Main Activity :

package com.example.animationtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn1 = (Button) findViewById(R.id.btn1);


    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, test.class));

        }
    });


}
    }

activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity" >

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

 </LinearLayout>

test.java :

package com.example.animationtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class test extends Activity {

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    btn1 = (Button) findViewById(R.id.btn1);

    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);

    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
         finish();
            overridePendingTransition(R.anim.slide_in_right,
                    R.anim.slide_out_right);
            startActivity(new Intent(test.this, MainActivity.class));


        }
    });
}

    }

test.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

 </LinearLayout>

Hope this helps.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Removing print statements can also fix the problem.

Apart from loading images, this error also happens when your code is printing continuously at a high rate, which is causing the error "IOPub data rate exceeded". E.g. if you have a print statement in a for loop somewhere that is being called over 1000 times.

How can you search Google Programmatically Java API

To search google using API you should use Google Custom Search, scraping web page is not allowed

In java you can use CustomSearch API Client Library for Java

The maven dependency is:

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-customsearch</artifactId>
    <version>v1-rev57-1.23.0</version>
</dependency> 

Example code searching using Google CustomSearch API Client Library

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

    String searchQuery = "test"; //The query to search
    String cx = "002845322276752338984:vxqzfa86nqc"; //Your search engine

    //Instance Customsearch
    Customsearch cs = new Customsearch.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), null) 
                   .setApplicationName("MyApplication") 
                   .setGoogleClientRequestInitializer(new CustomsearchRequestInitializer("your api key")) 
                   .build();

    //Set search parameter
    Customsearch.Cse.List list = cs.cse().list(searchQuery).setCx(cx); 

    //Execute search
    Search result = list.execute();
    if (result.getItems()!=null){
        for (Result ri : result.getItems()) {
            //Get title, link, body etc. from search
            System.out.println(ri.getTitle() + ", " + ri.getLink());
        }
    }

}

As you can see you will need to request an api key and setup an own search engine id, cx.

Note that you can search the whole web by selecting "Search entire web" on basic tab settings during setup of cx, but results will not be exactly the same as a normal browser google search.

Currently (date of answer) you get 100 api calls per day for free, then google like to share your profit.

git replace local version with remote version

Use the -s or --strategy option combined with the -X option. In your specific question, you want to keep all of the remote files and replace the local files of the same name.

Replace conflicts with the remote version

git merge -s recursive -Xtheirs upstream/master  

will use the remote repo version of all conflicting files.

Replace conflicts with the local version

git merge -s recursive -Xours upstream/master

will use the local repo version of all conflicting files.

Is there a .NET/C# wrapper for SQLite?

sqlite-net is an open source, minimal library to allow .NET and Mono applications to store data in SQLite 3 databases. More information at the wiki page.

It is written in C# and is meant to be simply compiled in with your projects. It was first designed to work with MonoTouch on the iPhone, but has grown up to work on all the platforms (Mono for Android, .NET, Silverlight, WP7, WinRT, Azure, etc.).

It is available as a Nuget package, where it is the 2nd most popular SQLite package with over 60,000 downloads as of 2014.

sqlite-net was designed as a quick and convenient database layer. Its design follows from these goals:

  • Very easy to integrate with existing projects and with MonoTouch projects.
  • Thin wrapper over SQLite and should be fast and efficient. (The library should not be the performance bottleneck of your queries.)
  • Very simple methods for executing CRUD operations and queries safely (using parameters) and for retrieving the results of those query in a strongly typed fashion.
  • Works with your data model without forcing you to change your classes. (Contains a small reflection-driven ORM layer.)
  • 0 dependencies aside from a compiled form of the sqlite2 library.

Non-goals include:

  • Not an ADO.NET implementation. This is not a full SQLite driver. If you need that, use System.Data.SQLite.

Nginx -- static file serving confusion with root & alias

In other words on keeping this brief: in case of root, location argument specified is part of filesystem's path and URI . On the other hand — for alias directive argument of location statement is part of URI only

So, alias is a different name that maps certain URI to certain path in the filesystem, whereas root appends location argument to the root path given as argument to root directive.

Java simple code: java.net.SocketException: Unexpected end of file from server

I got this exception too. MY error code is below

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(requestMethod);
        connection.setRequestProperty("Content-type", "JSON");

I found "Content-type" should not be "JSON",is wrong! I solved this exception by update this line to below

        connection.setRequestProperty("Content-type", "application/json");

you can check up your "Content-type"

Using $window or $location to Redirect in AngularJS

It might help you! demo

AngularJs Code-sample

var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
    $scope.ClickMeToRedirect = function () {
        var url = "http://" + $window.location.host + "/Account/Login";
        $log.log(url);
        $window.location.href = url;
    };
});

HTML Code-sample

<div ng-app="urlApp">
    <div ng-controller="urlCtrl">
        Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
    </div>
</div>

How to ignore whitespace in a regular expression subject string?

You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

/cats/ -> /c\s*a\s*t\s*s/

Simple check for SELECT query empty result

Use @@ROWCOUNT:

SELECT * FROM service s WHERE s.service_id = ?;

IF @@ROWCOUNT > 0 
   -- do stuff here.....

According to SQL Server Books Online:

Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.

How to get height of Keyboard?

Shorter version here:

func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height
        }
}

List directory tree structure in python?

Here's a function to do that with formatting:

import os

def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print('{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            print('{}{}'.format(subindent, f))

Pandas index column title or name

Setting the index name can also be accomplished at creation:

pd.DataFrame(data={'age': [10,20,30], 'height': [100, 170, 175]}, index=pd.Series(['a', 'b', 'c'], name='Tag'))

Fetch: POST json data

You only need to check if response is ok coz the call not returning anything.

var json = {
    json: JSON.stringify({
        a: 1,
        b: 2
    }),
    delay: 3
};

fetch('/echo/json/', {
    method: 'post',
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
    },
    body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then((response) => {if(response.ok){alert("the call works ok")}})
.catch (function (error) {
    console.log('Request failed', error);
});    

Quickest way to clear all sheet contents VBA

You can use the .Clear method:

Sheets("Zeros").UsedRange.Clear

Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.

Regex: Specify "space or start of string" and "space or end of string"

You can use any of the following:

\b      #A word break and will work for both spaces and end of lines.
(^|\s)  #the | means or. () is a capturing group. 


/\b(stackoverflow)\b/

Also, if you don't want to include the space in your match, you can use lookbehind/aheads.

(?<=\s|^)         #to look behind the match
(stackoverflow)   #the string you want. () optional
(?=\s|$)          #to look ahead.

How to split() a delimited string to a List<String>

Either use:

List<string> list = new List<string>(array);

or from LINQ:

List<string> list = array.ToList();

Or change your code to not rely on the specific implementation:

IList<string> list = array; // string[] implements IList<string>

Communication between tabs or windows

I created a module that works equal to the official Broadcastchannel but has fallbacks based on localstorage, indexeddb and unix-sockets. This makes sure it always works even with Webworkers or NodeJS. See pubkey:BroadcastChannel

How to enable/disable bluetooth programmatically in android

Here is a bit more robust way of doing this, also handling the return values of enable()\disable() methods:

public static boolean setBluetooth(boolean enable) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enable && !isEnabled) {
        return bluetoothAdapter.enable(); 
    }
    else if(!enable && isEnabled) {
        return bluetoothAdapter.disable();
    }
    // No need to change bluetooth state
    return true;
}

And add the following permissions into your manifest file:

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

But remember these important points:

This is an asynchronous call: it will return immediately, and clients should listen for ACTION_STATE_CHANGED to be notified of subsequent adapter state changes. If this call returns true, then the adapter state will immediately transition from STATE_OFF to STATE_TURNING_ON, and some time later transition to either STATE_OFF or STATE_ON. If this call returns false then there was an immediate problem that will prevent the adapter from being turned on - such as Airplane mode, or the adapter is already turned on.

UPDATE:

Ok, so how to implement bluetooth listener?:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                 BluetoothAdapter.ERROR);
            switch (state) {
            case BluetoothAdapter.STATE_OFF:
                // Bluetooth has been turned off;
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                // Bluetooth is turning off;
                break;
            case BluetoothAdapter.STATE_ON:
                // Bluetooth is on
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                // Bluetooth is turning on
                break;
            }
        }
    }
};

And how to register/unregister the receiver? (In your Activity class)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ...

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);
}

@Override
public void onStop() {
    super.onStop();

     // ...

    // Unregister broadcast listeners
    unregisterReceiver(mReceiver);
}

Superscript in CSS only?

try

.aftersup {
 font-size: 1em;
 margin: left;
 vertical-align: .7em;
}

or plain "after"

.after {
 font-size: 1em;
 margin: left;
 vertical-align: .7em;
}

".a.external:after" could be simplified

or

.after {
 font-size: 50%;
 margin: left;
 vertical-align: .7em;
}

using "font size 50%" - 50% of what size? this might not work well if not used within some tag defining text size previous to superscript...

if you use "font-size: 1em;" then the font size is set for sure, without reference to a tag that defines link text size, unless link text is set at 100% and superscript is 50% of that 100%.

Using "font-size: 1em;" actually sets font size baseline.

Set "vertical-align" size smaller, if you want superscript font to be smaller than link text

Set "vertical-align" size same as font size, if you want superscript font to be same size as link text

To align with link text, you need to set "margin" same as link text (left, center, right, justified).

.text {
  font-size: 1em;
  margin: left;
}
.aftersup {
  font-size: 1em;
  margin: left;
  vertical-align: .7em;
}

It should be something like below example links with superscript

<p class="text"><a href="url">https://stackoverflow.com/questions/501671/superscript-in-css-only</a><aftersup>+</aftersup></p>

or

<p class="text"><a href="url">https://stackoverflow.com/questions/501671/superscript-in-css-only</a><aftersup>You got this</aftersup></p>

or

<a href="url">https://stackoverflow.com/questions/501671/superscript-in-css-only</a><aftersup>+</aftersup>

or

<a href="url">https://stackoverflow.com/questions/501671/superscript-in-css-only<aftersup>You got this</aftersup>

As in...

Superscript in CSS only?+

or

Superscript in CSS only?You got this

HTML/CSS: how to put text both right and left aligned in a paragraph

I wouldn't put it in the same <p>, since IMHO the two infos are semantically too different. If you must, I'd suggest this:

<p style="text-align:right">
 <span style="float:left">I'll be on the left</span>
 I'll be on the right
</p>

how to increase java heap memory permanently?

You also use this below to expand the memory

export _JAVA_OPTIONS="-Xms512m -Xmx1024m -Xss512m -XX:MaxPermSize=1024m"

Xmx specifies the maximum memory allocation pool for a Java virtual machine (JVM)

Xms specifies the initial memory allocation pool.

Xss setting memory size of thread stack

XX:MaxPermSize: the maximum permanent generation size

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:

http://getbootstrap.com/javascript/#modals-usage

i.e.

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal('show');

cat, grep and cut - translated to python

you need to use os.system module to execute shell command

import os
os.system('command')

if you want to save the output for later use, you need to use subprocess module

import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]

Best way to find if an item is in a JavaScript array?

If you are using jQuery:

$.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);

For more information: http://api.jquery.com/jQuery.inArray/