Programs & Examples On #Zend filter

The zend-filter component provides a set of commonly needed data filters. It also provides a simple filter chaining mechanism by which multiple filters may be applied to a single datum in a user-defined order.

How can I open two pages from a single click without using JavaScript?

<a href="http://www.omsaicreche.blogspot.com" onclick="location.href='http://www.omsaivatikanoida.blogspot.com';" target="_blank">Open Two Links With One Click</a>

I tried the above codes. I could not get success in old page. Than I created a new page in blogger and types following codes... I was successful

In .NET, which loop runs faster, 'for' or 'foreach'?

foreach loops demonstrate more specific intent than for loops.

Using a foreach loop demonstrates to anyone using your code that you are planning to do something to each member of a collection irrespective of its place in the collection. It also shows you aren't modifying the original collection (and throws an exception if you try to).

The other advantage of foreach is that it works on any IEnumerable, where as for only makes sense for IList, where each element actually has an index.

However, if you need to use the index of an element, then of course you should be allowed to use a for loop. But if you don't need to use an index, having one is just cluttering your code.

There are no significant performance implications as far as I'm aware. At some stage in the future it might be easier to adapt code using foreach to run on multiple cores, but that's not something to worry about right now.

Using "Object.create" instead of "new"

new and Object.create serve different purposes. new is intended to create a new instance of an object type. Object.create is intended to simply create a new object and set its prototype. Why is this useful? To implement inheritance without accessing the __proto__ property. An object instance's prototype referred to as [[Prototype]] is an internal property of the virtual machine and is not intended to be directly accessed. The only reason it is actually possible to directly access [[Prototype]] as the __proto__ property is because it has always been a de-facto standard of every major virtual machine's implementation of ECMAScript, and at this point removing it would break a lot of existing code.

In response to the answer above by 7ochem, objects should absolutely never have their prototype set to the result of a new statement, not only because there's no point calling the same prototype constructor multiple times but also because two instances of the same class can end up with different behavior if one's prototype is modified after being created. Both examples are simply bad code as a result of misunderstanding and breaking the intended behavior of the prototype inheritance chain.

Instead of accessing __proto__, an instance's prototype should be written to when an it is created with Object.create or afterward with Object.setPrototypeOf, and read with Object.getPrototypeOf or Object.isPrototypeOf.

Also, as the Mozilla documentation of Object.setPrototypeOf points out, it is a bad idea to modify the prototype of an object after it is created for performance reasons, in addition to the fact that modifying an object's prototype after it is created can cause undefined behavior if a given piece of code that accesses it can be executed before OR after the prototype is modified, unless that code is very careful to check the current prototype or not access any property that differs between the two.

Given

const X = function (v) { this.v = v }; X.prototype.whatAmI = 'X'; X.prototype.getWhatIAm = () => this.whatAmI; X.prototype.getV = () => this.v;

the following VM pseudo-code is equivalent to the statement const x0 = new X(1);:

const x0 = {}; x0.[[Prototype]] = X.prototype; X.prototype.constructor.call(x0, 1);

Note although the constructor can return any value, the new statement always ignores its return value and returns a reference to the newly created object.

And the following pseudo-code is equivalent to the statement const x1 = Object.create(X.prototype);:

const x0 = {}; x0.[[Prototype]] = X.prototype;

As you can see, the only difference between the two is that Object.create does not execute the constructor, which can actually return any value but simply returns the new object reference this if not otherwise specified.

Now, if we wanted to create a subclass Y with the following definition:

const Y = function(u) { this.u = u; } Y.prototype.whatAmI = 'Y'; Y.prototype.getU = () => this.u;

Then we can make it inherit from X like this by writing to __proto__:

Y.prototype.__proto__ = X.prototype;

While the same thing could be accomplished without ever writing to __proto__ with:

Y.prototype = Object.create(X.prototype); Y.prototype.constructor = Y;

In the latter case, it is necessary to set the constructor property of the prototype so that the correct constructor is called by the new Y statement, otherwise new Y will call the function X. If the programmer does want new Y to call X, it would be more properly done in Y's constructor with X.call(this, u)

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

When I added the $(inherited) flag to the file in question (in this case it was LIBRARY_SEARCH_PATHS) it led to another error Undefined symbols for architecture arm64: "_swift_getTypeByMangledNameInContextInMetadataState

Changing the following worked and I was able to build:

>LIBRARY_SEARCH_PATHS = (
   "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
-  "\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)\"", <--- Change this...
+  "\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.2/$(PLATFORM_NAME)\"", <--- to this
   "\"$(inherited)\"",
> );

CSS: 100% width or height while keeping aspect ratio?

If you only define one dimension on an image the image aspect ratio will always be preserved.

Is the issue that the image is bigger/taller than you prefer?

You could put it inside a DIV that is set to the maximum height/width that you want for the image, and then set overflow:hidden. That would crop anything beyond what you want.

If an image is 100% wide and height:auto and you think it's too tall, that is specifically because the aspect ratio is preserved. You'll need to crop, or to change the aspect ratio.

Please provide some more information about what you're specifically trying to accomplish and I'll try to help more!

--- EDIT BASED ON FEEDBACK ---

Are you familiar with the max-width and max-height properties? You could always set those instead. If you don't set any minimum and you set a max height and width then your image will not be distorted (aspect ratio will be preserved) and it will not be any larger than whichever dimension is longest and hits its max.

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

How do you move a file?

Transferring a file using TortoiseSVN:

Step:1 Please Select the files which you want to move, Right-click and drag the files to the folder which you to move them to, A window will popup after follow the below instruction

SVN option

Step 2: After you click the above the commit the file as below mention

SVN Commit

How do I create a self-signed certificate for code signing on Windows?

Updated Answer

If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.

If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.

Original Answer

While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:

Creating a self-signed certificate authority (CA)

makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
         -a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer

(^ = allow batch command-line to wrap line)

This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).

The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.

Importing the CA certificate

Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:

certutil -user -addstore Root MyCA.cer

Creating a code-signing certificate (SPC)

makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
         -sky signature ^
         -ic MyCA.cer -iv MyCA.pvk ^
         -sv MySPC.pvk MySPC.cer

It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).

We'll also want to convert the certificate and key into a PFX file:

pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx

If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.

Using the certificate for signing code

signtool sign /v /f MySPC.pfx ^
              /t http://timestamp.url MyExecutable.exe

(See why timestamps may matter)

If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:

signtool sign /v /n "Me" /s SPC ^
              /t http://timestamp.url MyExecutable.exe

Some possible timestamp URLs for signtool /t are:

  • http://timestamp.verisign.com/scripts/timstamp.dll
  • http://timestamp.globalsign.com/scripts/timstamp.dll
  • http://timestamp.comodoca.com/authenticode

Full Microsoft documentation

Downloads

For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1). Your mileage may vary.

MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).

Do standard windows .ini files allow comments?

I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.

Edit

The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.

Convert a dta file to csv without Stata software

You could try doing it through R:

For Stata <= 15 you can use the haven package to read the dataset and then you simply write it to external CSV file:

library(haven)
yourData = read_dta("path/to/file")
write.csv(yourData, file = "yourStataFile.csv")

Alternatively, visit the link pointed by huntaub in a comment below.


For Stata <= 12 datasets foreign package can also be used

library(foreign)
yourData <- read.dta("yourStataFile.dta")

T-SQL XOR Operator

The xor operator is ^

For example: SELECT A ^ B where A and B are integer category data types.

Get a specific bit from byte

another way of doing it :)

return ((b >> bitNumber) & 1) != 0;

Display SQL query results in php

You cannot directly see the query result using mysql_query its only fires the query in mysql nothing else.

For getting the result you have to add a lil things in your script like

require_once('db.php');  
 $sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) ORDER BY idM1O LIMIT 1";

 $result = mysql_query($sql);
 //echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    print_r($row);
}

This will give you result;

How to concatenate strings in twig

This should work fine:

{{ 'http://' ~ app.request.host }}

To add a filter - like 'trans' - in the same tag use

{{ ('http://' ~ app.request.host) | trans }}

As Adam Elsodaney points out, you can also use string interpolation, this does require double quoted strings:

{{ "http://#{app.request.host}" }}

SQL Server Group by Count of DateTime Per Hour?

How about this? Assuming SQL Server 2008:

SELECT CAST(StartDate as date) AS ForDate,
       DATEPART(hour,StartDate) AS OnHour,
       COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
       DATEPART(hour,StartDate)

For pre-2008:

SELECT DATEADD(day,datediff(day,0,StartDate),0)   AS ForDate,
       DATEPART(hour,StartDate) AS OnHour,
       COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
       DATEPART(hour,StartDate)

This results in :

ForDate                 | OnHour | Totals
-----------------------------------------
2011-08-09 00:00:00.000     12       3

git pull error :error: remote ref is at but expected

After searching constantly, this is the solution that worked for me which entails unsetting/removing the Upstream

git branch --unset-upstream

Rails: How can I set default values in ActiveRecord?

I ran into problems with after_initialize giving ActiveModel::MissingAttributeError errors when doing complex finds:

eg:

@bottles = Bottle.includes(:supplier, :substance).where(search).order("suppliers.name ASC").paginate(:page => page_no)

"search" in the .where is hash of conditions

So I ended up doing it by overriding initialize in this way:

def initialize
  super
  default_values
end

private
 def default_values
     self.date_received ||= Date.current
 end

The super call is necessary to make sure the object initializing correctly from ActiveRecord::Base before doing my customize code, ie: default_values

Do I cast the result of malloc?

Casting the value returned by malloc() is not necessary now, but I'd like to add one point that seems no one has pointed out:

In the ancient days, that is, before ANSI C provides the void * as the generic type of pointers, char * is the type for such usage. In that case, the cast can shut down the compiler warnings.

Reference: C FAQ

jQuery calculate sum of values in all text fields

If you don't need to support IE8 then you can use the native Javascript Array.prototype.reduce() method. You will need to convert your JQuery object into an array first:

 var sum = $('.price').toArray().reduce(function(sum,element) {
     if(isNaN(sum)) sum = 0;
     return sum + Number(element.value);
 }, 0);

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

how to write value into cell with vba code without auto type conversion?

This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:

prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _ 
    param_cls_shift.Start_Date (string property of my class) 

Linux command to list all available commands and aliases

Why don't you just type:

seachstr

In the terminal.

The shell will say somehing like

seacrhstr: command not found 

EDIT:

Ok, I take the downvote, because the answer is stupid, I just want to know: What's wrong with this answer!!! The asker said:

and see if a command is available.

Typing the command will tell you if it is available!.

Probably he/she meant "with out executing the command" or "to include it in a script" but I cannot read his mind ( is not that I can't regularly it is just that he's wearing a mind reading deflector )

How to prevent a dialog from closing when a button is clicked

Super simple Kotlin approach

 with(AlertDialog.Builder(this)) {
        setTitle("Title")
        setView(R.layout.dialog_name)
        setPositiveButton("Ok", null)
        setNegativeButton("Cancel") { _, _ -> }
        create().apply {
            setOnShowListener {
                getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
                    //Validate and dismiss
                    dismiss()
                }
            }
        }
    }.show()

How to find the mysql data directory from command line in windows

You can try this-

mysql> select @@datadir;

PS- It works on every platform.

403 Forbidden You don't have permission to access /folder-name/ on this server

**403 Forbidden **

You don't have permission to access /Folder-Name/ on this server**

The solution for this problem is:

1.go to etc/apache2/apache2.conf

2.find the below code and change AllowOverride all to AllowOverride none

 <Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride all      Change this to--->  AllowOverride none
    Require all granted
 </Directory>

It will work fine on your Ubuntu server

How can a LEFT OUTER JOIN return more records than exist in the left table?

if multiple (x) rows in Dim_Member are associated with a single row in Susp_Visits, there will be x rows in the resul set.

Java 8 Streams: multiple filters vs. complex condition

The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.

Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x.isCool()) by filter(ItemType::isCool). That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single filter invocation using a lambda expression with &&.

But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.

In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks¹.

So there is no simple answer.

The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.


¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation

PHP Warning: Invalid argument supplied for foreach()

Try this.

if(is_array($value) || is_object($value)){
    foreach($value as $item){
     //somecode
    }
}

Array from dictionary keys in swift

NSDictionary is Class(pass by reference) NSDictionary is class type Dictionary is Structure(pass by value) Dictionary is structure of key and value ====== Array from NSDictionary ======

NSDictionary has allKeys and allValues get properties with type [Any].NSDictionary has get [Any] properties for allkeys and allvalues

  let objesctNSDictionary = 
    NSDictionary.init(dictionary: ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"])
            let objectArrayOfAllKeys:Array = objesctNSDictionary.allKeys
            let objectArrayOfAllValues:Array = objesctNSDictionary.allValues
            print(objectArrayOfAllKeys)
            print(objectArrayOfAllValues)

====== Array From Dictionary ======

Apple reference for Dictionary's keys and values properties. enter image description here

enter image description here

let objectDictionary:Dictionary = 
            ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
    let objectArrayOfAllKeys:Array = Array(objectDictionary.keys)          
    let objectArrayOfAllValues:Array = Array(objectDictionary.values)
    print(objectArrayOfAllKeys)
    print(objectArrayOfAllValues)

How can I put a database under git (version control)?

Here is what i am trying to do in my projects:

  • separate data and schema and default data.

The database configuration is stored in configuration file that is not under version control (.gitignore)

The database defaults (for setting up new Projects) is a simple SQL file under version control.

For the database schema create a database schema dump under the version control.

The most common way is to have update scripts that contains SQL Statements, (ALTER Table.. or UPDATE). You also need to have a place in your database where you save the current version of you schema)

