Programs & Examples On #Dataviewwebpart

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

Find OpenCV Version Installed on Ubuntu

You can look at the headers or libs installed. pkg-config can tell you where they are:

pkg-config --cflags opencv
pkg-config --libs opencv

Alternatively you can write a simple program and print the following defs:

CV_MAJOR_VERSION
CV_MINOR_VERSION

A similar question has been also asked here:

jQuery - Illegal invocation

Just for the record it can also happen if you try to use undeclared variable in data like

var layout = {};
$.ajax({
  ...
  data: {
    layout: laoyut // notice misspelled variable name
  },
  ...
});

Meaning of delta or epsilon argument of assertEquals for double values

Floating point calculations are not exact - there is often round-off errors, and errors due to representation. (For example, 0.1 cannot be exactly represented in binary floating point.)

Because of this, directly comparing two floating point values for equality is usually not a good idea, because they can be different by a small amount, depending upon how they were computed.

The "delta", as it's called in the JUnit javadocs, describes the amount of difference you can tolerate in the values for them to be still considered equal. The size of this value is entirely dependent upon the values you're comparing. When comparing doubles, I typically use the expected value divided by 10^6.

How do I append a node to an existing XML file in java

To append a new data element,just do this...

Document doc = docBuilder.parse(is);        
Node root=doc.getFirstChild();
Element newserver=doc.createElement("new_server");
root.appendChild(newserver);

easy.... 'is' is an InputStream object. rest is similar to your code....tried it just now...

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

There are my config to support L and old versions of android:

apply plugin: 'com.android.application'

android {
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.example.uladzimir_klyshevich.myapplication"
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }


    productFlavors {
        l {
            minSdkVersion 'android-L'
            targetSdkVersion 'android-L'
            compileSdkVersion 'android-L'
        }
        old {
            minSdkVersion 10
            targetSdkVersion 20
            //TODO comment second line if build is not compiles for "L"
            compileSdkVersion 20
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    lCompile 'com.android.support:appcompat-v7:21.+'
    oldCompile 'com.android.support:appcompat-v7:19.1.0'
}

As result you will have flavors:

oldDebug
oldRelease
lDebug
lRelease

And can install your application on old versions of android.

Duplicate Entire MySQL Database

Once upon a time in MySQL you could just copy all the table files to another directory in the mysql tree

mysql cli - create database db2

linux cli - cp db1 db2

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

SQL How to Select the most recent date item

Assuming your RDBMS know window functions and CTE and USER_ID is the patient's id:

WITH TT AS (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY USER_ID ORDER BY DOCUMENT_DATE DESC) AS N
    FROM test_table
)
SELECT *
FROM TT
WHERE N = 1;

I assumed you wanted to sort by DOCUMENT_DATE, you can easily change that if wanted. If your RDBMS doesn't know window functions, you'll have to do a join :

SELECT *
FROM test_table T1
INNER JOIN (SELECT USER_ID, MAX(DOCUMENT_DATE) AS maxDate
            FROM test_table
            GROUP BY USER_ID) T2
    ON T1.USER_ID = T2.USER_ID
        AND T1.DOCUMENT_DATE = T2.maxDate;

It would be good to tell us what your RDBMS is though. And this query selects the most recent date for every patient, you can add a condition for a given patient.

Execute PHP function with onclick

First, understand that you have three languages working together:

  • PHP: It only runs by the server and responds to requests like clicking on a link (GET) or submitting a form (POST).

  • HTML & JavaScript: It only runs in someone's browser (excluding NodeJS).

I'm assuming your file looks something like:

<!DOCTYPE HTML>
<html>
<?php
  function runMyFunction() {
    echo 'I just ran a php function';
  }

  if (isset($_GET['hello'])) {
    runMyFunction();
  }
?>

Hello there!
<a href='index.php?hello=true'>Run PHP Function</a>
</html>

Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST), this is how you have to run a PHP function even though they're in the same file. This gives you a level of security, "Should I run this script for this user or not?".

If you don't want to refresh the page, you can make a request to PHP without refreshing via a method called Asynchronous JavaScript and XML (AJAX).

That is something you can look up on YouTube though. Just search "jquery ajax"

I recommend Laravel to anyone new to start off right: http://laravel.com/

How to insert values in two dimensional array programmatically?

Think about it as array of array.

If you do this str[x][y], then there is array of length x where each element in turn contains array of length y. In java its not necessary for second dimension to have same length. So for x=i you can have y=m and x=j you can have y=n

For this your declaration looks like

String[][] test = new String[4][]; test[0] = new String[3]; test[1] = new String[2];

etc..

How to generate a random number between 0 and 1?

It seems to me you have not called srand first. Usage example here.

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

How can I get a resource "Folder" from inside my jar File?

Simple ... use OSGi. In OSGi you can iterate over your Bundle's entries with findEntries and findPaths.

Java HTML Parsing

Several years ago I used JTidy for the same purpose:

http://jtidy.sourceforge.net/

"JTidy is a Java port of HTML Tidy, a HTML syntax checker and pretty printer. Like its non-Java cousin, JTidy can be used as a tool for cleaning up malformed and faulty HTML. In addition, JTidy provides a DOM interface to the document that is being processed, which effectively makes you able to use JTidy as a DOM parser for real-world HTML.

JTidy was written by Andy Quick, who later stepped down from the maintainer position. Now JTidy is maintained by a group of volunteers.

More information on JTidy can be found on the JTidy SourceForge project page ."

Pyinstaller setting icons don't change

That's error of a module in pyinstaller. The stuff would be sth like this, right:

File "c:\users\p-stu\appdata\local\programs\python\python38-32\lib\site-packages\PyInstaller\utils\win32\icon.py", line 234, in CopyIcons
    except win32api.error as W32E:
AttrubuteError: module 'win32ctypes.pywin32.win32api' has no attribute 'error'

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

height: calc(100%) not working correctly in CSS

You need to ensure the html and body are set to 100% and also be sure to add vendor prefixes for calc, so -moz-calc, -webkit-calc.

Following CSS works:

html,body {
    background: blue;
    height:100%;
    padding:0;
    margin:0;
}
header {
    background: red;
    height: 20px;
    width:100%
}
h1 {
    font-size:1.2em;
    margin:0;
    padding:0;
    height: 30px;
    font-weight: bold;
    background:yellow
}
#theCalcDiv {
    background:green;
    height: -moz-calc(100% - (20px + 30px));
    height: -webkit-calc(100% - (20px + 30px));
    height: calc(100% - (20px + 30px));
    display:block
}

I also set your margin/padding to 0 on html and body, otherwise there would be a scrollbar when this is added on.

Here's an updated fiddle

http://jsfiddle.net/UF3mb/10/

Browser support is: IE9+, Firefox 16+ and with vendor prefix Firefox 4+, Chrome 19+, Safari 6+

How can I align two divs horizontally?

if you have two divs, you can use this to align the divs next to each other in the same row:

_x000D_
_x000D_
#keyword {_x000D_
    float:left;_x000D_
    margin-left:250px;_x000D_
    position:absolute;_x000D_
}_x000D_
_x000D_
#bar {_x000D_
    text-align:center;_x000D_
}
_x000D_
<div id="keyword">_x000D_
Keywords:_x000D_
</div>_x000D_
<div id="bar">_x000D_
    <input type = textbox   name ="keywords" value="" onSubmit="search()" maxlength=40>_x000D_
    <input type = button   name="go" Value="Go ahead and find" onClick="search()">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python Checking a string's first and last character

When you say [:-1] you are stripping the last element. Instead of slicing the string, you can apply startswith and endswith on the string object itself like this

if str1.startswith('"') and str1.endswith('"'):

So the whole program becomes like this

>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi

Even simpler, with a conditional expression, like this

>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi

Return number of rows affected by UPDATE statements

You might need to collect the stats as you go, but @@ROWCOUNT captures this:

declare @Fish table (
Name varchar(32)
)

insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT  --gives 1

update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3

Count number of lines in a git repository

I did this:

git ls-files | xargs file | grep "ASCII" | cut -d : -f 1 | xargs wc -l

this works if you count all text files in the repository as the files of interest. If some are considered documentation, etc, an exclusion filter can be added.

How to replace sql field value

To avoid update names that contain .com like [email protected] to [email protected], you can do this:

UPDATE Yourtable
SET Email = LEFT(@Email, LEN(@Email) - 4) + REPLACE(RIGHT(@Email, 4), '.com', '.org')

Can you have if-then-else logic in SQL?

The CASE statement is the closest to an IF statement in SQL, and is supported on all versions of SQL Server:

SELECT CASE <variable> 
           WHEN <value>      THEN <returnvalue> 
           WHEN <othervalue> THEN <returnthis> 
           ELSE <returndefaultcase> 
       END 
  FROM <table> 

IntelliJ: Error:java: error: release version 5 not supported

Within IntelliJ, open pom.xml file.

Add this section before <dependencies> (if your file already has a <properties> section, just add the <maven.compiler...> lines below to that existing section):

<properties> 
   <maven.compiler.source>1.8</maven.compiler.source> 
   <maven.compiler.target>1.8</maven.compiler.target> 
</properties>

error: command 'gcc' failed with exit status 1 on CentOS

I bet you have to install libxml2-devel or libxml++-devel or even python-devel. But it is only a wild guess, not seeing the actual error from the log file. But it seems gcc is missing either a header file or a library file.

How to call a SOAP web service on Android

This is a working example of consuming SOAP web services in android.

**Note ::***DON'T FORGET TO ADD ksoap2.jar in your project and also add the INTERNET permission in AndroidManifest file*

public final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
public final String METHOD_NAME = "FahrenheitToCelsius";
public final String PROPERTY_NAME = "Fahrenheit";
public final String SOAP_ACTION = "http://tempuri.org/FahrenheitToCelsius";
public final String SOAP_ADDRESS = "http://www.w3schools.com/webservices/tempconvert.asmx";


private class TestAsynk extends AsyncTask<String, Void, String> {

    @Override
    protected void onPostExecute(String result) {

        super.onPostExecute(result);
        Toast.makeText(getApplicationContext(),
                String.format("%.2f", Float.parseFloat(result)),
                Toast.LENGTH_SHORT).show();
    }

    @Override
    protected String doInBackground(String... params) {
        SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
                METHOD_NAME);
        request.addProperty(PROPERTY_NAME, params[0]);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;

        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(
                SOAP_ADDRESS);
        Object response = null;
        try {

            androidHttpTransport.call(SOAP_ACTION, envelope);
            response = envelope.getResponse();
            Log.e("Object response", response.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.toString();
    }
}

PySpark: multiple conditions in when clause

You get SyntaxError error exception because Python has no && operator. It has and and & where the latter one is the correct choice to create boolean expressions on Column (| for a logical disjunction and ~ for logical negation).

Condition you created is also invalid because it doesn't consider operator precedence. & in Python has a higher precedence than == so expression has to be parenthesized.

(col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>

On a side note when function is equivalent to case expression not WHEN clause. Still the same rules apply. Conjunction:

df.where((col("foo") > 0) & (col("bar") < 0))

Disjunction:

df.where((col("foo") > 0) | (col("bar") < 0))

You can of course define conditions separately to avoid brackets:

cond1 = col("Age") == "" 
cond2 = col("Survived") == "0"

cond1 & cond2

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Here is a complete answer that will hopefully help others...


I want to setup mysql replication using master and slave, and since the only thing I knew was that it uses log file(s) to synchronize, if the slave goes offline and gets out of sync, in theory it should only need to connect back to its master and keep reading the log file from where it left off, as user malonso mentioned.

So here are the test result after configuring the master and slave as mentioned by: http://dev.mysql.com/doc/refman/5.0/en/replication-howto.html ...

Provided you use the recommended master/slave configuration and don't write to the slave, he and I where right (as far as mysql-server 5.x is concerned). I didn't even need to use "START SLAVE;", it just caught up to its master. But there is a default 88000 something retries every 60 second so I guess if you exhaust that you might have to start or restart the slave. Anyways, for those like me who wanted to know if having a slave going offline and back up again requires manual intervention.. no, it doesn't.

Maybe the original poster had corruption in the log-file(s)? But most probably not just a server going off-line for a day.


pulled from /usr/share/doc/mysql-server-5.1/README.Debian.gz which probably makes sense to non debian servers as well:

* FURTHER NOTES ON REPLICATION
===============================
If the MySQL server is acting as a replication slave, you should not
set --tmpdir to point to a directory on a memory-based filesystem or to
a directory that is cleared when the server host restarts. A replication
slave needs some of its temporary files to survive a machine restart so
that it can replicate temporary tables or LOAD DATA INFILE operations. If
files in the temporary file directory are lost when the server restarts,
replication fails.

you can use something sql like: show variables like 'tmpdir'; to find out.

jQuery/JavaScript to replace broken images

I couldn't find a script to suit my needs, so I made a recursive function to check for broken images and attempt to reload them every four seconds until they are fixed.

I limited it to 10 attempts as if it's not loaded by then the image might not be present on server and the function would enter an infinite loop. I am still testing though. Feel free to tweak it :)

var retries = 0;
$.imgReload = function() {
    var loaded = 1;

    $("img").each(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {

            var src = $(this).attr("src");
            var date = new Date();
            $(this).attr("src", src + "?v=" + date.getTime()); //slightly change url to prevent loading from cache
            loaded =0;
        }
    });

    retries +=1;
    if (retries < 10) { // If after 10 retries error images are not fixed maybe because they
                        // are not present on server, the recursion will break the loop
        if (loaded == 0) {
            setTimeout('$.imgReload()',4000); // I think 4 seconds is enough to load a small image (<50k) from a slow server
        }
        // All images have been loaded
        else {
            // alert("images loaded");
        }
    }
    // If error images cannot be loaded  after 10 retries
    else {
        // alert("recursion exceeded");
    }
}

jQuery(document).ready(function() {
    setTimeout('$.imgReload()',5000);
});

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

How to convert from int to string in objective c: example code

If you just need an int to a string as you suggest, I've found the easiest way is to do as below:

[NSString stringWithFormat:@"%d",numberYouAreTryingToConvert]

generate days from date range

if you want the list of dates between two dates:

create table #dates ([date] smalldatetime)
while @since < @to
begin
     insert into #dates(dateadd(day,1,@since))
     set @since = dateadd(day,1,@since)
end
select [date] from #dates

*fiddle here: http://sqlfiddle.com/#!6/9eecb/3469

Get Value of a Edit Text field

I guess you will have to use this code when calling the "mEdit" your EditText object :

myActivity.this.mEdit.getText().toString()

Just make sure that the compiler know which EditText to call and use.

Add custom icons to font awesome

I suggest keeping your icons separate from FontAwesome and create and maintain your own custom library. Personally, I think it is much easier to maintain keeping FontAwesome separate if you are going to be creating your own icon library. You can then have FontAwesome loaded into your site from a CDN and never have to worry about keeping it up-to-date.

When creating your own custom icons, create each icon via Adobe Illustrator or similar software. Once your icons are created, save each individually in SVG format on your computer.

Next, head on over to IcoMoon: http://icomoon.io , which has the best font generating software (in my opinion), and it's free. IcoMoon will allow you to import your individual svg-saved fonts into a font library, then generate your custom icon glyph library in eot, ttf, woff, and svg. One format IcoMoon does not generate is woff2.

After generating your icon pack at IcoMoon, head over to FontSquirrel: http://fontsquirrel.com and use their font generator. Use your ttf file generated at IcoMoon. In the newly generated icon pack created, you'll now have your icon pack in woff2 format.

Make sure the files for eot, ttf, svg, woff, and woff2 are all the same name. You are generating an icon pack from two different websites/software, and they do name their generated output differently.

You'll have CSS generated for your icon pack at both locations. But the CSS generated at IcoMoon will not include the woff2 format in your @font-face {} declaration. Make sure to add that when you're adding your CSS to your project:

@font-face {
    font-family: 'customiconpackname';
    src: url('../fonts/customiconpack.eot?lchn8y');
    src: url('../fonts/customiconpack.eot?lchn8y#iefix') format('embedded-opentype'),
         url('../fonts/customiconpack.ttf?lchn8y') format('truetype'),
         url('../fonts/customiconpack.woff2?lchn8y') format('woff'),
         url('../fonts/customiconpack.woff?lchn8y') format('woff'),
         url('../fonts/customiconpack.svg?lchn8y#customiconpack') format('svg');
    font-weight: normal;
    font-style: normal;
}

Keep in mind that you can get the glyph unicode values of each icon in your icon pack using the IcoMoon software. These values can be helpful in assigning your icons via CSS, as in (assuming we're using the font-family declared in the example @font-face {...} above):

selector:after {
    font-family: 'customiconpackname';
    content: '\e953';
    }

You can also get the glyph unicode value e953 if you open the font-pack-generated svg file in a text editor. E.g.:

<glyph unicode="&#xe953;" glyph-name="eye" ... />

Sending data through POST request from a node.js server to a node.js server

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring');
var http = require('http');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

What is the difference between Task.Run() and Task.Factory.StartNew()

People already mentioned that

Task.Run(A);

Is equivalent to

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

But no one mentioned that

Task.Factory.StartNew(A);

Is equivalent to:

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current);

As you can see two parameters are different for Task.Run and Task.Factory.StartNew:

  1. TaskCreationOptions - Task.Run uses TaskCreationOptions.DenyChildAttach which means that children tasks can not be attached to the parent, consider this:

    var parentTask = Task.Run(() =>
    {
        var childTask = new Task(() =>
        {
            Thread.Sleep(10000);
            Console.WriteLine("Child task finished.");
        }, TaskCreationOptions.AttachedToParent);
        childTask.Start();
    
        Console.WriteLine("Parent task finished.");
    });
    
    parentTask.Wait();
    Console.WriteLine("Main thread finished.");
    

    When we invoke parentTask.Wait(), childTask will not be awaited, even though we specified TaskCreationOptions.AttachedToParent for it, this is because TaskCreationOptions.DenyChildAttach forbids children to attach to it. If you run the same code with Task.Factory.StartNew instead of Task.Run, parentTask.Wait() will wait for childTask because Task.Factory.StartNew uses TaskCreationOptions.None

