Programs & Examples On #Demoscene

Does "\d" in regex mean a digit?

[0-9] is not always equivalent to \d. In python3, [0-9] matches only 0123456789 characters, while \d matches [0-9] and other digit characters, for example Eastern Arabic numerals ??????????.

Pass a String from one Activity to another Activity in Android

First Activity Code :

Intent mIntent = new Intent(ActivityA.this, ActivityB.class);
mIntent.putExtra("easyPuzzle", easyPuzzle);

Second Activity Code :

String easyPuzzle = getIntent().getStringExtra("easyPuzzle");

How to change workspace and build record Root Directory on Jenkins?

You can also edit the config.xml file in your JENKINS_HOME directory. Use c32hedge's response as a reference and set the workspace location to whatever you want between the tags

How can I concatenate two arrays in Java?

Should do the trick. This is assuming String[] first and String[] second

List<String> myList = new ArrayList<String>(Arrays.asList(first));
myList.addAll(new ArrayList<String>(Arrays.asList(second)));
String[] both = myList.toArray(new String[myList.size()]);

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

solve this issue for angular

"styles": [
              "src/styles.css",
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]

Converting string to double in C#

Add a class as Public and use it very easily like convertToInt32()

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;

  /// <summary>
  /// Summary description for Common
  /// </summary>
  public static class Common
  {
     public static double ConvertToDouble(string Value) {
        if (Value == null) {
           return 0;
        }
        else {
           double OutVal;
           double.TryParse(Value, out OutVal);

           if (double.IsNaN(OutVal) || double.IsInfinity(OutVal)) {
              return 0;
           }
           return OutVal;
        }
     }
  }

Then Call The Function

double DirectExpense =  Common.ConvertToDouble(dr["DrAmount"].ToString());

How to check for palindrome using Python logic

#compare 1st half with reversed second half
# i.e. 'abba' -> 'ab' == 'ba'[::-1]

def is_palindrome( s ):
   return True if len( s ) < 2 else s[ :len( s ) // 2 ] == s[ -( len( s ) // 2 ):][::-1]

CAST DECIMAL to INT

1 cent: no space b/w CAST and (expression). i.e., CAST(columnName AS SIGNED).

Adding rows to tbody of a table using jQuery

As @wirey said appendTo should work, if not then you can try this:

$("#tblEntAttributes tbody").append(newRowContent);

Determine on iPhone if user has enabled push notifications

Though Zac's answer was perfectly correct till iOS 7, it has changed since iOS 8 arrived. Because enabledRemoteNotificationTypes has been deprecated from iOS 8 onwards. For iOS 8 and later, you need to use isRegisteredForRemoteNotifications.

  • for iOS 7 and before --> Use enabledRemoteNotificationTypes
  • for iOS 8 and later --> Use isRegisteredForRemoteNotifications.

Where is Python's sys.path initialized from?

"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"

-- http://docs.python.org/library/sys.html#sys.path

Resize iframe height according to content height in it

The trick is to acquire all the necessary iframe events from an external script. For instance, you have a script which creates the iFrame using document.createElement; in this same script you temporarily have access to the contents of the iFrame.

var dFrame = document.createElement("iframe");
dFrame.src = "http://www.example.com";
// Acquire onload and resize the iframe
dFrame.onload = function()
{
    // Setting the content window's resize function tells us when we've changed the height of the internal document
    // It also only needs to do what onload does, so just have it call onload
    dFrame.contentWindow.onresize = function() { dFrame.onload() };
    dFrame.style.height = dFrame.contentWindow.document.body.scrollHeight + "px";
}
window.onresize = function() {
    dFrame.onload();
}

This works because dFrame stays in scope in those functions, giving you access to the external iFrame element from within the scope of the frame, allowing you to see the actual document height and expand it as necessary. This example will work in firefox but nowhere else; I could give you the workarounds, but you can figure out the rest ;)

How to change column order in a table using sql query in sql server 2005?

Sql server internally build the script. It create a temporary table with new changes and copy the data and drop current table then recreate the table insert from temp table. I find it from "Generate Change script" option ssms 2014. Script like this. From Here: How to change column order in a table using sql query

BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_emps
    (
    id int NULL,
    ename varchar(20) NULL
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_emps SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.emps)
     EXEC('INSERT INTO dbo.Tmp_emps (id, ename)
        SELECT id, ename FROM dbo.emps WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.emps
GO
EXECUTE sp_rename N'dbo.Tmp_emps', N'emps', 'OBJECT' 
GO
COMMIT

Superscript in CSS only?

This is another clean solution:

sub, sup {vertical-align: baseline; position: relative; font-size: 70%;} /* 70% size of its parent element font-size which is good. */
sub {bottom: -0.6em;} /* use em becasue they adapt to parent font-size */
sup {top: -0.6em;} /* use em becasue they adapt to parent font-size */

In this way you can still use sup/sub tags but you fixed their idious behavior to always screw up paragraph line height.

So now you can do:

  <p>This is a line of text.</p>
  <p>This is a line of text, <sub>with sub text.</sub></p>
  <p>This is a line of text, <sup>with sup text.</sup></p>
  <p>This is a line of text.</p>

And your paragraph line height should not get screwed up.

Tested on IE7, IE8, FF3.6, SAFARI4, CHROME5, OPERA9

I tested using a p {line-height: 1.3;} (that is a good line height unless you want your lines to stick too close) and it still works, cause "-0.6em" is such a small amount that also with that line height the sub/sub text will fit and don't go over each other.

Forgot a detail that might be relevant I always use DOCTYPE in the 1st line of my page (specifically I use the HTML 4.01 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">). So I don't know if this solution works well when browser is in quirkmode (or not standard mode) due to lack of DOCTYPE or to a DOCTYPE that does not triggers Standard/Almost Standard mode.

How to set up fixed width for <td>?

Ok, I just figured out where was the problem - in Bootstrap is set up as a default value width for select element, thus, the solution is:

tr. something {
  td {
    select {
      width: 90px;
    }
  }
}

Anything else doesn't work me.

Add common prefix to all cells in Excel

Select the cell you want,

Go To Format Cells (or CTRL+1),

Select the "custom" Tab, enter your required format like : "X"#

use a space if needed.

for example, I needed to insert the word "Hours" beside my numbers and used this format : # "hours"

Can angularjs routes have optional parameter values?

Actually I think OZ_ may be somewhat correct.

If you have the route '/users/:userId' and navigate to '/users/' (note the trailing /), $routeParams in your controller should be an object containing userId: "" in 1.1.5. So no the paramater userId isn't completely ignored, but I think it's the best you're going to get.

How to remove youtube branding after embedding video in web page?

That watermark in the bottom right only appears on mouseover. There's no parameter to remove that, however if you stack a transparent div on top of the video and make it a higher z-index and the same size of the video, your mouseover will not trigger the watermark because your mouse will be hitting the div.

Of course the tradeoff for this is that you lose the ability to actually click on the video to pause it. But if you want to leave the ability to pause it, you could display the controls and have the top layer div cover up until the bottom 30 pixels or so, letting you click the controls.

sql try/catch rollback/commit - preventing erroneous commit after rollback

Below might be useful.

Source: https://msdn.microsoft.com/en-us/library/ms175976.aspx

BEGIN TRANSACTION;

BEGIN TRY
    -- your code --
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

Angular 2: How to write a for loop, not a foreach loop

The better way to do this is creating a fake array in component:

In Component:

fakeArray = new Array(12);

InTemplate:

<ng-container *ngFor = "let n of fakeArray">
     MyCONTENT
</ng-container>

Plunkr here

Check if string contains a value in array

If your $string is always consistent (ie. the domain name is always at the end of the string), you can use explode() with end(), and then use in_array() to check for a match (as pointed out by @Anand Solanki in their answer).

If not, you'd be better off using a regular expression to extract the domain from the string, and then use in_array() to check for a match.

$string = 'There is a url mysite3.com in this string';
preg_match('/(?:http:\/\/)?(?:www.)?([a-z0-9-_]+\.[a-z0-9.]{2,5})/i', $string, $matches);

if (empty($matches[1])) {
  // no domain name was found in $string
} else {
  if (in_array($matches[1], $owned_urls)) {
    // exact match found
  } else {
    // exact match not found
  }
}

The expression above could probably be improved (I'm not particularly knowledgeable in this area)

Here's a demo

"cannot be used as a function error"

You are using growthRate both as a variable name and a function name. The variable hides the function, and then you are trying to use the variable as if it was the function - that is not valid.

Rename the local variable.

Redirecting to a page after submitting form in HTML

For anyone else having the same problem, I figured it out myself.

_x000D_
_x000D_
    <html>_x000D_
      <body>_x000D_
        <form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
          <input type="hidden" name="fullname" value="Sam" />_x000D_
          <input type="hidden" name="city" value="Dubai&#32;" />_x000D_
          <input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
        </form>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.

No Activity found to handle Intent : android.intent.action.VIEW

Answer by Maragues made me check out logcat output. Appears that the path you pass to Uri needs to be prefixed with
file:/

Since it is a local path to your storage.

You may want too look at the path itself too.

`05-04 16:37:37.597: WARN/System.err(4065): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=/mnt/sdcard/mnt/sdcard/audio-android.3gp typ=audio/mp3 }`

Mount point seems to appear twice in the full path.

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

How to check all checkboxes using jQuery?

I think when user select all checkbox manually then checkall should be checked automatically or user unchecked one of them from all selected checkbox then checkall should be unchecked automically. here is my code..

_x000D_
_x000D_
$('#checkall').change(function () {_x000D_
    $('.cb-element').prop('checked',this.checked);_x000D_
});_x000D_
_x000D_
$('.cb-element').change(function () {_x000D_
 if ($('.cb-element:checked').length == $('.cb-element').length){_x000D_
  $('#checkall').prop('checked',true);_x000D_
 }_x000D_
 else {_x000D_
  $('#checkall').prop('checked',false);_x000D_
 }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<input type="checkbox" name="all" id="checkall" />Check All</br>_x000D_
<input type="checkbox" class="cb-element" /> Checkbox  1</br>_x000D_
<input type="checkbox" class="cb-element" /> Checkbox  2</br>_x000D_
<input type="checkbox" class="cb-element" /> Checkbox  3
_x000D_
_x000D_
_x000D_

How to generate .angular-cli.json file in Angular Cli?

Since Angular version 6 .angular-cli.json is deprecated. That file was replaced by angular.json file which supports workspaces.

How do you get a directory listing in C?

The most similar method to readdir is probably using the little-known _find family of functions.

How to keep the spaces at the end and/or at the beginning of a String?

If you need the space for the purpose of later concatenating it with other strings, then you can use the string formatting approach of adding arguments to your string definition:

<string name="error_">Error: %s</string>

Then for format the string (eg if you have an error returned by the server, otherwise use getString(R.string.string_resource_example)):

String message = context.getString(R.string.error_, "Server error message here")

Which results in:

Error: Server error message here

How to get selenium to wait for ajax response?

Here's a groovy version based on Morten Christiansen's answer.

void waitForAjaxCallsToComplete() {
    repeatUntil(
            { return getJavaScriptFunction(driver, "return (window.jQuery || {active : false}).active") },
            "Ajax calls did not complete before timeout."
    )
}

static void repeatUntil(Closure runUntilTrue, String errorMessage, int pollFrequencyMS = 250, int timeOutSeconds = 10) {
    def today = new Date()
    def end = today.time + timeOutSeconds
    def complete = false;

    while (today.time < end) {
        if (runUntilTrue()) {
            complete = true;
            break;
        }

        sleep(pollFrequencyMS);
    }
    if (!complete)
        throw new TimeoutException(errorMessage);
}

static String getJavaScriptFunction(WebDriver driver, String jsFunction) {
    def jsDriver = driver as JavascriptExecutor
    jsDriver.executeScript(jsFunction)
}

sql ORDER BY multiple values in specific order?

...
WHERE
   x_field IN ('f', 'p', 'i', 'a') ...
ORDER BY
   CASE x_field
      WHEN 'f' THEN 1
      WHEN 'p' THEN 2
      WHEN 'i' THEN 3
      WHEN 'a' THEN 4
      ELSE 5 --needed only is no IN clause above. eg when = 'b'
   END, id

Check if input is number or letter javascript

I think the easiest would be to create a Number object with the string and check if with the help of isInteger function provided by Number class itself.

Number.isInteger(Number('1')) //true
Number.isInteger(Number('1 mango')) //false
Number.isInteger(Number(1)) //true
Number.isInteger(Number(1.9)) //false

Can't append <script> element

Just create an element by parsing it with jQuery.

<div id="someElement"></div>
<script>
    var code = "<script>alert(123);<\/script>";
    $("#someElement").append($(code));
</script>

Working example: https://plnkr.co/edit/V2FE28Q2eBrJoJ6PUEBz

Difference between java HH:mm and hh:mm on SimpleDateFormat

Actually the last one is not weird. Code is setting the timezone for working instead of working2.

SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).

Fixing this error gives:

24:00:00
00:00:00
01:00:00

Neither BindingResult nor plain target object for bean name available as request attribute

I had problem like this, but with several "actions". My solution looks like this:

    <form method="POST" th:object="${searchRequest}" action="searchRequest" >
          <input type="text" th:field="*{name}"/>
          <input type="submit" value="find" th:value="find" />
    </form>
        ...
    <form method="POST" th:object="${commodity}" >
        <input type="text" th:field="*{description}"/>
        <input type="submit" value="add" />
    </form>

And controller

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @RequestMapping(value = "add", method = GET)
    public String showGoodsForm(Model model){
           model.addAttribute(new Commodity());
           model.addAttribute("searchRequest", new SearchRequest());
           return "goodsForm";
    }
    @RequestMapping(value = "add", method = POST)
    public ModelAndView processAddCommodities(
            @Valid Commodity commodity,
            Errors errors) {
        if (errors.hasErrors()) {
            ModelAndView model = new ModelAndView("goodsForm");
            model.addObject("searchRequest", new SearchRequest());
            return model;
        }
        ModelAndView model = new ModelAndView("redirect:/goods/" + commodity.getName());
        model.addObject(new Commodity());
        model.addObject("searchRequest", new SearchRequest());
        return model;
    }
    @RequestMapping(value="searchRequest", method=POST)
    public String processFindCommodity(SearchRequest commodity, Model model) {
    ...
        return "catalog";
    }

I'm sure - here is not "best practice", but it is works without "Neither BindingResult nor plain target object for bean name available as request attribute".

How to handle the `onKeyPress` event in ReactJS?

Late to the party, but I was trying to get this done in TypeScript and came up with this:

<div onKeyPress={(e: KeyboardEvent<HTMLDivElement>) => console.log(e.key)}

This prints the exact key pressed to the screen. So if you want to respond to all "a" presses when the div is in focus, you'd compare e.key to "a" - literally if(e.key === "a").

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

How to send list of file in a folder to a txt file in Linux

you can just use

ls > filenames.txt

(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd to go to that folder first, or you can ls ~/docs > filenames.txt

Plotting with C#

NPlot is a pretty good simple open source 2D plotting API. Unfortunately, the web site is down. I don't know if this is just temporary or not. I haven't heard of any bad news. It may come back up.

http://www.nplot.com

Here is an article describing it:

http://aspnet.4guysfromrolla.com/articles/072507-1.aspx

The previous article uses VB.NET, but obviously this will work with C#.

Again, not sure why nplot's site is not currently working but it is a somewhat popular plotting API that I've used in the past. I post it for your information and in case of the likely event nplot will be back up soon. :)

Edit:

Thanks to a Hosam Aly, it looks like the SourceForge project can still be accessed here:

http://sourceforge.net/projects/nplot

not:first-child selector

You can use any selector with not

p:not(:first-child){}
p:not(:first-of-type){}
p:not(:checked){}
p:not(:last-child){}
p:not(:last-of-type){}
p:not(:first-of-type){}
p:not(:nth-last-of-type(2)){}
p:not(nth-last-child(2)){}
p:not(:nth-child(2)){}

How do I create a new class in IntelliJ without using the mouse?

If you are already in the Project View, press Alt+Insert (New) | Class. Project View can be activated via Alt+1.

To create a new class in the same directory as the current one use Ctrl+Alt+Insert (New...).

You can also do it from the Navigation Bar, press Alt+Home, then choose package with arrow keys, then press Alt+Insert.

Another useful shortcut is View | Select In (Alt+F1), Project (1), then Alt+Insert to create a class near the existing one or use arrow keys to navigate through the packages.

And yet another way is to just type the class name in the existing code where you want to use it, IDEA will highlight it in red as it doesn't exist yet, then press Alt+Enter for the Intention Actions pop-up, choose Create Class.

Single-threaded apartment - cannot instantiate ActiveX control

The problem you're running into is that most background thread / worker APIs will create the thread in a Multithreaded Apartment state. The error message indicates that the control requires the thread be a Single Threaded Apartment.

You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.

var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();

How do I add a Font Awesome icon to input field?

.fa-file-o {
    position: absolute;
    left: 50px;
    top: 15px;
    color: #ffffff
}

<div>
 <span class="fa fa-file-o"></span>
 <input type="button" name="" value="IMPORT FILE"/>
</div>

Flatten list of lists

Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!

list_of_lists = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
flattened = [val for sublist in list_of_lists for val in sublist]

Nested list comprehensions evaluate in the same manner that they unwrap (i.e. add newline and tab for each new loop. So in this case:

flattened = [val for sublist in list_of_lists for val in sublist]

is equivalent to:

flattened = []
for sublist in list_of_lists:
    for val in sublist:
        flattened.append(val)

The big difference is that the list comp evaluates MUCH faster than the unraveled loop and eliminates the append calls!

If you have multiple items in a sublist the list comp will even flatten that. ie

>>> list_of_lists = [[180.0, 1, 2, 3], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> flattened  = [val for sublist in list_of_lists for val in sublist]
>>> flattened 
[180.0, 1, 2, 3, 173.8, 164.2, 156.5, 147.2,138.2]

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

=INDEX(GoogleFinance("CURRENCY:" & "EUR" & "USD", "price", A2), 2, 2)

where A2 is the cell with a date formatted as date.

Replace "EUR" and "USD" with your currency pair.

Center a position:fixed element

This solution does not require of you to define a width and height to your popup div.

http://jsfiddle.net/4Ly4B/33/

And instead of calculating the size of the popup, and minus half to the top, javascript is resizeing the popupContainer to fill out the whole screen...

(100% height, does not work when useing display:table-cell; (wich is required to center something vertically))...

Anyway it works :)

How to use a keypress event in AngularJS?

html

<textarea id="messageTxt" 
    rows="5" 
    placeholder="Escriba su mensaje" 
    ng-keypress="keyPressed($event)" 
    ng-model="smsData.mensaje">
</textarea>

controller.js

$scope.keyPressed = function (keyEvent) {
    if (keyEvent.keyCode == 13) {
        alert('presiono enter');
        console.log('presiono enter');
    }
};

Dropping Unique constraint from MySQL table

A unique constraint is also an index.

First use SHOW INDEX FROM tbl_name to find out the name of the index. The name of the index is stored in the column called key_name in the results of that query.

Then you can use DROP INDEX:

DROP INDEX index_name ON tbl_name

or the ALTER TABLE syntax:

ALTER TABLE tbl_name DROP INDEX index_name

Insert into C# with SQLCommand

You can use dapper library:

conn2.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) VALUES (@p1,@p2,@p3)", 
                new { p1 = klantId, p2 = klantNaam, p3 = klantVoornaam });

BTW Dapper is a Stack Overflow project :)

UPDATE: I believe you can't do it simpler without something like EF. Also try to use using statements when you are working with database connections. This will close connection automatically, even in case of exception. And connection will be returned to connections pool.

private readonly string _spionshopConnectionString;

private void Form1_Load(object sender, EventArgs e)
{            
    _spionshopConnectionString = ConfigurationManager
          .ConnectionStrings["connSpionshopString"].ConnectionString;
}

private void button4_Click(object sender, EventArgs e)
{
    using(var connection = new SqlConnection(_spionshopConnectionString))
    {
         connection.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) 
                              VALUES (@klantId,@klantNaam,@klantVoornaam)",
                              new { 
                                      klantId = Convert.ToInt32(textBox1.Text), 
                                      klantNaam = textBox2.Text, 
                                      klantVoornaam = textBox3.Text 
                                  });
    }
}

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

I found the solution :) finally.

We can append data in the request as multipartformdata.

Below is my code.

  Alamofire.upload(
        .POST,
        URLString: fullUrl, // http://httpbin.org/post
        multipartFormData: { multipartFormData in
            multipartFormData.appendBodyPart(fileURL: imagePathUrl!, name: "photo")
            multipartFormData.appendBodyPart(fileURL: videoPathUrl!, name: "video")
            multipartFormData.appendBodyPart(data: Constants.AuthKey.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"authKey")
            multipartFormData.appendBodyPart(data: "\(16)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"idUserChallenge")
            multipartFormData.appendBodyPart(data: "comment".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"comment")
            multipartFormData.appendBodyPart(data:"\(0.00)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"latitude")
            multipartFormData.appendBodyPart(data:"\(0.00)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"longitude")
            multipartFormData.appendBodyPart(data:"India".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"location")
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { request, response, JSON, error in


                }
            case .Failure(let encodingError):

            }
        }
    )

EDIT 1: For those who are trying to send an array instead of float, int or string, They can convert their array or any kind of data-structure in Json String, pass this JSON string as a normal string. And parse this json string at backend to get original array

Fast check for NaN in NumPy

Related to this is the question of how to find the first occurrence of NaN. This is the fastest way to handle that that I know of:

index = next((i for (i,n) in enumerate(iterable) if n!=n), None)

How to delete specific characters from a string in Ruby?

Using String#gsub with regular expression:

"((String1))".gsub(/^\(+|\)+$/, '')
# => "String1"
"(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
# => " parentheses "

This will remove surrounding parentheses only.

"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
# => " This (is) string "

SQLAlchemy: how to filter date field?

In fact, your query is right except for the typo: your filter is excluding all records: you should change the <= for >= and vice versa:

qry = DBSession.query(User).filter(
        and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
        filter(User.birthday >= '1985-01-17')

Also you can use between:

qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))

How to check if spark dataframe is empty?

Since Spark 2.4.0 there is Dataset.isEmpty.

It's implementation is :

def isEmpty: Boolean = 
  withAction("isEmpty", limit(1).groupBy().count().queryExecution) { plan =>
    plan.executeCollect().head.getLong(0) == 0
}

Note that a DataFrame is no longer a class in Scala, it's just a type alias (probably changed with Spark 2.0):

type DataFrame = Dataset[Row]

Merging two CSV files using Python

When I'm working with csv files, I often use the pandas library. It makes things like this very easy. For example:

import pandas as pd

a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)

Some explanation follows. First, we read in the csv files:

>>> a = pd.read_csv("filea.csv")
>>> b = pd.read_csv("fileb.csv")
>>> a
   title  stage    jan    feb
0   darn  3.001  0.421  0.532
1     ok  2.829  1.036  0.751
2  three  1.115  1.146  2.921
>>> b
   title    mar    apr    may       jun  Unnamed: 5
0   darn  0.631  1.321  0.951    1.7510         NaN
1     ok  1.001  0.247  2.456    0.3216         NaN
2  three  0.285  1.283  0.924  956.0000         NaN

and we see there's an extra column of data (note that the first line of fileb.csv -- title,mar,apr,may,jun, -- has an extra comma at the end). We can get rid of that easily enough:

>>> b = b.dropna(axis=1)
>>> b
   title    mar    apr    may       jun
0   darn  0.631  1.321  0.951    1.7510
1     ok  1.001  0.247  2.456    0.3216
2  three  0.285  1.283  0.924  956.0000

Now we can merge a and b on the title column:

>>> merged = a.merge(b, on='title')
>>> merged
   title  stage    jan    feb    mar    apr    may       jun
0   darn  3.001  0.421  0.532  0.631  1.321  0.951    1.7510
1     ok  2.829  1.036  0.751  1.001  0.247  2.456    0.3216
2  three  1.115  1.146  2.921  0.285  1.283  0.924  956.0000