Take a look at other big open source database projects (piwik,or your favorite cms system), they all use updatescripts (1.sql,2.sql,3.sh,4.php.5.sql)

But this a very time intensive job, you have to create, and test the updatescripts and you need to run a common updatescript that compares the version and run all necessary update scripts.

So theoretically (and thats what i am looking for) you could dumped the the database schema after each change (manually, conjob, git hooks (maybe before commit)) (and only in some very special cases create updatescripts)

After that in your common updatescript (run the normal updatescripts, for the special cases) and then compare the schemas (the dump and current database) and then automatically generate the nessesary ALTER Statements. There some tools that can do this already, but haven't found yet a good one.

Rounding float in Ruby

Pass an argument to round containing the number of decimal places to round to

>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

concat.js is being included in the concat task's source files public/js/*.js. You could have a task that removes concat.js (if the file exists) before concatenating again, pass an array to explicitly define which files you want to concatenate and their order, or change the structure of your project.

If doing the latter, you could put all your sources under ./src and your built files under ./dest

src
+-- css
¦   +-- 1.css
¦   +-- 2.css
¦   +-- 3.css
+-- js
    +-- 1.js
    +-- 2.js
    +-- 3.js

Then set up your concat task

concat: {
  js: {
    src: 'src/js/*.js',
    dest: 'dest/js/concat.js'
  },
  css: {
    src: 'src/css/*.css',
    dest: 'dest/css/concat.css'
  }
},

Your min task

min: {
  js: {
    src: 'dest/js/concat.js',
    dest: 'dest/js/concat.min.js'
  }
},

The build-in min task uses UglifyJS, so you need a replacement. I found grunt-css to be pretty good. After installing it, load it into your grunt file

grunt.loadNpmTasks('grunt-css');

And then set it up

cssmin: {
  css:{
    src: 'dest/css/concat.css',
    dest: 'dest/css/concat.min.css'
  }
}

Notice that the usage is similar to the built-in min.

Change your default task to

grunt.registerTask('default', 'concat min cssmin');

Now, running grunt will produce the results you want.

dest
+-- css
¦   +-- concat.css
¦   +-- concat.min.css
+-- js
    +-- concat.js
    +-- concat.min.js

What does the percentage sign mean in Python

Modulus operator; gives the remainder of the left value divided by the right value. Like:

3 % 1 would equal zero (since 3 divides evenly by 1)

3 % 2 would equal 1 (since dividing 3 by 2 results in a remainder of 1).

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

How many characters in varchar(max)

From http://msdn.microsoft.com/en-us/library/ms176089.aspx

varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

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

What's happening is that the shell is expanding "*test.c" into a list of files. Try escaping the asterisk as:

find . -name \*test.c

How can I convert uppercase letters to lowercase in Notepad++

Just select the text you want to change, right click and select UPPERCASE or lowercase depending on what you want.

Equivalent of Clean & build in Android Studio?

In latest releases of Android Studio one more option has been added dedicatedly for Clean.

Build > Clean Project 

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN

IF THEN ELSE

IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

DECLARE
  mark NUMBER :=50;
BEGIN
  mark :=& mark;
  IF (mark BETWEEN 85 AND 100) THEN
    dbms_output.put_line('mark is A ');
  elsif (mark BETWEEN 50 AND 65) THEN
    dbms_output.put_line('mark is D ');
  elsif (mark BETWEEN 66 AND 75) THEN
    dbms_output.put_line('mark is C ');
  elsif (mark BETWEEN 76 AND 84) THEN
    dbms_output.put_line('mark is B');
  ELSE
    dbms_output.put_line('mark is F');
  END IF;
END;
/

Javascript how to split newline

The problem is that when you initialize ks, the value hasn't been set.

You need to fetch the value when user submits the form. So you need to initialize the ks inside the callback function

(function($){
   $(document).ready(function(){
      $('#data').submit(function(e){
      //Here it will fetch the value of #keywords
         var ks = $('#keywords').val().split("\n");
         ...
      });
   });
})(jQuery);

A method to count occurrences in a list

How about something like this ...

var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };

var g = l1.GroupBy( i => i );

foreach( var grp in g )
{
  Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}

Edit per comment: I will try and do this justice. :)

In my example, it's a Func<int, TKey> because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int> (a grouping of ints keyed by an int). If I changed it to (i => i.ToString() ) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...

private string SampleMethod( int i )
{
  // magically return "One" if i == 1, "Two" if i == 2, etc.
}

So, that's a Func that would take an int and return a string, just like ...

i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 

But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).


In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

Postgres: How to convert a json string to text?

In 9.4.4 using the #>> operator works for me:

select to_json('test'::text) #>> '{}';

To use with a table column:

select jsoncol #>> '{}' from mytable;

How can I scan barcodes on iOS?

I believe this can be done using AVFramework, here is the sample code to do this

import UIKit
import AVFoundation

class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate
{

    @IBOutlet weak var lblQRCodeResult: UILabel!
    @IBOutlet weak var lblQRCodeLabel: UILabel!

    var objCaptureSession:AVCaptureSession?
    var objCaptureVideoPreviewLayer:AVCaptureVideoPreviewLayer?
    var vwQRCode:UIView?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.configureVideoCapture()
        self.addVideoPreviewLayer()
        self.initializeQRView()
    }

    func configureVideoCapture() {
        let objCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        var error:NSError?
        let objCaptureDeviceInput: AnyObject!
        do {
            objCaptureDeviceInput = try AVCaptureDeviceInput(device: objCaptureDevice) as AVCaptureDeviceInput

        } catch let error1 as NSError {
            error = error1
            objCaptureDeviceInput = nil
        }
        objCaptureSession = AVCaptureSession()
        objCaptureSession?.addInput(objCaptureDeviceInput as! AVCaptureInput)
        let objCaptureMetadataOutput = AVCaptureMetadataOutput()
        objCaptureSession?.addOutput(objCaptureMetadataOutput)
        objCaptureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        objCaptureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
    }

    func addVideoPreviewLayer() {
        objCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: objCaptureSession)
        objCaptureVideoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        objCaptureVideoPreviewLayer?.frame = view.layer.bounds
        self.view.layer.addSublayer(objCaptureVideoPreviewLayer!)
        objCaptureSession?.startRunning()
        self.view.bringSubviewToFront(lblQRCodeResult)
        self.view.bringSubviewToFront(lblQRCodeLabel)
    }

    func initializeQRView() {
        vwQRCode = UIView()
        vwQRCode?.layer.borderColor = UIColor.redColor().CGColor
        vwQRCode?.layer.borderWidth = 5
        self.view.addSubview(vwQRCode!)
        self.view.bringSubviewToFront(vwQRCode!)
    }

    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        if metadataObjects == nil || metadataObjects.count == 0 {
            vwQRCode?.frame = CGRectZero
            lblQRCodeResult.text = "QR Code wans't found"
            return
        }
        let objMetadataMachineReadableCodeObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
        if objMetadataMachineReadableCodeObject.type == AVMetadataObjectTypeQRCode {
            let objBarCode = objCaptureVideoPreviewLayer?.transformedMetadataObjectForMetadataObject(objMetadataMachineReadableCodeObject as AVMetadataMachineReadableCodeObject) as! AVMetadataMachineReadableCodeObject
            vwQRCode?.frame = objBarCode.bounds;
            if objMetadataMachineReadableCodeObject.stringValue != nil {
                lblQRCodeResult.text = objMetadataMachineReadableCodeObject.stringValue
            }
        }
    }
}

How can I enable CORS on Django REST Framework

You can do by using a custom middleware, even though knowing that the best option is using the tested approach of the package django-cors-headers. With that said, here is the solution:

create the following structure and files:

-- myapp/middleware/__init__.py

from corsMiddleware import corsMiddleware

-- myapp/middleware/corsMiddleware.py

class corsMiddleware(object):
    def process_response(self, req, resp):
        resp["Access-Control-Allow-Origin"] = "*"
        return resp

add to settings.py the marked line:

MIDDLEWARE_CLASSES = (
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",

    # Now we add here our custom middleware
     'app_name.middleware.corsMiddleware' <---- this line
)

Find where python is installed (if it isn't default dir)

On windows running where python should work.

How do I call a dynamically-named method in Javascript?

I wouldn't recommend using the window as some of the other answers suggest. Use this and scope accordingly.

this['yourDynamicFcnName'](arguments);

Another neat trick is calling within different scopes and using it for inheritance. Let's say you had nested the function and want access to the global window object. You could do this:

this['yourDynamicFcnName'].call(window, arguments);

How to check which locks are held on a table

You can also use the built-in sp_who2 stored procedure to get current blocked and blocking processes on a SQL Server instance. Typically you'd run this alongside a SQL Profiler instance to find a blocking process and look at the most recent command that spid issued in profiler.

How can I convert string to double in C++?

See C++ FAQ Lite How do I convert a std::string to a number?

See C++ Super-FAQ How do I convert a std::string to a number?

Please note that with your requirements you can't distinguish all the the allowed string representations of zero from the non numerical strings.

 // the requested function
 #include <sstream>
 double string_to_double( const std::string& s )
 {
   std::istringstream i(s);
   double x;
   if (!(i >> x))
     return 0;
   return x;
 } 

 // some tests
 #include <cassert>
 int main( int, char** )
 {
    // simple case:
    assert( 0.5 == string_to_double( "0.5"    ) );

    // blank space:
    assert( 0.5 == string_to_double( "0.5 "   ) );
    assert( 0.5 == string_to_double( " 0.5"   ) );

    // trailing non digit characters:
    assert( 0.5 == string_to_double( "0.5a"   ) );

    // note that with your requirements you can't distinguish
    // all the the allowed string representation of zero from
    // the non numerical strings:
    assert( 0 == string_to_double( "0"       ) );
    assert( 0 == string_to_double( "0."      ) );
    assert( 0 == string_to_double( "0.0"     ) );
    assert( 0 == string_to_double( "0.00"    ) );
    assert( 0 == string_to_double( "0.0e0"   ) );
    assert( 0 == string_to_double( "0.0e-0"  ) );
    assert( 0 == string_to_double( "0.0e+0"  ) );
    assert( 0 == string_to_double( "+0"      ) );
    assert( 0 == string_to_double( "+0."     ) );
    assert( 0 == string_to_double( "+0.0"    ) );
    assert( 0 == string_to_double( "+0.00"   ) );
    assert( 0 == string_to_double( "+0.0e0"  ) );
    assert( 0 == string_to_double( "+0.0e-0" ) );
    assert( 0 == string_to_double( "+0.0e+0" ) );
    assert( 0 == string_to_double( "-0"      ) );
    assert( 0 == string_to_double( "-0."     ) );
    assert( 0 == string_to_double( "-0.0"    ) );
    assert( 0 == string_to_double( "-0.00"   ) );
    assert( 0 == string_to_double( "-0.0e0"  ) );
    assert( 0 == string_to_double( "-0.0e-0" ) );
    assert( 0 == string_to_double( "-0.0e+0" ) );
    assert( 0 == string_to_double( "foobar"  ) );
    return 0;
 }

How to loop and render elements in React-native?

If u want a direct/ quick away, without assing to variables:

{
 urArray.map((prop, key) => {
     console.log(emp);
     return <Picker.Item label={emp.Name} value={emp.id} />;
 })
}

How to make a Bootstrap accordion collapse when clicking the header div?

I've noticed a couple of minor flaws in grim's jsfiddle.

To get the pointer to change to a hand for the whole of the panel use:

.panel-heading {
   cursor: pointer;
}

I've removed the <a> tag (a style issue) and kept data-toggle="collapse" data-parent="#accordion" data-target="#collapse..." on panel-heading throughout.

I've added a CSS method for displaying chevron, using font-awesome.css in my jsfiddle:

http://jsfiddle.net/weaversnap/7FqsX/1/

What is the best way to repeatedly execute a function every x seconds?

Lock your time loop to the system clock like this:

import time
starttime = time.time()
while True:
    print "tick"
    time.sleep(60.0 - ((time.time() - starttime) % 60.0))

Finding partial text in range, return an index

I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B

I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

wt = tt - cpu tm.
Tt = cpu tm + wt.

Where wt is a waiting time and tt is turnaround time. Cpu time is also called burst time.

Swift - iOS - Dates and times in different format

This is possibly an old thread but I was working on datetimes recently and was stuck with similar issue so I ended up creating a utility of mine which looks like this,

This utility would take a string date and would return an optional date object

        func toDate(dateFormat: DateFormatType) -> Date? {
        let formatter = DateFormatter()
        formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
        formatter.dateFormat = dateFormat.rawValue
        let temp = formatter.date(from: self)
        return formatter.date(from: self)
        }

the DateFormatType enum looks like this

        enum DateFormatType : String {
        case type1 = "yyyy-MM-dd - HH:mm:ss"
        case type2 = "dd/MM/yyyy"
        case type3 = "yyyy/MM/dd"
    }

One important thing I would like to mention here is the line

formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?

it's very important that you add this line because without this the DateFormatter would use it's default conversions to convert the date and you might end up seeing different dates if you are working with a remote team and get all sorts of issues with data depending on dates.

Hope this helps

How to create standard Borderless buttons (like in the design guideline mentioned)?

A great slide show on how to achieve the desired effect from Googles Nick Butcher (start at slide 20). He uses the standard android @attr to style the button and divider.

Execute curl command within a Python script

You could use urllib as @roippi said:

import urllib2
data = '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
url = 'http://localhost:8080/firewall/rules/0000000000000001'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
for x in f:
    print(x)
f.close()

Convert JS object to JSON string

The most popular way is below:

_x000D_
_x000D_
var obj = {name: "Martin", age: 30, country: "United States"};   _x000D_
// Converting JS object to JSON string_x000D_
var json = JSON.stringify(obj);_x000D_
console.log(json);
_x000D_
_x000D_
_x000D_

Regular Expressions- Match Anything

Honestly alot of the answers are old so i found that if you simply just test any string regardless of character content with "/.*/i" will sufficiently get EVERYTHING.

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});