  2. TaskScheduler - Task.Run uses TaskScheduler.Default which means that the default task scheduler (the one that runs tasks on Thread Pool) will always be used to run tasks. Task.Factory.StartNew on the other hand uses TaskScheduler.Current which means scheduler of the current thread, it might be TaskScheduler.Default but not always. In fact when developing Winforms or WPF applications it is required to update UI from the current thread, to do this people use TaskScheduler.FromCurrentSynchronizationContext() task scheduler, if you unintentionally create another long running task inside task that used TaskScheduler.FromCurrentSynchronizationContext() scheduler the UI will be frozen. A more detailed explanation of this can be found here

So generally if you are not using nested children task and always want your tasks to be executed on Thread Pool it is better to use Task.Run, unless you have some more complex scenarios.

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

:not(:empty) CSS selector is not working?

This should work in modern browsers:

input[value]:not([value=""])

It selects all inputs with value attribute and then select inputs with non empty value among them.

TERM environment variable not set

SOLVED: On Debian 10 by adding "EXPORT TERM=xterm" on the Script executed by CRONTAB (root) but executed as www-data.

$ crontab -e

*/15 * * * * /bin/su - www-data -s /bin/bash -c '/usr/local/bin/todos.sh'

FILE=/usr/local/bin/todos.sh

#!/bin/bash -p
export TERM=xterm && cd /var/www/dokuwiki/data/pages && clear && grep -r -h '|(TO-DO)' > /var/www/todos.txt && chmod 664 /var/www/todos.txt && chown www-data:www-data /var/www/todos.txt

Why does the order in which libraries are linked sometimes cause errors in GCC?

I have seen this a lot, some of our modules link in excess of a 100 libraries of our code plus system & 3rd party libs.

Depending on different linkers HP/Intel/GCC/SUN/SGI/IBM/etc you can get unresolved functions/variables etc, on some platforms you have to list libraries twice.

For the most part we use structured hierarchy of libraries, core, platform, different layers of abstraction, but for some systems you still have to play with the order in the link command.

Once you hit upon a solution document it so the next developer does not have to work it out again.

My old lecturer used to say, "high cohesion & low coupling", it’s still true today.

How do I detect a click outside an element?

The solutions here work fine when only one element is to be managed. If there are multiple elements, however, the problem is much more complicated. Tricks with e.stopPropagation() and all the others will not work.

I came up with a solution, and maybe it is not so easy, but it's better than nothing. Have a look:

$view.on("click", function(e) {

    if(model.isActivated()) return;

        var watchUnclick = function() {
            rootView.one("mouseleave", function() {
                $(document).one("click", function() {
                    model.deactivate();
                });
                rootView.one("mouseenter", function() {
                    watchUnclick();
                });
            });
        };
        watchUnclick();
        model.activate();
    });

Convert JSON String to JSON Object c#

You can try like following:

string output = JsonConvert.SerializeObject(jsonStr);

when exactly are we supposed to use "public static final String"?

The keyword final means that the value is constant(it cannot be changed). It is analogous to const in C.

And you can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).

Hope it helps.

Just what is an IntPtr exactly?

It's a "native (platform-specific) size integer." It's internally represented as void* but exposed as an integer. You can use it whenever you need to store an unmanaged pointer and don't want to use unsafe code. IntPtr.Zero is effectively NULL (a null pointer).

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
              from names) n2
  on (n2.author_id = n1.author_id)
Where true

used distinct if more inner join, because more join group performance is slow

How to hide status bar in Android

As FLAG_FULLSCREEN is deprecated from android R. You can use below code to hide status bar.

 @Suppress("DEPRECATION")
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {

           window.insetsController?.hide(WindowInsets.Type.statusBars())
    } else {

           window.setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN
            )
        }

Printing column separated by comma using Awk command line

A simple, although -less solution in :

while IFS=, read -r a a a b; do echo "$a"; done <inputfile

It works faster for small files (<100 lines) then as it uses less resources (avoids calling the expensive fork and execve system calls).

EDIT from Ed Morton (sorry for hi-jacking the answer, I don't know if there's a better way to address this):

To put to rest the myth that shell will run faster than awk for small files:

$ wc -l file
99 file

$ time while IFS=, read -r a a a b; do echo "$a"; done <file >/dev/null

real    0m0.016s
user    0m0.000s
sys     0m0.015s

$ time awk -F, '{print $3}' file >/dev/null

real    0m0.016s
user    0m0.000s
sys     0m0.015s

I expect if you get a REALY small enough file then you will see the shell script run in a fraction of a blink of an eye faster than the awk script but who cares?

And if you don't believe that it's harder to write robust shell scripts than awk scripts, look at this bug in the shell script you posted:

$ cat file
a,b,-e,d
$ cut -d, -f3 file
-e
$ awk -F, '{print $3}' file
-e
$ while IFS=, read -r a a a b; do echo "$a"; done <file

$

What does Html.HiddenFor do?

Like a lot of functions, this one can be used in many different ways to solve many different problems, I think of it as yet another tool in our toolbelts.

So far, the discussion has focused heavily on simply hiding an ID, but that is only one value, why not use it for lots of values! That is what I am doing, I use it to load up the values in a class only one view at a time, because html.beginform creates a new object and if your model object for that view already had some values passed to it, those values will be lost unless you provide a reference to those values in the beginform.

To see a great motivation for the html.hiddenfor, I recommend you see Passing data from a View to a Controller in .NET MVC - "@model" not highlighting

How can I tell how many objects I've stored in an S3 bucket?

Although this is an old question, and feedback was provided in 2015, right now it's much simpler, as S3 Web Console has enabled a "Get Size" option:

enter image description here

Which provides the following:

enter image description here

Padding a table row

This is a very old post, but I thought I should post my solution of a similar problem I faced recently.

Answer : I solved this issue by displaying the tr element as a block element i.e. specifying a CSS of display:block for the tr element. You can see this in code sample below.

_x000D_
_x000D_
<style>_x000D_
  tr {_x000D_
    display: block;_x000D_
    padding-bottom: 20px;_x000D_
  }_x000D_
  table {_x000D_
    border: 1px solid red;_x000D_
  }_x000D_
</style>_x000D_
<table>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <h2>Lorem Ipsum</h2>_x000D_
        <p>Fusce sodales lorem nec magna iaculis a fermentum lacus facilisis. Curabitur sodales risus sit amet neque fringilla feugiat. Ut tellus nulla, bibendum at faucibus ut, convallis eget neque. In hac habitasse platea dictumst. Nullam elit enim, gravida_x000D_
          eu blandit ut, pellentesque nec turpis. Proin faucibus, sem sed tempor auctor, ipsum velit pellentesque lorem, ut semper lorem eros ac eros. Vivamus mi urna, tempus vitae mattis eget, pretium sit amet sapien. Curabitur viverra lacus non tortor_x000D_
          luctus vitae euismod purus hendrerit. Praesent ut venenatis eros. Nulla a ligula erat. Mauris lobortis tempus nulla non scelerisque._x000D_
        </p>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<br>_x000D_
<br>This TEXT IS BELOW and OUTSIDE the TABLE element. NOTICE how the red table border is pushed down below the end of paragraph due to bottom padding being specified for the tr element. The key point here is that the tr element must be displayed as a block_x000D_
in order for padding to apply at the tr level.
_x000D_
_x000D_
_x000D_

How to add an element to a list?

Elements are added to list using append():

>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}

If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:

>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}

After doing that, you can assemble JSON again from dictionary you modified:

>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'

display html page with node.js

but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display.

That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.

You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391

Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js

TransactionRequiredException Executing an update/delete query

I Got the same error.

I just added the @Transactional annotation of javax.transaction.Transactional on the method.

'typeid' versus 'typeof' in C++

You can use Boost demangle to accomplish a nice looking name:

#include <boost/units/detail/utility.hpp>

and something like

To_main_msg_evt ev("Failed to initialize cards in " + boost::units::detail::demangle(typeid(*_IO_card.get()).name()) + ".\n", true, this);

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

"make clean" results in "No rule to make target `clean'"

You have fallen victim to the most common of errors in Makefiles. You always need to put a Tab at the beginning of each command. You've put spaces before the $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) and @rm -f $(PROGRAMS) *.o core lines. If you replace them with a Tab, you'll be fine.

However, this error doesn't lead to a "No rule to make target ..." error. That probably means your issue lies beyond your Makefile. Have you checked this is the correct Makefile, as in the one you want to be specifying your commands? Try explicitly passing it as a parameter to make, make -f Makefile and let us know what happens.

In Swift how to call method with parameters on GCD main thread?

Modern versions of Swift use DispatchQueue.main.async to dispatch to the main thread:

DispatchQueue.main.async { 
  // your code here
}

To dispatch after on the main queue, use:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  // your code here
}

Older versions of Swift used:

dispatch_async(dispatch_get_main_queue(), {
  let delegateObj = UIApplication.sharedApplication().delegate as YourAppDelegateClass
  delegateObj.addUIImage("yourstring")
})

How to set button click effect in Android?

This can be achieved by creating a drawable xml file containing a list of states for the button. So for example if you create a new xml file called "button.xml" with the following code:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/YOURIMAGE" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:drawable="@drawable/YOURIMAGE" />
</selector>

To keep the background image with a darkened appearance on press, create a second xml file and call it gradient.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/YOURIMAGE"/>
    </item>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <gradient android:angle="90" android:startColor="#880f0f10" android:centerColor="#880d0d0f" android:endColor="#885d5d5e"/>
        </shape>
    </item>
</layer-list>

In the xml of your button set the background to be the button xml e.g.

android:background="@drawable/button"

Hope this helps!

Edit: Changed the above code to show an image (YOURIMAGE) in the button as opposed to a block colour.

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Directly from the Windows.h header file:

#ifndef WIN32_LEAN_AND_MEAN
    #include <cderr.h>
    #include <dde.h>
    #include <ddeml.h>
    #include <dlgs.h>
    #ifndef _MAC
        #include <lzexpand.h>
        #include <mmsystem.h>
        #include <nb30.h>
        #include <rpc.h>
    #endif
    #include <shellapi.h>
    #ifndef _MAC
        #include <winperf.h>
        #include <winsock.h>
    #endif
    #ifndef NOCRYPT
        #include <wincrypt.h>
        #include <winefs.h>
        #include <winscard.h>
    #endif

    #ifndef NOGDI
        #ifndef _MAC
            #include <winspool.h>
            #ifdef INC_OLE1
                #include <ole.h>
            #else
                #include <ole2.h>
            #endif /* !INC_OLE1 */
        #endif /* !MAC */
        #include <commdlg.h>
    #endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

Also, from Microsoft's support page:

To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

VC_EXTRALEAN
WIN32_LEAN_AND_MEAN

You can use them to reduce the size of the Win32 header files.

Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

C++ Redefinition Header Files (winsock2.h)

#pragma once is flakey, even on MS compilers, and is not supported by many other compilers. As many other people have mentioned, using include guards is the way to go. Don't use #pragma once at all - it'll make your life much easier.

How to open google chrome from terminal?

In Terminal, type open -a Google\ Chrome

This will open Google Chrome application without any need to manipulate directories!

HTTP GET in VB.NET

In VB.NET:

Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184")

In C#:

System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184");

C#: easiest way to populate a ListBox from a List

Try :

List<string> MyList = new List<string>();
MyList.Add("HELLO");
MyList.Add("WORLD");

listBox1.DataSource = MyList;

Have a look at ListControl.DataSource Property

How to restart ADB manually from Android Studio

After reinstalling Android Studio, Is working without adb kill-server

Copy files on Windows Command Line with Progress

If you want to copy files and see a "progress" I suggest the script below in Batch that I used from another script as a base

I used a progress bar and a percentage while the script copies the game files Nuclear throne:

@echo off
title NTU Installer
setlocal EnableDelayedExpansion

@echo Iniciando instalacao...
if not exist "C:\NTU" (
    md "C:\NTU
)
if not exist "C:\NTU\Profile" (
    md "C:\NTU\Profile"
)
ping -n 5 localhost >nul

for %%f in (*.*) do set/a vb+=1
set "barra="
::loop da barra
for /l %%i in (1,1,70) do set "barra=!barra!Û"
rem barra vaiza para ser preenchida
set "resto="
rem loop da barra vazia
for /l %%i in (1,1,110) do set "resto=!resto!"
set i=0
rem carregameno de arquivos
for %%f in (*.*) do (
    >>"log_ntu.css" (
        copy "%%f" "C:\NTU">nul
        echo Copiado:%%f
    )
    cls
    set /a i+=1,percent=i*100/vb,barlen=70*percent/100
    for %%a in (!barlen!) do echo  !percent!%% /                         
    [!barra:~0,%%a!%resto%]
    echo Instalado:[%%f] / Complete:[!percent!%%/100%]
    ping localhost -n 1.9  >nul
)
xcopy /e "Profile" "C:\NTU\Profile">"log_profile.css"              

@echo Criando atalho na area de trabalho...
copy "NTU.lnk" "C:\Users\%username%\Desktop">nul
ping localhost -n 4  >nul

@echo Arquivos instalados!
pause

`React/RCTBridgeModule.h` file not found

I ran into this issue after doing a manual react-native link of a dependency which didn't support auto link on RN 0.59+

The solution was to select the xcodeproj file under the Libraries folder in Xcode and then in Build Settings, change Header Search Paths to add these two (recursive):

$(SRCROOT)/../../../ios/Pods/Headers/Public/React-Core
$(SRCROOT)/../../../ios/Pods/Headers/Public

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

Maximum size of an Array in Javascript

You could try something like this to test and trim the length:

http://jsfiddle.net/orolo/wJDXL/

_x000D_
_x000D_
var longArray = [1, 2, 3, 4, 5, 6, 7, 8];_x000D_
_x000D_
if (longArray.length >= 6) {_x000D_
  longArray.length = 3;_x000D_
}_x000D_
_x000D_
alert(longArray); //1, 2, 3
_x000D_
_x000D_
_x000D_

Redis - Connect to Remote Server

  • if you downloaded redis yourself (not apt-get install redis-server) and then edited the redis.conf with the above suggestions, make sure your start redis with the config like so: ./src/redis-server redis.conf

    • also side note i am including a screenshot of virtual box setting to connect to redis, if you are on windows and connecting to a virtualbox vm.

enter image description here

Difference between signed / unsigned char

There are three char types: (plain) char, signed char and unsigned char. Any char is usually an 8-bit integer* and in that sense, a signed and unsigned char have a useful meaning (generally equivalent to uint8_t and int8_t). When used as a character in the sense of text, use a char (also referred to as a plain char). This is typically a signed char but can be implemented either way by the compiler.

* Technically, a char can be any size as long as sizeof(char) is 1, but it is usually an 8-bit integer.

Custom domain for GitHub project pages

The selected answer is the good one, but is long, so you might not read the key point:

I got an error with the SSL when accesign www.example.com but it worked fine if I go to example.com

If it happens the same to you, probably your error is that in the DNS configuration you have set:

CNAME www.example.com --> example.com  (WRONG)

But, what you have to do is:

CNAME www.example.com --> username.github.io  (GOOD)

or

CNAME www.example.com --> organization.github.io  (GOOD)

That was my error

Retrieving Data from SQL Using pyodbc

You are so close!

import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')
cursor = cnxn.cursor()

cursor.execute("SELECT WORK_ORDER.TYPE,WORK_ORDER.STATUS, WORK_ORDER.BASE_ID, WORK_ORDER.LOT_ID FROM WORK_ORDER")
for row in cursor.fetchall():
    print row

(the "columns()" function collects meta-data about the columns in the named table, as opposed to the actual data).

Change type of varchar field to integer: "cannot be cast automatically to type integer"

I got the same problem. Than I realized I had a default string value for the column I was trying to alter. Removing the default value made the error go away :)

Manually put files to Android emulator SD card

Use the adb tool that comes with the SDK.

adb push myDirectory /sdcard/targetDir

If you only specify /sdcard/ (with the trailing slash) as destination, then the CONTENTS of myDirectory will end up in the root of /sdcard.

Homebrew install specific version of formula?

UPDATE: This method is deprecated and no longer works.

This method results in error: Installation of mysql from a GitHub commit URL is unsupported! brew extract mysql to a stable tap on GitHub instead. (UsageError)

$ brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/c77882756a832ac1d87e7396c114158e5619016c/Formula/mysql.rb
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (homebrew/core and homebrew/cask).

...

Traceback (most recent call last):
    9: from /usr/local/Homebrew/Library/Homebrew/brew.rb:122:in `<main>'
    8: from /usr/local/Homebrew/Library/Homebrew/cmd/install.rb:132:in `install'
    7: from /usr/local/Homebrew/Library/Homebrew/cli/parser.rb:302:in `parse'
    6: from /usr/local/Homebrew/Library/Homebrew/cli/parser.rb:651:in `formulae'
    5: from /usr/local/Homebrew/Library/Homebrew/cli/parser.rb:651:in `map'
    4: from /usr/local/Homebrew/Library/Homebrew/cli/parser.rb:655:in `block in formulae'
    3: from /usr/local/Homebrew/Library/Homebrew/formulary.rb:351:in `factory'
    2: from /usr/local/Homebrew/Library/Homebrew/formulary.rb:138:in `get_formula'
    1: from /usr/local/Homebrew/Library/Homebrew/formulary.rb:142:in `klass'
/usr/local/Homebrew/Library/Homebrew/formulary.rb:227:in `load_file': Invalid usage: Installation of mysql from a GitHub commit URL is unsupported! `brew extract mysql` to a stable tap on GitHub instead. (UsageError)
    12: from /usr/local/Homebrew/Library/Homebrew/brew.rb:155:in `<main>'
    11: from /usr/local/Homebrew/Library/Homebrew/brew.rb:157:in `rescue in <main>'
    10: from /usr/local/Homebrew/Library/Homebrew/help.rb:64:in `help'
     9: from /usr/local/Homebrew/Library/Homebrew/help.rb:83:in `command_help'
     8: from /usr/local/Homebrew/Library/Homebrew/help.rb:103:in `parser_help'
     7: from /usr/local/Homebrew/Library/Homebrew/cli/parser.rb:302:in `parse'
     6: from /usr/local/Homebrew/Library/Homebrew/cli/parser.rb:651:in `formulae'
     5: from /usr/local/Homebrew/Library/Homebrew/cli/parser.rb:651:in `map'
     4: from /usr/local/Homebrew/Library/Homebrew/cli/parser.rb:655:in `block in formulae'
     3: from /usr/local/Homebrew/Library/Homebrew/formulary.rb:351:in `factory'
     2: from /usr/local/Homebrew/Library/Homebrew/formulary.rb:138:in `get_formula'
     1: from /usr/local/Homebrew/Library/Homebrew/formulary.rb:142:in `klass'
/usr/local/Homebrew/Library/Homebrew/formulary.rb:227:in `load_file': Invalid usage: Installation of mysql from a GitHub commit URL is unsupported! `brew extract mysql` to a stable tap on GitHub instead. (UsageError)

I tried to install with the recommended command, but it doesn't work in this particular instance of MySQL 5.7.10. You may have better luck with a more recent Formula.

$ brew extract --version=5.7.10 mysql homebrew/cask
==> Searching repository history
==> Writing formula for mysql from revision 0fa511b to:
/usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask/Formula/[email protected]

$ 

$ brew install /usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask/Formula/[email protected]
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> Updated Formulae
Updated 1 formula.
Error: undefined method `core_tap?' for nil:NilClass