and finally write this out:

>>> merged.to_csv("output.csv", index=False)

producing:

title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0

Convert a string to an enum in C#

Not sure when this was added but on the Enum class there is now a

Parse<TEnum>(stringValue)

Used like so with example in question:

var MyStatus = Enum.Parse<StatusEnum >("Active")

or ignoring casing by:

var MyStatus = Enum.Parse<StatusEnum >("active", true)

Here is the decompiled methods this uses:

    [NullableContext(0)]
    public static TEnum Parse<TEnum>([Nullable(1)] string value) where TEnum : struct
    {
      return Enum.Parse<TEnum>(value, false);
    }

    [NullableContext(0)]
    public static TEnum Parse<TEnum>([Nullable(1)] string value, bool ignoreCase) where TEnum : struct
    {
      TEnum result;
      Enum.TryParse<TEnum>(value, ignoreCase, true, out result);
      return result;
    }

How can I remove a key from a Python dictionary?

Another way is by using items() + dict comprehension.

items() coupled with dict comprehension can also help us achieve the task of key-value pair deletion, but it has the drawback of not being an in place dict technique. Actually a new dict if created except for the key we don’t wish to include.

test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21}

# Printing dictionary before removal
print ("dictionary before performing remove is : " + str(test_dict))

# Using items() + dict comprehension to remove a dict. pair
# removes  vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'}

# Printing dictionary after removal
print ("dictionary after remove is : " + str(new_dict))

Output:

dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}

using "if" and "else" Stored Procedures MySQL

you can use CASE WHEN as follow as achieve the as IF ELSE.

SELECT FROM A a 
LEFT JOIN B b 
ON a.col1 = b.col1 
AND (CASE 
        WHEN a.col2 like '0%' then TRIM(LEADING '0' FROM a.col2)
        ELSE substring(a.col2,1,2)
    END
)=b.col2; 

p.s:just in case somebody needs this way.

MVC controller : get JSON object from HTTP body?

use Request.Form to get the Data

Controller:

    [HttpPost]
    public ActionResult Index(int? id)
    {
        string jsonData= Request.Form[0]; // The data from the POST
    }

I write this to try

View:

<input type="button" value="post" id="btnPost" />

<script type="text/javascript">
    $(function () {
        var test = {
            number: 456,
            name: "Ryu"
        }
        $("#btnPost").click(function () {
            $.post('@Url.Action("Index", "Home")', JSON.stringify(test));
        });
    });
</script>

and write Request.Form[0] or Request.Params[0] in controller can get the data.

I don't write <form> tag in view.

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

Try this:

str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)

Or, use single-quotes to quote your search and replace strings:

str.replace('"', '\\"');   // (Still need to escape the backslash)

As pointed out by helmus, if the first parameter passed to .replace() is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g (global) flag:

str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');

But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:

var str = "Dude, he totally said that \"You Rock!\"";

But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.

Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.

Retrofit 2.0 how to get deserialised error response.body

if(!response.isSuccessful()) {
    StringBuilder error = new StringBuilder();
    try {
        BufferedReader bufferedReader = null;
        if (response.errorBody() != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(
                    response.errorBody().byteStream()));

            String eLine = null;
            while ((eLine = bufferedReader.readLine()) != null) {
                error.append(eLine);
            }
            bufferedReader.close();
        }

    } catch (Exception e) {
        error.append(e.getMessage());
    }

    Log.e("Error", error.toString());
}

adb connection over tcp not working now

ADb used to work fine for me for a week. But now suddenly today it says the machine actively refused connection.

fix:

step 1: go check you phone's IP Adress once again, it keeps changing.
step 2: If it changed. Just use that new IP to connect.

Hope it helped someone :)

Can you test google analytics on a localhost address?

Updated for 2014

This can now be achieved by simply setting the domain to none.

ga('create', 'UA-XXXX-Y', 'none');

See: https://developers.google.com/analytics/devguides/collection/analyticsjs/domains#localhost

How to save and load numpy.array() data properly?

For a short answer you should use np.save and np.load. The advantages of these is that they are made by developers of the numpy library and they already work (plus are likely already optimized nicely) e.g.

import numpy as np
from pathlib import Path

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2

np.save(path/'x', x)
np.save(path/'y', y)

x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')

print(x is x_loaded) # False
print(x == x_loaded) # [[ True  True  True  True  True]]

Expanded answer:

In the end it really depends in your needs because you can also save it human readable format (see this Dump a NumPy array into a csv file) or even with other libraries if your files are extremely large (see this best way to preserve numpy arrays on disk for an expanded discussion).

However, (making an expansion since you use the word "properly" in your question) I still think using the numpy function out of the box (and most code!) most likely satisfy most user needs. The most important reason is that it already works. Trying to use something else for any other reason might take you on an unexpectedly LONG rabbit hole to figure out why it doesn't work and force it work.

Take for example trying to save it with pickle. I tried that just for fun and it took me at least 30 minutes to realize that pickle wouldn't save my stuff unless I opened & read the file in bytes mode with wb. Took time to google, try thing, understand the error message etc... Small detail but the fact that it already required me to open a file complicated things in unexpected ways. To add that it required me to re-read this (which btw is sort of confusing) Difference between modes a, a+, w, w+, and r+ in built-in open function?.

So if there is an interface that meets your needs use it unless you have a (very) good reason (e.g. compatibility with matlab or for some reason your really want to read the file and printing in python really doesn't meet your needs, which might be questionable). Furthermore, most likely if you need to optimize it you'll find out later down the line (rather than spend ages debugging useless stuff like opening a simple numpy file).

So use the interface/numpy provide. It might not be perfect it's most likely fine, especially for a library that's been around as long as numpy.

I already spent the saving and loading data with numpy in a bunch of way so have fun with it, hope it helps!

import numpy as np
import pickle
from pathlib import Path

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2

# using save (to npy), savez (to npz)
np.save(path/'x', x)
np.save(path/'y', y)
np.savez(path/'db', x=x, y=y)
with open(path/'db.pkl', 'wb') as db_file:
    pickle.dump(obj={'x':x, 'y':y}, file=db_file)

## using loading npy, npz files
x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')
db = np.load(path/'db.npz')
with open(path/'db.pkl', 'rb') as db_file:
    db_pkl = pickle.load(db_file)

print(x is x_loaded)
print(x == x_loaded)
print(x == db['x'])
print(x == db_pkl['x'])
print('done')

Some comments on what I learned:

  • np.save as expected, this already compresses it well (see https://stackoverflow.com/a/55750128/1601580), works out of the box without any file opening. Clean. Easy. Efficient. Use it.
  • np.savez uses a uncompressed format (see docs) Save several arrays into a single file in uncompressed .npz format. If you decide to use this (you were warned to go away from the standard solution so expect bugs!) you might discover that you need to use argument names to save it, unless you want to use the default names. So don't use this if the first already works (or any works use that!)
  • Pickle also allows for arbitrary code execution. Some people might not want to use this for security reasons.
  • human readable files are expensive to make etc. Probably not worth it.
  • there is something called hdf5 for large files. Cool! https://stackoverflow.com/a/9619713/1601580

Note this is not an exhaustive answer. But for other resources check this:

socket programming multiple client to one server

For every client you need to start separate thread. Example:

public class ThreadedEchoServer {

    static final int PORT = 1978;

    public static void main(String args[]) {
        ServerSocket serverSocket = null;
        Socket socket = null;

        try {
            serverSocket = new ServerSocket(PORT);
        } catch (IOException e) {
            e.printStackTrace();

        }
        while (true) {
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                System.out.println("I/O error: " + e);
            }
            // new thread for a client
            new EchoThread(socket).start();
        }
    }
}

and

public class EchoThread extends Thread {
    protected Socket socket;

    public EchoThread(Socket clientSocket) {
        this.socket = clientSocket;
    }

    public void run() {
        InputStream inp = null;
        BufferedReader brinp = null;
        DataOutputStream out = null;
        try {
            inp = socket.getInputStream();
            brinp = new BufferedReader(new InputStreamReader(inp));
            out = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            return;
        }
        String line;
        while (true) {
            try {
                line = brinp.readLine();
                if ((line == null) || line.equalsIgnoreCase("QUIT")) {
                    socket.close();
                    return;
                } else {
                    out.writeBytes(line + "\n\r");
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
    }
}

You can also go with more advanced solution, that uses NIO selectors, so you will not have to create thread for every client, but that's a bit more complicated.

How to download Javadoc to read offline?

Links to access the JDK documentation

By the way, a history of Java SE versions.

How can I run an external command asynchronously from Python?

I've had good success with the asyncproc module, which deals nicely with the output from the processes. For example:

import os
from asynproc import Process
myProc = Process("myprogram.app")

while True:
    # check to see if process has ended
    poll = myProc.wait(os.WNOHANG)
    if poll is not None:
        break
    # print any new output
    out = myProc.read()
    if out != "":
        print out

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

Anton,

As a best practice one should n't create user objects in the primary filegroup. When you have bandwidth, create a new file group and move the user objects and leave the system objects in primary.

The following queries will help you identify the space used in each file and the top tables that have highest number of rows and if there are any heaps. Its a good starting point to investigate this issue.

SELECT  
ds.name as filegroupname
, df.name AS 'FileName' 
, physical_name AS 'PhysicalName'
, size/128 AS 'TotalSizeinMB'
, size/128.0 - CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS int)/128.0 AS 'AvailableSpaceInMB' 
, CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS int)/128.0 AS 'ActualSpaceUsedInMB'
, (CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS int)/128.0)/(size/128)*100. as '%SpaceUsed'
FROM sys.database_files df LEFT OUTER JOIN sys.data_spaces ds  
    ON df.data_space_id = ds.data_space_id;

EXEC xp_fixeddrives
select  t.name as TableName,  
    i.name as IndexName, 
    p.rows as Rows
from sys.filegroups fg (nolock) join sys.database_files df (nolock)
    on fg.data_space_id = df.data_space_id join sys.indexes i (nolock) 
    on df.data_space_id = i.data_space_id join sys.tables t (nolock)
    on i.object_id = t.object_id join sys.partitions p (nolock)
on t.object_id = p.object_id and i.index_id = p.index_id  
where fg.name = 'PRIMARY' and t.type = 'U'  
order by rows desc
select  t.name as TableName,  
    i.name as IndexName, 
    p.rows as Rows
from sys.filegroups fg (nolock) join sys.database_files df (nolock)
    on fg.data_space_id = df.data_space_id join sys.indexes i (nolock) 
    on df.data_space_id = i.data_space_id join sys.tables t (nolock)
    on i.object_id = t.object_id join sys.partitions p (nolock)
on t.object_id = p.object_id and i.index_id = p.index_id  
where fg.name = 'PRIMARY' and t.type = 'U' and i.index_id = 0 
order by rows desc

RSpec: how to test if a method was called?

In the new rspec expect syntax this would be:

expect(subject).to receive(:bar).with("an argument I want")

"Untrusted App Developer" message when installing enterprise iOS Application

In my case, i just change some step below with iOS 9.3 To solve this problem:

Settings -> General -> Device Management -> Developer app Choose your current developer account name. Taps Trust "Your developer account name" Taps "Trust" in pop up. Done

Round up double to 2 decimal places

Adding to above answer if we want to format Double multiple times, we can use protocol extension of Double like below:

extension Double {
    var dollarString:String {
        return String(format: "$%.2f", self)
    }
}

let a = 45.666

print(a.dollarString) //will print "$45.67"

How to refresh an access form

No, it is like I want to run Form_Load of Form A,if it is possible

-- Varun Mahajan

The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:

Form B:

Sub RunFormALoad()
   Forms!FormA.ToDoOnLoad
End Sub

Form A:

Public Sub Form_Load()
    ToDoOnLoad
End Sub    

Sub ToDoOnLoad()
    txtText = "Hi"
End Sub

How do I change the formatting of numbers on an axis with ggplot?

Another option is to format your axis tick labels with commas is by using the package scales, and add

 scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = comma)

to your ggplot statement.

If you don't want to load the package, use:

scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = scales::comma)

Using os.walk() to recursively traverse directories in Python