$.ajax({
    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            submitForm(event, data);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
        // STOP LOADING SPINNER
    }
});
}

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

if(isset($_GET['files']))
{  
$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
    {
        $files[] = $uploaddir .$file['name'];
    }
    else
    {
        $error = true;
    }
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

?>

IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
{
  // Create a jQuery object from the form
$form = $(event.target);

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
{
    formData = formData + '&filenames[]=' + value;
});

$.ajax({
    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    },
    complete: function()
    {
        // STOP LOADING SPINNER
    }
});
}

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

Python: How to get stdout after running os.system?

If all you need is the stdout output, then take a look at subprocess.check_output():

import subprocess

batcmd="dir"
result = subprocess.check_output(batcmd, shell=True)

Because you were using os.system(), you'd have to set shell=True to get the same behaviour. You do want to heed the security concerns about passing untrusted arguments to your shell.

If you need to capture stderr as well, simply add stderr=subprocess.STDOUT to the call:

result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)

to redirect the error output to the default output stream.

If you know that the output is text, add text=True to decode the returned bytes value with the platform default encoding; use encoding="..." instead if that codec is not correct for the data you receive.

How to completely uninstall Visual Studio 2010?

Download and install IOBIT uninstaller: http://www.iobit.com/advanceduninstaller.php, find the date in which you install Visual Studio and select all programas from that date r elated to VS. Then run de batch uninstaller. It is not a fully automated solution but it is a lot quicker than going one by one int he add / remove programs in Windows. It even has a power scan to clean the registry.

Why is there no xrange function in Python3?

One way to fix up your python2 code is:

import sys

if sys.version_info >= (3, 0):
    def xrange(*args, **kwargs):
        return iter(range(*args, **kwargs))

Get name of property as a string

I modified your solution to chain over multiple properties:

public static string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
    MemberExpression me = propertyLambda.Body as MemberExpression;
    if (me == null)
    {
        throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
    }

    string result = string.Empty;
    do
    {
        result = me.Member.Name + "." + result;
        me = me.Expression as MemberExpression;
    } while (me != null);

    result = result.Remove(result.Length - 1); // remove the trailing "."
    return result;
}

Usage:

string name = GetPropertyName(() => someObject.SomeProperty.SomeOtherProperty);
// returns "SomeProperty.SomeOtherProperty"

Java BigDecimal: Round to the nearest whole value

Here's an awfully complicated solution, but it works:

public static BigDecimal roundBigDecimal(final BigDecimal input){
    return input.round(
        new MathContext(
            input.toBigInteger().toString().length(),
            RoundingMode.HALF_UP
        )
    );
}

Test Code:

List<BigDecimal> bigDecimals =
    Arrays.asList(new BigDecimal("100.12"),
        new BigDecimal("100.44"),
        new BigDecimal("100.50"),
        new BigDecimal("100.75"));
for(final BigDecimal bd : bigDecimals){
    System.out.println(roundBigDecimal(bd).toPlainString());
}

Output:

100
100
101
101

How to use string.substr() function?

Possible solution without using substr()

#include<iostream>
#include<string>

using namespace std;


int main() {
    string c="12345";
    int p=0;

    for(int i=0;i<c.length();i++) {
        cout<<c[i];
        p++;

        if (p % 2 == 0 && i != c.length()-1) {
            cout<<" "<<c[i];
            p++;
        }
    }
}

Can I force a UITableView to hide the separator between empty cells?

You can achieve what you want by defining a footer for the tableview. See this answer for more details:Eliminate Extra separators below UITableView

ValueError: unconverted data remains: 02:05

The value of st at st = datetime.strptime(st, '%A %d %B') line something like 01 01 2013 02:05 and the strptime can't parse this. Indeed, you get an hour in addition of the date... You need to add %H:%M at your strptime.

best way to get the key of a key/value javascript object

You can use Object.keys functionality to get the keys like:

const tempObjects={foo:"bar"}

Object.keys(tempObjects).forEach(obj=>{
   console.log("Key->"+obj+ "value->"+tempObjects[obj]);
});

HTTP GET Request in Node.js Express

Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)

How to read a file without newlines?

another example:

Reading file one row at the time. Removing unwanted chars with from end of the string str.rstrip(chars)

with open(filename, 'r') as fileobj:
    for row in fileobj:
        print( row.rstrip('\n') )

see also str.strip([chars]) and str.lstrip([chars])

(python >= 2.0)

How do you round a float to 2 decimal places in JRuby?

Float#round can take a parameter in Ruby 1.9, not in Ruby 1.8. JRuby defaults to 1.8, but it is capable of running in 1.9 mode.

Using curl to upload POST data with files

The issue that lead me here turned out to be a basic user error - I wasn't including the @ sign in the path of the file and so curl was posting the path/name of the file rather than the contents. The Content-Length value was therefore 8 rather than the 479 I expected to see given the legnth of my test file.

The Content-Length header will be automatically calculated when curl reads and posts the file.

curl -i -H "Content-Type: application/xml" --data "@test.xml" -v -X POST https://<url>/<uri/

... < Content-Length: 479 ...

Posting this here to assist other newbies in future.

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

The difference between creating an array with the implicit array and the array constructor is subtle but important.

When you create an array using

var a = [];

You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.

If you use:

var a = new Array();

You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.

Take the following example:

function Array() {
    this.is = 'SPARTA';
}

var a = new Array();
var b = [];

alert(a.is);  // => 'SPARTA'
alert(b.is);  // => undefined
a.push('Woa'); // => TypeError: a.push is not a function
b.push('Woa'); // => 1 (OK)

In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as push, where the other does not.

While you may expect this to happen, it just illustrates the fact that [] is not the same as new Array().

It's probably best to just use [] if you know you just want an array. I also do not suggest going around and redefining Array...

How to check if String value is Boolean type in Java?

I suggest that you take a look at the Java docs for these methods. It appears that you are using them incorrectly. These methods will not tell you if the string is a valid boolean value, but instead they return a boolean, set to true or false, based on the string that you pass in, "true" or "false".

http://www.j2ee.me/javase/6/docs/api/java/lang/Boolean.html

Angularjs: Get element in controller

$element is one of four locals that $compileProvider gives to $controllerProvider which then gets given to $injector. The injector injects locals in your controller function only if asked.

The four locals are:

  • $scope
  • $element
  • $attrs
  • $transclude

The official documentation: AngularJS $compile Service API Reference - controller