Error: Failed to load cask: /usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask/Formula/[email protected]
Cask '[email protected]' is unreadable: wrong constant name #<Class:0x00007f9b9498cad8>
Warning: Treating /usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask/Formula/[email protected] as a formula.
==> Installing [email protected] from homebrew/cask
==> Downloading https://homebrew.bintray.com/bottles/cmake-3.19.4.big_sur.bottle.tar.gz
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/278f2ad1caf664019ff7b4a7fc5493999c06adf503637447af13a617d45cf484?response-content-disposition=attachment%3Bfilenam
######################################################################## 100.0%
==> Downloading https://downloads.sourceforge.net/project/boost/boost/1.59.0/boost_1_59_0.tar.bz2
==> Downloading from https://phoenixnap.dl.sourceforge.net/project/boost/boost/1.59.0/boost_1_59_0.tar.bz2
######################################################################## 100.0%
==> Downloading https://cdn.mysql.com/Downloads/MySQL-5.7/mysql-5.7.10.tar.gz

curl: (22) The requested URL returned error: 404 Not Found
Error: Failed to download resource "[email protected]"
Download failed: https://cdn.mysql.com/Downloads/MySQL-5.7/mysql-5.7.10.tar.gz

You could modify the Formula at the path above (written in ruby) to attempt to achieve your desired result (e.g., an installation of MySQL 5.7.10 on a recent macOS version).


You can use the strategy of identifying the formula and a particular commit in the history of the formula that matches the version of the package you'd like to install.

  1. Go to https://github.com/Homebrew/homebrew-core

  2. Press t on your keyboard to activate the file finder.

  3. Identify a formula that looks most relevant, perhaps: Formula/mysql.rb, bringing you to a forumla file location: https://github.com/Homebrew/homebrew-core/blob/master/Formula/mysql.rb.

  4. Look at the revision history by clicking on the History button, which is located at https://github.com/Homebrew/homebrew-core/commits/master/Formula/mysql.rb. If you're interested in MySQL 5.7.10, you might want to click the latest revision prior to 5.7.11, which navigates to a GitHub commit:

https://github.com/Homebrew/homebrew-core/commit/c77882756a832ac1d87e7396c114158e5619016c#Formula/mysql.rb

NOTE: You may have to view the commit history in your console per GitHub's suggestion if the commit history does not load in your browser. Replace the commit SHA above in the URL if you're interested in seeing that commit on GitHub. Alternatively, skip to step 7, below.

  1. Click the "View" button to view the source for the mysql.rb file after the commit was applied.

  2. Then click the "Raw" button to view the raw source.

  3. Copy the URL. Alternatively, build the URL yourself with the mysql.rb file name to identify your formula and the particular version of that formula (identified by the commmit SHA in the URL below).

https://raw.githubusercontent.com/Homebrew/homebrew-core/c77882756a832ac1d87e7396c114158e5619016c/Formula/mysql.rb

  1. Install it with $ brew install [URL from step 7]

     $ brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/c77882756a832ac1d87e7396c114158e5619016c/Formula/mysql.rb
    

Any way to declare an array in-line?

As Draemon says, the closest that Java comes to inline arrays is new String[]{"blah", "hey", "yo"} however there is a neat trick that allows you to do something like

array("blah", "hey", "yo") with the type automatically inferred.

I have been working on a useful API for augmenting the Java language to allow for inline arrays and collection types. For more details google project Espresso4J or check it out here

Converting Float to Dollars and Cents

In python 3, you can use:

import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
locale.currency( 1234.50, grouping = True )

Output

'$1,234.50'

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

Move the -h and specify that mydir is a directory

attrib /S /D /L -H mydir\*.*

'too many values to unpack', iterating over a dict. key=>string, value=>list

Can't be iterating directly in dictionary. So you can through converting into tuple.

first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']

fields = {
    'first_names': first_names,
    'last_name': last_names,
         } 
tup_field=tuple(fields.items())
for names in fields.items():
     field,possible_values = names
     tup_possible_values=tuple(possible_values)
     for pvalue in tup_possible_values:
           print (field + "is" + pvalue)

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

  • pyenv - manages different python versions,
  • all others - create virtual environment (which has isolated python version and installed "requirements"),

pipenv want combine all, in addition to previous it installs "requirements" (into the active virtual environment or create its own if none is active)

So maybe you will be happy with pipenv only.

But I use: pyenv + pyenv-virtualenvwrapper, + pipenv (pipenv for installing requirements only).

In Debian:

  1. apt install libffi-dev

  2. install pyenv based on https://www.tecmint.com/pyenv-install-and-manage-multiple-python-versions-in-linux/, but..

  3. .. but instead of pyenv-virtualenv install pyenv-virtualenvwrapper (which can be standalone library or pyenv plugin, here the 2nd option):

    pyenv install 3.9.0

    git clone https://github.com/pyenv/pyenv-virtualenvwrapper.git $(pyenv root)/plugins/pyenv-virtualenvwrapper

    into ~/.bashrc add: export $VIRTUALENVWRAPPER_PYTHON="/usr/bin/python3"

    source ~/.bashrc

    pyenv virtualenvwrapper

Then create virtual environments for your projects (workingdir must exist):

pyenv local 3.9.0  # to prevent 'interpreter not found' in mkvirtualenv
python -m pip install --upgrade pip setuptools wheel
mkvirtualenv <venvname> -p python3.9 -a <workingdir>

and switch between projects:

workon <venvname>
python -m pip install --upgrade pip setuptools wheel pipenv

Inside a project I have the file requirements.txt, without fixing the versions inside (if some version limitation is not neccessary). You have 2 possible tools to install them into the current virtual environment: pip-tools or pipenv. Lets say you will use pipenv:

pipenv install -r requirements.txt

this will create Pipfile and Pipfile.lock files, fixed versions are in the 2nd one. If you want reinstall somewhere exactly same versions then (Pipfile.lock must be present):

pipenv install

Remember that Pipfile.lock is related to some Python version and need to be recreated if you use a different one.

As you see I write requirements.txt. This has some problems: You must remove a removed package from Pipfile too. So writing Pipfile directly is probably better.

So you can see I use pipenv very poorly. Maybe if you will use it well, it can replace everything?

EDIT 2021.01: I have changed my stack to: pyenv + pyenv-virtualenvwrapper + poetry. Ie. I use no apt or pip installation of virtualenv or virtualenvwrapper, and instead I install pyenv's plugin pyenv-virtualenvwrapper. This is easier way.

Poetry is great for me:

poetry add <package>   # install single package
poetry remove <package>
poetry install   # if you remove poetry.lock poetry will re-calculate versions

How to display HTML in TextView?

If you want to be able to configure it through xml without any modification in java code you may find this idea helpful. Simply you call init from constructor and set the text as html

public class HTMLTextView extends TextView {
    ... constructors calling init...
    private void init(){
       setText(Html.fromHtml(getText().toString()));
    }    
}

xml:

<com.package.HTMLTextView
android:text="@string/about_item_1"/>

Bootstrap 3 with remote Modal

Here's my solution (leveraging a few above) that makes use of BS3's own structure to re-instate the old remote loading behaviour. It should be seamless.

I'm going to keep the code variable heavy and descriptive to keep things understandable. I'm also assuming the presence of JQuery. Javascript heavy lifter types will handily streamline the code.

For reference here's a link that invokes a BS3 modal:

<li><a data-toggle="modal" href="terms.html" data-target="#terms">Terms of Use</a></li>

In youre Javascript you're going to need the following.

// Make sure the DOM elements are loaded and accounted for
$(document).ready(function() {

  // Match to Bootstraps data-toggle for the modal
  // and attach an onclick event handler
  $('a[data-toggle="modal"]').on('click', function(e) {

    // From the clicked element, get the data-target arrtibute
    // which BS3 uses to determine the target modal
    var target_modal = $(e.currentTarget).data('target');
    // also get the remote content's URL
    var remote_content = e.currentTarget.href;

    // Find the target modal in the DOM
    var modal = $(target_modal);
    // Find the modal's <div class="modal-body"> so we can populate it
    var modalBody = $(target_modal + ' .modal-body');

    // Capture BS3's show.bs.modal which is fires
    // immediately when, you guessed it, the show instance method
    // for the modal is called
    modal.on('show.bs.modal', function () {
            // use your remote content URL to load the modal body
            modalBody.load(remote_content);
        }).modal();
        // and show the modal

    // Now return a false (negating the link action) to prevent Bootstrap's JS 3.1.1
    // from throwing a 'preventDefault' error due to us overriding the anchor usage.
    return false;
  });
});

We're just about there. One thing you may want to do is style the modal body with a max-height, so that long content will scroll.

In your CSS, you'll need the following:

.modal-body{
    max-height: 300px;
    overflow-y: scroll;
}

Just for refference I'll include the modal's HTML, which is a knock-off of every Bootsrap Modal Example you've ever seen:

<div id="terms" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3 id="termsLabel" class="modal-title">TERMS AND CONDITIONS</h3>
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

How to strip all whitespace from string

Try a regex with re.sub. You can search for all whitespace and replace with an empty string.

\s in your pattern will match whitespace characters - and not just a space (tabs, newlines, etc). You can read more about it in the manual.

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

What is the correct way to declare a boolean variable in Java?

There is no reason to do that. In fact, I would choose to combine declaration and initialization as in

final Boolean isMatch = email1.equals (email2);

using the final keyword so you can't change it (accidentally) afterwards anymore either.

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

How to send HTTP request in java?

Apache HttpComponents. The examples for the two modules - HttpCore and HttpClient will get you started right away.

Not that HttpUrlConnection is a bad choice, HttpComponents will abstract a lot of the tedious coding away. I would recommend this, if you really want to support a lot of HTTP servers/clients with minimum code. By the way, HttpCore could be used for applications (clients or servers) with minimum functionality, whereas HttpClient is to be used for clients that require support for multiple authentication schemes, cookie support etc.

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

SELECT word FROM table WHERE word NOT LIKE '%a%' 
AND word NOT LIKE '%b%' 
AND word NOT LIKE '%c%';

How to dynamically create generic C# object using reflection?

Check out this article and this simple example. Quick translation of same to your classes ...

var d1 = typeof(Task<>);
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

Per your edit: For that case, you can do this ...

var d1 = Type.GetType("GenericTest.TaskA`1"); // GenericTest was my namespace, add yours
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

To see where I came up with backtick1 for the name of the generic class, see this article.

Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:

Type type = typeof(IReadOnlyDictionary<,>);

MySQL foreign key constraints, cascade delete

I think (I'm not certain) that foreign key constraints won't do precisely what you want given your table design. Perhaps the best thing to do is to define a stored procedure that will delete a category the way you want, and then call that procedure whenever you want to delete a category.

CREATE PROCEDURE `DeleteCategory` (IN category_ID INT)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
BEGIN

DELETE FROM
    `products`
WHERE
    `id` IN (
        SELECT `products_id`
        FROM `categories_products`
        WHERE `categories_id` = category_ID
    )
;

DELETE FROM `categories`
WHERE `id` = category_ID;

END

You also need to add the following foreign key constraints to the linking table:

ALTER TABLE `categories_products` ADD
    CONSTRAINT `Constr_categoriesproducts_categories_fk`
    FOREIGN KEY `categories_fk` (`categories_id`) REFERENCES `categories` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT `Constr_categoriesproducts_products_fk`
    FOREIGN KEY `products_fk` (`products_id`) REFERENCES `products` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE

The CONSTRAINT clause can, of course, also appear in the CREATE TABLE statement.

Having created these schema objects, you can delete a category and get the behaviour you want by issuing CALL DeleteCategory(category_ID) (where category_ID is the category to be deleted), and it will behave how you want. But don't issue a normal DELETE FROM query, unless you want more standard behaviour (i.e. delete from the linking table only, and leave the products table alone).

Difference between Return and Break statements

break:- These transfer statement bypass the correct flow of execution to outside of the current loop by skipping on the remaining iteration

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            break;
        }
        System.out.println(i);
    }
} 

output will be 
0
1
2
3
4

Continue :-These transfer Statement will bypass the flow of execution to starting point of the loop inorder to continue with next iteration by skipping all the remaining instructions .

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            continue;
        }
        System.out.println(i);
    }
} 

output will be:
0
1
2
3
4
6
7
8
9 

return :- At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed. The following example illustrates this point. Here, return causes execution to return to the Java run-time system, since it is the run-time system that calls main( ).

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            return;
        }
        System.out.println(i)
    }
} 


output will be :
0
1
2
3
4

Short description of the scoping rules?

The scoping rules for Python 2.x have been outlined already in other answers. The only thing I would add is that in Python 3.0, there is also the concept of a non-local scope (indicated by the 'nonlocal' keyword). This allows you to access outer scopes directly, and opens up the ability to do some neat tricks, including lexical closures (without ugly hacks involving mutable objects).

EDIT: Here's the PEP with more information on this.

How can I take an UIImage and give it a black border?

You can add border to the UIImageView, and then change the size of the UIimageView according to the image size:

#import <QuartzCore/QuartzCore.h>