try this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""FileTreeMaker.py: ..."""

__author__  = "legendmohe"

import os
import argparse
import time

class FileTreeMaker(object):

    def _recurse(self, parent_path, file_list, prefix, output_buf, level):
        if len(file_list) == 0 \
            or (self.max_level != -1 and self.max_level <= level):
            return
        else:
            file_list.sort(key=lambda f: os.path.isfile(os.path.join(parent_path, f)))
            for idx, sub_path in enumerate(file_list):
                if any(exclude_name in sub_path for exclude_name in self.exn):
                    continue

                full_path = os.path.join(parent_path, sub_path)
                idc = "??"
                if idx == len(file_list) - 1:
                    idc = "??"

                if os.path.isdir(full_path) and sub_path not in self.exf:
                    output_buf.append("%s%s[%s]" % (prefix, idc, sub_path))
                    if len(file_list) > 1 and idx != len(file_list) - 1:
                        tmp_prefix = prefix + "?  "
                    else:
                        tmp_prefix = prefix + "    "
                    self._recurse(full_path, os.listdir(full_path), tmp_prefix, output_buf, level + 1)
                elif os.path.isfile(full_path):
                    output_buf.append("%s%s%s" % (prefix, idc, sub_path))

    def make(self, args):
        self.root = args.root
        self.exf = args.exclude_folder
        self.exn = args.exclude_name
        self.max_level = args.max_level

        print("root:%s" % self.root)

        buf = []
        path_parts = self.root.rsplit(os.path.sep, 1)
        buf.append("[%s]" % (path_parts[-1],))
        self._recurse(self.root, os.listdir(self.root), "", buf, 0)

        output_str = "\n".join(buf)
        if len(args.output) != 0:
            with open(args.output, 'w') as of:
                of.write(output_str)
        return output_str

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-r", "--root", help="root of file tree", default=".")
    parser.add_argument("-o", "--output", help="output file name", default="")
    parser.add_argument("-xf", "--exclude_folder", nargs='*', help="exclude folder", default=[])
    parser.add_argument("-xn", "--exclude_name", nargs='*', help="exclude name", default=[])
    parser.add_argument("-m", "--max_level", help="max level",
                        type=int, default=-1)
    args = parser.parse_args()
    print(FileTreeMaker().make(args))

you will get this:

root:.
[.]
??[.idea]
?  ??[scopes]
?  ?  ??scope_settings.xml
?  ??.name
?  ??Demo.iml
?  ??encodings.xml
?  ??misc.xml
?  ??modules.xml
?  ??vcs.xml
?  ??workspace.xml
??[test1]
?  ??test1.txt
??[test2]
?  ??[test2-2]
?  ?  ??[test2-3]
?  ?      ??test2
?  ?      ??test2-3-1
?  ??test2
??folder_tree_maker.py
??tree.py

"for loop" with two variables?

Any reason you can't use a nested for loop?

for i in range(x):
   for j in range(y):
       #code that uses i and j

Sending email through Gmail SMTP server with C#

This code works for me, and also allows in gmail access from unsecure apps, and removing authentication in 2 steps:

Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(MailAddress, Password)

Check for null variable in Windows batch

To test for the existence of a command line paramater, use empty brackets:

IF [%1]==[] echo Value Missing

or

IF [%1] EQU [] echo Value Missing

The SS64 page on IF will help you here. Under "Does %1 exist?".

You can't set a positional parameter, so what you should do is do something like

SET MYVAR=%1

You can then re-set MYVAR based on its contents.

Remove border from buttons

This seems to work for me perfectly.

button:focus { outline: none; }

Implement a simple factory pattern with Spring 3 annotations

I suppose you to use org.springframework.beans.factory.config.ServiceLocatorFactoryBean. It will much simplify your code. Except MyServiceAdapter u can only create interface MyServiceAdapter with method MyService getMyService and with alies to register your classes

Code

bean id="printStrategyFactory" class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
        <property name="YourInterface" value="factory.MyServiceAdapter" />
    </bean>

    <alias name="myServiceOne" alias="one" />
    <alias name="myServiceTwo" alias="two" />

Set an environment variable in git bash

Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.

Regexp Java for password validation

Use Passay library which is powerful api.

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

For a class diagram using Oracle database, use the following steps:

File ? Data Modeler ? Import ? Data Dictionary ? select DB connection ? Next ? select database->select tabels -> Finish

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

Best solution: Goto jboss-as-7.1.1.Final\standalone\deployments folder and delete all existing files....

Run again your problem will be solved

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

Disable ONLY_FULL_GROUP_BY

One important thing to note, if you have ANSI on sql_mode:

Equivalent to REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, and (as of MySQL 5.7.5) ONLY_FULL_GROUP_BY.

See https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_ansi

Http 415 Unsupported Media type error with JSON

I was sending "delete" rest request and it failed with 415. I saw what content-type my server uses to hit the api. In my case, It was "application/json" instead of "application/json; charset=utf8".

So ask from your api developer And in the meantime try sending request with content-type= "application/json" only.

Including external jar-files in a new jar-file build with Ant

Two options, either reference the new jars in your classpath or unpack all classes in the enclosing jars and re-jar the whole lot! As far as I know packaging jars within jars is not recommeneded and you'll forever have the class not found exception!

jQuery get selected option value (not the text, but the attribute 'value')

One of my options didn't have a value: <option>-----</option>. I was trying to use if (!$(this).val()) { .. } but I was getting strange results. Turns out if you don't have a value attribute on your <option> element, it returns the text inside of it instead of an empty string. If you don't want val() to return anything for your option, make sure to add value="".

Excel - programm cells to change colour based on another cell

Select ColumnB and as two CF formula rules apply:

Green: =AND(B1048576="X",B1="Y")

Red: =AND(B1048576="X",B1="W")

enter image description here

How to count the number of true elements in a NumPy bool array

That question solved a quite similar question for me and I thought I should share :

In raw python you can use sum() to count True values in a list :

>>> sum([True,True,True,False,False])
3

But this won't work :

>>> sum([[False, False, True], [True, False, True]])
TypeError...

JSLint is suddenly reporting: Use the function form of "use strict"

There's nothing innately wrong with the string form.

Rather than avoid the "global" strict form for worry of concatenating non-strict javascript, it's probably better to just fix the damn non-strict javascript to be strict.

Angular HttpClient "Http failure during parsing"

Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);

Becuase if you turn it to text but backend asks for json, it will return an error...

Change a Git remote HEAD to point to something besides master

For gitolite people, gitolite supports a command called -- wait for it -- symbolic-ref. It allows you to run that command remotely if you have W (write) permission to the repo.

Switch to another branch without changing the workspace files

It sounds like you made changes, committing them to master along the way, and now you want to combine them into a single commit.

If so, you want to rebase your commits, squashing them into a single commit.

I'm not entirely sure of what exactly you want, so I'm not going to tempt you with a script. But I suggest you read up on git rebase and the options for "squash"ing, and try a few things out.

Efficient way of having a function only execute once in a loop

One object-oriented approach and make your function a class, aka as a "functor", whose instances automatically keep track of whether they've been run or not when each instance is created.

Since your updated question indicates you may need many of them, I've updated my answer to deal with that by using a class factory pattern. This is a bit unusual, and it may have been down-voted for that reason (although we'll never know for sure because they never left a comment). It could also be done with a metaclass, but it's not much simpler.

def RunOnceFactory():
    class RunOnceBase(object): # abstract base class
        _shared_state = {} # shared state of all instances (borg pattern)
        has_run = False
        def __init__(self, *args, **kwargs):
            self.__dict__ = self._shared_state
            if not self.has_run:
                self.stuff_done_once(*args, **kwargs)
                self.has_run = True
    return RunOnceBase

if __name__ == '__main__':
    class MyFunction1(RunOnceFactory()):
        def stuff_done_once(self, *args, **kwargs):
            print("MyFunction1.stuff_done_once() called")

    class MyFunction2(RunOnceFactory()):
        def stuff_done_once(self, *args, **kwargs):
            print("MyFunction2.stuff_done_once() called")

    for _ in range(10):
        MyFunction1()  # will only call its stuff_done_once() method once
        MyFunction2()  # ditto

Output:

MyFunction1.stuff_done_once() called
MyFunction2.stuff_done_once() called

Note: You could make a function/class able to do stuff again by adding a reset() method to its subclass that reset the shared has_run attribute. It's also possible to pass regular and keyword arguments to the stuff_done_once() method when the functor is created and the method is called, if desired.

And, yes, it would be applicable given the information you added to your question.

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

shared global variables in C

In the header file

header file

#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef  MAIN_FILE
int global;
#else
extern int global;
#endif
#endif

In the file with the file you want the global to live:

#define MAIN_FILE
#include "share.h"

In the other files that need the extern version:

#include "share.h"

JPA: unidirectional many-to-one and cascading delete

Create a bi-directional relationship, like this:

@Entity
public class Parent implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
    private Set<Child> children;
}

Best way to unselect a <select> in jQuery?

There are lots of answers here but unfortunately all of them are quite old and therefore rely on attr/removeAttr which is really not the way to go.

@coffeeyesplease correctly mentions that a good, cross-browser solution is to use

$("select").val([]);

Another good cross-browser solution is

// Note the use of .prop instead of .attr
$("select option").prop("selected", false);

You can see it run a self-test here. Tested on IE 7/8/9, FF 11, Chrome 19.

How to reset all checkboxes using jQuery or pure JS?

 $(":checkbox:checked").each(function () {

 this.click(); 
});

to unchecked checked box, turn your logic around to do opposite

How To Include CSS and jQuery in my WordPress plugin?

Just to append to @pixeline's answer (tried to add a simple comment but the site said I needed 50 reputation).

If you are writing your plugin for the admin section then you should use:

add_action('admin_enqueue_scripts', "add_my_css_and_my_js_files");

The admin_enqueueu_scripts is the correct hook for the admin section, use wp_enqueue_scripts for the front end.

Correct way to pass multiple values for same parameter name in GET request

I would suggest looking at how browsers handle forms by default. For example take a look at the form element <select multiple> and how it handles multiple values from this example at w3schools.

<form action="/action_page.php">
<select name="cars" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<input type="submit">
</form>

For PHP use:

<select name="cars[]" multiple>

Live example from above at w3schools.com

From above if you click "saab, opel" and click submit, it will generate a result of cars=saab&cars=opel. Then depending on the back-end server, the parameter cars should come across as an array that you can further process.

Hope this helps anyone looking for a more 'standard' way of handling this issue.

Program to find largest and second largest number in array

Try Out with this:

    firstMax = arr[0];

    for (int i = 0; i<n; i++) {

        if (firstMax < arr[i]  ) {
            secondMax = firstMax;
            firstMax = arr[i];
        }
    }

Excel VBA Run-time error '13' Type mismatch

I had the same problem as you mentioned here above and my code was doing great all day yesterday.

I kept on programming this morning and when I opened my application (my file with an Auto_Open sub), I got the Run-time error '13' Type mismatch, I went on the web to find answers, I tried a lot of things, modifications and at one point I remembered that I read somewhere about "Ghost" data that stays in a cell even if we don't see it.

My code do only data transfer from one file I opened previously to another and Sum it. My code stopped at the third SheetTab (So it went right for the 2 previous SheetTab where the same code went without stopping) with the Type mismatch message. And it does that every time at the same SheetTab when I restart my code.

So I selected the cell where it stopped, manually entered 0,00 (Because the Type mismatch comes from a Summation variables declared in a DIM as Double) and copied that cell in all the subsequent cells where the same problem occurred. It solved the problem. Never had the message again. Nothing to do with my code but the "Ghost" or data from the past. It is like when you want to use the Control+End and Excel takes you where you had data once and deleted it. Had to "Save" and close the file when you wanted to use the Control+End to make sure Excel pointed you to the right cell.

Program "make" not found in PATH

Make sure you have installed 'make' tool through Cygwin's installer.

What is base 64 encoding used for?

When you have some binary data that you want to ship across a network, you generally don't do it by just streaming the bits and bytes over the wire in a raw format. Why? because some media are made for streaming text. You never know -- some protocols may interpret your binary data as control characters (like a modem), or your binary data could be screwed up because the underlying protocol might think that you've entered a special character combination (like how FTP translates line endings).

So to get around this, people encode the binary data into characters. Base64 is one of these types of encodings.

Why 64?
Because you can generally rely on the same 64 characters being present in many character sets, and you can be reasonably confident that your data's going to end up on the other side of the wire uncorrupted.

How to show text on image when hovering?

It's simple. Wrap the image and the "appear on hover" description in a div with the same dimensions of the image. Then, with some CSS, order the description to appear while hovering that div.

_x000D_
_x000D_
/* quick reset */_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
}_x000D_
_x000D_
/* relevant styles */_x000D_
.img__wrap {_x000D_
  position: relative;_x000D_
  height: 200px;_x000D_
  width: 257px;_x000D_
}_x000D_
_x000D_
.img__description {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  background: rgba(29, 106, 154, 0.72);_x000D_
  color: #fff;_x000D_
  visibility: hidden;_x000D_
  opacity: 0;_x000D_
_x000D_
  /* transition effect. not necessary */_x000D_
  transition: opacity .2s, visibility .2s;_x000D_
}_x000D_
_x000D_
.img__wrap:hover .img__description {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div class="img__wrap">_x000D_
  <img class="img__img" src="http://placehold.it/257x200.jpg" />_x000D_
  <p class="img__description">This image looks super neat.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

A nice fiddle: https://jsfiddle.net/govdqd8y/

How to serve .html files with Spring

I'd just add that you don't need to implement a controller method for that as you can use the view-controller tag (Spring 3) in the servlet configuration file:

<mvc:view-controller path="/" view-name="/WEB-INF/jsp/index.html"/>

Turn on torch/flash on iPhone

See a better answer below: https://stackoverflow.com/a/10054088/308315


Old answer:

First, in your AppDelegate .h file:

#import <AVFoundation/AVFoundation.h>

@interface AppDelegate : NSObject <UIApplicationDelegate> {

    AVCaptureSession *torchSession;

}

@property (nonatomic, retain) AVCaptureSession * torchSession;

@end

Then in your AppDelegate .m file:

@implementation AppDelegate

@synthesize torchSession;

- (void)dealloc {
    [torchSession release];

    [super dealloc];
}

- (id) init {
    if ((self = [super init])) {

    // initialize flashlight
    // test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
        Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
        if (captureDeviceClass != nil) {

            AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

            if ([device hasTorch] && [device hasFlash]){

                if (device.torchMode == AVCaptureTorchModeOff) {

                NSLog(@"Setting up flashlight for later use...");

                    AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
                    AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];

                    AVCaptureSession *session = [[AVCaptureSession alloc] init];

                [session beginConfiguration];
                    [device lockForConfiguration:nil];

                    [session addInput:flashInput];
                    [session addOutput:output];

                    [device unlockForConfiguration];

                    [output release];

                [session commitConfiguration];
                [session startRunning];

                [self setTorchSession:session];
                [session release];
                    }

            }

        }
    } 
    return self;
}

Then anytime you want to turn it on, just do something like this:

// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    [device lockForConfiguration:nil];

    [device setTorchMode:AVCaptureTorchModeOn];
    [device setFlashMode:AVCaptureFlashModeOn];

    [device unlockForConfiguration];

}

And similar for turning it off:

// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    [device lockForConfiguration:nil];

    [device setTorchMode:AVCaptureTorchModeOff];
    [device setFlashMode:AVCaptureFlashModeOff];

    [device unlockForConfiguration];
}

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...

UPDATE:

Apparently this syntax is only available starting on SQL Server 2008.

PHP7 : install ext-dom issue

simply run

sudo apt install php-xml

its worked for me

Angular2 Routing with Hashtag to page anchor

A simple solution that works for pages without any query parameters, is browser back / forward, router and deep-linking compliant.

<a (click)="jumpToId('anchor1')">Go To Anchor 1</a>


ngOnInit() {

    // If your page is dynamic
    this.yourService.getWhatever()
        .then(
            data => {
            this.componentData = data;
            setTimeout(() => this.jumpToId( window.location.hash.substr(1) ), 100);
        }
    );

    // If your page is static
    // this.jumpToId( window.location.hash.substr(1) )
}

jumpToId( fragment ) {

    // Use the browser to navigate
    window.location.hash = fragment;

    // But also scroll when routing / deep-linking to dynamic page
    // or re-clicking same anchor
    if (fragment) {
        const element = document.querySelector('#' + fragment);
        if (element) element.scrollIntoView();
    }
}

The timeout is simply to allow the page to load any dynamic data "protected" by an *ngIf. This can also be used to scroll to the top of the page when changing route - just provide a default top anchor tag.

How to read file with space separated values in pandas

If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:

 import csv

 csv.register_dialect('skip_space', skipinitialspace=True)
 with open(my_file, 'r') as f:
      reader=csv.reader(f , delimiter=' ', dialect='skip_space')
      for item in reader:
          print(item)

HTTPS using Jersey Client

Waking up a dead question here but the answers provided will not work with jdk 7 (I read somewhere that a bug is open for this for Oracle Engineers but not fixed yet). Along with the link that @Ryan provided, you will have to also add :

System.setProperty("jsse.enableSNIExtension", "false");

(Courtesy to many stackoverflow answers combined together to figure this out)

The complete code will look as follows which worked for me (without setting the system property the Client Config did not work for me):

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class ClientHelper
{
    public static ClientConfig configureClient()
    {
        System.setProperty("jsse.enableSNIExtension", "false");
        TrustManager[] certs = new TrustManager[]
        {
            new X509TrustManager()
            {
                @Override
                public X509Certificate[] getAcceptedIssuers()
                {
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException
                {
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException
                {
                }
            }
        };
        SSLContext ctx = null;
        try
        {
            ctx = SSLContext.getInstance("SSL");
            ctx.init(null, certs, new SecureRandom());
        }
        catch (java.security.GeneralSecurityException ex)
        {
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        ClientConfig config = new DefaultClientConfig();
        try
        {
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
                    new HostnameVerifier()
            {
                @Override
                public boolean verify(String hostname, SSLSession session)
                {
                    return true;
                }
            },
                    ctx));
        }
        catch (Exception e)
        {
        }
        return config;
    }

    public static Client createClient()
    {
        return Client.create(ClientHelper.configureClient());
    }

@viewChild not working - cannot read property nativeElement of undefined

it just simple :import this directory

import {Component, Directive, Input, ViewChild} from '@angular/core';

Jquery show/hide table rows

The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:

    var black = $('.black');
    var white = $('.white');

The selector will find every element classed under black or white. Button functions stay as stated above:

    $('#showBlackButton').click(function() {
           black.show();
           white.hide();
    });

    $('#showWhiteButton').click(function() {
           white.show();
           black.hide();
    });

How to match "any character" in regular expression?

Yes, you can. That should work.

  • . = any char except newline
  • \. = the actual dot character
  • .? = .{0,1} = match any char except newline zero or one times
  • .* = .{0,} = match any char except newline zero or more times
  • .+ = .{1,} = match any char except newline one or more times

Remove a file from a Git repository without deleting it from the local filesystem

Also, if you have commited sensitive data (e.g. a file containing passwords), you should completely delete it from the history of the repository. Here's a guide explaining how to do that: http://help.github.com/remove-sensitive-data/

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

For some reason, adding the environment variable didn't work for me.

I was able to specify a path to Firefox in the command line node configuration, as described on this page (grid2).

-browser “browserName=firefox,version=3.6,firefox_binary=c:\Program Files\Mozilla Firefox\firefox.exe ,maxInstances=3, platform=WINDOWS”

How do I restrict a float value to only two places after the decimal point in C?

How about this:

float value = 37.777779;
float rounded = ((int)(value * 100 + .5) / 100.0);

How to get index of object by its property in JavaScript?

Why don't you use a small work-around?

Create a new array with names as indexes. after that all searches will use indexes. So, only one loop. After that you don't need to loop through all elements!

var Data = [
    {id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
    ]
var searchArr = []
Data.forEach(function(one){
  searchArr[one.name]=one;
})
console.log(searchArr['Nick'])

http://jsbin.com/xibala/1/edit

live example.

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

I had to run my commands in the one and same terminal, not seperately.

nohup sudo Xvfb :10 -ac
export DISPLAY=:10
java -jar vendor/se/selenium-server-standalone/bin/selenium-server-standalone.jar -Dwebdriver.chrome.bin="/usr/bin/google-chrome" -Dwebdriver.chrome.driver="vendor/bin/chromedriver"

Using regular expressions to do mass replace in Notepad++ and Vim

This will work. Tested it in my vim. the single quotes are the trouble.

1,$s/^<option value value=['].['] >/

Comparing Arrays of Objects in JavaScript

I have worked a bit on a simple algorithm to compare contents of two objects and return an intelligible list of difference. Thought I would share. It borrows some ideas for jQuery, namely the map function implementation and the object and array type checking.

It returns a list of "diff objects", which are arrays with the diff info. It's very simple.

Here it is:

// compare contents of two objects and return a list of differences
// returns an array where each element is also an array in the form:
// [accessor, diffType, leftValue, rightValue ]
//
// diffType is one of the following:
//   value: when primitive values at that index are different
//   undefined: when values in that index exist in one object but don't in 
//              another; one of the values is always undefined
//   null: when a value in that index is null or undefined; values are
//         expressed as boolean values, indicated wheter they were nulls
//   type: when values in that index are of different types; values are 
//         expressed as types
//   length: when arrays in that index are of different length; values are
//           the lengths of the arrays
//

function DiffObjects(o1, o2) {
    // choose a map() impl.
    // you may use $.map from jQuery if you wish
    var map = Array.prototype.map?
        function(a) { return Array.prototype.map.apply(a, Array.prototype.slice.call(arguments, 1)); } :
        function(a, f) { 
            var ret = new Array(a.length), value;
            for ( var i = 0, length = a.length; i < length; i++ ) 
                ret[i] = f(a[i], i);
            return ret.concat();
        };

    // shorthand for push impl.
    var push = Array.prototype.push;

    // check for null/undefined values
    if ((o1 == null) || (o2 == null)) {
        if (o1 != o2)
            return [["", "null", o1!=null, o2!=null]];

        return undefined; // both null
    }
    // compare types
    if ((o1.constructor != o2.constructor) ||
        (typeof o1 != typeof o2)) {
        return [["", "type", Object.prototype.toString.call(o1), Object.prototype.toString.call(o2) ]]; // different type

    }

    // compare arrays
    if (Object.prototype.toString.call(o1) == "[object Array]") {
        if (o1.length != o2.length) { 
            return [["", "length", o1.length, o2.length]]; // different length
        }
        var diff =[];
        for (var i=0; i<o1.length; i++) {
            // per element nested diff
            var innerDiff = DiffObjects(o1[i], o2[i]);
            if (innerDiff) { // o1[i] != o2[i]
                // merge diff array into parent's while including parent object name ([i])
                push.apply(diff, map(innerDiff, function(o, j) { o[0]="[" + i + "]" + o[0]; return o; }));
            }
        }
        // if any differences were found, return them
        if (diff.length)
            return diff;
        // return nothing if arrays equal
        return undefined;
    }

    // compare object trees
    if (Object.prototype.toString.call(o1) == "[object Object]") {
        var diff =[];
        // check all props in o1
        for (var prop in o1) {
            // the double check in o1 is because in V8 objects remember keys set to undefined 
            if ((typeof o2[prop] == "undefined") && (typeof o1[prop] != "undefined")) {
                // prop exists in o1 but not in o2
                diff.push(["[" + prop + "]", "undefined", o1[prop], undefined]); // prop exists in o1 but not in o2

            }
            else {
                // per element nested diff
                var innerDiff = DiffObjects(o1[prop], o2[prop]);
                if (innerDiff) { // o1[prop] != o2[prop]
                    // merge diff array into parent's while including parent object name ([prop])
                    push.apply(diff, map(innerDiff, function(o, j) { o[0]="[" + prop + "]" + o[0]; return o; }));
                }

            }
        }
        for (var prop in o2) {
            // the double check in o2 is because in V8 objects remember keys set to undefined 
            if ((typeof o1[prop] == "undefined") && (typeof o2[prop] != "undefined")) {
                // prop exists in o2 but not in o1
                diff.push(["[" + prop + "]", "undefined", undefined, o2[prop]]); // prop exists in o2 but not in o1

            }
        }
        // if any differences were found, return them
        if (diff.length)
            return diff;
        // return nothing if objects equal
        return undefined;
    }
    // if same type and not null or objects or arrays
    // perform primitive value comparison
    if (o1 != o2)
        return [["", "value", o1, o2]];

    // return nothing if values are equal
    return undefined;
}

Get the correct week number of a given date

Good news! A pull request adding System.Globalization.ISOWeek to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.

The type has the following signature, which should cover most ISO week needs:

namespace System.Globalization
{
    public static class ISOWeek
    {
        public static int GetWeekOfYear(DateTime date);
        public static int GetWeeksInYear(int year);
        public static int GetYear(DateTime date);
        public static DateTime GetYearEnd(int year);
        public static DateTime GetYearStart(int year);
        public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek);
    }
}

You can find the source code here.

UPDATE: These APIs have also been included in the 2.1 version of .NET Standard.

DISABLE the Horizontal Scroll

Try this one to disable width-scrolling just for body the all document just is body body{overflow-x: hidden;}

First letter capitalization for EditText

Try This Code, it will capitalize first character of all words.

- set addTextChangedListener for EditText view

edt_text.addTextChangedListener(watcher);

- Add TextWatcher

TextWatcher watcher = new TextWatcher() {
    int mStart = 0;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mStart = start + count;
    }

    @Override
    public void afterTextChanged(Editable s) {
        String input = s.toString();
        String capitalizedText;
        if (input.length() < 1)
            capitalizedText = input;
        else if (input.length() > 1 && input.contains(" ")) {
            String fstr = input.substring(0, input.lastIndexOf(" ") + 1);
            if (fstr.length() == input.length()) {
                capitalizedText = fstr;
            } else {
                String sstr = input.substring(input.lastIndexOf(" ") + 1);
                sstr = sstr.substring(0, 1).toUpperCase() + sstr.substring(1);
                capitalizedText = fstr + sstr;
            }
        } else
            capitalizedText = input.substring(0, 1).toUpperCase() + input.substring(1);

        if (!capitalizedText.equals(edt_text.getText().toString())) {
            edt_text.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    edt_text.setSelection(mStart);
                    edt_text.removeTextChangedListener(this);
                }
            });
            edt_text.setText(capitalizedText);
        }
    }
};

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

Pass a JavaScript function as parameter

Example 1:

funct("z", function (x) { return x; });

function funct(a, foo){
    foo(a) // this will return a
}

Example 2:

function foodemo(value){
    return 'hello '+value;
}

function funct(a, foo){
    alert(foo(a));
}

//call funct    
funct('world!',foodemo); //=> 'hello world!'

look at this

Filter dict to contain only certain keys?

You can do that with project function from my funcy library:

from funcy import project
small_dict = project(big_dict, keys)

Also take a look at select_keys.

Get the device width in javascript

Ya mybe u can use document.documentElement.clientWidth to get the device width of client and keep tracking the device width by put on setInterval

just like

setInterval(function(){
        width = document.documentElement.clientWidth;
        console.log(width);
    }, 1000);

How to move all HTML element children to another parent using JavaScript?

DEMO

Basically, you want to loop through each direct descendent of the old-parent node, and move it to the new parent. Any children of a direct descendent will get moved with it.

var newParent = document.getElementById('new-parent');
var oldParent = document.getElementById('old-parent');

while (oldParent.childNodes.length > 0) {
    newParent.appendChild(oldParent.childNodes[0]);
}

Java JDBC - How to connect to Oracle using Service Name instead of SID

This discussion helped me resolve the issue I was struggling with for days. I looked around all over the internet until I found the answered by Jim Tough on May 18 '11 at 15:17. With that answer I was able to connect. Now I want to give back and help others with a complete example. Here goes:

import java.sql.*; 

public class MyDBConnect {

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

        try { 
            String dbURL = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=whatEverYourHostNameIs)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=yourServiceName)))";
            String strUserID = "yourUserId";
            String strPassword = "yourPassword";
            Connection myConnection=DriverManager.getConnection(dbURL,strUserID,strPassword);

            Statement sqlStatement = myConnection.createStatement();
            String readRecordSQL = "select * from sa_work_order where WORK_ORDER_NO = '1503090' ";  
            ResultSet myResultSet = sqlStatement.executeQuery(readRecordSQL);
            while (myResultSet.next()) {
                System.out.println("Record values: " + myResultSet.getString("WORK_ORDER_NO"));
            }
            myResultSet.close();
            myConnection.close();

        } catch (Exception e) {
            System.out.println(e);
        }       
    }
}

Loop X number of times

This may be what you are looking for:

for ($i=1; $i -le $ActiveCampaigns; $i++)
{
  $PQCampaign     = Get-Variable -Name "PQCampaign$i"     -ValueOnly
  $PQCampaignPath = Get-Variable -Name "PQCampaignPath$i" -ValueOnly

  # Do stuff with $PQCampaign and $PQCampaignPath
}

Add resources, config files to your jar using gradle

Be aware that the path under src/main/resources must match the package path of your .class files wishing to access the resource. See my answer here.

'typeid' versus 'typeof' in C++

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

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

and something like

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

Generate a random number in a certain range in MATLAB

ocw.mit.edu is a great resource that has helped me a bunch. randi is the best option, but if your into number fun try using the floor function with rand to get what you want.

I drew a number line and came up with

floor(rand*8) + 13

Unable to use Intellij with a generated sources folder

With gradle, the project settings will be cleared whenever you refresh the gradle settings. Instead you need to add the following lines (or similar) in your build.gradle, I'm using kotlin so:

sourceSets {
    main {
        java {
            srcDir "${buildDir.absolutePath}/generated/source/kapt/main"
        }
    }
}

ReactJS - Add custom event listener to component

First off, custom events don't play well with React components natively. So you cant just say <div onMyCustomEvent={something}> in the render function, and have to think around the problem.

Secondly, after taking a peek at the documentation for the library you're using, the event is actually fired on document.body, so even if it did work, your event handler would never trigger.

Instead, inside componentDidMount somewhere in your application, you can listen to nv-enter by adding

document.body.addEventListener('nv-enter', function (event) {
    // logic
});

Then, inside the callback function, hit a function that changes the state of the component, or whatever you want to do.

Turning off eslint rule for a specific file

Based on the number of rules you want to ignore (All, or Some), and the scope of disabling it (Line(s), File(s), Everywhere), we have 2 × 3 = 6 cases.


1) Disabling "All rules"


Case 1.1: You want to disable "All Rules" for "One or more Lines"

Two ways you can do this:

  1. Put /* eslint-disable-line */ at the end of the line(s),
  2. or /* eslint-disable-next-line */ right before the line.

Case 1.2: You want to disable "All Rules" for "One File"

  • Put the comment of /* eslint-disable */ at the top of the file.

Case 1.3: You want to disable "All rules" for "Some Files"

There are 3 ways you can do this:

  1. You can go with 1.2 and add /* eslint-disable */ on top of the files, one by one.
  2. You can put the file name(s) in .eslintignore. This works well especially if you have a path that you want to be ignored. (e.g. apidoc/**)
  3. Alternatively, if you don't want to have a separate .eslintignore file, you can add "eslintIgnore": ["file1.js", "file2.js"] in package.json as instructed here.

2) Disabling "Some Rules"


Case 2.1: You want to disable "Some Rules" for "One or more Lines"

Two ways you can do this:

  1. You can put /* eslint-disable-line quotes */ (replace quotes with your rules) at the end of the line(s),

  2. or /* eslint-disable-next-line no-alert, quotes, semi */ before the line.


Case 2.2: You want to disable "Some Rules" for "One File"

  • Put the /* eslint-disable no-use-before-define */ comment at the top of the file.

More examples here.


Case 2.3: You want to disable "Some Rules" for "Some files"

  • This is less straight-forward. You should put them in "excludedFiles" object of "overrides" section of your .eslintrc as instructed here.

How do I get the current absolute URL in Ruby on Rails?

you can get absolute url by calling:

request.original_url

or

request.env['HTTP_REFERER']

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

How do I select last 5 rows in a table without sorting?

Without an order, this is impossible. What defines the "bottom"? The following will select 5 rows according to how they are stored in the database.

SELECT TOP 5 * FROM [TableName]

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

You need to create a query (in Visual Studio, right-click on the DB connection -> New Query) and execute the following SQL:

ALTER TABLE tblAlpha
ADD CONSTRAINT MyConstraint FOREIGN KEY (FK_id) REFERENCES
tblGamma(GammaID)
ON UPDATE CASCADE

To verify that your foreign key was created, execute the following SQL:

SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS

Credit to E Jensen (http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=532377&SiteID=1)

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

A typical algo for tic-tac-toe should look like this:

Board : A nine-element vector representing the board. We store 2 (indicating Blank), 3 (indicating X), or 5 (indicating O). Turn: An integer indicating which move of the game about to be played. The 1st move will be indicated by 1, last by 9.

The Algorithm

The main algorithm uses three functions.

Make2: returns 5 if the center square of the board is blank i.e. if board[5]=2. Otherwise, this function returns any non-corner square (2, 4, 6 or 8).

Posswin(p): Returns 0 if player p can’t win on his next move; otherwise, it returns the number of the square that constitutes a winning move. This function will enable the program both to win and to block opponents win. This function operates by checking each of the rows, columns, and diagonals. By multiplying the values of each square together for an entire row (or column or diagonal), the possibility of a win can be checked. If the product is 18 (3 x 3 x 2), then X can win. If the product is 50 (5 x 5 x 2), then O can win. If a winning row (column or diagonal) is found, the blank square in it can be determined and the number of that square is returned by this function.

Go (n): makes a move in square n. this procedure sets board [n] to 3 if Turn is odd, or 5 if Turn is even. It also increments turn by one.

The algorithm has a built-in strategy for each move. It makes the odd numbered move if it plays X, the even-numbered move if it plays O.

Turn = 1    Go(1)   (upper left corner).
Turn = 2    If Board[5] is blank, Go(5), else Go(1).
Turn = 3    If Board[9] is blank, Go(9), else Go(3).
Turn = 4    If Posswin(X) is not 0, then Go(Posswin(X)) i.e. [ block opponent’s win], else Go(Make2).
Turn = 5    if Posswin(X) is not 0 then Go(Posswin(X)) [i.e. win], else if Posswin(O) is not 0, then Go(Posswin(O)) [i.e. block win], else if Board[7] is blank, then Go(7), else Go(3). [to explore other possibility if there be any ].
Turn = 6    If Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else Go(Make2).
Turn = 7    If Posswin(X) is not 0 then Go(Posswin(X)), else if Posswin(X) is not 0, then Go(Posswin(O)) else go anywhere that is blank.
Turn = 8    if Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else go anywhere that is blank.
Turn = 9    Same as Turn=7.

I have used it. Let me know how you guys feel.

Can't install Scipy through pip

If you are totally new to python read step by step or go directly to last step. Follow the below method to install scipy 0.18.1 on Windows 64-bit , Python 64-bit . If below command is not working then proceed further

pip install scipy

Be careful with the versions of

  1. Python

  2. Windows

  3. .whl version of numpy and scipy files

  4. First install numpy and scipy.

    pip install FileName.whl
    
  5. For Numpy:http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy For Scipy:http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

Be aware of the file name (check the version number).

Ex :scipy-0.18.1-cp35-cp35m-win_amd64.whl

To check which version is supported by your pip, go to point No 2 below.

If you are using .whl file . Following errors are likely to occur .

  1. You are using pip version 7.1.0, however version 8.1.2 is available.

You should consider upgrading via the 'python -m pip install --upgrade pip' command

  1. scipy-0.15.1-cp33-none-win_amd64.whl.whl is not supported wheel on this platform

For the above error: start Python and type :

import pip
print(pip.pep425tags.get_supported())

Output:

[('cp35', 'cp35m', 'win_amd64'), ('cp35', 'none', 'win_amd64'), ('py3', 'none', 'win_amd64'), ('cp35', 'none', 'any'), ('cp3', 'none', 'any'), ('py35', 'none', 'any'), ('py3', 'none', 'any'), ('py34', 'none', 'any'), ('py33', 'none', 'any'), ('py32', 'none', 'any'), ('py31', 'none', 'any'), ('py30', 'none', 'any')]

In the output you will observe cp35 is there , so download cp35 for numpy as well as scipy.Further edits are most welcome.

What is a Java String's default initial value?

Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.

Using variables inside strings

This functionality is not built-in to C# 5 or below.
Update: C# 6 now supports string interpolation, see newer answers.

The recommended way to do this would be with String.Format:

string name = "Scott";
string output = String.Format("Hello {0}", name);

However, I wrote a small open-source library called SmartFormat that extends String.Format so that it can use named placeholders (via reflection). So, you could do:

string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".

Hope you like it!

How can I use Python to get the system hostname?

Both of these are pretty portable:

import platform
platform.node()

import socket
socket.gethostname()

Any solutions using the HOST or HOSTNAME environment variables are not portable. Even if it works on your system when you run it, it may not work when run in special environments such as cron.

Uncaught TypeError: Cannot assign to read only property

If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.

var globalObject = {
    name:"a",
    age:20
}
function() {
    let localObject = {
    name:'a',
    age:21
    }
    this.globalObject = localObject;
}

Command not found after npm install in zsh

On Ubuntu, after installing ZSH, and prevously on the bash terminal installed Node or other packages,

First open:

nano .zshrc

And uncomment the second line:

export PATH=$HOME/bin:/usr/local/bin:$PATH

This works for me, and without writting any line, and I think this option is available on Mac too.

How can I interrupt a running code in R with a keyboard command?

Control-C works, although depending on what the process is doing it might not take right away.

If you're on a unix based system, one thing I do is control-z to go back to the command line prompt and then issue a 'kill' to the process ID.

Create a git patch from the uncommitted changes in the current working directory

If you haven't yet commited the changes, then:

git diff > mypatch.patch

But sometimes it happens that part of the stuff you're doing are new files that are untracked and won't be in your git diff output. So, one way to do a patch is to stage everything for a new commit (git add each file, or just git add .) but don't do the commit, and then:

git diff --cached > mypatch.patch

Add the 'binary' option if you want to add binary files to the patch (e.g. mp3 files):

git diff --cached --binary > mypatch.patch

You can later apply the patch:

git apply mypatch.patch

BASH Syntax error near unexpected token 'done'

Sometimes this error happens because of unexpected CR characters in file, usually because the file was generated on a Windows system which uses CR line endings. You can fix this by running os2unix or tr, for example:

tr -d '\015' < yourscript.sh > newscript.sh

This removes any CR characters from the file.

How to configure CORS in a Spring Boot + Spring Security application?

If you are using Spring Security, you can do the following to ensure that CORS requests are handled first:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors().and()
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

See Spring 4.2.x CORS for more information.

Without Spring Security this will work:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
        }
    };
}

Find the smallest positive integer that does not occur in a given sequence

For the space complexity of O(1) and time complexity of O(N) and if the array can be modified then it could be as follows:

public int getFirstSmallestPositiveNumber(int[] arr) {
    // set positions of non-positive or out of range elements as free (use 0 as marker)
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] <= 0 || arr[i] > arr.length) {
            arr[i] = 0;
        }
    }

    //iterate through the whole array again mapping elements [1,n] to positions [0, n-1]
    for (int i = 0; i < arr.length; i++) {
        int prev = arr[i];
        // while elements are not on their correct positions keep putting them there
        while (prev > 0 && arr[prev - 1] != prev) {
            int next = arr[prev - 1];
            arr[prev - 1] = prev;
            prev = next;
        }
    }

    // now, the first unmapped position is the smallest element
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] != i + 1) {
            return i + 1;
        }
    }
    return arr.length + 1;
}

@Test
public void testGetFirstSmallestPositiveNumber() {
    int[][] arrays = new int[][]{{1,-1,-5,-3,3,4,2,8},
      {5, 4, 3, 2, 1}, 
      {0, 3, -2, -1, 1}};

    for (int i = 0; i < arrays.length; i++) {
        System.out.println(getFirstSmallestPositiveNumber(arrays[i]));
    }
}  

Output:

5

6

2

How to convert file to base64 in JavaScript?

Try the solution using the FileReader class:

function getBase64(file) {
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}

var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file); // prints the base64 string

Notice that .files[0] is a File type, which is a sublcass of Blob. Thus it can be used with FileReader.
See the complete working example.

MySQL FULL JOIN?

SELECT  p.LastName, p.FirstName, o.OrderNo
FROM    persons AS p
LEFT JOIN
        orders AS o
ON      o.orderNo = p.p_id
UNION ALL
SELECT  NULL, NULL, orderNo
FROM    orders
WHERE   orderNo NOT IN
        (
        SELECT  p_id
        FROM    persons
        )

How to convert float to varchar in SQL Server

this is the solution I ended up using in sqlserver 2012 (since all the other suggestions had the drawback of truncating fractional part or some other drawback).

declare @float float = 1000000000.1234;
select format(@float, N'#.##############################');

output:

1000000000.1234

this has the further advantage (in my case) to make thousands separator and localization easy:

select format(@float, N'#,##0.##########', 'de-DE');

output:

1.000.000.000,1234

Inverse of matrix in R

Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 

Comments in Android Layout xml

As other said, the comment in XML are like this

<!-- this is a comment -->

Notice that they can span on multiple lines

<!--
    This is a comment
    on multiple lines
-->

But they cannot be nested

<!-- This <!-- is a comment --> This is not -->

Also you cannot use them inside tags

<EditText <!--This is not valid--> android:layout_width="fill_parent" />

How to identify server IP address in PHP

I found this to work for me: GetHostByName("");

Running XAMPP v1.7.1 on Windows 7 running Apache webserver. Unfortunately it just give my gateway IP address.

Scala check if element is present in a list

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)

Where does forever store console.log output?

Forever takes command line options for output:

-l  LOGFILE      Logs the forever output to LOGFILE
-o  OUTFILE      Logs stdout from child script to OUTFILE
-e  ERRFILE      Logs stderr from child script to ERRFILE

For example:

forever start -o out.log -e err.log my-script.js

See here for more info

JavaScript calculate the day of the year (1 - 366)

I find it very interesting that no one considered using UTC since it is not subject to DST. Therefore, I propose the following:

function daysIntoYear(date){
    return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}

You can test it with the following:

[new Date(2016,0,1), new Date(2016,1,1), new Date(2016,2,1), new Date(2016,5,1), new Date(2016,11,31)]
    .forEach(d => 
        console.log(`${d.toLocaleDateString()} is ${daysIntoYear(d)} days into the year`));

Which outputs for the leap year 2016 (verified using http://www.epochconverter.com/days/2016):

1/1/2016 is 1 days into the year
2/1/2016 is 32 days into the year
3/1/2016 is 61 days into the year
6/1/2016 is 153 days into the year
12/31/2016 is 366 days into the year

Passing a variable from one php include file to another: global vs. not

This is all you have to do:

In front.inc

global $name;
$name = 'james';

Opening PDF String in new window with javascript

Just for information, the below

window.open("data:application/pdf," + encodeURI(pdfString)); 

does not work anymore in Chrome. Yesterday, I came across with the same issue and tried this solution, but did not work (it is 'Not allowed to navigate top frame to data URL'). You cannot open the data URL directly in a new window anymore. But, you can wrap it in iframe and make it open in a new window like below. =)

let pdfWindow = window.open("")
pdfWindow.document.write(
    "<iframe width='100%' height='100%' src='data:application/pdf;base64, " +
    encodeURI(yourDocumentBase64VarHere) + "'></iframe>"
)

Inverse dictionary lookup in Python

Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:

key = next(key for key, value in dd.items() if value == 'value')

where dd is the dict. Will raise StopIteration if no match is found, so you might want to catch that and return a more appropriate exception like ValueError or KeyError.

Squash my last X commits together using Git

To avoid having to resolve any merge conflicts when rebasing onto a commit in the same branch, you can use the following command

git rebase -i <last commit id before your changes start> -s recursive -X ours

To squash all commits into one, when you are prompted to edit commits to be merged (-i flag), update all but first action from pick to squash as recommended in other answers too.

Here, we use the merge strategy (-s flag) recursive and strategy option (-X) ours to make sure that the later commits in the history win any merge conflicts.

NOTE: Do not confuse this with git rebase -s ours which does something else.

Reference: git rebase recursive merge strategy

PHP output showing little black diamonds with a question mark

I also faced this ? issue. Meanwhile I ran into three cases where it happened:

  1. substr()

    I was using substr() on a UTF8 string which cut UTF8 characters, thus the cut chars could not be displayed correctly. Use mb_substr($utfstring, 0, 10, 'utf-8'); instead. Credits

  2. htmlspecialchars()

    Another problem was using htmlspecialchars() on a UTF8 string. The fix is to use: htmlspecialchars($utfstring, ENT_QUOTES, 'UTF-8');

  3. preg_replace()

    Lastly I found out that preg_replace() can lead to problems with UTF. The code $string = preg_replace('/[^A-Za-z0-9ÄäÜüÖöß]/', ' ', $string); for example transformed the UTF string "F(×)=2×-3" into "F ? 2? ". The fix is to use mb_ereg_replace() instead.

I hope this additional information will help to get rid of such problems.

PostgreSQL: Drop PostgreSQL database through command line

This worked for me:

select pg_terminate_backend(pid) from pg_stat_activity where datname='YourDatabase';

for postgresql earlier than 9.2 replace pid with procpid

DROP DATABASE "YourDatabase";

http://blog.gahooa.com/2010/11/03/how-to-force-drop-a-postgresql-database-by-killing-off-connection-processes/

Difference between x86, x32, and x64 architectures?

x86 means Intel 80x86 compatible. This used to include the 8086, a 16-bit only processor. Nowadays it roughly means any CPU with a 32-bit Intel compatible instruction set (usually anything from Pentium onwards). Never read x32 being used.

x64 means a CPU that is x86 compatible but has a 64-bit mode as well (most often the 64-bit instruction set as introduced by AMD is meant; Intel's idea of a 64-bit mode was totally stupid and luckily Intel admitted that and is now using AMDs variant).

So most of the time you can simplify it this way: x86 is Intel compatible in 32-bit mode, x64 is Intel compatible in 64-bit mode.

JavaFX How to set scene background image

I know this is an old Question

But in case you want to do it programmatically or the java way

For Image Backgrounds; you can use BackgroundImage class

BackgroundImage myBI= new BackgroundImage(new Image("my url",32,32,false,true),
        BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
          BackgroundSize.DEFAULT);
//then you set to your node
myContainer.setBackground(new Background(myBI));

For Paint or Fill Backgrounds; you can use BackgroundFill class

BackgroundFill myBF = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1),
         new Insets(0.0,0.0,0.0,0.0));// or null for the padding
//then you set to your node or container or layout
myContainer.setBackground(new Background(myBF));

Keeps your java alive && your css dead..

BehaviorSubject vs Observable?

Observable: Different result for each Observer

One very very important difference. Since Observable is just a function, it does not have any state, so for every new Observer, it executes the observable create code again and again. This results in:

The code is run for each observer . If its a HTTP call, it gets called for each observer

This causes major bugs and inefficiencies

BehaviorSubject (or Subject ) stores observer details, runs the code only once and gives the result to all observers .

Ex:

JSBin: http://jsbin.com/qowulet/edit?js,console

_x000D_
_x000D_
// --- Observable ---_x000D_
let randomNumGenerator1 = Rx.Observable.create(observer => {_x000D_
   observer.next(Math.random());_x000D_
});_x000D_
_x000D_
let observer1 = randomNumGenerator1_x000D_
      .subscribe(num => console.log('observer 1: '+ num));_x000D_
_x000D_
let observer2 = randomNumGenerator1_x000D_
      .subscribe(num => console.log('observer 2: '+ num));_x000D_
_x000D_
_x000D_
// ------ BehaviorSubject/ Subject_x000D_
_x000D_
let randomNumGenerator2 = new Rx.BehaviorSubject(0);_x000D_
randomNumGenerator2.next(Math.random());_x000D_
_x000D_
let observer1Subject = randomNumGenerator2_x000D_
      .subscribe(num=> console.log('observer subject 1: '+ num));_x000D_
      _x000D_
let observer2Subject = randomNumGenerator2_x000D_
      .subscribe(num=> console.log('observer subject 2: '+ num));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.3/Rx.min.js"></script>
_x000D_
_x000D_
_x000D_

Output :

"observer 1: 0.7184075243594013"
"observer 2: 0.41271850211336103"
"observer subject 1: 0.8034263165479893"
"observer subject 2: 0.8034263165479893"

Observe how using Observable.create created different output for each observer, but BehaviorSubject gave the same output for all observers. This is important.


Other differences summarized.

?????????????????????????????????????????????????????????????????????????????
?         Observable                  ?     BehaviorSubject/Subject         ?      
????????????????????????????????????????????????????????????????????????????? 
? Is just a function, no state        ? Has state. Stores data in memory    ?
?????????????????????????????????????????????????????????????????????????????
? Code run for each observer          ? Same code run                       ?
?                                     ? only once for all observers         ?
?????????????????????????????????????????????????????????????????????????????
? Creates only Observable             ?Can create and also listen Observable?
? ( data producer alone )             ? ( data producer and consumer )      ?
?????????????????????????????????????????????????????????????????????????????
? Usage: Simple Observable with only  ? Usage:                              ?
? one Obeserver.                      ? * Store data and modify frequently  ?
?                                     ? * Multiple observers listen to data ?
?                                     ? * Proxy between Observable  and     ?
?                                     ?   Observer                          ?
?????????????????????????????????????????????????????????????????????????????

Finding current executable's path without /proc/self/exe

Depending on the version of QNX Neutrino, there are different ways to find the full path and name of the executable file that was used to start the running process. I denote the process identifier as <PID>. Try the following:

  1. If the file /proc/self/exefile exists, then its contents are the requested information.
  2. If the file /proc/<PID>/exefile exists, then its contents are the requested information.
  3. If the file /proc/self/as exists, then:
    1. open() the file.
    2. Allocate a buffer of, at least, sizeof(procfs_debuginfo) + _POSIX_PATH_MAX.
    3. Give that buffer as input to devctl(fd, DCMD_PROC_MAPDEBUG_BASE,....
    4. Cast the buffer to a procfs_debuginfo*.
    5. The requested information is at the path field of the procfs_debuginfo structure. Warning: For some reason, sometimes, QNX omits the first slash / of the file path. Prepend that / when needed.
    6. Clean up (close the file, free the buffer, etc.).
  4. Try the procedure in 3. with the file /proc/<PID>/as.
  5. Try dladdr(dlsym(RTLD_DEFAULT, "main"), &dlinfo) where dlinfo is a Dl_info structure whose dli_fname might contain the requested information.

I hope this helps.

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Here's some future-proof code for browsers that may lack escape/unescape(). Note that IE 9 and older don't support atob/btoa(), so you'd need to use custom base64 functions for them.

// Polyfill for escape/unescape
if( !window.unescape ){
    window.unescape = function( s ){
        return s.replace( /%([0-9A-F]{2})/g, function( m, p ) {
            return String.fromCharCode( '0x' + p );
        } );
    };
}
if( !window.escape ){
    window.escape = function( s ){
        var chr, hex, i = 0, l = s.length, out = '';
        for( ; i < l; i ++ ){
            chr = s.charAt( i );
            if( chr.search( /[A-Za-z0-9\@\*\_\+\-\.\/]/ ) > -1 ){
                out += chr; continue; }
            hex = s.charCodeAt( i ).toString( 16 );
            out += '%' + ( hex.length % 2 != 0 ? '0' : '' ) + hex;
        }
        return out;
    };
}

// Base64 encoding of UTF-8 strings
var utf8ToB64 = function( s ){
    return btoa( unescape( encodeURIComponent( s ) ) );
};
var b64ToUtf8 = function( s ){
    return decodeURIComponent( escape( atob( s ) ) );
};

A more comprehensive example for UTF-8 encoding and decoding can be found here: http://jsfiddle.net/47zwb41o/

git revert back to certain commit

http://www.kernel.org/pub/software/scm/git/docs/git-revert.html

using git revert <commit> will create a new commit that reverts the one you dont want to have.

You can specify a list of commits to revert.

An alternative: http://git-scm.com/docs/git-reset

git reset will reset your copy to the commit you want.

Is it possible to specify condition in Count()?

Depends what you mean, but the other interpretation of the meaning is where you want to count rows with a certain value, but don't want to restrict the SELECT to JUST those rows...

You'd do it using SUM() with a clause in, like this instead of using COUNT(): e.g.

SELECT SUM(CASE WHEN Position = 'Manager' THEN 1 ELSE 0 END) AS ManagerCount,
    SUM(CASE WHEN Position = 'CEO' THEN 1 ELSE 0 END) AS CEOCount
FROM SomeTable

Parsing JSON using C

Do you need to parse arbitrary JSON structures, or just data that's specific to your application. If the latter, you can make it a lot lighter and more efficient by not having to generate any hash table/map structure mapping JSON keys to values; you can instead just store the data directly into struct fields or whatever.

Changing the row height of a datagridview

you can do that on RowAdded Event :

_data_grid_view.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this._data_grid_view_RowsAdded);

private void _data_grid_view_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            _data_grid_view.Rows[e.RowIndex].Height = 42;
        }

when a row add to the dataGridView it just change it height to 42.

How to change colour of blue highlight on select box dropdown

Just found this whilst looking for a solution. I've only tested it FF 32.0.3

box-shadow: 0 0 10px 100px #fff inset;

Use a loop to plot n charts Python

We can create a for loop and pass all the numeric columns into it. The loop will plot the graphs one by one in separate pane as we are including plt.figure() into it.

import pandas as pd
import seaborn as sns
import numpy as np

numeric_features=[x for x in data.columns if data[x].dtype!="object"]
#taking only the numeric columns from the dataframe.

for i in data[numeric_features].columns:
    plt.figure(figsize=(12,5))
    plt.title(i)
    sns.boxplot(data=data[i])

Use FontAwesome or Glyphicons with css :before

This approach should be avoided. The default value for vertical-align is baseline. Changing the font-family of only the pseudo element will result in elements with differing fonts. Different fonts can have different font metrics and different baselines. In order for different baselines to align, the overall height of the element would have to increase. See this effect in action.

It is always better to have one element per font icon.

SQL Server Text type vs. varchar data type

TEXT is used for large pieces of string data. If the length of the field exceeed a certain threshold, the text is stored out of row.

VARCHAR is always stored in row and has a limit of 8000 characters. If you try to create a VARCHAR(x), where x > 8000, you get an error:

Server: Msg 131, Level 15, State 3, Line 1

The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)

These length limitations do not concern VARCHAR(MAX) in SQL Server 2005, which may be stored out of row, just like TEXT.

Note that MAX is not a kind of constant here, VARCHAR and VARCHAR(MAX) are very different types, the latter being very close to TEXT.

In prior versions of SQL Server you could not access the TEXT directly, you only could get a TEXTPTR and use it in READTEXT and WRITETEXT functions.

In SQL Server 2005 you can directly access TEXT columns (though you still need an explicit cast to VARCHAR to assign a value for them).

TEXT is good:

  • If you need to store large texts in your database
  • If you do not search on the value of the column
  • If you select this column rarely and do not join on it.

VARCHAR is good:

  • If you store little strings
  • If you search on the string value
  • If you always select it or use it in joins.

By selecting here I mean issuing any queries that return the value of the column.

By searching here I mean issuing any queries whose result depends on the value of the TEXT or VARCHAR column. This includes using it in any JOIN or WHERE condition.

As the TEXT is stored out of row, the queries not involving the TEXT column are usually faster.

Some examples of what TEXT is good for:

  • Blog comments
  • Wiki pages
  • Code source

Some examples of what VARCHAR is good for:

  • Usernames
  • Page titles
  • Filenames

As a rule of thumb, if you ever need you text value to exceed 200 characters AND do not use join on this column, use TEXT.

Otherwise use VARCHAR.

P.S. The same applies to UNICODE enabled NTEXT and NVARCHAR as well, which you should use for examples above.

P.P.S. The same applies to VARCHAR(MAX) and NVARCHAR(MAX) that SQL Server 2005+ uses instead of TEXT and NTEXT. You'll need to enable large value types out of row for them with sp_tableoption if you want them to be always stored out of row.

As mentioned above and here, TEXT is going to be deprecated in future releases:

The text in row option will be removed in a future version of SQL Server. Avoid using this option in new development work, and plan to modify applications that currently use text in row. We recommend that you store large data by using the varchar(max), nvarchar(max), or varbinary(max) data types. To control in-row and out-of-row behavior of these data types, use the large value types out of row option.

Converting characters to integers in Java

Character.getNumericValue(c)

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

How to pass value from <option><select> to form action

you can simply use your own code but add name for the select tag

<form method="POST" action="index.php?action=contact_agent&agent_id=">
    <select name="agent_id">
        <option value="1">Agent Homer</option>
        <option value="2">Agent Lenny</option>
        <option value="3">Agent Carl</option>
    </select>

then you can access it like this

String agent=request.getparameter("agent_id");

Change the On/Off text of a toggle button Android

In some cases, you need to force refresh the view in order to make it work.

toggleButton.setTextOff(textOff);
toggleButton.requestLayout();

toggleButton.setTextOn(textOn);
toggleButton.requestLayout();

ISO time (ISO 8601) in Python

Local to ISO 8601:

import datetime
datetime.datetime.now().isoformat()
>>> 2020-03-20T14:28:23.382748

UTC to ISO 8601:

import datetime
datetime.datetime.utcnow().isoformat()
>>> 2020-03-20T01:30:08.180856

Local to ISO 8601 without microsecond:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:30:43

UTC to ISO 8601 with TimeZone information (Python 3):

import datetime
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
>>> 2020-03-20T01:31:12.467113+00:00

UTC to ISO 8601 with Local TimeZone information without microsecond (Python 3):

import datetime
datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:31:43+13:00

Local to ISO 8601 with TimeZone information (Python 3):

import datetime
datetime.datetime.now().astimezone().isoformat()
>>> 2020-03-20T14:32:16.458361+13:00

Notice there is a bug when using astimezone() on utc time. This gives an incorrect result:

datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result

For Python 2, see and use pytz.

How to replace DOM element in place using Javascript?

A.replaceWith(span) - No parent needed

Generic form:

target.replaceWith(element)

Way better/cleaner than the previous method.

For your use case:

A.replaceWith(span)

Advanced usage

  1. You can pass multiple values (or use spread operator ...).
  2. Any string value will be added as a text element.

Examples:

// Initially [child1, target, child3]

target.replaceWith(span, "foo")     // [child1, span, "foo", child3]

const list = ["bar", span]
target.replaceWith(...list, "fizz")  // [child1, "bar", span, "fizz", child3]

Safely handling null target

If your target has a chance to be null, you can consider using the newish ?. optional chaining operator. Nothing will happen if target doesn't exist. Read more here.

target?.replaceWith(element)

Related DOM methods

  1. Read More - child.before and child.after
  2. Read More - parent.prepend and parent.append

Mozilla Docs

Supported Browsers - 94% Apr 2020

TensorFlow, "'module' object has no attribute 'placeholder'"

The error shows up because we are using tensorflow version 2 and the command is from version 1. So if we use:

tf.compat.v1.summary.(method_name)

It'll work

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

Could someone explain this for me - for (int i = 0; i < 8; i++)

The generic view of a loop is

for (initialization; condition; increment-decrement){}

The first part initializes the code. The second part is the condition that will continue to run the loop as long as it is true. The last part is what will be run after each iteration of the loop. The last part is typically used to increment or decrement a counter, but it doesn't have to.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.

This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.

Loop through list with both content and index

enumerate() makes this prettier:

for index, value in enumerate(S):
    print index, value

See here for more.