The source code from Github angular.js/compile.js:

 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
    var elementControllers = createMap();
    for (var controllerKey in controllerDirectives) {
      var directive = controllerDirectives[controllerKey];
      var locals = {
        $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
        $element: $element,
        $attrs: attrs,
        $transclude: transcludeFn
      };

      var controller = directive.controller;
      if (controller == '@') {
        controller = attrs[directive.name];
      }

      var controllerInstance = $controller(controller, locals, true, directive.controllerAs);

Add a auto increment primary key to existing table in oracle

Say your table is called t1 and your primary-key is called id
First, create the sequence:

create sequence t1_seq start with 1 increment by 1 nomaxvalue; 

Then create a trigger that increments upon insert:

create trigger t1_trigger
before insert on t1
for each row
   begin
     select t1_seq.nextval into :new.id from dual;
   end;

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

How do I make a placeholder for a 'select' box?

Here is a CSS solution that works beautifully. The content is added (and absolutely positioned relative to the container) after the containing element (via :after pseudo-class).

It gets its text from the placeholder attribute that I defined where I used the directive (attr(placeholder)). Another key factor is pointer-events: none - this allows clicks on the placeholder text to pass through to the select. Otherwise it won't drop down if the user clicks the text.

I add the .empty class myself in my select directive, but normally I find that angular adds/removes .ng-empty for me (I assume it's because I'm injecting version 1.2 of Angular in my code sample).

(The sample also demonstrates how to wrap HTML elements in AngularJS to create your own custom inputs)

_x000D_
_x000D_
var app = angular.module("soDemo", []);_x000D_
app.controller("soDemoController", function($scope) {_x000D_
  var vm = {};_x000D_
  vm.names = [{_x000D_
      id: 1,_x000D_
      name: 'Jon'_x000D_
    },_x000D_
    {_x000D_
      id: 2,_x000D_
      name: 'Joe'_x000D_
    }, {_x000D_
      id: 3,_x000D_
      name: 'Bob'_x000D_
    }, {_x000D_
      id: 4,_x000D_
      name: 'Jane'_x000D_
    }_x000D_
  ];_x000D_
  vm.nameId;_x000D_
  $scope.vm = vm;_x000D_
});_x000D_
_x000D_
app.directive('soSelect', function soSelect() {_x000D_
  var directive = {_x000D_
    restrict: 'E',_x000D_
    require: 'ngModel',_x000D_
    scope: {_x000D_
      'valueProperty': '@',_x000D_
      'displayProperty': '@',_x000D_
      'modelProperty': '=',_x000D_
      'source': '=',_x000D_
    },_x000D_
    link: link,_x000D_
    template: getTemplate_x000D_
  };_x000D_
  return directive;_x000D_
_x000D_
_x000D_
  /////////////////////////////////_x000D_
  function link(scope, element, attrs, ngModelController) {_x000D_
    init();_x000D_
    return;_x000D_
_x000D_
_x000D_
    ///////////// IMPLEMENTATION_x000D_
_x000D_
    function init() {_x000D_
      initDataBinding();_x000D_
    }_x000D_
_x000D_
_x000D_
    function initDataBinding() {_x000D_
      ngModelController.$render = function() {_x000D_
        if (scope.model === ngModelController.$viewValue) return;_x000D_
        scope.model = ngModelController.$viewValue;_x000D_
      }_x000D_
_x000D_
      scope.$watch('model', function(newValue) {_x000D_
        if (newValue === undefined) {_x000D_
          element.addClass('empty');_x000D_
          return;_x000D_
        }_x000D_
        element.removeClass('empty');_x000D_
        ngModelController.$setViewValue(newValue);_x000D_
      });_x000D_
    }_x000D_
  }_x000D_
_x000D_
_x000D_
  function getTemplate(element, attrs) {_x000D_
    var attributes = [_x000D_
      'ng-model="model"',_x000D_
      'ng-required="true"'_x000D_
    ];_x000D_
_x000D_
    if (angular.isDefined(attrs.placeholder)) {_x000D_
      attributes.push('placeholder="{{placeholder}}"');_x000D_
    }_x000D_
_x000D_
    var ngOptions = '';_x000D_
_x000D_
    if (angular.isDefined(attrs.valueProperty)) {_x000D_
      ngOptions += 'item.' + attrs.valueProperty + ' as ';_x000D_
    }_x000D_
_x000D_
    ngOptions += 'item.' + attrs.displayProperty + ' for item in source';_x000D_
    ngOptions += '"';_x000D_
    attributes.push('ng-options="' + ngOptions + '"');_x000D_
_x000D_
    var html = '<select ' + attributes.join(' ') + '></select>';_x000D_
_x000D_
    return html;_x000D_
  }_x000D_
});
_x000D_
so-select {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
so-select select {_x000D_
  font-family: 'Helvetica';_x000D_
  display: inline-block;_x000D_
  height: 24px;_x000D_
  width: 200px;_x000D_
  padding: 0 1px;_x000D_
  font-size: 12px;_x000D_
  color: #222;_x000D_
  border: 1px solid #c7c7c7;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
_x000D_
so-select.empty:before {_x000D_
  font-family: 'Helvetica';_x000D_
  font-size: 12px;_x000D_
  content: attr(placeholder);_x000D_
  position: absolute;_x000D_
  pointer-events: none;_x000D_
  left: 6px;_x000D_
  top: 3px;_x000D_
  z-index: 0;_x000D_
  color: #888;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="soDemo" ng-controller="soDemoController">_x000D_
  <so-select value-property="id" display-property="name" source="vm.names" ng-model="vm.nameId" placeholder="(select name)"></so-select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

if you have Firebase included also, make them of same version as the error says.

Change text from "Submit" on input tag

The value attribute on submit-type <input> elements controls the text displayed.

<input type="submit" class="like" value="Like" />

What HTTP traffic monitor would you recommend for Windows?

Try Wireshark:

Wireshark is the world's foremost network protocol analyzer, and is the de facto (and often de jure) standard across many industries and educational institutions.

There is a bit of a learning curve but it is far and away the best tool available.

How to listen for a WebView finishing loading a URL?

If you want show a progress bar you need to listen for a progress change event, not just for the completion of page:

mWebView.setWebChromeClient(new WebChromeClient(){

            @Override
            public void onProgressChanged(WebView view, int newProgress) {

                //change your progress bar
            }


        });

BTW if you want display just an Indeterminate ProgressBar overriding the method onPageFinished is enough

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

Swift 3

extension Date {
    
    func toString(template: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: NSLocale.current)
        return formatter.string(from: self)
    }
    
}

Usage

let now = Date()
let nowStr0 = now.toString(template: "EEEEdMMM") // Tuesday, May 9
let nowStr1 = now.toString(template: "yyyy-MM-dd") // 2017-05-09
let nowStr2 = now.toString(template: "HH:mm:ss") // 17:47:09

Play with template to match your needs. Examples and doc here to help you build the template you need.

Note

You may want to cache your DateFormatter if you plan to use it in TableView for instance. To give an idea, looping over 1000 dates took me 0.5 sec using the above toString(template: String) function, compared to 0.05 sec using myFormatter.string(from: Date).

css absolute position won't work with margin-left:auto margin-right: auto

if the absolute element has a width,you can use the code below

.divtagABS{
    width:300px;
    positon:absolute;
    left:0;
    right:0;
    margin:0 auto;
}

How to set a value of a variable inside a template code?

Create a template tag:

The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.

Create a file named define_action.py inside of the templatetags directory with the following code:

from django import template
register = template.Library()

@register.simple_tag
def define(val=None):
  return val

Note: Development server won’t automatically restart. After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.


Then in your template you can assign values to the context like this:

{% load define_action %}
{% if item %}

   {% define "Edit" as action %}

{% else %}

   {% define "Create" as action %}

{% endif %}


Would you like to {{action}} this item?

How to get full REST request body using Jersey?

Try this using this single code:

import javax.ws.rs.POST;
import javax.ws.rs.Path;

@Path("/serviceX")
public class MyClassRESTService {

    @POST
    @Path("/doSomething")   
    public void someMethod(String x) {

        System.out.println(x);
                // String x contains the body, you can process
                // it, parse it using JAXB and so on ...

    }
}

The url for try rest services ends .... /serviceX/doSomething

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

try using this one

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri https://apod.nasa.gov/apod/

Convert JSON to DataTable

json = File.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\" +download_file[0]);
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

Check play state of AVPlayer

Answer is Objective C

if (player.timeControlStatus == AVPlayerTimeControlStatusPlaying) {
    //player is playing
}
else if (player.timeControlStatus == AVPlayerTimeControlStatusPaused) {
    //player is pause
}
else if (player.timeControlStatus == AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate) {
    //player is waiting to play
}

How to make Java honor the DNS Caching Timeout?

So I decided to look at the java source code because I found official docs a bit confusing. And what I found (for OpenJDK 11) mostly aligns with what others have written. What is important is the order of evaluation of properties.

InetAddressCachePolicy.java (I'm omitting some boilerplate for readability):


String tmpString = Security.getProperty("networkaddress.cache.ttl");
if (tmpString != null) {
   tmp = Integer.valueOf(tmpString);
   return;
}
...
String tmpString = System.getProperty("sun.net.inetaddr.ttl");
if (tmpString != null) {
   tmp = Integer.valueOf(tmpString);
   return;
}
...
if (tmp != null) {
  cachePolicy = tmp < 0 ? FOREVER : tmp;
  propertySet = true;
} else {
  /* No properties defined for positive caching. If there is no
  * security manager then use the default positive cache value.
  */
  if (System.getSecurityManager() == null) {
    cachePolicy = 30;
  }
}

You can clearly see that the security property is evaluated first, system property second and if any of them is set cachePolicy value is set to that number or -1 (FOREVER) if they hold a value that is bellow -1. If nothing is set it defaults to 30 seconds. As it turns out for OpenJDK that is almost always the case because by default java.security does not set that value, only a negative one.

#networkaddress.cache.ttl=-1 <- this line is commented out
networkaddress.cache.negative.ttl=10

BTW if the networkaddress.cache.negative.ttl is not set (removed from the file) the default inside the java class is 0. Documentation is wrong in this regard. This is what tripped me over.

Create a string of variable length, filled with a repeated character

ES2015 the easiest way is to do something like

'X'.repeat(data.length)

X being any string, data.length being the desired length.

see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

XPath to fetch SQL XML value

I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.

For basic XPath know-how, I'd recommend the W3Schools tutorial.

Keras model.summary() result - Understanding the # of Parameters

Number of parameters is the amount of numbers that can be changed in the model. Mathematically this means number of dimensions of your optimization problem. For you as a programmer, each of this parameters is a floating point number, which typically takes 4 bytes of memory, allowing you to predict the size of this model once saved.

This formula for this number is different for each neural network layer type, but for Dense layer it is simple: each neuron has one bias parameter and one weight per input: N = n_neurons * ( n_inputs + 1).

initializing a boolean array in java

Arrays in Java start indexing at 0. So in your example you are referring to an element that is outside the array by one.

It should probably be something like freq[Global.iParameter[2]-1]=false;

You would need to loop through the array to initialize all of it, this line only initializes the last element.

Actually, I'm pretty sure that false is default for booleans in Java, so you might not need to initialize at all.

Best Regards

Business logic in MVC

A1: Business Logic goes to Model part in MVC. Role of Model is to contain data and business logic. Controller on the other hand is responsible to receive user input and decide what to do.

A2: A Business Rule is part of Business Logic. They have a has a relationship. Business Logic has Business Rules.

Take a look at Wikipedia entry for MVC. Go to Overview where it mentions the flow of MVC pattern.

Also look at Wikipedia entry for Business Logic. It is mentioned that Business Logic is comprised of Business Rules and Workflow.

Check if a value exists in ArrayList

public static void linktest()
{
    System.setProperty("webdriver.chrome.driver","C://Users//WDSI//Downloads/chromedriver.exe");
    driver=new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://toolsqa.wpengine.com/");
    //List<WebElement> allLinkElements=(List<WebElement>) driver.findElement(By.xpath("//a"));
    //int linkcount=allLinkElements.size();
    //System.out.println(linkcount);
    List<WebElement> link = driver.findElements(By.tagName("a"));
    String data="HOME";
    int linkcount=link.size();
    System.out.println(linkcount);
    for(int i=0;i<link.size();i++) { 
        if(link.get(i).getText().contains(data)) {
            System.out.println("true");         
        }
    } 
}

jQuery 'each' loop with JSON array

Try (untested):

$.getJSON("data.php", function(data){
    $.each(data.justIn, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.recent, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.old, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });    
});

I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:

$.getJSON("data.php", function(data){
    $.each(data, function(k, v) {
        alert(k + ' ' + v);
        $.each(v, function(k1, v1) {
            alert(k1 + ' ' + v1);
        });
    });
}); 

Capture close event on Bootstrap Modal

This is worked for me, anyone can try it

$("#myModal").on("hidden.bs.modal", function () {
    for (instance in CKEDITOR.instances)
        CKEDITOR.instances[instance].destroy();
    $('#myModal .modal-body').html('');    
});

you can open ckEditor in Modal window

Should switch statements always contain a default clause?

The default case may not necessary in the switch used by enum. when switch contained all value, the default case will never execute. So in this case, it is not necessary.

Why shouldn't I use mysql_* functions in PHP?

The MySQL extension:

  • Is not under active development
  • Is officially deprecated as of PHP 5.5 (released June 2013).
  • Has been removed entirely as of PHP 7.0 (released December 2015)
    • This means that as of 31 Dec 2018 it does not exist in any supported version of PHP. If you are using a version of PHP which supports it, you are using a version which doesn't get security problems fixed.
  • Lacks an OO interface
  • Doesn't support:
    • Non-blocking, asynchronous queries
    • Prepared statements or parameterized queries
    • Stored procedures
    • Multiple Statements
    • Transactions
    • The "new" password authentication method (on by default in MySQL 5.6; required in 5.7)
    • Any of the new functionality in MySQL 5.1 or later

Since it is deprecated, using it makes your code less future proof.

Lack of support for prepared statements is particularly important as they provide a clearer, less error-prone method of escaping and quoting external data than manually escaping it with a separate function call.

See the comparison of SQL extensions.

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

This problem is just because you have declared the column in CHAR, VARCHAR or TEXT datatype. Just change the datatype to INT, BIGINT etc. This is will solved the problem of your custom ordering.

Angular EXCEPTION: No provider for Http

I faced this issue in my code. I only put this code in my app.module.ts.

import { HttpModule } from '@angular/http';

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

iPhone hide Navigation Bar only on first page

One slight tweak I had to make on the other answers is to only unhide the bar in viewWillDisappear if the reason it is disappearing is due to a navigation item being pushed on it. This is because the view can disappear for other reasons.

So I only unhide the bar if this view is no longer the topmost view:

- (void) viewWillDisappear:(BOOL)animated
{
    if (self.navigationController.topViewController != self)
    {
        [self.navigationController setNavigationBarHidden:NO animated:animated];
    }

    [super viewWillDisappear:animated];
}

Creating Dynamic button with click event in JavaScript

Firstly, you need to change this line:

element.setAttribute("onclick", alert("blabla"));

To something like this:

element.setAttribute("onclick", function() { alert("blabla"); });

Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.

What is the difference between cache and persist?

With cache(), you use only the default storage level :

  • MEMORY_ONLY for RDD
  • MEMORY_AND_DISK for Dataset

With persist(), you can specify which storage level you want for both RDD and Dataset.

From the official docs:

  • You can mark an RDD to be persisted using the persist() or cache() methods on it.
  • each persisted RDD can be stored using a different storage level
  • The cache() method is a shorthand for using the default storage level, which is StorageLevel.MEMORY_ONLY (store deserialized objects in memory).

Use persist() if you want to assign a storage level other than :

  • MEMORY_ONLY to the RDD
  • or MEMORY_AND_DISK for Dataset

Interesting link for the official documentation : which storage level to choose

Best way to convert pdf files to tiff files

using python this is what I ended up with

    import os
    os.popen(' '.join([
                       self._ghostscriptPath + 'gswin32c.exe', 
                       '-q',
                       '-dNOPAUSE',
                       '-dBATCH',
                       '-r300',
                       '-sDEVICE=tiff12nc',
                       '-sPAPERSIZE=a4',
                       '-sOutputFile=%s %s' % (tifDest, pdfSource),
                       ]))

Using ffmpeg to change framerate

In general, to set a video's FPS to 24, almost always you can do:

With Audio and without re-encoding:

# Extract video stream
ffmpeg -y -i input_video.mp4 -c copy -f h264 output_raw_bitstream.h264
# Extract audio stream
ffmpeg -y -i input_video.mp4 -vn -acodec copy output_audio.aac
# Remux with new FPS 
ffmpeg -y -r 24 -i output_raw_bitstream.h264 -i output-audio.aac -c copy output.mp4

If you want to find the video format (H264 in this case), you can use FFprobe, like this

ffprobe -loglevel error -select_streams v -show_entries stream=codec_name -of default=nw=1:nk=1 input_video.mp4

which will output:

h264

Read more in How can I analyze file and detect if the file is in H.264 video format?


With re-encoding:

ffmpeg -y -i input_video.mp4 -vf -r 24 output.mp4

Python find elements in one list that are not in the other

I used two methods and I found one method useful over other. Here is my answer:

My input data:

crkmod_mpp = ['M13','M18','M19','M24']
testmod_mpp = ['M13','M14','M15','M16','M17','M18','M19','M20','M21','M22','M23','M24']

Method1: np.setdiff1d I like this approach over other because it preserves the position

test= list(np.setdiff1d(testmod_mpp,crkmod_mpp))
print(test)
['M15', 'M16', 'M22', 'M23', 'M20', 'M14', 'M17', 'M21']

Method2: Though it gives same answer as in Method1 but disturbs the order

test = list(set(testmod_mpp).difference(set(crkmod_mpp)))
print(test)
['POA23', 'POA15', 'POA17', 'POA16', 'POA22', 'POA18', 'POA24', 'POA21']

Method1 np.setdiff1d meets my requirements perfectly. This answer for information.

How to iterate over rows in a DataFrame in Pandas

While iterrows() is a good option, sometimes itertuples() can be much faster:

df = pd.DataFrame({'a': randn(1000), 'b': randn(1000),'N': randint(100, 1000, (1000)), 'x': 'x'})

%timeit [row.a * 2 for idx, row in df.iterrows()]
# => 10 loops, best of 3: 50.3 ms per loop

%timeit [row[1] * 2 for row in df.itertuples()]
# => 1000 loops, best of 3: 541 µs per loop

How to use a keypress event in AngularJS?

You can use ng-keydown ="myFunction($event)" as attribute.

<input ng-keydown="myFunction($event)" type="number">

myFunction(event) {
    if(event.keyCode == 13) {   // '13' is the key code for enter
        // do what you want to do when 'enter' is pressed :)
    }
}

jQuery UI DatePicker to show month year only

after digging jQueryUI.com for datepicker, here's my conclusion and answer to your question.

First, I would say no to your question. You can't use jQueryUI datepicker for picking month and year only. It is not supported. It has no callback function for that.

But you can hack it to display only month and and year by using css to hide the days, etc. And I think won't make sense still cause you need the dates to be click in order to pick a date.

I can say you just have to use another datepicker. Like what Roger suggested.

Using Predicate in Swift

This is really just a syntax switch. OK, so we have this method call:

[NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];

In Swift, constructors skip the "blahWith…" part and just use the class name as a function and then go straight to the arguments, so [NSPredicate predicateWithFormat: …] would become NSPredicate(format: …). (For another example, [NSArray arrayWithObject: …] would become NSArray(object: …). This is a regular pattern in Swift.)

So now we just need to pass the arguments to the constructor. In Objective-C, NSString literals look like @"", but in Swift we just use quotation marks for strings. So that gives us:

let resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)

And in fact that is exactly what we need here.

(Incidentally, you'll notice some of the other answers instead use a format string like "name contains[c] \(searchText)". That is not correct. That uses string interpolation, which is different from predicate formatting and will generally not work for this.)

String Concatenation in EL

1.The +(operator) has not effect to that in using EL. 2.so this is the way,to use that

<c:set var="enabled" value="${value} enabled" />


<c:out value="${empty value ? 'none' : enabled}" />

is this helpful to You ?

SQL Server: Maximum character length of object names

Yes, it is 128, except for temp tables, whose names can only be up to 116 character long. It is perfectly explained here.

And the verification can be easily made with the following script contained in the blog post before:

DECLARE @i NVARCHAR(800)
SELECT @i = REPLICATE('A', 116)
SELECT @i = 'CREATE TABLE #'+@i+'(i int)'
PRINT @i
EXEC(@i)

What is the purpose and use of **kwargs?

  • kwargs in **kwargs is just variable name. You can very well have **anyVariableName
  • kwargs stands for "keyword arguments". But I feel they should better be called as "named arguments", as these are simply arguments passed along with names (I dont find any significance to the word "keyword" in the term "keyword arguments". I guess "keyword" usually means words reserved by programming language and hence not to be used by the programmer for variable names. No such thing is happening here in case of kwargs.). So we give names param1 and param2 to two parameter values passed to the function as follows: func(param1="val1",param2="val2"), instead of passing only values: func(val1,val2). Thus, I feel they should be appropriately called "arbitrary number of named arguments" as we can specify any number of these parameters (that is, arguments) if func has signature func(**kwargs)

So being said that let me explain "named arguments" first and then "arbitrary number of named arguments" kwargs.

Named arguments

  • named args should follow positional args
  • order of named args is not important
  • Example

    def function1(param1,param2="arg2",param3="arg3"):
        print("\n"+str(param1)+" "+str(param2)+" "+str(param3)+"\n")
    
    function1(1)                      #1 arg2 arg3   #1 positional arg
    function1(param1=1)               #1 arg2 arg3   #1 named arg
    function1(1,param2=2)             #1 2 arg3      #1 positional arg, 1 named arg
    function1(param1=1,param2=2)      #1 2 arg3      #2 named args       
    function1(param2=2, param1=1)     #1 2 arg3      #2 named args out of order
    function1(1, param3=3, param2=2)  #1 2 3         #
    
    #function1()                      #invalid: required argument missing
    #function1(param2=2,1)            #invalid: SyntaxError: non-keyword arg after keyword arg
    #function1(1,param1=11)           #invalid: TypeError: function1() got multiple values for argument 'param1'
    #function1(param4=4)              #invalid: TypeError: function1() got an unexpected keyword argument 'param4'
    

Arbitrary number of named arguments kwargs

  • Sequence of function parameters:
    1. positional parameters
    2. formal parameter capturing arbitrary number of arguments (prefixed with *)
    3. named formal parameters
    4. formal parameter capturing arbitrary number of named parameters (prefixed with **)
  • Example

    def function2(param1, *tupleParams, param2, param3, **dictionaryParams):
        print("param1: "+ param1)
        print("param2: "+ param2)
        print("param3: "+ param3)
        print("custom tuple params","-"*10)
        for p in tupleParams:
            print(str(p) + ",")
        print("custom named params","-"*10)
        for k,v in dictionaryParams.items():
            print(str(k)+":"+str(v))
    
    function2("arg1",
              "custom param1",
              "custom param2",
              "custom param3",
              param3="arg3",
              param2="arg2", 
              customNamedParam1 = "val1",
              customNamedParam2 = "val2"
              )
    
    # Output
    #
    #param1: arg1
    #param2: arg2
    #param3: arg3
    #custom tuple params ----------
    #custom param1,
    #custom param2,
    #custom param3,
    #custom named params ----------
    #customNamedParam2:val2
    #customNamedParam1:val1
    

Passing tuple and dict variables for custom args

To finish it up, let me also note that we can pass

  • "formal parameter capturing arbitrary number of arguments" as tuple variable and
  • "formal parameter capturing arbitrary number of named parameters" as dict variable

Thus the same above call can be made as follows:

tupleCustomArgs = ("custom param1", "custom param2", "custom param3")
dictCustomNamedArgs = {"customNamedParam1":"val1", "customNamedParam2":"val2"}

function2("arg1",
      *tupleCustomArgs,    #note *
      param3="arg3",
      param2="arg2", 
      **dictCustomNamedArgs     #note **
      )

Finally note * and ** in function calls above. If we omit them, we may get ill results.

Omitting * in tuple args:

function2("arg1",
      tupleCustomArgs,   #omitting *
      param3="arg3",
      param2="arg2", 
      **dictCustomNamedArgs
      )

prints

param1: arg1
param2: arg2
param3: arg3
custom tuple params ----------
('custom param1', 'custom param2', 'custom param3'),
custom named params ----------
customNamedParam2:val2
customNamedParam1:val1

Above tuple ('custom param1', 'custom param2', 'custom param3') is printed as is.

Omitting dict args:

function2("arg1",
      *tupleCustomArgs,   
      param3="arg3",
      param2="arg2", 
      dictCustomNamedArgs   #omitting **
      )

gives

dictCustomNamedArgs
         ^
SyntaxError: non-keyword arg after keyword arg

Android Linear Layout - How to Keep Element At Bottom Of View?

You will have to expand one of your upper views to fill the remaining space by setting android:layout_weight="1" on it. This will push your last view down to the bottom.

Here is a brief sketch of what I mean:

<LinearLayout android:orientation="vertical">
    <View/>
    <View android:layout_weight="1"/>
    <View/>
    <View android:id="@+id/bottom"/>
</LinearLayout>

where each of the child view heights is "wrap_content" and everything else is "fill_parent".

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

I don't want to sound too negative, but there are occasions when what you want is almost impossible without a lot of "artificial" tuning of page breaks.

If the callout falls naturally near the bottom of a page, and the figure falls on the following page, moving the figure back one page will probably displace the callout forward.

I would recommend (as far as possible, and depending on the exact size of the figures):

  • Place the figures with [t] (or [h] if you must)
  • Place the figures as near as possible to the "right" place (differs for [t] and [h])
  • Include the figures from separate files with \input, which will make them much easier to move around when you're doing the final tuning

In my experience, this is a big eater-up of non-available time (:-)


In reply to Jon's comment, I think this is an inherently difficult problem, because the LaTeX guys are no slouches. You may like to read Frank Mittelbach's paper.

How to put labels over geom_bar for each bar in R with ggplot2

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

Dynamically allocating an array of objects

  1. Use array or common container for objects only if they have default and copy constructors.

  2. Store pointers otherwise (or smart pointers, but may meet some issues in this case).

PS: Always define own default and copy constructors otherwise auto-generated will be used

How do I overload the square-bracket operator in C#?

Here is an example returning a value from an internal List object. Should give you the idea.

  public object this[int index]
  {
     get { return ( List[index] ); }
     set { List[index] = value; }
  }

Get pixel's RGB using PIL

Yes, this way:

im = Image.open('image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))

print(r, g, b)
(65, 100, 137)

The reason you were getting a single value before with pix[1, 1] is because GIF pixels refer to one of the 256 values in the GIF color palette.

See also this SO post: Python and PIL pixel values different for GIF and JPEG and this PIL Reference page contains more information on the convert() function.

By the way, your code would work just fine for .jpg images.

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

If anyone is having this problem when trying to run Jupyter kernel from a virtualenv, just add correct PYTHONPATH to kernel.json of your virtualenv kernel (Python 3 in example):

{
 "argv": [
  "/usr/local/Cellar/python/3.6.5/bin/python3.6",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "Python 3 (TensorFlow)",
 "language": "python",
 "env": {
     "PYTHONPATH":     "/Users/dimitrijer/git/mlai/.venv/lib/python3.6:/Users/dimitrijer/git/mlai/.venv/lib/python3.6/lib-dynload:/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6:/Users/dimitrijer/git/mlai/.venv/lib/python3.6/site-packages"
}
}

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding (or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:

sys.stdout.buffer.write(some_bytes_object)

This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.

How to programmatically set the SSLContext of a JAX-WS client?

I had problems trusting a self signed certificate when setting up the trust manager. I used the SSLContexts builder of the apache httpclient to create a custom SSLSocketFactory

SSLContext sslcontext = SSLContexts.custom()
        .loadKeyMaterial(keyStoreFile, "keystorePassword.toCharArray(), keyPassword.toCharArray())
        .loadTrustMaterial(trustStoreFile, "password".toCharArray(), new TrustSelfSignedStrategy())
        .build();
SSLSocketFactory customSslFactory = sslcontext.getSocketFactory()
bindingProvider.getRequestContext().put(JAXWSProperties.SSL_SOCKET_FACTORY, customSslFactory);

and passing in the new TrustSelfSignedStrategy() as an argument in the loadTrustMaterial method.

How can I load webpage content into a div on page load?

Take a look into jQuery's .load() function:

<script>
    $(function(){
        $('#siteloader').load('http://www.somesitehere.com');
    });
</script>

However, this only works on the same domain of the JS file.

How to specify a port number in SQL Server connection string?

Use a comma to specify a port number with SQL Server:

mycomputer.test.xxx.com,1234

It's not necessary to specify an instance name when specifying the port.

Lots more examples at http://www.connectionstrings.com/. It's saved me a few times.

Prevent direct access to a php include file

An alternative (or complement) to Chuck's solution would be to deny access to files matching a specific pattern by putting something like this in your .htaccess file

<FilesMatch "\.(inc)$">
    Order deny,allow
    Deny from all
</FilesMatch>

How to create a user in Django?

Have you confirmed that you are passing actual values and not None?

from django.shortcuts import render

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed
    if userName and userPass and userMail:
       u,created = User.objects.get_or_create(userName, userMail)
       if created:
          # user was created
          # set the password here
       else:
          # user was retrieved
    else:
       # request was empty

    return render(request,'home.html')

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

ComboBox.SelectedText doesn't give me the SelectedText

If you bind your Combobox to something like KeyValuePair, with properties in the constructor like so...:

 DataSource = dataSource,
 DisplayMember = "Value",
 ValueMember = "Key"

so dataSource is of type KeyValuePair...

You end up with having to do this...

  string v = ((KeyValuePair)((ComboBox)c).SelectedItem).Value;

(I had a Dynamic form - where c was of type Control - so had to cast it to ComboBox)

Accessing variables from other functions without using global variables

Consider using namespaces:

(function() {
    var local_var = 'foo';
    global_var = 'bar'; // this.global_var and window.global_var also work

    function local_function() {}
    global_function = function() {};
})();

Both local_function and global_function have access to all local and global variables.

Edit: Another common pattern:

var ns = (function() {
    // local stuff
    function foo() {}
    function bar() {}
    function baz() {} // this one stays invisible

    // stuff visible in namespace object
    return {
        foo : foo,
        bar : bar
    };
})();

The returned properties can now be accessed via the namespace object, e.g. ns.foo, while still retaining access to local definitions.

How to 'insert if not exists' in MySQL?

on duplicate key update, or insert ignore can be viable solutions with MySQL.


Example of on duplicate key update update based on mysql.com

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

UPDATE table SET c=c+1 WHERE a=1;

Example of insert ignore based on mysql.com

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name [(col_name,...)]
    {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
    [ ON DUPLICATE KEY UPDATE
      col_name=expr
        [, col_name=expr] ... ]

Or:

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    SET col_name={expr | DEFAULT}, ...
    [ ON DUPLICATE KEY UPDATE
      col_name=expr
        [, col_name=expr] ... ]

Or:

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name [(col_name,...)]
    SELECT ...
    [ ON DUPLICATE KEY UPDATE
      col_name=expr
        [, col_name=expr] ... ]

Convert List<DerivedClass> to List<BaseClass>

The way to make this work is to iterate over the list and cast the elements. This can be done using ConvertAll:

List<A> listOfA = new List<C>().ConvertAll(x => (A)x);

You could also use Linq:

List<A> listOfA = new List<C>().Cast<A>().ToList();

Does Java have a complete enum for HTTP response codes?

If you are using Netty, you can use:

How to start a stopped Docker container with a different command?

Edit this file (corresponding to your stopped container):

vi /var/lib/docker/containers/923...4f6/config.json

Change the "Path" parameter to point at your new command, e.g. /bin/bash. You may also set the "Args" parameter to pass arguments to the command.

Restart the docker service (note this will stop all running containers):

service docker restart

List your containers and make sure the command has changed:

docker ps -a

Start the container and attach to it, you should now be in your shell!

docker start -ai mad_brattain

Worked on Fedora 22 using Docker 1.7.1.

NOTE: If your shell is not interactive (e.g. you did not create the original container with -it option), you can instead change the command to "/bin/sleep 600" or "/bin/tail -f /dev/null" to give you enough time to do "docker exec -it CONTID /bin/bash" as another way of getting a shell.

NOTE2: Newer versions of docker have config.v2.json, where you will need to change either Entrypoint or Cmd (thanks user60561).

How would you implement an LRU cache in Java?

I'm looking for a better LRU cache using Java code. Is it possible for you to share your Java LRU cache code using LinkedHashMap and Collections#synchronizedMap? Currently I'm using LRUMap implements Map and the code works fine, but I'm getting ArrayIndexOutofBoundException on load testing using 500 users on the below method. The method moves the recent object to front of the queue.

private void moveToFront(int index) {
        if (listHead != index) {
            int thisNext = nextElement[index];
            int thisPrev = prevElement[index];
            nextElement[thisPrev] = thisNext;
            if (thisNext >= 0) {
                prevElement[thisNext] = thisPrev;
            } else {
                listTail = thisPrev;
            }
            //old listHead and new listHead say new is 1 and old was 0 then prev[1]= 1 is the head now so no previ so -1
            // prev[0 old head] = new head right ; next[new head] = old head
            prevElement[index] = -1;
            nextElement[index] = listHead;
            prevElement[listHead] = index;
            listHead = index;
        }
    }

get(Object key) and put(Object key, Object value) method calls the above moveToFront method.

Read a text file in R line by line

I write a code to read file line by line to meet my demand which different line have different data type follow articles: read-line-by-line-of-a-file-in-r and determining-number-of-linesrecords. And it should be a better solution for big file, I think. My R version (3.3.2).

con = file("pathtotargetfile", "r")
readsizeof<-2    # read size for one step to caculate number of lines in file
nooflines<-0     # number of lines
while((linesread<-length(readLines(con,readsizeof)))>0)    # calculate number of lines. Also a better solution for big file
  nooflines<-nooflines+linesread

con = file("pathtotargetfile", "r")    # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines
typelist = list(0,'c',0,'c',0,0,'c',0)    # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand.
for(i in 1:nooflines) {
  tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE)
  print(is.vector(tmp))
  print(tmp)
}
close(con)

C#: Limit the length of a string?

Here is another alternative answer to this issue. This extension method works quite well. This solves the issues of the string being shorter than the maximum length and also the maximum length being negative.

public static string Left( this string str, int length ) {
  if (str == null)
    return str;
  return str.Substring(0, Math.Min(Math.Abs(length), str.Length));
}

Another solution would be to limit the length to be non-negative values, and just zero-out negative values.

public static string Left( this string str, int length ) {
  if (str == null)
    return str;
  return str.Substring(0, Math.Min(Math.Max(0,length), str.Length));
}

How to take input in an array + PYTHON?

arr = []
elem = int(raw_input("insert how many elements you want:"))
for i in range(0, elem):
    arr.append(int(raw_input("Enter next no :")))
print arr

How to obtain the last path segment of a URI

Here's a short method to do it:

public static String getLastBitFromUrl(final String url){
    // return url.replaceFirst("[^?]*/(.*?)(?:\\?.*)","$1);" <-- incorrect
    return url.replaceFirst(".*/([^/?]+).*", "$1");
}

Test Code:

public static void main(final String[] args){
    System.out.println(getLastBitFromUrl(
        "http://example.com/foo/bar/42?param=true"));
    System.out.println(getLastBitFromUrl("http://example.com/foo"));
    System.out.println(getLastBitFromUrl("http://example.com/bar/"));
}

Output:

42
foo
bar

Explanation:

.*/      // find anything up to the last / character
([^/?]+) // find (and capture) all following characters up to the next / or ?
         // the + makes sure that at least 1 character is matched
.*       // find all following characters


$1       // this variable references the saved second group from above
         // I.e. the entire string is replaces with just the portion
         // captured by the parentheses above

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

WebRTC is designed for high-performance, high quality communication of video, audio and arbitrary data. In other words, for apps exactly like what you describe.

WebRTC apps need a service via which they can exchange network and media metadata, a process known as signaling. However, once signaling has taken place, video/audio/data is streamed directly between clients, avoiding the performance cost of streaming via an intermediary server.

WebSocket on the other hand is designed for bi-directional communication between client and server. It is possible to stream audio and video over WebSocket (see here for example), but the technology and APIs are not inherently designed for efficient, robust streaming in the way that WebRTC is.

As other replies have said, WebSocket can be used for signaling.

I maintain a list of WebRTC resources: strongly recommend you start by looking at the 2013 Google I/O presentation about WebRTC.

Reload content in modal (twitter bootstrap)

It will works for all version of twitterbootstrap

Javascript code :

<script type="text/javascript">
/* <![CDATA[ */
(function(){
   var bsModal = null;
   $("[data-toggle=modal]").click(function(e) {
      e.preventDefault();
      var trgId = $(this).attr('data-target'); 
      if ( bsModal == null ) 
       bsModal = $(trgId).modal;
      $.fn.bsModal = bsModal;
      $(trgId + " .modal-body").load($(this).attr("href"));
      $(trgId).bsModal('show');
    });
 })();
/* <![CDATA[ */
</script>

links to modal are

<a data-toggle="modal" data-target="#myModal" href="edit1.aspx">Open modal 1</a>
<a data-toggle="modal" data-target="#myModal" href="edit2.aspx">Open modal 2</a>
<a data-toggle="modal" data-target="#myModal" href="edit3.aspx">Open modal 3</a>

pop up modal

<div id="myModal" class="modal hide fade in">
<div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
    <input type="submit" class="btn btn-success" value="Save"/>
</div>

What does the term "Tuple" Mean in Relational Databases?

In relational databases, tables are relations (in mathematical meaning). Relations are sets of tuples. Thus table row in relational database is tuple in relation.

Wiki on relations:

In mathematics (more specifically, in set theory and logic), a relation is a property that assigns truth values to combinations (k-tuples) of k individuals. Typically, the property describes a possible connection between the components of a k-tuple. For a given set of k-tuples, a truth value is assigned to each k-tuple according to whether the property does or does not hold.

html table cell width for different rows

You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.

You can however have cells span multiple columns, such as:

<table>
    <tr>
        <td>25</td>
        <td>50</td>
        <td>25</td>
    </tr>
    <tr>
        <td colspan="2">75</td>
        <td>20</td>
    </tr>
</table>

As an aside, you should avoid using style attributes like border and bgcolor and prefer CSS for those.

nginx - client_max_body_size has no effect

Assuming you have already set the client_max_body_size and various PHP settings (upload_max_filesize / post_max_size , etc) in the other answers, then restarted or reloaded NGINX and PHP without any result, run this...

nginx -T

This will give you any unresolved errors in your NGINX configs. In my case, I struggled with the 413 error for a whole day before I realized there were some other unresolved SSL errors in the NGINX config (wrong pathing for certs) that needed to be corrected. Once I fixed the unresolved issues I got from 'nginx -T', reloaded NGINX, and EUREKA!! That fixed it.

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

To remotely capture http or https traffic with charles you will need to do the following:

HOST - Machine running Charles and hosting the proxy CLIENT – User’s machine generating the traffic you will capture

Host Machine

  1. Install fully licensed charles version
  2. Proxy -> Proxy Settings -> check “Enable Transparent HTTP Proxying”
  3. Proxy -> SSL Proxying Settings -> check “enable SSL Proxying”
  4. Proxy -> SSL Proxying Settings -> click Add button and input * in both fields
  5. Proxy -> Access Control Settings -> Add your local subnet (ex: 192.168.2.0/24) to authorize all machines on your local network to use the proxy from another machine
  6. It might be advisable to set up the “auto save tool” in charles, this will auto save and rotate the charles logs.

Client Machine:

  1. Install and permanently accept/trust the charles SSL certificate
    http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/
  2. Configure IE, Firefox, and Chrome to use the socket charles is hosting the proxy on (ex: 192.168.1.100:8888)

When I tested this out I picked up two lines of a Facebook HTTPS chat (one was a line TO someone, and the other FROM)

you can also capture android emulator traffic this way if you start the emulator with:

emulator -avd <avd name> -http-proxy http://local_ip:8888/

Where LOCAL_IP is the IP address of your computer, not 127.0.0.1 as that is the IP address of the emulated phone.

Source: http://brakertech.com/capture-https-traffic-remotely-with-charles/

How to stop tracking and ignore changes to a file in Git?

Lots of people advise you to use git update-index --assume-unchanged. Indeed, this may be a good solution, but only in the short run.

What you probably want to do is this: git update-index --skip-worktree.

(The third option, which you probably don't want is: git rm --cached. It will keep your local file, but will be marked as removed from the remote repository.)

Difference between the first two options?

  • assume-unchanged is to temporary allow you to hide modifications from a file. If you want to hide modifications done to a file, modify the file, then checkout another branch, you'll have to use no-assume-unchanged then probably stash modifications done.
  • skip-worktree will follow you whatever the branch you checkout, with your modifications!

Use case of assume-unchanged

It assumes this file should not be modified, and gives you a cleaner output when doing git status. But when checking out to another branch, you need to reset the flag and commit or stash changes before so. If you pull with this option activated, you'll need to solve conflicts and git won't auto merge. It actually only hides modifications (git status won't show you the flagged files).

I like to use it when I only want to stop tracking changes for a while + commit a bunch of files (git commit -a) related to the same modification.

Use case of skip-worktree

You have a setup class containing parameters (eg. including passwords) that your friends have to change accordingly to their setup.

  • 1: Create a first version of this class, fill in fields you can fill and leave others empty/null.
  • 2: Commit and push it to the remote server.
  • 3: git update-index --skip-worktree MySetupClass.java
  • 4: Update your configuration class with your own parameters.
  • 5: Go back to work on another functionnality.

The modifications you do will follow you whatever the branch. Warning: if your friends also want to modify this class, they have to have the same setup, otherwise their modifications would be pushed to the remote repository. When pulling, the remote version of the file should overwrite yours.

PS: do one or the other, but not both as you'll have undesirable side-effects. If you want to try another flag, you should disable the latter first.

Does Arduino use C or C++?

Arduino sketches are written in C++.

Here is a typical construct you'll encounter:

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
...
lcd.begin(16, 2);
lcd.print("Hello, World!");

That's C++, not C.

Hence do yourself a favor and learn C++. There are plenty of books and online resources available.

Bootstrap with jQuery Validation Plugin

For full compatibility with Bootstrap 3 I added support for input-group, radio and checkbox, that was missing in the other solutions.

Update 10/20/2017: Inspected suggestions of the other answers and added additional support for special markup of radio-inline, better error placement for a group of radios or checkboxes and added support for a custom .novalidation class to prevent validation of controls. Hope this helps and thanks for the suggestions.

After including the validation plugin add the following call:

$.validator.setDefaults({
    errorElement: "span",
    errorClass: "help-block",
    highlight: function (element, errorClass, validClass) {
        // Only validation controls
        if (!$(element).hasClass('novalidation')) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        }
    },
    unhighlight: function (element, errorClass, validClass) {
        // Only validation controls
        if (!$(element).hasClass('novalidation')) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        }
    },
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        }
        else if (element.prop('type') === 'radio' && element.parent('.radio-inline').length) {
            error.insertAfter(element.parent().parent());
        }
        else if (element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
            error.appendTo(element.parent().parent());
        }
        else {
            error.insertAfter(element);
        }
    }
});

This works for all Bootstrap 3 form classes. If you use a horizontal form you have to use the following markup. This ensures that the help-block text respects the validation states ("has-error", ...) of the form-group.

<div class="form-group">
    <div class="col-lg-12">
        <div class="checkbox">
            <label id="LabelConfirm" for="CheckBoxConfirm">
                <input type="checkbox" name="CheckBoxConfirm" id="CheckBoxConfirm" required="required" />
                I have read all the information 
            </label>
        </div>
    </div>
</div>

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Ignoring upper case and lower case in Java

You have to use the String method .toLowerCase() or .toUpperCase() on both the input and the string you are trying to match it with.

Example:

public static void findPatient() {
    System.out.print("Enter part of the patient name: ");
    String name = sc.nextLine();

    System.out.print(myPatientList.showPatients(name));
}

//the other class
ArrayList<String> patientList;

public void showPatients(String name) {
    boolean match = false;

    for(String matchingname : patientList) {
        if (matchingname.toLowerCase().contains(name.toLowerCase())) {
            match = true;
        }
    }
}

How to change target build on Android project?

The problem sometimes occurs when there are errors in the project.

For instance, if your project is configured with a target of 3.2 but the 3.2 libraries are not available, you will not be able to change the version to 4.0!

The usual (perhaps brutal) solution I use is to create a new project with the correct target and copy src, res and manifest into the new project.

Update:

This seems to work:

  1. Change the selected through the build properties as normal
  2. Manually edit project.properties AND default.properties to make sure they both reflect the desired target.
  3. Close the project and re-open it

I always run Android Tools | Fix Project Properties after making any changes to the build target.

How can I force clients to refresh JavaScript files?

In PHP:

function latest_version($file_name){
    echo $file_name."?".filemtime($_SERVER['DOCUMENT_ROOT'] .$file_name);
}

In HTML:

<script type="text/javascript" src="<?php latest_version('/a-o/javascript/almanacka.js'); ?>">< /script>

How it works:

In HTML, write the filepath and name as you wold do, but in the function only. PHP gets the filetime of the file and returns the filepath+name+"?"+time of latest change

Case insensitive 'Contains(string)'

Just to build on the answer here, you can create a string extension method to make this a little more user-friendly:

    public static bool ContainsIgnoreCase(this string paragraph, string word)
    {
        return CultureInfo.CurrentCulture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0;
    }

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Passing data between view controllers

Create the property in the next view controller .h file and define getters and setters.

Add this property in NextVC.h on nextVC:

@property (strong, nonatomic) NSString *indexNumber;

Add

@synthesize indexNumber; in NextVC.m

And last

NextVC *vc = [[NextVC alloc]init];

vc.indexNumber = @"123";

[self.navigationController vc animated:YES];

Change div height on button click

You have to set height as a string value when you use pixels.

document.getElementById('chartdiv').style.height = "200px"

Also try adding a DOCTYPE to your HTML for Internet Explorer.

<!DOCTYPE html>
<html> ...

ssh: connect to host github.com port 22: Connection timed out

inside the .ssh folder Create "config" file

Host github.com
User git
Hostname ssh.github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
Port 443

Host gitlab.com
Hostname altssh.gitlab.com
User git
Port 443
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa

jQuery: Setting select list 'selected' based on text, failing strangely

$("#my-select option:contains(" + myText +")").attr("selected", true);

This returns the first option containing your text description.

Changing git commit message after push (given that no one pulled from remote)

Another option is to create an additional "errata commit" (and push) which references the commit object that contains the error -- the new errata commit also provides the correction. An errata commit is a commit with no substantive code changes but an important commit message -- for example, add one space character to your readme file and commit that change with the important commit message, or use the git option --allow-empty. It's certainly easier and safer than rebasing, it doesn't modify true history, and it keeps the branch tree clean (using amend is also a good choice if you are correcting the most recent commit, but an errata commit may be a good choice for older commits). This type of thing so rarely happens that simply documenting the mistake is good enough. In the future, if you need to search through a git log for a feature keyword, the original (erroneous) commit may not appear because the wrong keyword was used in that original commit (the original typo) -- however, the keyword will appear in the errata commit which will then point you to the original commit that had the typo. Here's an example:

$ git log
commit 0c28141c68adae276840f17ccd4766542c33cf1d
Author: First Last 
Date:   Wed Aug 8 15:55:52 2018 -0600

    Errata commit:
    This commit has no substantive code change.
    This commit is provided only to document a correction to a previous commit message.
    This pertains to commit object e083a7abd8deb5776cb304fa13731a4182a24be1
    Original incorrect commit message:
        Changed background color to red
    Correction (*change highlighted*):
        Changed background color to *blue*

commit 032d0ff0601bff79bdef3c6f0a02ebfa061c4ad4
Author: First Last 
Date:   Wed Aug 8 15:43:16 2018 -0600

    Some interim commit message

commit e083a7abd8deb5776cb304fa13731a4182a24be1
Author: First Last 
Date:   Wed Aug 8 13:31:32 2018 -0600

    Changed background color to red

Create directory if it does not exist

Try the -Force parameter:

New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist

You can use Test-Path -PathType Container to check first.

See the New-Item MSDN help article for more details.

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

Is there a Pattern Matching Utility like GREP in Windows?

As mentioned above, the gnuwin32 project has a Windows CLI version of grep.

If you want something with a graphical interface, I would recommend the (open-source) tool AstroGrep.

Looking for a good Python Tree data structure

Building on the answer given above with the single line Tree using defaultdict, you can make it a class. This will allow you to set up defaults in a constructor and build on it in other ways.

class Tree(defaultdict):
    def __call__(self):
        return Tree(self)

    def __init__(self, parent):
        self.parent = parent
        self.default_factory = self

This example allows you to make a back reference so that each node can refer to its parent in the tree.

>>> t = Tree(None)
>>> t[0][1][2] = 3
>>> t
defaultdict(defaultdict(..., {...}), {0: defaultdict(defaultdict(..., {...}), {1: defaultdict(defaultdict(..., {...}), {2: 3})})})
>>> t[0][1].parent
defaultdict(defaultdict(..., {...}), {1: defaultdict(defaultdict(..., {...}), {2: 3})})
>>> t2 = t[0][1]
>>> t2
defaultdict(defaultdict(..., {...}), {2: 3})
>>> t2[2]
3

Next, you could even override __setattr__ on class Tree so that when reassigning the parent, it removes it as a child from that parent. Lots of cool stuff with this pattern.

How to generate .NET 4.0 classes from xsd?

simple enough; just run (at the vs command prompt)

xsd your.xsd /classes

(which will create your.cs). Note, however, that most of the intrinsic options here haven't changed much since 2.0

For the options, use xsd /? or see MSDN; for example /enableDataBinding can be useful.

Else clause on Python while statement

The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.

One way to think about it is as an if/else construct with respect to the condition:

if condition:
    handle_true()
else:
    handle_false()

is analogous to the looping construct:

while condition:
    handle_true()
else:
    # condition is false now, handle and go on with the rest of the program
    handle_false()

An example might be along the lines of:

while value < threshold:
    if not process_acceptable_value(value):
        # something went wrong, exit the loop; don't pass go, don't collect 200
        break
    value = update(value)
else:
    # value >= threshold; pass go, collect 200
    handle_threshold_reached()

How can I properly handle 404 in ASP.NET MVC?

I really like cottsaks solution and think its very clearly explained. my only addition was to alter step 2 as follows

public abstract class MyController : Controller
{

    #region Http404 handling

    protected override void HandleUnknownAction(string actionName)
    {
        //if controller is ErrorController dont 'nest' exceptions
        if(this.GetType() != typeof(ErrorController))
        this.InvokeHttp404(HttpContext);
    }

    public ActionResult InvokeHttp404(HttpContextBase httpContext)
    {
        IController errorController = ObjectFactory.GetInstance<ErrorController>();
        var errorRoute = new RouteData();
        errorRoute.Values.Add("controller", "Error");
        errorRoute.Values.Add("action", "Http404");
        errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString);
        errorController.Execute(new RequestContext(
             httpContext, errorRoute));

        return new EmptyResult();
    }

    #endregion
}

Basically this stops urls containing invalid actions AND controllers from triggering the exception routine twice. eg for urls such as asdfsdf/dfgdfgd

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

Please

  1. locate the file [XAMPP Installation Directory]\php\php.ini (e.g. C:\xampp\php\php.ini)
  2. open php.ini in Notepad or any Text editor
  3. locate the line containing max_execution_time and
  4. increase the value from 30 to some larger number (e.g. set: max_execution_time = 90)
  5. then restart Apache web server from the XAMPP control panel

If there will still be the same error after that, try to increase the value for the max_execution_time further more.

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

I need to get all the cookies from the browser

Modern approach.

let c = document.cookie.split(";").reduce( (ac, cv, i) => Object.assign(ac, {[cv.split('=')[0]]: cv.split('=')[1]}), {});

console.log(c);

;)

Java Ordered Map

Modern Java version of Steffi Keran's answer

public class Solution {
    public static void main(String[] args) {
        // create a simple hash map and insert some key-value pairs into it
        Map<String, Integer> map = new HashMap<>();
        map.put("Python", 3);
        map.put("C", 0);
        map.put("JavaScript", 4);
        map.put("C++", 1);
        map.put("Golang", 5);
        map.put("Java", 2);
        // Create a linked list from the above map entries
        List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());
        // sort the linked list using Collections.sort()
        list.sort(Comparator.comparing(Map.Entry::getValue));
        list.forEach(System.out::println);
    }
}

Does C# have an equivalent to JavaScript's encodeURIComponent()?

HttpUtility.HtmlEncode / Decode
HttpUtility.UrlEncode / Decode

You can add a reference to the System.Web assembly if it's not available in your project

Empty set literal?

No, there's no literal syntax for the empty set. You have to write set().

How can I check what version/edition of Visual Studio is installed programmatically?

All the information in this thread is now out of date with the recent release of vswhere. Download that and use it.

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

The fix for me was to set property HorizontalAlignment="Stretch" on ItemsPresenter inside ScrollViewer..

Hope this helps someone...

<Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBox">
                    <ScrollViewer x:Name="ScrollViewer" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" Padding="{TemplateBinding Padding}" HorizontalAlignment="Stretch">
                        <ItemsPresenter  Height="252" HorizontalAlignment="Stretch"/>
                    </ScrollViewer>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

what about just store the output to the static table ? Like

-- SubProcedure: subProcedureName
---------------------------------
-- Save the value
DELETE lastValue_subProcedureName
INSERT INTO lastValue_subProcedureName (Value)
SELECT @Value
-- Return the value
SELECT @Value

-- Procedure
--------------------------------------------
-- get last value of subProcedureName
SELECT Value FROM lastValue_subProcedureName

its not ideal, but its so simple and you don't need to rewrite everything.

UPDATE: the previous solution does not work well with parallel queries (async and multiuser accessing) therefore now Iam using temp tables

-- A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. 
-- The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. 
-- The table cannot be referenced by the process that called the stored procedure that created the table.
IF OBJECT_ID('tempdb..#lastValue_spGetData') IS NULL
CREATE TABLE #lastValue_spGetData (Value INT)

-- trigger stored procedure with special silent parameter
EXEC dbo.spGetData 1 --silent mode parameter

nested spGetData stored procedure content

-- Save the output if temporary table exists.
IF OBJECT_ID('tempdb..#lastValue_spGetData') IS NOT NULL
BEGIN
    DELETE #lastValue_spGetData
    INSERT INTO #lastValue_spGetData(Value)
    SELECT Col1 FROM dbo.Table1
END

 -- stored procedure return
 IF @silentMode = 0
 SELECT Col1 FROM dbo.Table1

AngularJS Error: $injector:unpr Unknown Provider

Since this is the first Stackoverflow question that appears on Google when searching for Error: $injector:unpr Unknown Provider I'll add this here.

Make sure that in your index.html any modules/dependencies are not being loaded after they are needed.

For example in my code customFactory.factory.js begins like this:

angular
   .module("app.module1")
   .factory("customFactory", customFactory);

However the index.html looked like this:

    <script src="/src/client/app/customFactory.factory.js"></script>
    <script src="/src/client/app/module1.module.js"></script>

Where it should've really looked like this:

    <script src="/src/client/app/module1.module.js"></script>
    <script src="/src/client/app/customFactory.factory.js"></script>

Since customFactory.factory.js is declared as part of module1, it needs to be loaded before customFactory

Simple (I think) Horizontal Line in WPF?

Use a Border of height 1 and don't set the Width (i.e. Width = Auto, HorizontalAlignment = Stretch, the default)

Android: failed to convert @drawable/picture into a drawable

file name must contain only abc...xyz 012...789 _ . in Resources folder.

for ex:

my-image.png is False!
MyImage.png is False!
my image.png is False!
...
...

my-xml.xml is False!
MyXml.xml is False!
my xml.xml is False!
...
...

How can I use getSystemService in a non-activity class (LocationManager)?

I don't know if this will help, but I did this:

LocationManager locationManager  = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);

How to use ConcurrentLinkedQueue?

The ConcurentLinkedQueue is a very efficient wait/lock free implementation (see the javadoc for reference), so not only you don't need to synchronize, but the queue will not lock anything, thus being virtually as fast as a non synchronized (not thread safe) one.

Executing a batch file in a remote machine through PsExec

You have an extra -c you need to get rid of:

psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"

Infinity symbol with HTML

Infinity is a reserved character in HTML. Following are its values in various forms.

  • Hex : 8734
  • Decimal : 221E
  • Entity : &infin;

To use in html code

_x000D_
_x000D_
<p>The html symbol is &#8734; </p>_x000D_
<p>The html symbol is &#x221E; </p>_x000D_
<p>The html symbol is &infin; </p>
_x000D_
_x000D_
_x000D_

Reference : HTML Symbols - HTML Infinity Symbol

Access is denied when attaching a database

I was reading this page and they have an interesting sentence in there:

Caution: Be very selective when adding users to these roles. For example, sysadmin maps out to dbo in every database and is the equivalent of logging in using the sa account.

Of course, they also have this:

Permissions that are granted to users and roles and are database specific. All permissions are cumulative with the exception of a DENY. A denied permission at either a user level or at a role level overrides the same permission granted via other role memberships with the exception of the sysadmin fixed server role. (A sysadmin retains all permissions, even if a role they are a member of has a DENY permission.)

So if you're a domain admin and in SQL 'sysadmin' group, the world should be your crustacean.

Of course, according to Microsoft, you should be taking a quick look at these two pages:
Link to Database Prerequisites

Link to Installing Databases

You're being naughty and trying to attach them manually :) Seriously though, do you have all the prerequisites for the AdventureWorks2008 database?
I suspect this is just another Microsoft oddity/edge case, but I could be wrong.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Use the directions API.

Make an ajax call i.e.

https://maps.googleapis.com/maps/api/directions/json?parameters

and then parse the responce

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

In my case, just using flex-shrink: 0 didn't work. But adding flex-grow: 1 to it worked.

.item {
    flex-shrink: 0;
    flex-grow: 1;
}

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I had this error because I hadn't installed ASP.NET through Server Roles and Features. Added that and it all worked as expected

Check if a string within a list contains a specific string with Linq

I think you want Any:

if (myList.Any(str => str.Contains("Mdd LH")))

It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)