// adding border to the imageView
[imageView.layer setBorderColor: [[UIColor whiteColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];

// resize the imageView to fit the image size
CGSize size = [image size];
float factor = size.width / self.frame.size.width;
if (factor < size.height / self.frame.size.height) {
    factor = size.height / self.frame.size.height;
}

CGRect rect = CGRectMake(0, 0, size.width/factor, size.height/factor);
imageView.frame = rect;

Make sure you to set the origin of the imageView to the center

How to overcome "'aclocal-1.15' is missing on your system" warning?

The whole point of Autotools is to provide an arcane M4-macro-based language which ultimately compiles to a shell script called ./configure. You can ship this compiled shell script with the source code and that script should do everything to detect the environment and prepare the program for building. Autotools should only be required by someone who wants to tweak the tests and refresh that shell script.

It defeats the point of Autotools if GNU This and GNU That has to be installed on the system for it to work. Originally, it was invented to simplify the porting of programs to various Unix systems, which could not be counted on to have anything on them. Even the constructs used by the generated shell code in ./configure had to be very carefully selected to make sure they would work on every broken old shell just about everywhere.

The problem you're running into is due to some broken Makefile steps invented by people who simply don't understand what Autotools is for and the role of the final ./configure script.

As a workaround, you can go into the Makefile and make some changes to get this out of the way. As an example, I'm building the Git head of GNU Awk and running into this same problem. I applied this patch to Makefile.in, however, and I can sucessfully make gawk:

diff --git a/Makefile.in b/Makefile.in

index 5585046..b8b8588 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -312,12 +312,12 @@ distcleancheck_listfiles = find . -type f -print

 # Directory for gawk's data files. Automake supplies datadir.
 pkgdatadir = $(datadir)/awk
-ACLOCAL = @ACLOCAL@
+ACLOCAL = true
 AMTAR = @AMTAR@
 AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
+AUTOCONF = true
+AUTOHEADER = true
+AUTOMAKE = true
 AWK = @AWK@
 CC = @CC@
 CCDEPMODE = @CCDEPMODE@

Basically, I changed things so that the harmless true shell command is substituted for all the Auto-stuff programs.

The actual build steps for Gawk don't need the Auto-stuff! It's only involved in some rules that get invoked if parts of the Auto-stuff have changed and need to be re-processed. However, the Makefile is structured in such a way that it fails if the tools aren't present.

Before the above patch:

$ ./configure
[...]
$ make gawk
CDPATH="${ZSH_VERSION+.}:" && cd . && /bin/bash /home/kaz/gawk/missing aclocal-1.15 -I m4
/home/kaz/gawk/missing: line 81: aclocal-1.15: command not found
WARNING: 'aclocal-1.15' is missing on your system.
         You should only need it if you modified 'acinclude.m4' or
         'configure.ac' or m4 files included by 'configure.ac'.
         The 'aclocal' program is part of the GNU Automake package:
         <http://www.gnu.org/software/automake>
         It also requires GNU Autoconf, GNU m4 and Perl in order to run:
         <http://www.gnu.org/software/autoconf>
         <http://www.gnu.org/software/m4/>
         <http://www.perl.org/>
make: *** [aclocal.m4] Error 127

After the patch:

$ ./configure
[...]
$ make gawk
CDPATH="${ZSH_VERSION+.}:" && cd . && true -I m4
CDPATH="${ZSH_VERSION+.}:" && cd . && true
gcc -std=gnu99 -DDEFPATH='".:/usr/local/share/awk"' -DDEFLIBPATH="\"/usr/local/lib/gawk\"" -DSHLIBEXT="\"so"\" -DHAVE_CONFIG_H -DGAWK -DLOCALEDIR='"/usr/local/share/locale"' -I.     -g -O2 -DNDEBUG -MT array.o -MD -MP -MF .deps/array.Tpo -c -o array.o array.c 
[...]
gcc -std=gnu99  -g -O2 -DNDEBUG  -Wl,-export-dynamic -o gawk array.o awkgram.o builtin.o cint_array.o command.o debug.o dfa.o eval.o ext.o field.o floatcomp.o gawkapi.o gawkmisc.o getopt.o getopt1.o int_array.o io.o main.o mpfr.o msg.o node.o profile.o random.o re.o regex.o replace.o str_array.o symbol.o version.o      -ldl -lm
$ ./gawk --version
GNU Awk 4.1.60, API: 1.2
Copyright (C) 1989, 1991-2015 Free Software Foundation.
[...]

There we go. As you can see, the CDPATH= command lines there are where the Auto-stuff was being invoked, where you see the true commands. These report successful termination, and so it just falls through that junk to do the darned build, which is perfectly configured.

I did make gawk because there are some subdirectories that get built which fail; the trick has to be repeated for their respective Makefiles.

If you're running into this kind of thing with a pristine, official tarball of the program from its developers, then complain. It should just unpack, ./configure and make without you having to patch anything or install any Automake or Autoconf materials.

Ideally, a pull of their Git head should also behave that way.

How to get current user who's accessing an ASP.NET application?

I ran in the same issue.

This is what worked for me:

Setting up Authentication in IIS Panel

Setting up Properties of Windows Authentication in IIS

Setting up Properties of Windows Authentication in IIS NTLM has to be the topmost

NTLM has to be the topmost. Further Web.config modifications, make sure you already have or add if these do not exist:

<system.web>

  <authentication mode="Windows" />
  <identity impersonate="true"/>

</system.web>

 <!-- you need the following lines of code to bypass errors, concerning type of Application Pool (integrated pipeline or classic) -->

<system.webServer>
   <validation validateIntegratedModeConfiguration="false"/>
</system.webServer>

See below a legit explanation for the two nodes and

Difference between <system.web> and <system.webServer>?

And, of course , you get the username by

//I am using the following to get the index of the separator "\\" and remove the Domain name from the string
int indexOfSlashChar = HttpContext.Current.User.Identity.Name.IndexOf("\\"); 

loggedInWindowsUserName = HttpContext.Current.User.Identity.Name.Substring(indexOfSlashChar + 1);

getaddrinfo: nodename nor servname provided, or not known

I ran into a similar situation today - deploying an app to a mac os x server, and receiving the 'getaddrinfo' message when I tried to access an external api. It turns out that the error occurs when the ssh session that originally launched the app is no longer active. That's why everything works perfectly if you ssh into your server and run commands manually (or launch the server manually) - as long as you keep your ssh session alive, this error won't occur.

Whether this is a bug or a quirk in OS X, I'm not sure. Here's the page that led me to the solution - http://lists.apple.com/archives/unix-porting/2010/Jul/msg00001.html

All I had to do was update my capistrano task to launch the app using 'nohup'. So changing

run "cd #{current_path} && RAILS_ENV=production unicorn_rails -c config/unicorn.rb -D"

to

run "cd #{current_path} && RAILS_ENV=production nohup unicorn_rails -c config/unicorn.rb -D"

did the trick for me.

Hope this helps somebody - it was quite a pain to figure out!

How to create the branch from specific commit in different branch

If you are using this form of the branch command (with start point), it does not matter where your HEAD is.

What you are doing:

git checkout dev
git branch test 07aeec983bfc17c25f0b0a7c1d47da8e35df7af8
  • First, you set your HEAD to the branch dev,

  • Second, you start a new branch on commit 07aeec98. There is no bb.txt at this commit (according to your github repo).

If you want to start a new branch at the location you have just checked out, you can either run branch with no start point:

git branch test

or as other have answered, branch and checkout there in one operation:

git checkout -b test

I think that you might be confused by that fact that 07aeec98 is part of the branch dev. It is true that this commit is an ancestor of dev, its changes are needed to reach the latest commit in dev. However, they are other commits that are needed to reach the latest dev, and these are not necessarily in the history of 07aeec98.

8480e8ae (where you added bb.txt) is for example not in the history of 07aeec98. If you branch from 07aeec98, you won't get the changes introduced by 8480e8ae.

In other words: if you merge branch A and branch B into branch C, then create a new branch on a commit of A, you won't get the changes introduced in B.

Same here, you had two parallel branches master and dev, which you merged in dev. Branching out from a commit of master (older than the merge) won't provide you with the changes of dev.


If you want to permanently integrate new changes from master into your feature branches, you should merge master into them and go on. This will create merge commits in your feature branches, though.

If you have not published your feature branches, you can also rebase them on the updated master: git rebase master featureA. Be prepared to solve possible conflicts.

If you want a workflow where you can work on feature branches free of merge commits and still integrate with newer changes in master, I recommend the following:

  • base every new feature branch on a commit of master
  • create a dev branch on a commit of master
  • when you need to see how your feature branch integrates with new changes in master, merge both master and the feature branch into dev.

Do not commit into dev directly, use it only for merging other branches.

For example, if you are working on feature A and B:

a---b---c---d---e---f---g -master
    \       \
     \       \-x -featureB
      \
       \-j---k -featureA

Merge branches into a dev branch to check if they work well with the new master:

a---b---c---d---e---f---g -master
    \       \            \
     \       \            \--x'---k' -dev
      \       \             /    /   
       \       \-x----------    /    -featureB
        \                      /
         \-j---k--------------- -featureA

You can continue working on your feature branches, and keep merging in new changes from both master and feature branches into dev regularly.

a---b---c---d---e---f---g---h---i----- -master
    \       \            \            \
     \       \            \--x'---k'---i'---l' -dev
      \       \             /    /         /
       \       \-x----------    /         /  -featureB
        \                      /         /  
         \-j---k-----------------l------ -featureA

When it is time to integrate the new features, merge the feature branches (not dev!) into master.

How to search text using php if ($text contains "World")

If you are looking an algorithm to rank search results based on relevance of multiple words here comes a quick and easy way of generating search results with PHP only.

Implementation of the vector space model in PHP

function get_corpus_index($corpus = array(), $separator=' ') {

    $dictionary = array();
    $doc_count = array();

    foreach($corpus as $doc_id => $doc) {
        $terms = explode($separator, $doc);
        $doc_count[$doc_id] = count($terms);

        // tf–idf, short for term frequency–inverse document frequency, 
        // according to wikipedia is a numerical statistic that is intended to reflect 
        // how important a word is to a document in a corpus

        foreach($terms as $term) {
            if(!isset($dictionary[$term])) {
                $dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
            }
            if(!isset($dictionary[$term]['postings'][$doc_id])) {
                $dictionary[$term]['document_frequency']++;
                $dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
            }

            $dictionary[$term]['postings'][$doc_id]['term_frequency']++;
        }

        //from http://phpir.com/simple-search-the-vector-space-model/

    }

    return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}

function get_similar_documents($query='', $corpus=array(), $separator=' '){

    $similar_documents=array();

    if($query!=''&&!empty($corpus)){

        $words=explode($separator,$query);
        $corpus=get_corpus_index($corpus);
        $doc_count=count($corpus['doc_count']);

        foreach($words as $word) {
            $entry = $corpus['dictionary'][$word];
            foreach($entry['postings'] as $doc_id => $posting) {

                //get term frequency–inverse document frequency
                $score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);

                if(isset($similar_documents[$doc_id])){
                    $similar_documents[$doc_id]+=$score;
                }
                else{
                    $similar_documents[$doc_id]=$score;
                }

            }
        }

        // length normalise
        foreach($similar_documents as $doc_id => $score) {
            $similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
        }

        // sort fro  high to low
        arsort($similar_documents);
    }   
    return $similar_documents;
}

IN YOUR CASE

$query = 'world';

$corpus = array(
    1 => 'hello world',
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

RESULTS

Array
(
    [1] => 0.79248125036058
)

MATCHING MULTIPLE WORDS AGAINST MULTIPLE PHRASES

$query = 'hello world';

$corpus = array(
    1 => 'hello world how are you today?',
    2 => 'how do you do world',
    3 => 'hello, here you are! how are you? Are we done yet?'
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

RESULTS

Array
(
    [1] => 0.74864218272161
    [2] => 0.43398500028846
)

from How do I check if a string contains a specific word in PHP?

How to use Visual Studio C++ Compiler?

In Visual Studio, you can't just open a .cpp file and expect it to run. You must create a project first, or open the .cpp in some existing project.

In your case, there is no project, so there is no project to build.

Go to File --> New --> Project --> Visual C++ --> Win32 Console Application. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".

Then, You can add .cpp files you created outside the Visual Studio by right clicking in the Solution explorer on folder icon "Source" and Add->Existing Item.

Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.

Then you can press ctrl+F5 to compile without debugging and can see output on console window.

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

There is no difference at all!

1) git checkout -b branch origin/branch

If there is no --track and no --no-track, --track is assumed as default. The default can be changed with the setting branch.autosetupmerge.

In effect, 1) behaves like git checkout -b branch --track origin/branch.

2) git checkout --track origin/branch

“As a convenience”, --track without -b implies -b and the argument to -b is guessed to be “branch”. The guessing is driven by the configuration variable remote.origin.fetch.

In effect, 2) behaves like git checkout -b branch --track origin/branch.

As you can see: no difference.

But it gets even better:

3) git checkout branch

is also equivalent to git checkout -b branch --track origin/branch if “branch” does not exist yet but “origin/branch” does1.


All three commands set the “upstream” of “branch” to be “origin/branch” (or they fail).

Upstream is used as reference point of argument-less git status, git push, git merge and thus git pull (if configured like that (which is the default or almost the default)).

E.g. git status tells you how far behind or ahead you are of upstream, if one is configured.

git push is configured to push the current branch upstream by default2 since git 2.0.

1 ...and if “origin” is the only remote having “branch”
2 the default (named “simple”) also enforces for both branch names to be equal

How to get a key in a JavaScript object by its value?

Here is my solution first:

For example, I suppose that we have an object that contains three value pairs:

function findKey(object, value) {

    for (let key in object)
        if (object[key] === value) return key;

    return "key is not found";
}

const object = { id_1: "apple", id_2: "pear", id_3: "peach" };

console.log(findKey(object, "pear"));
//expected output: id_2

We can simply write a findKey(array, value) that takes two parameters which are an object and the value of the key you are looking for. As such, this method is reusable and you do not need to manually iterate the object every time by only passing two parameters for this function.

Converting a String to DateTime

Put this code in a static class> public static class ClassName{ }

public static DateTime ToDateTime(this string datetime, char dateSpliter = '-', char timeSpliter = ':', char millisecondSpliter = ',')
{
   try
   {
      datetime = datetime.Trim();
      datetime = datetime.Replace("  ", " ");
      string[] body = datetime.Split(' ');
      string[] date = body[0].Split(dateSpliter);
      int year = date[0].ToInt();
      int month = date[1].ToInt();
      int day = date[2].ToInt();
      int hour = 0, minute = 0, second = 0, millisecond = 0;
      if (body.Length == 2)
      {
         string[] tpart = body[1].Split(millisecondSpliter);
         string[] time = tpart[0].Split(timeSpliter);
         hour = time[0].ToInt();
         minute = time[1].ToInt();
         if (time.Length == 3) second = time[2].ToInt();
         if (tpart.Length == 2) millisecond = tpart[1].ToInt();
      }
      return new DateTime(year, month, day, hour, minute, second, millisecond);
   }
   catch
   {
      return new DateTime();
   }
}

In this way, you can use

string datetime = "2009-05-08 14:40:52,531";
DateTime dt0 = datetime.TToDateTime();

DateTime dt1 = "2009-05-08 14:40:52,531".ToDateTime();
DateTime dt5 = "2009-05-08".ToDateTime();
DateTime dt2 = "2009/05/08 14:40:52".ToDateTime('/');
DateTime dt3 = "2009/05/08 14.40".ToDateTime('/', '.');
DateTime dt4 = "2009-05-08 14:40-531".ToDateTime('-', ':', '-');

What does "request for member '*******' in something not a structure or union" mean?

You are trying to access a member of a structure, but in something that is not a structure. For example:

struct {
    int a;
    int b;
} foo;
int fum;
fum.d = 5;

Quicksort with Python

This is a version of the quicksort using Hoare partition scheme and with fewer swaps and local variables

def quicksort(array):
    qsort(array, 0, len(array)-1)

def qsort(A, lo, hi):
    if lo < hi:
        p = partition(A, lo, hi)
        qsort(A, lo, p)
        qsort(A, p + 1, hi)

def partition(A, lo, hi):
    pivot = A[lo]
    i, j = lo-1, hi+1
    while True:
      i += 1
      j -= 1
      while(A[i] < pivot): i+= 1
      while(A[j] > pivot ): j-= 1

      if i >= j: 
          return j

      A[i], A[j] = A[j], A[i]


test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)

Reading specific columns from a text file in python

First of all we open the file and as datafile then we apply .read() method reads the file contents and then we split the data which returns something like: ['5', '10', '6', '6', '20', '1', '7', '30', '4', '8', '40', '3', '9', '23', '1', '4', '13', '6'] and the we applied list slicing on this list to start from the element at index position 1 and skip next 3 elements untill it hits the end of the loop.

with open("sample.txt", "r") as datafile:
    print datafile.read().split()[1::3]

Output:

['10', '20', '30', '40', '23', '13']

variable is not declared it may be inaccessible due to its protection level

Pay close attention to the first part of the error: "variable is not declared"

Ignore the second part: "it may be inaccessible due to its protection level". It's a red herring.

Some questions... (the answers might be in that image you posted, but I can't seem to make it larger and my eyes don't read that small of print... Any chance you can post the code in a way these older eyes can read it? Makes it hard to know the total picture. In particular I am suspicious of your Page directives.)

We know that 1stReasonTypes is a listbox, but for some reason it seems like we don't know WHICH listbox. This is why I want to see your page directives.

But also, how are you calling the private method FormRefresh()? It's not an event handler, which makes me wonder if you are trying to reference a listbox in a form that is not handled properly in this code behind.

You may need to find the control 1stReasonTypes. Try maybe putting your listbox inside something like

<div id="MyFormDiv" runat="server">.....</div>

then in FormRefresh(), do a...

Dim 1stReasonTypesNew As listbox = MyFormDiv.FindControl("1stReasonTypes")

Or use an existing control, object, or page instead of a div. More info on FindControl: http://msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx

But no matter how you slice it, there is something funky going here such that 1stReasonTypes doesn't know which exact listbox it's supposed to be.

MS SQL Date Only Without Time

Here's a query that will return all results within a range of days.

DECLARE @startDate DATETIME
DECLARE @endDate DATETIME

SET @startDate = DATEADD(day, -30, GETDATE())
SET @endDate = GETDATE()

SELECT *
FROM table
WHERE dateColumn >= DATEADD(day, DATEDIFF(day, 0, @startDate), 0)
  AND dateColumn <  DATEADD(day, 1, DATEDIFF(day, 0, @endDate))

Cleaning up old remote git branches

I'll have to add an answer here, because the other answers are either not covering my case or are needlessly complicated. I use github with other developers and I just want all the local branches whose remotes were (possibly merged and) deleted from a github PR to be deleted in one go from my machine. No, things like git branch -r --merged don't cover the branches that were not merged locally, or the ones that were not merged at all (abandoned) etc, so a different solution is needed.

Anyway, the first step I got it from other answers:

git fetch --prune

A dry run of git remote prune origin seemed like it would do the same thing in my case, so I went with the shortest version to keep it simple.

Now, a git branch -v should mark the branches whose remotes are deleted as [gone]. Therefore, all I need to do is:

git branch -v|grep \\[gone\\]|awk '{print $1}'|xargs -I{} git branch -D {}

As simple as that, it deletes everything I want for the above scenario.

The less common xargs syntax is so that it also works on Mac & BSD in addition to Linux. Careful, this command is not a dry run so it will force-delete all the branches marked as [gone]. Obviously, this being git nothing is gone forever, if you see branches deleted that you remember you wanted kept you can always undelete them (the above command will have listed their hash on deletion, so a simple git checkout -b <branch> <hash>.

Edit: Just add this alias to your .bashrc/.bash_profile, the two commands made into one and I updated the second to work on all shells:

alias old_branch_delete='git fetch -p && git branch -vv | awk "/: gone]/{print \$1}" | xargs git branch -D'

Meaning of ${project.basedir} in pom.xml

${project.basedir} is the root directory of your project.

${project.build.directory} is equivalent to ${project.basedir}/target

as it is defined here: https://github.com/apache/maven/blob/trunk/maven-model-builder/src/main/resources/org/apache/maven/model/pom-4.0.0.xml#L53

Make multiple-select to adjust its height to fit options without scroll bar

For jQuery you can try this. I always do the following and it works.

$(function () {
   $("#multiSelect").attr("size",$("#multiSelect option").length);
});

Replace all occurrences of a String using StringBuilder?

Look at JavaDoc of replaceAll method of String class:

Replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)

As you can see you can use Pattern and Matcher to do that.

Deleting an object in java?

//Just use a List
//create the list
public final List<Object> myObjects;

//instantiate the list
myObjects = new ArrayList<Object>();

//add objects to the list
Object object = myObject;
myObjects.add(object);

//remove the object calling this method if you have more than 1 objects still works with 1
//object too.

private void removeObject(){
int len = myObjects.size();
for(int i = 0;i<len; i++){
Objects object = myObjects.get(i);
myObjects.remove(object);
}
}

Tower of Hanoi: Recursive Algorithm

I agree this one isn't immediate when you first look at it, but it's fairly simple when you get down to it.

Base case: your tower is of size 1. So you can do it in one move, from source directly to dest.

Recursive case: your tower is of size n > 1. So you move the top tower of size n-1 to an extra peg (by), move the bottom "tower" of size 1 to the destination peg, and move the top tower from by to dest.

So with a simple case, you have a tower of height 2:

 _|_    |     |
__|__   |     |
===== ===== =====

First step: move the top tower of 2-1 (=1) to the extra peg (the middle one, lets say).

  |     |     |
__|__  _|_    |
===== ===== =====

Next: move the bottom disc to the destination:

  |     |     |
  |    _|_  __|__
===== ===== =====

And finally, move the top tower of (2-1)=1 to the destination.

  |     |    _|_
  |     |   __|__
===== ===== =====

If you think about it, even if the tower were 3 or more, there will always be an empty extra peg, or a peg with all larger discs, for the recursion to use when swapping towers around.

Javascript Append Child AFTER Element

If you are looking for a plain JS solution, then you just use insertBefore() against nextSibling.

Something like:

parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);

Note that default value of nextSibling is null, so, you don't need to do anything special for that.

Update: You don't even need the if checking presence of parentGuest.nextSibling like the currently accepted answer does, because if there's no next sibling, it will return null, and passing null to the 2nd argument of insertBefore() means: append at the end.

Reference:

.

IF you are using jQuery (ignore otherwise, I have stated plain JS answer above), you can leverage the convenient after() method:

$("#one").after("<li id='two'>");

Reference:

Is there a NumPy function to return the first index of something in an array?

For 1D arrays, I'd recommend np.flatnonzero(array == value)[0], which is equivalent to both np.nonzero(array == value)[0][0] and np.where(array == value)[0][0] but avoids the ugliness of unboxing a 1-element tuple.

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

Is it because some culture format issue?

Yes. Your user must be in a culture where the time separator is a dot. Both ":" and "/" are interpreted in a culture-sensitive way in custom date and time formats.

How can I make sure the result string is delimited by colon instead of dot?

I'd suggest specifying CultureInfo.InvariantCulture:

string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
                                CultureInfo.InvariantCulture);

Alternatively, you could just quote the time and date separators:

string text = dateTime.ToString("MM'/'dd'/'yyyy HH':'mm':'ss.fff");

... but that will give you "interesting" results that you probably don't expect if you get users running in a culture where the default calendar system isn't the Gregorian calendar. For example, take the following code:

using System;
using System.Globalization;
using System.Threading;

class Test
{
    static void Main()        
    {
        DateTime now = DateTime.Now;
        CultureInfo culture = new CultureInfo("ar-SA"); // Saudi Arabia
        Thread.CurrentThread.CurrentCulture = culture;
        Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
    }
} 

That produces output (on September 18th 2013) of:

11/12/1434 15:04:31.750

My guess is that your web service would be surprised by that!