How do I get the current timezone name in Postgres 9.3?

This may or may not help you address your problem, OP, but to get the timezone of the current server relative to UTC (UT1, technically), do:

SELECT EXTRACT(TIMEZONE FROM now())/3600.0;

The above works by extracting the UT1-relative offset in minutes, and then converting it to hours using the factor of 3600 secs/hour.

Example:

SET SESSION timezone TO 'Asia/Kabul';
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
-- output: 4.5 (as of the writing of this post)

(docs).

How to modify STYLE attribute of element with known ID using JQuery

$("span").mouseover(function () {
$(this).css({"background-color":"green","font-size":"20px","color":"red"});
});

<div>
Sachin Tendulkar has been the most complete batsman of his time, the most prolific     runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.
</div>

Calculate age given the birth date in the format YYYYMMDD

I would go for readability:

function _calculateAge(birthday) { // birthday is a date
    var ageDifMs = Date.now() - birthday.getTime();
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}

Disclaimer: This also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).

Instead I would recommend using a library for this, if precision is very important. Also @Naveens post, is probably the most accurate, as it doesn't rely on the time of day.


Benchmarks: http://jsperf.com/birthday-calculation/15

How can I Convert HTML to Text in C#?

Just a note about the HtmlAgilityPack for posterity. The project contains an example of parsing text to html, which, as noted by the OP, does not handle whitespace at all like anyone writing HTML would envisage. There are full-text rendering solutions out there, noted by others to this question, which this is not (it cannot even handle tables in its current form), but it is lightweight and fast, which is all I wanted for creating a simple text version of HTML emails.

using System.IO;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

//small but important modification to class https://github.com/zzzprojects/html-agility-pack/blob/master/src/Samples/Html2Txt/HtmlConvert.cs
public static class HtmlToText
{

    public static string Convert(string path)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.Load(path);
        return ConvertDoc(doc);
    }

    public static string ConvertHtml(string html)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);
        return ConvertDoc(doc);
    }

    public static string ConvertDoc (HtmlDocument doc)
    {
        using (StringWriter sw = new StringWriter())
        {
            ConvertTo(doc.DocumentNode, sw);
            sw.Flush();
            return sw.ToString();
        }
    }

    internal static void ConvertContentTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo)
    {
        foreach (HtmlNode subnode in node.ChildNodes)
        {
            ConvertTo(subnode, outText, textInfo);
        }
    }
    public static void ConvertTo(HtmlNode node, TextWriter outText)
    {
        ConvertTo(node, outText, new PreceedingDomTextInfo(false));
    }
    internal static void ConvertTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo)
    {
        string html;
        switch (node.NodeType)
        {
            case HtmlNodeType.Comment:
                // don't output comments
                break;
            case HtmlNodeType.Document:
                ConvertContentTo(node, outText, textInfo);
                break;
            case HtmlNodeType.Text:
                // script and style must not be output
                string parentName = node.ParentNode.Name;
                if ((parentName == "script") || (parentName == "style"))
                {
                    break;
                }
                // get text
                html = ((HtmlTextNode)node).Text;
                // is it in fact a special closing node output as text?
                if (HtmlNode.IsOverlappedClosingElement(html))
                {
                    break;
                }
                // check the text is meaningful and not a bunch of whitespaces
                if (html.Length == 0)
                {
                    break;
                }
                if (!textInfo.WritePrecedingWhiteSpace || textInfo.LastCharWasSpace)
                {
                    html= html.TrimStart();
                    if (html.Length == 0) { break; }
                    textInfo.IsFirstTextOfDocWritten.Value = textInfo.WritePrecedingWhiteSpace = true;
                }
                outText.Write(HtmlEntity.DeEntitize(Regex.Replace(html.TrimEnd(), @"\s{2,}", " ")));
                if (textInfo.LastCharWasSpace = char.IsWhiteSpace(html[html.Length - 1]))
                {
                    outText.Write(' ');
                }
                    break;
            case HtmlNodeType.Element:
                string endElementString = null;
                bool isInline;
                bool skip = false;
                int listIndex = 0;
                switch (node.Name)
                {
                    case "nav":
                        skip = true;
                        isInline = false;
                        break;
                    case "body":
                    case "section":
                    case "article":
                    case "aside":
                    case "h1":
                    case "h2":
                    case "header":
                    case "footer":
                    case "address":
                    case "main":
                    case "div":
                    case "p": // stylistic - adjust as you tend to use
                        if (textInfo.IsFirstTextOfDocWritten)
                        {
                            outText.Write("\r\n");
                        }
                        endElementString = "\r\n";
                        isInline = false;
                        break;
                    case "br":
                        outText.Write("\r\n");
                        skip = true;
                        textInfo.WritePrecedingWhiteSpace = false;
                        isInline = true;
                        break;
                    case "a":
                        if (node.Attributes.Contains("href"))
                        {
                            string href = node.Attributes["href"].Value.Trim();
                            if (node.InnerText.IndexOf(href, StringComparison.InvariantCultureIgnoreCase)==-1)
                            {
                                endElementString =  "<" + href + ">";
                            }  
                        }
                        isInline = true;
                        break;
                    case "li": 
                        if(textInfo.ListIndex>0)
                        {
                            outText.Write("\r\n{0}.\t", textInfo.ListIndex++); 
                        }
                        else
                        {
                            outText.Write("\r\n*\t"); //using '*' as bullet char, with tab after, but whatever you want eg "\t->", if utf-8 0x2022
                        }
                        isInline = false;
                        break;
                    case "ol": 
                        listIndex = 1;
                        goto case "ul";
                    case "ul": //not handling nested lists any differently at this stage - that is getting close to rendering problems
                        endElementString = "\r\n";
                        isInline = false;
                        break;
                    case "img": //inline-block in reality
                        if (node.Attributes.Contains("alt"))
                        {
                            outText.Write('[' + node.Attributes["alt"].Value);
                            endElementString = "]";
                        }
                        if (node.Attributes.Contains("src"))
                        {
                            outText.Write('<' + node.Attributes["src"].Value + '>');
                        }
                        isInline = true;
                        break;
                    default:
                        isInline = true;
                        break;
                }
                if (!skip && node.HasChildNodes)
                {
                    ConvertContentTo(node, outText, isInline ? textInfo : new PreceedingDomTextInfo(textInfo.IsFirstTextOfDocWritten){ ListIndex = listIndex });
                }
                if (endElementString != null)
                {
                    outText.Write(endElementString);
                }
                break;
        }
    }
}
internal class PreceedingDomTextInfo
{
    public PreceedingDomTextInfo(BoolWrapper isFirstTextOfDocWritten)
    {
        IsFirstTextOfDocWritten = isFirstTextOfDocWritten;
    }
    public bool WritePrecedingWhiteSpace {get;set;}
    public bool LastCharWasSpace { get; set; }
    public readonly BoolWrapper IsFirstTextOfDocWritten;
    public int ListIndex { get; set; }
}
internal class BoolWrapper
{
    public BoolWrapper() { }
    public bool Value { get; set; }
    public static implicit operator bool(BoolWrapper boolWrapper)
    {
        return boolWrapper.Value;
    }
    public static implicit operator BoolWrapper(bool boolWrapper)
    {
        return new BoolWrapper{ Value = boolWrapper };
    }
}