I'd actually suggest not only using the invariant culture, but also changing to an ISO-8601 date format:

string text = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");

This is a more globally-accepted format - it's also sortable, and makes the month and day order obvious. (Whereas 06/07/2013 could be interpreted as June 7th or July 6th depending on the reader's culture.)

Updating version numbers of modules in a multi-module Maven project

The best way is, since you intend to bundle your modules together, you can specify <dependencyManagement> tag in outer most pom.xml (parent module) direct under <project> tag. It controls the version and group name. In your individual module, you just need to specify the <artifactId> tag in your pom.xml. It will take the version from parent file.

Reordering arrays

EDIT: Please check out Andy's answer as his answer came first and this is solely an extension of his

I know this is an old question, but I think it's worth it to include Array.prototype.sort().

Here's an example from MDN along with the link

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// [1, 2, 3, 4, 5]

Luckily it doesn't only work with numbers:

arr.sort([compareFunction])

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

I noticed that you're ordering them by first name:

let playlist = [
    {artist:"Herbie Hancock", title:"Thrust"},
    {artist:"Lalo Schifrin", title:"Shifting Gears"},
    {artist:"Faze-O", title:"Riding High"}
];

// sort by name
playlist.sort((a, b) => {
  if(a.artist < b.artist) { return -1; }
  if(a.artist > b.artist) { return  1; }

  // else names must be equal
  return 0;
});

note that if you wanted to order them by last name you would have to either have a key for both first_name & last_name or do some regex magic, which I can't do XD

Hope that helps :)

Integrate ZXing in Android Studio

I was integrating ZXING into an Android application and there were no good sources for the input all over, I will give you a hint on what worked for me - because it turned out to be very easy.

There is a real handy git repository that provides the zxing android library project as an AAR archive.

All you have to do is add this to your build.gradle

repositories {
    jcenter()
}

dependencies {
    implementation 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
    implementation 'com.google.zxing:core:3.2.0'
}

and Gradle does all the magic to compile the code and makes it accessible in your app.

To start the Scanner afterwards, use this class/method: From the Activity:

new IntentIntegrator(this).initiateScan(); // `this` is the current Activity

From a Fragment:

IntentIntegrator.forFragment(this).initiateScan(); // `this` is the current Fragment
// If you're using the support library, use IntentIntegrator.forSupportFragment(this) instead.

There are several customizing options:

IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0);  // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();

They have a sample-project and are providing several integration examples:

If you already visited the link you going to see that I just copy&pasted the code from the git README. If not, go there to get some more insight and code examples.

WPF binding to Listbox selectedItem

For me, I usually use DataContext together in order to bind two-depth property such as this question.

<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />

Or, I prefer to use ElementName because it achieves bindings only with view controls.

<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />

Connect to mysql on Amazon EC2 from a remote server

For some configurations of ubuntu, the bind-address needs be changed in this file:

/etc/mysql/mysql.conf.d/mysqld.cnf 

How to decrypt an encrypted Apple iTunes iPhone backup?

Security researchers Jean-Baptiste Bédrune and Jean Sigwald presented how to do this at Hack-in-the-box Amsterdam 2011.

Since then, Apple has released an iOS Security Whitepaper with more details about keys and algorithms, and Charlie Miller et al. have released the iOS Hacker’s Handbook, which covers some of the same ground in a how-to fashion. When iOS 10 first came out there were changes to the backup format which Apple did not publicize at first, but various people reverse-engineered the format changes.

Encrypted backups are great

The great thing about encrypted iPhone backups is that they contain things like WiFi passwords that aren’t in regular unencrypted backups. As discussed in the iOS Security Whitepaper, encrypted backups are considered more “secure,” so Apple considers it ok to include more sensitive information in them.

An important warning: obviously, decrypting your iOS device’s backup removes its encryption. To protect your privacy and security, you should only run these scripts on a machine with full-disk encryption. While it is possible for a security expert to write software that protects keys in memory, e.g. by using functions like VirtualLock() and SecureZeroMemory() among many other things, these Python scripts will store your encryption keys and passwords in strings to be garbage-collected by Python. This means your secret keys and passwords will live in RAM for a while, from whence they will leak into your swap file and onto your disk, where an adversary can recover them. This completely defeats the point of having an encrypted backup.

How to decrypt backups: in theory

The iOS Security Whitepaper explains the fundamental concepts of per-file keys, protection classes, protection class keys, and keybags better than I can. If you’re not already familiar with these, take a few minutes to read the relevant parts.

Now you know that every file in iOS is encrypted with its own random per-file encryption key, belongs to a protection class, and the per-file encryption keys are stored in the filesystem metadata, wrapped in the protection class key.

To decrypt:

  1. Decode the keybag stored in the BackupKeyBag entry of Manifest.plist. A high-level overview of this structure is given in the whitepaper. The iPhone Wiki describes the binary format: a 4-byte string type field, a 4-byte big-endian length field, and then the value itself.

    The important values are the PBKDF2 ITERations and SALT, the double protection salt DPSL and iteration count DPIC, and then for each protection CLS, the WPKY wrapped key.

  2. Using the backup password derive a 32-byte key using the correct PBKDF2 salt and number of iterations. First use a SHA256 round with DPSL and DPIC, then a SHA1 round with ITER and SALT.

    Unwrap each wrapped key according to RFC 3394.

  3. Decrypt the manifest database by pulling the 4-byte protection class and longer key from the ManifestKey in Manifest.plist, and unwrapping it. You now have a SQLite database with all file metadata.

  4. For each file of interest, get the class-encrypted per-file encryption key and protection class code by looking in the Files.file database column for a binary plist containing EncryptionKey and ProtectionClass entries. Strip the initial four-byte length tag from EncryptionKey before using.

    Then, derive the final decryption key by unwrapping it with the class key that was unwrapped with the backup password. Then decrypt the file using AES in CBC mode with a zero IV.

How to decrypt backups: in practice

First you’ll need some library dependencies. If you’re on a mac using a homebrew-installed Python 2.7 or 3.7, you can install the dependencies with:

CFLAGS="-I$(brew --prefix)/opt/openssl/include" \
LDFLAGS="-L$(brew --prefix)/opt/openssl/lib" \    
    pip install biplist fastpbkdf2 pycrypto

In runnable source code form, here is how to decrypt a single preferences file from an encrypted iPhone backup:

#!/usr/bin/env python3.7
# coding: UTF-8

from __future__ import print_function
from __future__ import division

import argparse
import getpass
import os.path
import pprint
import random
import shutil
import sqlite3
import string
import struct
import tempfile
from binascii import hexlify

import Crypto.Cipher.AES # https://www.dlitz.net/software/pycrypto/
import biplist
import fastpbkdf2
from biplist import InvalidPlistException


def main():
    ## Parse options
    parser = argparse.ArgumentParser()
    parser.add_argument('--backup-directory', dest='backup_directory',
                    default='testdata/encrypted')
    parser.add_argument('--password-pipe', dest='password_pipe',
                        help="""\
Keeps password from being visible in system process list.
Typical use: --password-pipe=<(echo -n foo)
""")
    parser.add_argument('--no-anonymize-output', dest='anonymize',
                        action='store_false')
    args = parser.parse_args()
    global ANONYMIZE_OUTPUT
    ANONYMIZE_OUTPUT = args.anonymize
    if ANONYMIZE_OUTPUT:
        print('Warning: All output keys are FAKE to protect your privacy')

    manifest_file = os.path.join(args.backup_directory, 'Manifest.plist')
    with open(manifest_file, 'rb') as infile:
        manifest_plist = biplist.readPlist(infile)
    keybag = Keybag(manifest_plist['BackupKeyBag'])
    # the actual keys are unknown, but the wrapped keys are known
    keybag.printClassKeys()

    if args.password_pipe:
        password = readpipe(args.password_pipe)
        if password.endswith(b'\n'):
            password = password[:-1]
    else:
        password = getpass.getpass('Backup password: ').encode('utf-8')

    ## Unlock keybag with password
    if not keybag.unlockWithPasscode(password):
        raise Exception('Could not unlock keybag; bad password?')
    # now the keys are known too
    keybag.printClassKeys()

    ## Decrypt metadata DB
    manifest_key = manifest_plist['ManifestKey'][4:]
    with open(os.path.join(args.backup_directory, 'Manifest.db'), 'rb') as db:
        encrypted_db = db.read()

    manifest_class = struct.unpack('<l', manifest_plist['ManifestKey'][:4])[0]
    key = keybag.unwrapKeyForClass(manifest_class, manifest_key)
    decrypted_data = AESdecryptCBC(encrypted_db, key)

    temp_dir = tempfile.mkdtemp()
    try:
        # Does anyone know how to get Python’s SQLite module to open some
        # bytes in memory as a database?
        db_filename = os.path.join(temp_dir, 'db.sqlite3')
        with open(db_filename, 'wb') as db_file:
            db_file.write(decrypted_data)
        conn = sqlite3.connect(db_filename)
        conn.row_factory = sqlite3.Row
        c = conn.cursor()
        # c.execute("select * from Files limit 1");
        # r = c.fetchone()
        c.execute("""
            SELECT fileID, domain, relativePath, file
            FROM Files
            WHERE relativePath LIKE 'Media/PhotoData/MISC/DCIM_APPLE.plist'
            ORDER BY domain, relativePath""")
        results = c.fetchall()
    finally:
        shutil.rmtree(temp_dir)

    for item in results:
        fileID, domain, relativePath, file_bplist = item

        plist = biplist.readPlistFromString(file_bplist)
        file_data = plist['$objects'][plist['$top']['root'].integer]
        size = file_data['Size']

        protection_class = file_data['ProtectionClass']
        encryption_key = plist['$objects'][
            file_data['EncryptionKey'].integer]['NS.data'][4:]

        backup_filename = os.path.join(args.backup_directory,
                                    fileID[:2], fileID)
        with open(backup_filename, 'rb') as infile:
            data = infile.read()
            key = keybag.unwrapKeyForClass(protection_class, encryption_key)
            # truncate to actual length, as encryption may introduce padding
            decrypted_data = AESdecryptCBC(data, key)[:size]

        print('== decrypted data:')
        print(wrap(decrypted_data))
        print()

        print('== pretty-printed plist')
        pprint.pprint(biplist.readPlistFromString(decrypted_data))

##
# this section is mostly copied from parts of iphone-dataprotection
# http://code.google.com/p/iphone-dataprotection/

CLASSKEY_TAGS = [b"CLAS",b"WRAP",b"WPKY", b"KTYP", b"PBKY"]  #UUID
KEYBAG_TYPES = ["System", "Backup", "Escrow", "OTA (icloud)"]
KEY_TYPES = ["AES", "Curve25519"]
PROTECTION_CLASSES={
    1:"NSFileProtectionComplete",
    2:"NSFileProtectionCompleteUnlessOpen",
    3:"NSFileProtectionCompleteUntilFirstUserAuthentication",
    4:"NSFileProtectionNone",
    5:"NSFileProtectionRecovery?",

    6: "kSecAttrAccessibleWhenUnlocked",
    7: "kSecAttrAccessibleAfterFirstUnlock",
    8: "kSecAttrAccessibleAlways",
    9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
    10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
    11: "kSecAttrAccessibleAlwaysThisDeviceOnly"
}
WRAP_DEVICE = 1
WRAP_PASSCODE = 2

class Keybag(object):
    def __init__(self, data):
        self.type = None
        self.uuid = None
        self.wrap = None
        self.deviceKey = None
        self.attrs = {}
        self.classKeys = {}
        self.KeyBagKeys = None #DATASIGN blob
        self.parseBinaryBlob(data)

    def parseBinaryBlob(self, data):
        currentClassKey = None

        for tag, data in loopTLVBlocks(data):
            if len(data) == 4:
                data = struct.unpack(">L", data)[0]
            if tag == b"TYPE":
                self.type = data
                if self.type > 3:
                    print("FAIL: keybag type > 3 : %d" % self.type)
            elif tag == b"UUID" and self.uuid is None:
                self.uuid = data
            elif tag == b"WRAP" and self.wrap is None:
                self.wrap = data
            elif tag == b"UUID":
                if currentClassKey:
                    self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
                currentClassKey = {b"UUID": data}
            elif tag in CLASSKEY_TAGS:
                currentClassKey[tag] = data
            else:
                self.attrs[tag] = data
        if currentClassKey:
            self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey

    def unlockWithPasscode(self, passcode):
        passcode1 = fastpbkdf2.pbkdf2_hmac('sha256', passcode,
                                        self.attrs[b"DPSL"],
                                        self.attrs[b"DPIC"], 32)
        passcode_key = fastpbkdf2.pbkdf2_hmac('sha1', passcode1,
                                            self.attrs[b"SALT"],
                                            self.attrs[b"ITER"], 32)
        print('== Passcode key')
        print(anonymize(hexlify(passcode_key)))
        for classkey in self.classKeys.values():
            if b"WPKY" not in classkey:
                continue
            k = classkey[b"WPKY"]
            if classkey[b"WRAP"] & WRAP_PASSCODE:
                k = AESUnwrap(passcode_key, classkey[b"WPKY"])
                if not k:
                    return False
                classkey[b"KEY"] = k
        return True

    def unwrapKeyForClass(self, protection_class, persistent_key):
        ck = self.classKeys[protection_class][b"KEY"]
        if len(persistent_key) != 0x28:
            raise Exception("Invalid key length")
        return AESUnwrap(ck, persistent_key)

    def printClassKeys(self):
        print("== Keybag")
        print("Keybag type: %s keybag (%d)" % (KEYBAG_TYPES[self.type], self.type))
        print("Keybag version: %d" % self.attrs[b"VERS"])
        print("Keybag UUID: %s" % anonymize(hexlify(self.uuid)))
        print("-"*209)
        print("".join(["Class".ljust(53),
                    "WRAP".ljust(5),
                    "Type".ljust(11),
                    "Key".ljust(65),
                    "WPKY".ljust(65),
                    "Public key"]))
        print("-"*208)
        for k, ck in self.classKeys.items():
            if k == 6:print("")

            print("".join(
                [PROTECTION_CLASSES.get(k).ljust(53),
                str(ck.get(b"WRAP","")).ljust(5),
                KEY_TYPES[ck.get(b"KTYP",0)].ljust(11),
                anonymize(hexlify(ck.get(b"KEY", b""))).ljust(65),
                anonymize(hexlify(ck.get(b"WPKY", b""))).ljust(65),
            ]))
        print()

def loopTLVBlocks(blob):
    i = 0
    while i + 8 <= len(blob):
        tag = blob[i:i+4]
        length = struct.unpack(">L",blob[i+4:i+8])[0]
        data = blob[i+8:i+8+length]
        yield (tag,data)
        i += 8 + length

def unpack64bit(s):
    return struct.unpack(">Q",s)[0]
def pack64bit(s):
    return struct.pack(">Q",s)

def AESUnwrap(kek, wrapped):
    C = []
    for i in range(len(wrapped)//8):
        C.append(unpack64bit(wrapped[i*8:i*8+8]))
    n = len(C) - 1
    R = [0] * (n+1)
    A = C[0]

    for i in range(1,n+1):
        R[i] = C[i]

    for j in reversed(range(0,6)):
        for i in reversed(range(1,n+1)):
            todec = pack64bit(A ^ (n*j+i))
            todec += pack64bit(R[i])
            B = Crypto.Cipher.AES.new(kek).decrypt(todec)
            A = unpack64bit(B[:8])
            R[i] = unpack64bit(B[8:])

    if A != 0xa6a6a6a6a6a6a6a6:
        return None
    res = b"".join(map(pack64bit, R[1:]))
    return res

ZEROIV = "\x00"*16
def AESdecryptCBC(data, key, iv=ZEROIV, padding=False):
    if len(data) % 16:
        print("AESdecryptCBC: data length not /16, truncating")
        data = data[0:(len(data)/16) * 16]
    data = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv).decrypt(data)
    if padding:
        return removePadding(16, data)
    return data

##
# here are some utility functions, one making sure I don’t leak my
# secret keys when posting the output on Stack Exchange

anon_random = random.Random(0)
memo = {}
def anonymize(s):
    if type(s) == str:
        s = s.encode('utf-8')
    global anon_random, memo
    if ANONYMIZE_OUTPUT:
        if s in memo:
            return memo[s]
        possible_alphabets = [
            string.digits,
            string.digits + 'abcdef',
            string.ascii_letters,
            "".join(chr(x) for x in range(0, 256)),
        ]
        for a in possible_alphabets:
            if all((chr(c) if type(c) == int else c) in a for c in s):
                alphabet = a
                break
        ret = "".join([anon_random.choice(alphabet) for i in range(len(s))])
        memo[s] = ret
        return ret
    else:
        return s

def wrap(s, width=78):
    "Return a width-wrapped repr(s)-like string without breaking on \’s"
    s = repr(s)
    quote = s[0]
    s = s[1:-1]
    ret = []
    while len(s):
        i = s.rfind('\\', 0, width)
        if i <= width - 4: # "\x??" is four characters
            i = width
        ret.append(s[:i])
        s = s[i:]
    return '\n'.join("%s%s%s" % (quote, line ,quote) for line in ret)

def readpipe(path):
    if stat.S_ISFIFO(os.stat(path).st_mode):
        with open(path, 'rb') as pipe:
            return pipe.read()
    else:
        raise Exception("Not a pipe: {!r}".format(path))

if __name__ == '__main__':
    main()

Which then prints this output:

Warning: All output keys are FAKE to protect your privacy
== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class                                                WRAP Type       Key                                                              WPKY                                                             Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete                             2    AES                                                                         4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen                   2    AES                                                                         09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2    AES                                                                         e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone                                 2    AES                                                                         902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery?                            3    AES                                                                         a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072

kSecAttrAccessibleWhenUnlocked                       2    AES                                                                         09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock                   2    AES                                                                         0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways                             2    AES                                                                         b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly         3    AES                                                                         417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly     3    AES                                                                         b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly               3    AES                                                                         9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2

== Passcode key
ee34f5bb635830d698074b1e3e268059c590973b0f1138f1954a2a4e1069e612

== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class                                                WRAP Type       Key                                                              WPKY                                                             Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete                             2    AES        64e8fc94a7b670b0a9c4a385ff395fe9ba5ee5b0d9f5a5c9f0202ef7fdcb386f 4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen                   2    AES        22a218c9c446fbf88f3ccdc2ae95f869c308faaa7b3e4fe17b78cbf2eeaf4ec9 09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2    AES        1004c6ca6e07d2b507809503180edf5efc4a9640227ac0d08baf5918d34b44ef e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone                                 2    AES        2e809a0cd1a73725a788d5d1657d8fd150b0e360460cb5d105eca9c60c365152 902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery?                            3    AES        9a078d710dcd4a1d5f70ea4062822ea3e9f7ea034233e7e290e06cf0d80c19ca a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072