As an example, the following HTML code...

<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
        <header>
            Whatever Inc.
        </header>
        <main>
            <p>
                Thanks for your enquiry. As this is the 1<sup>st</sup> time you have contacted us, we would like to clarify a few things:
            </p>
            <ol>
                <li>
                    Please confirm this is your email by replying.
                </li>
                <li>
                    Then perform this step.
                </li>
            </ol>
            <p>
                Please solve this <img alt="complex equation" src="http://upload.wikimedia.org/wikipedia/commons/8/8d/First_Equation_Ever.png"/>. Then, in any order, could you please:
            </p>
            <ul>
                <li>
                    a point.
                </li>
                <li>
                    another point, with a <a href="http://en.wikipedia.org/wiki/Hyperlink">hyperlink</a>.
                </li>
            </ul>
            <p>
                Sincerely,
            </p>
            <p>
                The whatever.com team
            </p>
        </main>
        <footer>
            Ph: 000 000 000<br/>
            mail: whatever st
        </footer>
    </body>
</html>

...will be transformed into:

Whatever Inc. 


Thanks for your enquiry. As this is the 1st time you have contacted us, we would like to clarify a few things: 

1.  Please confirm this is your email by replying. 
2.  Then perform this step. 

Please solve this [complex equation<http://upload.wikimedia.org/wikipedia/commons/8/8d/First_Equation_Ever.png>]. Then, in any order, could you please: 

*   a point. 
*   another point, with a hyperlink<http://en.wikipedia.org/wiki/Hyperlink>. 

Sincerely, 

The whatever.com team 


Ph: 000 000 000
mail: whatever st 

...as opposed to:

        Whatever Inc.


            Thanks for your enquiry. As this is the 1st time you have contacted us, we would like to clarify a few things:

                Please confirm this is your email by replying.

                Then perform this step.


            Please solve this . Then, in any order, could you please:

                a point.

                another point, with a hyperlink.


            Sincerely,


            The whatever.com team

        Ph: 000 000 000
        mail: whatever st

Is there any way to configure multiple registries in a single npmrc file

On version 4.4.1, if you can change package name, use:

npm config set @myco:registry http://reg.example.com

Where @myco is your package scope.

You can install package in this way:

npm install @myco/my-package

For more info: https://docs.npmjs.com/misc/scope

How to scan a folder in Java?

Visualizing the tree structure was the most convenient way for me :

public static void main(String[] args) throws IOException {
    printTree(0, new File("START/FROM/DIR"));
}

static void printTree(int depth, File file) throws IOException { 
    StringBuilder indent = new StringBuilder();
    String name = file.getName();

    for (int i = 0; i < depth; i++) {
        indent.append(".");
    }

    //Pretty print for directories
    if (file.isDirectory()) { 
        System.out.println(indent.toString() + "|");
        if(isPrintName(name)){
            System.out.println(indent.toString() + "*" + file.getName() + "*");
        }
    }
    //Print file name
    else if(isPrintName(name)) {
        System.out.println(indent.toString() + file.getName()); 
    }
    //Recurse children
    if (file.isDirectory()) { 
        File[] files = file.listFiles(); 
        for (int i = 0; i < files.length; i++){
            printTree(depth + 4, files[i]);
        } 
    }
}

//Exclude some file names
static boolean isPrintName(String name){
    if (name.charAt(0) == '.') {
        return false;
    }
    if (name.contains("svn")) {
        return false;
    }
    //.
    //. Some more exclusions
    //.
    return true;
}

How to include a font .ttf using CSS?

I know this is an old post but this solved my problem.

_x000D_
_x000D_
@font-face{_x000D_
  font-family: "Font Name";_x000D_
  src: url("../fonts/font-name.ttf") format("truetype");_x000D_
}
_x000D_
_x000D_
_x000D_

notice src:url("../fonts/font-name.ttf"); we use two periods to go back to the root directory and then into the fonts folder or wherever your file is located.

hope this helps someone down the line:) happy coding