kSecAttrAccessibleWhenUnlocked                       2    AES        606e5328816af66736a69dfe5097305cf1e0b06d6eb92569f48e5acac3f294a4 09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock                   2    AES        6a4b5292661bac882338d5ebb51fd6de585befb4ef5f8ffda209be8ba3af1b96 0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways                             2    AES        c0ed717947ce8d1de2dde893b6026e9ee1958771d7a7282dd2116f84312c2dd2 b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly         3    AES        80d8c7be8d5103d437f8519356c3eb7e562c687a5e656cfd747532f71668ff99 417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly     3    AES        a875a15e3ff901351c5306019e3b30ed123e6c66c949bdaa91fb4b9a69a3811e b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly               3    AES        1e7756695d337e0b06c764734a9ef8148af20dcc7a636ccfea8b2eb96a9e9373 9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2

== decrypted data:
'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD '
'PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist versi'
'on="1.0">\n<dict>\n\t<key>DCIMLastDirectoryNumber</key>\n\t<integer>100</integ'
'er>\n\t<key>DCIMLastFileNumber</key>\n\t<integer>3</integer>\n</dict>\n</plist'
'>\n'

== pretty-printed plist
{'DCIMLastDirectoryNumber': 100, 'DCIMLastFileNumber': 3}

Extra credit

The iphone-dataprotection code posted by Bédrune and Sigwald can decrypt the keychain from a backup, including fun things like saved wifi and website passwords:

$ python iphone-dataprotection/python_scripts/keychain_tool.py ...

--------------------------------------------------------------------------------------
|                              Passwords                                             |
--------------------------------------------------------------------------------------
|Service           |Account          |Data           |Access group  |Protection class|
--------------------------------------------------------------------------------------
|AirPort           |Ed’s Coffee Shop |<3FrenchRoast  |apple         |AfterFirstUnlock|
...

That code no longer works on backups from phones using the latest iOS, but there are some golang ports that have been kept up to date allowing access to the keychain.

ImportError: No module named 'google'

According to https://developers.google.com/api-client-library/python/apis/oauth2/v1 you need to install google-api-python-client package:

pip install --upgrade google-api-python-client

JQuery html() vs. innerHTML

Given the general support of .innerHTML these days, the only effective difference now is that .html() will execute code in any <script> tags if there are any in the html you give it. .innerHTML, under HTML5, will not.

From the jQuery docs:

By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, <img onload="">). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.

Note: both .innerHTML and .html() can execute js other ways (e.g the onerror attribute).

Simple URL GET/POST function in Python

You could use this to wrap urllib2:

def URLRequest(url, params, method="GET"):
    if method == "POST":
        return urllib2.Request(url, data=urllib.urlencode(params))
    else:
        return urllib2.Request(url + "?" + urllib.urlencode(params))

That will return a Request object that has result data and response codes.

How to install iPhone application in iPhone Simulator

I see you have a problem. Try building your app as Release and then check out your source codes build folder. It may be called Release-iphonesimulator. Inside here will be the app. Then go to (home folder)/Library/Application Support/iPhone Simulator (if you can't find it, try pressing Command - J and choosing arrange by name). Go to an OS that has apps in it in the iPhone sim, like 4.1. In that folder there should be an Applications folder. Open that, and there should be folders with random lettering. Pick any one, and replace it with the app you have. Make sure to delete anything in the little folders!

If it doesn't work, then I'm dumbfounded.

Finding Key associated with max Value in a Java Map

An answer that returns an Optional since the map may have no max value if it is empty: map.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

You cannot use Set Transaction Isolation Level Read Uncommitted in a View (you can only have one script in there in fact), so you would have to use (nolock) if dirty rows should be included.

How to run php files on my computer

I just put the content in the question in a file called test.php and ran php test.php. (In the folder where the test.php is.)

$ php foo.php                                                                                                                                                                                                                                                                                                                                    
15

How many bytes in a JavaScript string?

If you're using node.js, there is a simpler solution using buffers :

function getBinarySize(string) {
    return Buffer.byteLength(string, 'utf8');
}

There is a npm lib for that : https://www.npmjs.org/package/utf8-binary-cutter (from yours faithfully)

How to remove an id attribute from a div using jQuery?

I'm not sure what jQuery api you're looking at, but you should only have to specify id.

$('#thumb').removeAttr('id');

How to call a method after bean initialization is complete?

You can use something like:

<beans>
    <bean id="myBean" class="..." init-method="init"/>
</beans>

This will call the "init" method when the bean is instantiated.

ASP.NET Web API session or something?

Well, REST by design is stateless. By adding session (or anything else of that kind) you are making it stateful and defeating any purpose of having a RESTful API.

The whole idea of RESTful service is that every resource is uniquely addressable using a universal syntax for use in hypermedia links and each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP".

So whatever you are trying to do with Web API here, should most likely be re-architectured if you wish to have a RESTful API.

With that said, if you are still willing to go down that route, there is a hacky way of adding session to Web API, and it's been posted by Imran here http://forums.asp.net/t/1780385.aspx/1

Code (though I wouldn't really recommend that):

public class MyHttpControllerHandler
  : HttpControllerHandler, IRequiresSessionState
{
    public MyHttpControllerHandler(RouteData routeData): base(routeData)
    { }
}

public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MyHttpControllerHandler(requestContext.RouteData);
    }
}

public class ValuesController : ApiController
{
   public string GET(string input)
   {
       var session = HttpContext.Current.Session;
       if (session != null)
       {
           if (session["Time"] == null)
           {
               session["Time"] = DateTime.Now;
           }
           return "Session Time: " + session["Time"] + input;
       }
       return "Session is not availabe" + input;
    }
}

and then add the HttpControllerHandler to your API route:

route.RouteHandler = new MyHttpControllerRouteHandler();

How to clear File Input

This is the method I like to use as well but I believe you need to add the bool true parameter to the clone method in order for any events to remain attached with the new object and you need to clear the contents.

    var input = $("#fileInput");

    function clearInput() {
        input = input.val('').clone(true);
    };

https://api.jquery.com/clone/

Simple prime number generator in Python

Here is a numpy version of Sieve of Eratosthenes having both okay complexity (lower than sorting an array of length n) and vectorization.

import numpy as np 
def generate_primes(n):
    is_prime = np.ones(n+1,dtype=bool)
    is_prime[0:2] = False
    for i in range(int(n**0.5)+1):
        if is_prime[i]:
            is_prime[i*2::i]=False
    return np.where(is_prime)[0]

Timings:

import time    
for i in range(2,10):
    timer =time.time()
    generate_primes(10**i)
    print('n = 10^',i,' time =', round(time.time()-timer,6))

>> n = 10^ 2  time = 5.6e-05
>> n = 10^ 3  time = 6.4e-05
>> n = 10^ 4  time = 0.000114
>> n = 10^ 5  time = 0.000593
>> n = 10^ 6  time = 0.00467
>> n = 10^ 7  time = 0.177758
>> n = 10^ 8  time = 1.701312
>> n = 10^ 9  time = 19.322478

How to fix corrupt HDFS FIles

If you just want to get your HDFS back to normal state and don't worry much about the data, then

This will list the corrupt HDFS blocks:

hdfs fsck -list-corruptfileblocks

This will delete the corrupted HDFS blocks:

hdfs fsck / -delete

Note that, you might have to use sudo -u hdfs if you are not the sudo user (assuming "hdfs" is name of the sudo user)

SQL Current month/ year question

select * from your_table where MONTH(mont_year) = MONTH(NOW()) and YEAR(mont_year) = YEAR(NOW());

Note: (month_year) means your column that contain date format. I think that will solve your problem. Let me know if that query doesn't works.

What is the dual table in Oracle?

DUAL is necessary in PL/SQL development for using functions that are only available in SQL

e.g.

DECLARE
x XMLTYPE;
BEGIN
SELECT xmlelement("hhh", 'stuff')
INTO x
FROM dual;
END;

Redirect all output to file using Bash on Linux?

You can execute a subshell and redirect all output while still putting the process in the background:

( ./script.sh blah > ~/log/blah.log 2>&1 ) &
echo $! > ~/pids/blah.pid

Get Enum from Description attribute

Should be pretty straightforward, its just the reverse of your previous method;

public static int GetEnumFromDescription(string description, Type enumType)
{
    foreach (var field in enumType.GetFields())
    {
        DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute;
        if(attribute == null)
            continue;
        if(attribute.Description == description)
        {
            return (int) field.GetValue(null);
        }
    }
    return 0;
}

Usage:

Console.WriteLine((Animal)GetEnumFromDescription("Giant Panda",typeof(Animal)));

Bash script to calculate time elapsed

You can use Bash's time keyword here with an appropriate format string

TIMEFORMAT='It takes %R seconds to complete this task...'
time {
    #command block that takes time to complete...
    #........
 }

Here's what the reference says about TIMEFORMAT:

The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The ‘%’ character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.

%%

    A literal ‘%’.
%[p][l]R

    The elapsed time in seconds.
%[p][l]U

    The number of CPU seconds spent in user mode.
%[p][l]S

    The number of CPU seconds spent in system mode.
%P

    The CPU percentage, computed as (%U + %S) / %R. 

The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.

The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included.

If this variable is not set, Bash acts as if it had the value

$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'

If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.

Oracle - How to generate script from sql developer

This worked for me:

  • In SQL Developer, right click the object that you want to generate a script for. i.e. the table name
  • Select Quick DLL > Save To File
  • This will then write the create statement to an external sql file.

Note, you can also highlight multiple objects at the same time, so you could generate one script that contains create statements for all tables within the database.

Convenient C++ struct initialisation

For me the laziest way to allow inline inizialization is use this macro.

#define METHOD_MEMBER(TYPE, NAME, CLASS) \
CLASS &set_ ## NAME(const TYPE &_val) { NAME = _val; return *this; } \
TYPE NAME;

struct foo {
    METHOD_MEMBER(string, attr1, foo)
    METHOD_MEMBER(int, attr2, foo)
    METHOD_MEMBER(double, attr3, foo)
};

// inline usage
foo test = foo().set_attr1("hi").set_attr2(22).set_attr3(3.14);

That macro create attribute and self reference method.

Firebase FCM force onTokenRefresh() to be called

How I update my deviceToken

First when I login I send the first device token under the user collection and the current logged in user.

After that, I just override onNewToken(token:String) in my FirebaseMessagingService() and just update that value if a new token is generated for that user

class MyFirebaseMessagingService: FirebaseMessagingService() {
    override fun onMessageReceived(p0: RemoteMessage) {
        super.onMessageReceived(p0)
    }

    override fun onNewToken(token: String) {
    super.onNewToken(token)
    val currentUser= FirebaseAuth.getInstance().currentUser?.uid
    if(currentUser != null){
        FirebaseFirestore.getInstance().collection("user").document(currentUser).update("deviceToken",token)
    }
 }
} 

Each time your app opens it will check for a new token, if the user is not yet signed in it will not update the token, if the user is already logged in you can check for a newToken

Compute row average in pandas

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

PHP DOMDocument loadHTML not encoding UTF-8 correctly

You must feed the DOMDocument a version of your HTML with a header that make sense. Just like HTML5.

$profile ='<?xml version="1.0" encoding="'.$_encoding.'"?>'. $html;

maybe is a good idea to keep your html as valid as you can, so you don't get into issues when you'll start query... around :-) and stay away from htmlentities!!!! That's an an necessary back and forth wasting resources. keep your code insane!!!!

Http Get using Android HttpURLConnection

I have created with callBack(delegate) response to Activity class.

public class WebService extends AsyncTask<String, Void, String> {

    private Context mContext;
    private OnTaskDoneListener onTaskDoneListener;
    private String urlStr = "";

    public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) {
        this.mContext = context;
        this.urlStr = url;
        this.onTaskDoneListener = onTaskDoneListener;
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            URL mUrl = new URL(urlStr);
            HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Content-length", "0");
            httpConnection.setUseCaches(false);
            httpConnection.setAllowUserInteraction(false);
            httpConnection.setConnectTimeout(100000);
            httpConnection.setReadTimeout(100000);

            httpConnection.connect();

            int responseCode = httpConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                return sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        if (onTaskDoneListener != null && s != null) {
            onTaskDoneListener.onTaskDone(s);
        } else
            onTaskDoneListener.onError();
    }
}

where

public interface OnTaskDoneListener {
    void onTaskDone(String responseData);

    void onError();
}

You can modify according to your needs. It's for get

Finding element in XDocument?

The Elements() method returns an IEnumerable<XElement> containing all child elements of the current node. For an XDocument, that collection only contains the Root element. Therefore the following is required:

var query = from c in xmlFile.Root.Elements("Band")
            select c;

Powershell v3 Invoke-WebRequest HTTPS error

If you run this as administrator, that error should go away

How to use jQuery to call an ASP.NET web service?

I use this method as a wrapper so that I can send parameters. Also using the variables in the top of the method allows it to be minimized at a higher ratio and allows for some code reuse if making multiple similar calls.

function InfoByDate(sDate, eDate){
    var divToBeWorkedOn = "#AjaxPlaceHolder";
    var webMethod = "http://MyWebService/Web.asmx/GetInfoByDates";
    var parameters = "{'sDate':'" + sDate + "','eDate':'" + eDate + "'}";

    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $(divToBeWorkedOn).html(msg.d);
        },
        error: function(e){
            $(divToBeWorkedOn).html("Unavailable");
        }
    });
}

I hope that helps.

Please note that this requires the 3.5 framework to expose JSON webmethods that can be consumed in this manner.

Windows Scipy Install: No Lapack/Blas Resources Found

install intel's distribution of python https://software.intel.com/en-us/intel-distribution-for-python

better of for distribution of python should contain them initially

PHP multidimensional array search by value

/**
 * searches a simple as well as multi dimension array
 * @param type $needle
 * @param type $haystack
 * @return boolean
 */
public static function in_array_multi($needle, $haystack){
    $needle = trim($needle);
    if(!is_array($haystack))
        return False;

    foreach($haystack as $key=>$value){
        if(is_array($value)){
            if(self::in_array_multi($needle, $value))
                return True;
            else
               self::in_array_multi($needle, $value);
        }
        else
        if(trim($value) === trim($needle)){//visibility fix//
            error_log("$value === $needle setting visibility to 1 hidden");
            return True;
        }
    }

    return False;
}

How do I create a WPF Rounded Corner container?

I know that this isn't an answer to the initial question ... but you often want to clip the inner content of that rounded corner border you just created.

Chris Cavanagh has come up with an excellent way to do just this.

I have tried a couple different approaches to this ... and I think this one rocks.

Here is the xaml below:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Background="Black"
>
    <!-- Rounded yellow border -->
    <Border
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        BorderBrush="Yellow"
        BorderThickness="3"
        CornerRadius="10"
        Padding="2"
    >
        <Grid>
            <!-- Rounded mask (stretches to fill Grid) -->
            <Border
                Name="mask"
                Background="White"
                CornerRadius="7"
            />

            <!-- Main content container -->
            <StackPanel>
                <!-- Use a VisualBrush of 'mask' as the opacity mask -->
                <StackPanel.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </StackPanel.OpacityMask>

                <!-- Any content -->
                <Image Source="http://chriscavanagh.files.wordpress.com/2006/12/chriss-blog-banner.jpg"/>
                <Rectangle
                    Height="50"
                    Fill="Red"/>
                <Rectangle
                    Height="50"
                    Fill="White"/>
                <Rectangle
                    Height="50"
                    Fill="Blue"/>
            </StackPanel>
        </Grid>
    </Border>
</Page>

Remove Server Response Header IIS7

Try setting the HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters\DisableServerHeader registry entry to a REG_DWORD of 1.

Plot inline or a separate window using Matplotlib in Spyder IDE

type

%matplotlib qt

when you want graphs in a separate window and

%matplotlib inline

when you want an inline plot

C++ Dynamic Shared Library on Linux

Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library

Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.

If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.

Get a pixel from HTML Canvas?

// Get pixel data
var imageData = context.getImageData(x, y, width, height);

// Color at (x,y) position
var color = [];
color['red'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 0];
color['green'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 1];
color['blue'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 2];
color['alpha'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 3];

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

2015-05-27-191152.jpg << Looking back at your image format, I occasionally confused between .png and .jpg and encountered the same error.

Update using LINQ to SQL

In the absence of more detailed info:

using(var dbContext = new dbDataContext())
{
    var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId);
    if(data != null)
    {
        data.SomeField = newValue;
    }
    dbContext.SubmitChanges();
}

What is the cause for "angular is not defined"

You have to put your script tag after the one that references Angular. Move it out of the head:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>

The way you've set it up now, your script runs before Angular is loaded on the page.

How to avoid "Permission denied" when using pip with virtualenv

In my case, I was using mkvirtualenv, but didn't tell it I was going to be using python3. I got this error:

mkvirtualenv hug
pip3 install hug -U

....
error: could not create '/usr/lib/python3.4/site-packages': Permission denied

It worked after specifying python3:

mkvirtualenv --python=/usr/bin/python3 hug
pip3 install hug -U

Binding List<T> to DataGridView in WinForm

After adding new item to persons add:

myGrid.DataSource = null;
myGrid.DataSource = persons;

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

How to redirect a page using onclick event in php?

you are using onclick which is javascript event. there is two ways

Javascript

<input type="button" value="Home" class="homebutton" id="btnHome" 
onClick="window.location = 'http://google.com'" />

Or PHP

create another page as redirect.php and put

<?php header('location : google.com') ?>

and insert this link on any page within the same directory

<a href="redirect.php">google<a/>

hope this helps its simplest!!

How to set min-height for bootstrap container

Two things are happening here.

  1. You are not using the container class properly.
  2. You are trying to override Bootstrap's CSS for the container class

Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.

What you want to do is the following:

<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
    <div class="row">
        <div class="col-md-4 myClassName">  <!-- myClassName is defined in my CSS as you defined your container -->
            <img src="#.jpg" height="200px" width="300px">
        </div>
    </div>
</div>

Here you can find more info on the Bootstrap grid system.

That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...

.container {
   padding-right: 15px;
   padding-left: 15px;
   margin-right: auto;
   margin-left: auto;
   max-width: 900px;
   overflow:hidden;
   min-height:0px !important;
}

But I have always found that the "!important" clause just makes for messy CSS.

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

First convert your Chart.js canvas to base64 string.

var url_base64 = document.getElementById('myChart').toDataURL('image/png');

Set it as a href attribute for anchor tag.

link.href = url_base64;

<a id='link' download='filename.png'>Save as Image</a>

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

Yet another parse_requirements hack that also parses environment markers into extras_require:

from collections import defaultdict
from pip.req import parse_requirements

requirements = []
extras = defaultdict(list)
for r in parse_requirements('requirements.txt', session='hack'):
    if r.markers:
        extras[':' + str(r.markers)].append(str(r.req))
    else:
        requirements.append(str(r.req))

setup(
    ...,
    install_requires=requirements,
    extras_require=extras
)

It should support both sdist and binary dists.

As stated by others, parse_requirements has several shortcomings, so this is not what you should do on public projects, but it may suffice for internal/personal projects.

How to install a node.js module without using npm?

Download the code from github into the node_modules directory

var moduleName = require("<name of directory>")

that should do it.

if the module has dependancies and has a package.json, open the module and enter npm install.

Hope this helps

What in layman's terms is a Recursive Function using PHP

Recursion used for Kaprekar's constant

function KaprekarsConstant($num, $count = 1) {
    $input = str_split($num);
    sort($input);

    $ascendingInput  = implode($input);
    $descendingInput = implode(array_reverse($input));

    $result = $ascendingInput > $descendingInput 
        ? $ascendingInput - $descendingInput 
        : $descendingInput - $ascendingInput;

    if ($result != 6174) {
        return KaprekarsConstant(sprintf('%04d', $result), $count + 1);
    }

    return $count;

}

The function keeps calling itself with the result of the calculation until it reaches Kaprekars constant, at which it will return the amount of times the calculations was made.

/edit For anyone that doesn't know Kaprekars Constant, it needs an input of 4 digits with at least two distinct digits.

Iterating through a list in reverse order in java

As has been suggested at least twice, you can use descendingIterator with a Deque, in particular with a LinkedList. If you want to use the for-each loop (i.e., have an Iterable), you can construct and use a wraper like this:

import java.util.*;

public class Main {

    public static class ReverseIterating<T> implements Iterable<T> {
        private final LinkedList<T> list;

        public ReverseIterating(LinkedList<T> list) {
            this.list = list;
        }

        @Override
        public Iterator<T> iterator() {
            return list.descendingIterator();
        }
    }

    public static void main(String... args) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");

        for (String s : new ReverseIterating<String>(list)) {
            System.out.println(s);
        }
    }
}

Get top most UIViewController

In a very rare case, with custom segue, the top most view controller is not in a navigation stack or tab bar controller or presented, but its view is inserted to the top of key windown's subviews.

In such situation, it's necessary to check if UIApplication.shared.keyWindow.subviews.last == self.view to determine if the current view controller is the top most.

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Playing m3u8 Files with HTML Video Tag

<html>
<body>
    <video width="600" height="400" controls>
        <source src="index.m3u8" type="application/x-mpegURL">
    </video>
</body> 

Stream HLS or m3u8 files using above code. it works for desktop: ms edge browser (not working with desktop chrome) and mobile: chrome,opera mini browser.

To play on all browser use flash based media player. media player to support all browser

How to make function decorators and chain them together?

If you are not into long explanations, see Paolo Bergantino’s answer.

Decorator Basics

Python’s functions are objects

To understand decorators, you must first understand that functions are objects in Python. This has important consequences. Let’s see why with a simple example :

def shout(word="yes"):
    return word.capitalize()+"!"

print(shout())
# outputs : 'Yes!'

# As an object, you can assign the function to a variable like any other object 
scream = shout

# Notice we don't use parentheses: we are not calling the function,
# we are putting the function "shout" into the variable "scream".
# It means you can then call "shout" from "scream":

print(scream())
# outputs : 'Yes!'

# More than that, it means you can remove the old name 'shout',
# and the function will still be accessible from 'scream'

del shout
try:
    print(shout())
except NameError as e:
    print(e)
    #outputs: "name 'shout' is not defined"

print(scream())
# outputs: 'Yes!'

Keep this in mind. We’ll circle back to it shortly.

Another interesting property of Python functions is they can be defined inside another function!

def talk():

    # You can define a function on the fly in "talk" ...
    def whisper(word="yes"):
        return word.lower()+"..."

    # ... and use it right away!
    print(whisper())

# You call "talk", that defines "whisper" EVERY TIME you call it, then
# "whisper" is called in "talk". 
talk()
# outputs: 
# "yes..."

# But "whisper" DOES NOT EXIST outside "talk":

try:
    print(whisper())
except NameError as e:
    print(e)
    #outputs : "name 'whisper' is not defined"*
    #Python's functions are objects

Functions references

Okay, still here? Now the fun part...

You’ve seen that functions are objects. Therefore, functions:

  • can be assigned to a variable
  • can be defined in another function

That means that a function can return another function.

def getTalk(kind="shout"):

    # We define functions on the fly
    def shout(word="yes"):
        return word.capitalize()+"!"

    def whisper(word="yes") :
        return word.lower()+"...";

    # Then we return one of them
    if kind == "shout":
        # We don't use "()", we are not calling the function,
        # we are returning the function object
        return shout  
    else:
        return whisper

# How do you use this strange beast?

# Get the function and assign it to a variable
talk = getTalk()      

# You can see that "talk" is here a function object:
print(talk)
#outputs : <function shout at 0xb7ea817c>

# The object is the one returned by the function:
print(talk())
#outputs : Yes!

# And you can even use it directly if you feel wild:
print(getTalk("whisper")())
#outputs : yes...

There’s more!

If you can return a function, you can pass one as a parameter:

def doSomethingBefore(func): 
    print("I do something before then I call the function you gave me")
    print(func())

doSomethingBefore(scream)
#outputs: 
#I do something before then I call the function you gave me
#Yes!

Well, you just have everything needed to understand decorators. You see, decorators are “wrappers”, which means that they let you execute code before and after the function they decorate without modifying the function itself.

Handcrafted decorators

How you’d do it manually:

# A decorator is a function that expects ANOTHER function as parameter
def my_shiny_new_decorator(a_function_to_decorate):

    # Inside, the decorator defines a function on the fly: the wrapper.
    # This function is going to be wrapped around the original function
    # so it can execute code before and after it.
    def the_wrapper_around_the_original_function():

        # Put here the code you want to be executed BEFORE the original function is called
        print("Before the function runs")

        # Call the function here (using parentheses)
        a_function_to_decorate()

        # Put here the code you want to be executed AFTER the original function is called
        print("After the function runs")

    # At this point, "a_function_to_decorate" HAS NEVER BEEN EXECUTED.
    # We return the wrapper function we have just created.
    # The wrapper contains the function and the code to execute before and after. It’s ready to use!
    return the_wrapper_around_the_original_function

# Now imagine you create a function you don't want to ever touch again.
def a_stand_alone_function():
    print("I am a stand alone function, don't you dare modify me")

a_stand_alone_function() 
#outputs: I am a stand alone function, don't you dare modify me

# Well, you can decorate it to extend its behavior.
# Just pass it to the decorator, it will wrap it dynamically in 
# any code you want and return you a new function ready to be used:

a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function_decorated()
#outputs:
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs

Now, you probably want that every time you call a_stand_alone_function, a_stand_alone_function_decorated is called instead. That’s easy, just overwrite a_stand_alone_function with the function returned by my_shiny_new_decorator:

a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
#outputs:
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs

# That’s EXACTLY what decorators do!

Decorators demystified

The previous example, using the decorator syntax:

@my_shiny_new_decorator
def another_stand_alone_function():
    print("Leave me alone")

another_stand_alone_function()  
#outputs:  
#Before the function runs
#Leave me alone
#After the function runs

Yes, that’s all, it’s that simple. @decorator is just a shortcut to:

another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)

Decorators are just a pythonic variant of the decorator design pattern. There are several classic design patterns embedded in Python to ease development (like iterators).

Of course, you can accumulate decorators:

def bread(func):
    def wrapper():
        print("</''''''\>")
        func()
        print("<\______/>")
    return wrapper

def ingredients(func):
    def wrapper():
        print("#tomatoes#")
        func()
        print("~salad~")
    return wrapper

def sandwich(food="--ham--"):
    print(food)

sandwich()
#outputs: --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>

Using the Python decorator syntax:

@bread
@ingredients
def sandwich(food="--ham--"):
    print(food)

sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>

The order you set the decorators MATTERS:

@ingredients
@bread
def strange_sandwich(food="--ham--"):
    print(food)

strange_sandwich()
#outputs:
##tomatoes#
#</''''''\>
# --ham--
#<\______/>
# ~salad~

Now: to answer the question...

As a conclusion, you can easily see how to answer the question:

# The decorator to make it bold
def makebold(fn):
    # The new function the decorator returns
    def wrapper():
        # Insertion of some code before and after
        return "<b>" + fn() + "</b>"
    return wrapper

# The decorator to make it italic
def makeitalic(fn):
    # The new function the decorator returns
    def wrapper():
        # Insertion of some code before and after
        return "<i>" + fn() + "</i>"
    return wrapper

@makebold
@makeitalic
def say():
    return "hello"

print(say())
#outputs: <b><i>hello</i></b>

# This is the exact equivalent to 
def say():
    return "hello"
say = makebold(makeitalic(say))

print(say())
#outputs: <b><i>hello</i></b>

You can now just leave happy, or burn your brain a little bit more and see advanced uses of decorators.


Taking decorators to the next level

Passing arguments to the decorated function

# It’s not black magic, you just have to let the wrapper 
# pass the argument:

def a_decorator_passing_arguments(function_to_decorate):
    def a_wrapper_accepting_arguments(arg1, arg2):
        print("I got args! Look: {0}, {1}".format(arg1, arg2))
        function_to_decorate(arg1, arg2)
    return a_wrapper_accepting_arguments

# Since when you are calling the function returned by the decorator, you are
# calling the wrapper, passing arguments to the wrapper will let it pass them to 
# the decorated function

@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
    print("My name is {0} {1}".format(first_name, last_name))

print_full_name("Peter", "Venkman")
# outputs:
#I got args! Look: Peter Venkman
#My name is Peter Venkman

Decorating methods

One nifty thing about Python is that methods and functions are really the same. The only difference is that methods expect that their first argument is a reference to the current object (self).

That means you can build a decorator for methods the same way! Just remember to take self into consideration:

def method_friendly_decorator(method_to_decorate):
    def wrapper(self, lie):
        lie = lie - 3 # very friendly, decrease age even more :-)
        return method_to_decorate(self, lie)
    return wrapper


class Lucy(object):

    def __init__(self):
        self.age = 32

    @method_friendly_decorator
    def sayYourAge(self, lie):
        print("I am {0}, what did you think?".format(self.age + lie))

l = Lucy()
l.sayYourAge(-3)
#outputs: I am 26, what did you think?

If you’re making general-purpose decorator--one you’ll apply to any function or method, no matter its arguments--then just use *args, **kwargs:

def a_decorator_passing_arbitrary_arguments(function_to_decorate):
    # The wrapper accepts any arguments
    def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
        print("Do I have args?:")
        print(args)
        print(kwargs)
        # Then you unpack the arguments, here *args, **kwargs
        # If you are not familiar with unpacking, check:
        # http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
        function_to_decorate(*args, **kwargs)
    return a_wrapper_accepting_arbitrary_arguments

@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():
    print("Python is cool, no argument here.")

function_with_no_argument()
#outputs
#Do I have args?:
#()
#{}
#Python is cool, no argument here.

@a_decorator_passing_arbitrary_arguments
def function_with_arguments(a, b, c):
    print(a, b, c)

function_with_arguments(1,2,3)
#outputs
#Do I have args?:
#(1, 2, 3)
#{}
#1 2 3 

@a_decorator_passing_arbitrary_arguments
def function_with_named_arguments(a, b, c, platypus="Why not ?"):
    print("Do {0}, {1} and {2} like platypus? {3}".format(a, b, c, platypus))

function_with_named_arguments("Bill", "Linus", "Steve", platypus="Indeed!")
#outputs
#Do I have args ? :
#('Bill', 'Linus', 'Steve')
#{'platypus': 'Indeed!'}
#Do Bill, Linus and Steve like platypus? Indeed!

class Mary(object):

    def __init__(self):
        self.age = 31

    @a_decorator_passing_arbitrary_arguments
    def sayYourAge(self, lie=-3): # You can now add a default value
        print("I am {0}, what did you think?".format(self.age + lie))

m = Mary()
m.sayYourAge()
#outputs
# Do I have args?:
#(<__main__.Mary object at 0xb7d303ac>,)
#{}
#I am 28, what did you think?

Passing arguments to the decorator

Great, now what would you say about passing arguments to the decorator itself?

This can get somewhat twisted, since a decorator must accept a function as an argument. Therefore, you cannot pass the decorated function’s arguments directly to the decorator.

Before rushing to the solution, let’s write a little reminder:

# Decorators are ORDINARY functions
def my_decorator(func):
    print("I am an ordinary function")
    def wrapper():
        print("I am function returned by the decorator")
        func()
    return wrapper

# Therefore, you can call it without any "@"

def lazy_function():
    print("zzzzzzzz")

decorated_function = my_decorator(lazy_function)
#outputs: I am an ordinary function

# It outputs "I am an ordinary function", because that’s just what you do:
# calling a function. Nothing magic.

@my_decorator
def lazy_function():
    print("zzzzzzzz")

#outputs: I am an ordinary function

It’s exactly the same. "my_decorator" is called. So when you @my_decorator, you are telling Python to call the function 'labelled by the variable "my_decorator"'.

This is important! The label you give can point directly to the decorator—or not.

Let’s get evil. ?

def decorator_maker():

    print("I make decorators! I am executed only once: "
          "when you make me create a decorator.")

    def my_decorator(func):

        print("I am a decorator! I am executed only when you decorate a function.")

        def wrapped():
            print("I am the wrapper around the decorated function. "
                  "I am called when you call the decorated function. "
                  "As the wrapper, I return the RESULT of the decorated function.")
            return func()

        print("As the decorator, I return the wrapped function.")

        return wrapped

    print("As a decorator maker, I return a decorator")
    return my_decorator

# Let’s create a decorator. It’s just a new function after all.
new_decorator = decorator_maker()       
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator

# Then we decorate the function

def decorated_function():
    print("I am the decorated function.")

decorated_function = new_decorator(decorated_function)
#outputs:
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function

# Let’s call the function:
decorated_function()
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.

No surprise here.

Let’s do EXACTLY the same thing, but skip all the pesky intermediate variables:

def decorated_function():
    print("I am the decorated function.")
decorated_function = decorator_maker()(decorated_function)
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function.

# Finally:
decorated_function()    
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.

Let’s make it even shorter:

@decorator_maker()
def decorated_function():
    print("I am the decorated function.")
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function.

#Eventually: 
decorated_function()    
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.

Hey, did you see that? We used a function call with the "@" syntax! :-)

So, back to decorators with arguments. If we can use functions to generate the decorator on the fly, we can pass arguments to that function, right?

def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):

    print("I make decorators! And I accept arguments: {0}, {1}".format(decorator_arg1, decorator_arg2))

    def my_decorator(func):
        # The ability to pass arguments here is a gift from closures.
        # If you are not comfortable with closures, you can assume it’s ok,
        # or read: https://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
        print("I am the decorator. Somehow you passed me arguments: {0}, {1}".format(decorator_arg1, decorator_arg2))

        # Don't confuse decorator arguments and function arguments!
        def wrapped(function_arg1, function_arg2) :
            print("I am the wrapper around the decorated function.\n"
                  "I can access all the variables\n"
                  "\t- from the decorator: {0} {1}\n"
                  "\t- from the function call: {2} {3}\n"
                  "Then I can pass them to the decorated function"
                  .format(decorator_arg1, decorator_arg2,
                          function_arg1, function_arg2))
            return func(function_arg1, function_arg2)

        return wrapped

    return my_decorator

@decorator_maker_with_arguments("Leonard", "Sheldon")
def decorated_function_with_arguments(function_arg1, function_arg2):
    print("I am the decorated function and only knows about my arguments: {0}"
           " {1}".format(function_arg1, function_arg2))

decorated_function_with_arguments("Rajesh", "Howard")
#outputs:
#I make decorators! And I accept arguments: Leonard Sheldon
#I am the decorator. Somehow you passed me arguments: Leonard Sheldon
#I am the wrapper around the decorated function. 
#I can access all the variables 
#   - from the decorator: Leonard Sheldon 
#   - from the function call: Rajesh Howard 
#Then I can pass them to the decorated function
#I am the decorated function and only knows about my arguments: Rajesh Howard

Here it is: a decorator with arguments. Arguments can be set as variable:

c1 = "Penny"
c2 = "Leslie"

@decorator_maker_with_arguments("Leonard", c1)
def decorated_function_with_arguments(function_arg1, function_arg2):
    print("I am the decorated function and only knows about my arguments:"
           " {0} {1}".format(function_arg1, function_arg2))

decorated_function_with_arguments(c2, "Howard")
#outputs:
#I make decorators! And I accept arguments: Leonard Penny
#I am the decorator. Somehow you passed me arguments: Leonard Penny
#I am the wrapper around the decorated function. 
#I can access all the variables 
#   - from the decorator: Leonard Penny 
#   - from the function call: Leslie Howard 
#Then I can pass them to the decorated function
#I am the decorated function and only know about my arguments: Leslie Howard

As you can see, you can pass arguments to the decorator like any function using this trick. You can even use *args, **kwargs if you wish. But remember decorators are called only once. Just when Python imports the script. You can't dynamically set the arguments afterwards. When you do "import x", the function is already decorated, so you can't change anything.


Let’s practice: decorating a decorator

Okay, as a bonus, I'll give you a snippet to make any decorator accept generically any argument. After all, in order to accept arguments, we created our decorator using another function.

We wrapped the decorator.

Anything else we saw recently that wrapped function?

Oh yes, decorators!

Let’s have some fun and write a decorator for the decorators:

def decorator_with_args(decorator_to_enhance):
    """ 
    This function is supposed to be used as a decorator.
    It must decorate an other function, that is intended to be used as a decorator.
    Take a cup of coffee.
    It will allow any decorator to accept an arbitrary number of arguments,
    saving you the headache to remember how to do that every time.
    """

    # We use the same trick we did to pass arguments
    def decorator_maker(*args, **kwargs):

        # We create on the fly a decorator that accepts only a function
        # but keeps the passed arguments from the maker.
        def decorator_wrapper(func):

            # We return the result of the original decorator, which, after all, 
            # IS JUST AN ORDINARY FUNCTION (which returns a function).
            # Only pitfall: the decorator must have this specific signature or it won't work:
            return decorator_to_enhance(func, *args, **kwargs)

        return decorator_wrapper

    return decorator_maker

It can be used as follows:

# You create the function you will use as a decorator. And stick a decorator on it :-)
# Don't forget, the signature is "decorator(func, *args, **kwargs)"
@decorator_with_args 
def decorated_decorator(func, *args, **kwargs): 
    def wrapper(function_arg1, function_arg2):
        print("Decorated with {0} {1}".format(args, kwargs))
        return func(function_arg1, function_arg2)
    return wrapper

# Then you decorate the functions you wish with your brand new decorated decorator.

@decorated_decorator(42, 404, 1024)
def decorated_function(function_arg1, function_arg2):
    print("Hello {0} {1}".format(function_arg1, function_arg2))

decorated_function("Universe and", "everything")
#outputs:
#Decorated with (42, 404, 1024) {}
#Hello Universe and everything

# Whoooot!

I know, the last time you had this feeling, it was after listening a guy saying: "before understanding recursion, you must first understand recursion". But now, don't you feel good about mastering this?


Best practices: decorators

  • Decorators were introduced in Python 2.4, so be sure your code will be run on >= 2.4.
  • Decorators slow down the function call. Keep that in mind.
  • You cannot un-decorate a function. (There are hacks to create decorators that can be removed, but nobody uses them.) So once a function is decorated, it’s decorated for all the code.
  • Decorators wrap functions, which can make them hard to debug. (This gets better from Python >= 2.5; see below.)

The functools module was introduced in Python 2.5. It includes the function functools.wraps(), which copies the name, module, and docstring of the decorated function to its wrapper.

(Fun fact: functools.wraps() is a decorator! ?)

# For debugging, the stacktrace prints you the function __name__
def foo():
    print("foo")

print(foo.__name__)
#outputs: foo

# With a decorator, it gets messy    
def bar(func):
    def wrapper():
        print("bar")
        return func()
    return wrapper

@bar
def foo():
    print("foo")

print(foo.__name__)
#outputs: wrapper

# "functools" can help for that

import functools

def bar(func):
    # We say that "wrapper", is wrapping "func"
    # and the magic begins
    @functools.wraps(func)
    def wrapper():
        print("bar")
        return func()
    return wrapper

@bar
def foo():
    print("foo")

print(foo.__name__)
#outputs: foo

How can the decorators be useful?

Now the big question: What can I use decorators for?

Seem cool and powerful, but a practical example would be great. Well, there are 1000 possibilities. Classic uses are extending a function behavior from an external lib (you can't modify it), or for debugging (you don't want to modify it because it’s temporary).

You can use them to extend several functions in a DRY’s way, like so:

def benchmark(func):
    """
    A decorator that prints the time a function takes
    to execute.
    """
    import time
    def wrapper(*args, **kwargs):
        t = time.clock()
        res = func(*args, **kwargs)
        print("{0} {1}".format(func.__name__, time.clock()-t))
        return res
    return wrapper


def logging(func):
    """
    A decorator that logs the activity of the script.
    (it actually just prints it, but it could be logging!)
    """
    def wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        print("{0} {1} {2}".format(func.__name__, args, kwargs))
        return res
    return wrapper


def counter(func):
    """
    A decorator that counts and prints the number of times a function has been executed
    """
    def wrapper(*args, **kwargs):
        wrapper.count = wrapper.count + 1
        res = func(*args, **kwargs)
        print("{0} has been used: {1}x".format(func.__name__, wrapper.count))
        return res
    wrapper.count = 0
    return wrapper

@counter
@benchmark
@logging
def reverse_string(string):
    return str(reversed(string))

print(reverse_string("Able was I ere I saw Elba"))
print(reverse_string("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!"))

#outputs:
#reverse_string ('Able was I ere I saw Elba',) {}
#wrapper 0.0
#wrapper has been used: 1x 
#ablE was I ere I saw elbA
#reverse_string ('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!',) {}
#wrapper 0.0
#wrapper has been used: 2x
#!amanaP :lanac a ,noep a ,stah eros ,raj a ,hsac ,oloR a ,tur a ,mapS ,snip ,eperc a ,)lemac a ro( niaga gab ananab a ,gat a ,nat a ,gab ananab a ,gag a ,inoracam ,elacrep ,epins ,spam ,arutaroloc a ,shajar ,soreh ,atsap ,eonac a ,nalp a ,nam A

Of course the good thing with decorators is that you can use them right away on almost anything without rewriting. DRY, I said:

@counter
@benchmark
@logging
def get_random_futurama_quote():
    from urllib import urlopen
    result = urlopen("http://subfusion.net/cgi-bin/quote.pl?quote=futurama").read()
    try:
        value = result.split("<br><b><hr><br>")[1].split("<br><br><hr>")[0]
        return value.strip()
    except:
        return "No, I'm ... doesn't!"


print(get_random_futurama_quote())
print(get_random_futurama_quote())

#outputs:
#get_random_futurama_quote () {}
#wrapper 0.02
#wrapper has been used: 1x
#The laws of science be a harsh mistress.
#get_random_futurama_quote () {}
#wrapper 0.01
#wrapper has been used: 2x
#Curse you, merciful Poseidon!

Python itself provides several decorators: property, staticmethod, etc.

  • Django uses decorators to manage caching and view permissions.
  • Twisted to fake inlining asynchronous functions calls.

This really is a large playground.

What's the best way to use R scripts on the command line (terminal)?

If you are interested in parsing command line arguments to an R script try RScript which is bundled with R as of version 2.5.x

http://stat.ethz.ch/R-manual/R-patched/library/utils/html/Rscript.html

How to set the maximum memory usage for JVM?

The NativeHeap can be increasded by -XX:MaxDirectMemorySize=256M (default is 128)

I've never used it. Maybe you'll find it useful.

jquery datatables default sort

Datatables supports HTML5 data-* attributes for this functionality.

It supports multiple columns in the sort order (it's 0-based)

<table data-order="[[ 1, 'desc' ], [2, 'asc' ]]">
    <thead>
        <tr>
            <td>First</td>
            <td>Another column</td>
            <td>A third</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>z</td>
            <td>1</td>
            <td>$%^&*</td>
        </tr>
        <tr>
            <td>y</td>
            <td>2</td>
            <td>*$%^&</td>
        </tr>
    </tbody>
</table>

Now my jQuery is simply $('table').DataTables(); and I get my second and third columns sorted in desc / asc order.

Here's some other nice attributes for the <table> that I find myself reusing:

data-page-length="-1" will set the page length to All (pass 25 for page length 25)...

data-fixed-header="true" ... Make a guess

Confused about Service vs Factory

The basic difference, is that provider allows to set primitive (non-objects), array, or callback function values into the factory declared variable, and thus if returning an object it has to be explicitly declared and returned.

On the other hand a service can only be used to set the service declared variable to an object, thus we can avoid the explicit creation and returning of the objects, while on the other hand it allows usage of the this keyword.

Or in short words "provider is a more generic form while service is limited to objects only".

Comment shortcut Android Studio

Comment method like pro developers:

Windows/linux:

Line Comment : Ctrl + /

Block Comment : Ctrl + Shift

Method Commenting:

Type `/**` and press `Enter Key`

it will add the comment snippet like we see in standard documentation, give it a try this once.

/**
 * 
 * @param addOpacity
 */
public void setOpacityOnUserImage(boolean addOpacity) {
// Your business logic. 
}

Stop Chrome Caching My JS Files

I was getting the same css file when I browse website(on hosting company server with real domain) and I was unable to get the updated version on chrome. I was able to get the updated version of the file when I browse it on Firefox. None of these answers worked for me. I also have the website files on my machine and browse the site with localhost using my local apache server. I shut down my apache server and I was able to get the updated file. Somehow my local apache server was messing with the chrome cache. Hope this helps someone as it was very hard for me to fix this.

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

Width equal to content

By default p tags are block elements, which means they take 100% of the parent width.

You can change their display property with:

#container p {
   display:inline-block;
}

But it puts the elements side by side.

To keep each element on its own line you can use:

#container p {
   clear:both;
   float:left;
}

(If you use float and need to clear after floated elements, see this link for different techniques: http://css-tricks.com/all-about-floats/)

Demo: http://jsfiddle.net/CvJ3W/5/

Edit

If you go for the solution with display:inline-block but want to keep each item in one line, you can just add a <br> tag after each one:

<div id="container">
  <p>Sample Text 1</p><br/>
  <p>Sample Text 2</p><br/>
  <p>Sample Text 3</p><br/>
</div>

New demo: http://jsfiddle.net/CvJ3W/7/

jquery simple image slideshow tutorial

This is by far the easiest example I have found on the net. http://jonraasch.com/blog/a-simple-jquery-slideshow

Summaring the example, this is what you need to do a slideshow:

HTML:

<div id="slideshow">
    <img src="img1.jpg" style="position:absolute;" class="active" />
    <img src="img2.jpg" style="position:absolute;" />
    <img src="img3.jpg" style="position:absolute;" />
</div>

Position absolute is used to put an each image over the other.

CSS

<style type="text/css">
    .active{
        z-index:99;
    }
</style>

The image that has the class="active" will appear over the others, the class=active property will change with the following Jquery code.

<script>
    function slideSwitch() {
        var $active = $('div#slideshow IMG.active');
        var $next = $active.next();    

        $next.addClass('active');

        $active.removeClass('active');
    }

    $(function() {
        setInterval( "slideSwitch()", 5000 );
    });
</script>

If you want to go further with slideshows I suggest you to have a look at the link above (to see animated oppacity changes - 2n example) or at other more complex slideshows tutorials.

VBA: How to display an error message just like the standard error message which has a "Debug" button?

For Me I just wanted to see the error in my VBA application so in the function I created the below code..

Function Database_FileRpt
'-------------------------
On Error GoTo CleanFail
'-------------------------
'
' Create_DailyReport_Action and code


CleanFail:

'*************************************

MsgBox "********************" _

& vbCrLf & "Err.Number: " & Err.Number _

& vbCrLf & "Err.Description: " & Err.Description _

& vbCrLf & "Err.Source: " & Err.Source _

& vbCrLf & "********************" _

& vbCrLf & "...Exiting VBA Function: Database_FileRpt" _

& vbCrLf & "...Excel VBA Program Reset." _

, , "VBA Error Exception Raised!"

*************************************

 ' Note that the next line will reset the error object to 0, the variables 
above are used to remember the values
' so that the same error can be re-raised

Err.Clear

' *************************************

Resume CleanExit

CleanExit:

'cleanup code , if any, goes here. runs regardless of error state.

Exit Function  ' SUB  or Function    

End Function  ' end of Database_FileRpt

' ------------------

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

SELECT CONVERT(varchar(11),Getdate(),105)

How to center a subview of UIView

I would use:

child.center = CGPointMake(parent.bounds.height / 2, parent.bounds.width / 2)

This is simple, short, and sweet. If you use @Hejazi's answer above and parent.center is set to anything other than (0,0) your subview will not be centered!

Can I add extension methods to an existing static class?

It's not possible.

And yes, I think MS made a mistake here.

Their decision does not make sense and forces programmers to write (as described above) a pointless wrapper class.

Here is a good example: Trying to extend static MS Unit testing class Assert: I want 1 more Assert method AreEqual(x1,x2).

The only way to do this is to point to different classes or write a wrapper around 100s of different Assert methods. Why!?

If the decision was being made to allow extensions of instances, I see no logical reason to not allow static extensions. The arguments about sectioning libraries does not stand up once instances can be extended.

How to call C++ function from C?

I would do it in the following way:

(If working with MSVC, ignore the GCC compilation commands)

Suppose that I have a C++ class named AAA, defined in files aaa.h, aaa.cpp, and that the class AAA has a method named sayHi(const char *name), that I want to enable for C code.

The C++ code of class AAA - Pure C++, I don't modify it:

aaa.h

#ifndef AAA_H
#define AAA_H

class AAA {
    public:
        AAA();
        void sayHi(const char *name);
};

#endif

aaa.cpp

#include <iostream>

#include "aaa.h"

AAA::AAA() {
}

void AAA::sayHi(const char *name) {
    std::cout << "Hi " << name << std::endl;
}

Compiling this class as regularly done for C++. This code "does not know" that it is going to be used by C code. Using the command:

g++ -fpic -shared aaa.cpp -o libaaa.so

Now, also in C++, creating a C connector. Defining it in files aaa_c_connector.h, aaa_c_connector.cpp. This connector is going to define a C function, named AAA_sayHi(cosnt char *name), that will use an instance of AAA and will call its method:

aaa_c_connector.h

#ifndef AAA_C_CONNECTOR_H 
#define AAA_C_CONNECTOR_H 

#ifdef __cplusplus
extern "C" {
#endif

void AAA_sayHi(const char *name);

#ifdef __cplusplus
}
#endif


#endif

aaa_c_connector.cpp

#include <cstdlib>

#include "aaa_c_connector.h"
#include "aaa.h"

#ifdef __cplusplus
extern "C" {
#endif

// Inside this "extern C" block, I can implement functions in C++, which will externally 
//   appear as C functions (which means that the function IDs will be their names, unlike
//   the regular C++ behavior, which allows defining multiple functions with the same name
//   (overloading) and hence uses function signature hashing to enforce unique IDs),


static AAA *AAA_instance = NULL;

void lazyAAA() {
    if (AAA_instance == NULL) {
        AAA_instance = new AAA();
    }
}

void AAA_sayHi(const char *name) {
    lazyAAA();
    AAA_instance->sayHi(name);
}

#ifdef __cplusplus
}
#endif

Compiling it, again, using a regular C++ compilation command:

g++ -fpic -shared aaa_c_connector.cpp -L. -laaa -o libaaa_c_connector.so

Now I have a shared library (libaaa_c_connector.so), that implements the C function AAA_sayHi(const char *name). I can now create a C main file and compile it all together:

main.c

#include "aaa_c_connector.h"

int main() {
    AAA_sayHi("David");
    AAA_sayHi("James");

    return 0;
}

Compiling it using a C compilation command:

gcc main.c -L. -laaa_c_connector -o c_aaa

I will need to set LD_LIBRARY_PATH to contain $PWD, and if I run the executable ./c_aaa, I will get the output I expect:

Hi David
Hi James

EDIT:

On some linux distributions, -laaa and -lstdc++ may also be required for the last compilation command. Thanks to @AlaaM. for the attention

Read whole ASCII file into C++ std::string

If you happen to use glibmm you can try Glib::file_get_contents.

#include <iostream>
#include <glibmm.h>

int main() {
    auto filename = "my-file.txt";
    try {
        std::string contents = Glib::file_get_contents(filename);
        std::cout << "File data:\n" << contents << std::endl;
    catch (const Glib::FileError& e) {
        std::cout << "Oops, an error occurred:\n" << e.what() << std::endl;
    }

    return 0;
}

How do I get the dialer to open with phone number displayed?

As @ashishduh mentioned above, using android:autoLink="phone is also a good solution. But this option comes with one drawback, it doesn't work with all phone number lengths. For instance, a phone number of 11 numbers won't work with this option. The solution is to prefix your phone numbers with the country code.

Example:

08034448845 won't work

but +2348034448845 will

How can I find all of the distinct file extensions in a folder hierarchy?

No need for the pipe to sort, awk can do it all:

find . -type f | awk -F. '!a[$NF]++{print $NF}'

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

In the web development world, the term "redirect" is the act of sending the client an empty HTTP response with just a Location header containing the new URL to which the client has to send a brand new GET request. So basically:

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with Location: other.jsp header
  • Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
  • Server sends a HTTP response back with content of other.jsp.

You can track it with the web browser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.

Exactly the above is achieved by sendRedirect("other.jsp"). The RequestDispatcher#forward() doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with content of other.jsp.

However, as the original HTTP request was to some.jsp, the URL in browser address bar remains unchanged. Also, any request attributes set in the controller behind some.jsp will be available in other.jsp. This does not happen during a redirect because you're basically forcing the client to create a new HTTP request on other.jsp, hereby throwing away the original request on some.jsp including all of its attribtues.


The RequestDispatcher is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in the /WEB-INF folder and use a Servlet which controls, preprocesses and postprocesses the requests. The JSPs in the /WEB-INF folder are not directly accessible by URL, but the Servlet can access them using RequestDispatcher#forward().

You can for example have a JSP file in /WEB-INF/login.jsp and a LoginServlet which is mapped on an url-pattern of /login. When you invoke http://example.com/context/login, then the servlet's doGet() will be invoked. You can do any preprocessing stuff in there and finally forward the request like:

request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

When you submit a form, you normally want to use POST:

<form action="login" method="post">

This way the servlet's doPost() will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).

If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher for this.

If a POST is successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).

User user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user); // Login user.
    response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
    request.setAttribute("error", "Unknown login, please try again."); // Set error.
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}

A redirect thus instructs the client to fire a new GET request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experiences. This is also called the POST-Redirect-GET pattern.

See also:

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

Here's a variation I had to solve that's worth sharing: for each unique string in columnA I wanted to find the most common associated string in columnB.

df.groupby('columnA').agg({'columnB': lambda x: x.mode().any()}).reset_index()

The .any() picks one if there's a tie for the mode. (Note that using .any() on a Series of ints returns a boolean rather than picking one of them.)

For the original question, the corresponding approach simplifies to

df.groupby('columnA').columnB.agg('max').reset_index().

How to get your Netbeans project into Eclipse

  1. Make sure you have sbt and run sbt eclipse from the project root directory.
  2. In eclipse, use File --> Import --> General --> Existing Projects into Workspace, selecting that same location, so that eclipse builds its project structure for the file structure having just been prepared by sbt.

Safest way to get last record ID from a table

SELECT LAST(row_name) FROM table_name

What is C# analog of C++ std::pair?

C# has tuples as of version 4.0.

How to properly -filter multiple strings in a PowerShell copy script

Something like this should work (it did for me). The reason for wanting to use -Filter instead of -Include is that include takes a huge performance hit compared to -Filter.

Below just loops each file type and multiple servers/workstations specified in separate files.

##  
##  This script will pull from a list of workstations in a text file and search for the specified string


## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside

$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'

##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'

foreach ($server in $servers)
    {

    foreach ($filetype in $filetypes)
    {

    ## below creates the search path.  This could be further improved to exclude the windows directory
    $serverString = "\\"+$server+"\c$\Program Files"


    ## Display the server being queried
    write-host “Server:” $server "searching for " $filetype in $serverString

    Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
    #-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
    Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt

    $os = gwmi win32_operatingsystem -computer $server
    $sp = $os | % {$_.servicepackmajorversion}
    $a = $os | % {$_.caption}

    ##  Below will list again the server name as well as its OS and SP
    ##  Because the script may not be monitored, this helps confirm the machine has been successfully scanned
        write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp


    }

}
#end script