Programs & Examples On #Html help workshop

What is the equivalent of Java's System.out.println() in Javascript?

There isn't one, at least, not unless you are using a "developer" tool of some kind in your browser, e.g. Firebug in Firefox or the Developer tools in Safari. Then you can usually use console.log.

If I'm doing something in, say, an iOS device, I might add a <div id="debug" /> and then log to it.

Automatically pass $event with ng-click?

Add a $event to the ng-click, for example:

<button type="button" ng-click="saveOffer($event)" accesskey="S"></button>

Then the jQuery.Event was passed to the callback:

enter image description here

how to find host name from IP with out login to the host

If you are specifically looking for a Windows machine, try below command:

nbtstat -a 10.228.42.57

capture div into image using html2canvas

You can get the screenshot of a division and save it easily just using the below snippet. Here I'm used the entire body, you can choose the specific image/div elements just by putting the id/class names.

 html2canvas(document.getElementsByClassName("image-div")[0], {
  useCORS: true,
}).then(function (canvas) {
  var imageURL = canvas.toDataURL("image/png");
  let a = document.createElement("a");
  a.href = imageURL;
  a.download = imageURL;
  a.click();
});

How to find my realm file?

I have taken this one step further. I have created a swift file called RealmFunctions and in it, I have created this function

    import RealmSwift
    func realmAndPath() -> Realm {
        if dev {
            // location of my desktop
            return try! Realm(path: "/Users/slynch/Desktop/TestRealm.realm")
        } else {
            return try! Realm()
        }
    }

Now in my main view controller, I have a global boolean variable called dev

var dev: Bool = true // when in development mode
var dev: Bool = false // when I want to run on my device or upload to app stor.

Now, all I have to do in my code is

let realm = realmAndPath()

So when in development mode, I can find my realm database on my desktop and can open in Realm Browser.

Comparing two integer arrays in Java

If you know the arrays are of the same size it is provably faster to sort then compare

Arrays.sort(array1)
Arrays.sort(array2)
return Arrays.equals(array1, array2)

If you do not want to change the order of the data in the arrays then do a System.arraycopy first.

Reload content in modal (twitter bootstrap)

It will works for all version of twitterbootstrap

Javascript code :

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

links to modal are

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

pop up modal

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

.htaccess redirect all pages to new domain

The below answer could potentially cause an infinite redirect loop...

Here, this one redirects everything after the domain name on the URL to the exact same copy on the new domain URL:

RewriteEngine on 
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]
www.example.net/somepage.html?var=foo

redirects to:

www.newdomain.com/somepage.html?var=foo

Pass table as parameter into sql server UDF

you can do something like this

/* CREATE USER DEFINED TABLE TYPE */

CREATE TYPE StateMaster AS TABLE
(
 StateCode VARCHAR(2),
 StateDescp VARCHAR(250)
)
GO

/*CREATE FUNCTION WHICH TAKES TABLE AS A PARAMETER */

CREATE FUNCTION TableValuedParameterExample(@TmpTable StateMaster READONLY)
RETURNS  VARCHAR(250)
AS
BEGIN
 DECLARE @StateDescp VARCHAR(250)
 SELECT @StateDescp = StateDescp FROM @TmpTable
 RETURN @StateDescp
END
GO

/*CREATE STORED PROCEDURE WHICH TAKES TABLE AS A PARAMETER */

CREATE PROCEDURE TableValuedParameterExample_SP
(
@TmpTable StateMaster READONLY
)
AS
BEGIN
 INSERT INTO StateMst 
  SELECT * FROM @TmpTable
END
GO


BEGIN
/* DECLARE VARIABLE OF TABLE USER DEFINED TYPE */
DECLARE @MyTable StateMaster

/* INSERT DATA INTO TABLE TYPE */
INSERT INTO @MyTable VALUES('11','AndhraPradesh')
INSERT INTO @MyTable VALUES('12','Assam')

/* EXECUTE STORED PROCEDURE */
EXEC TableValuedParameterExample_SP @MyTable
GO

For more details check this link: http://sailajareddy-technical.blogspot.in/2012/09/passing-table-valued-parameter-to.html

How to cancel a pull request on github?

In the spirit of a DVCS (as in "Distributed"), you don't cancel something you have published:
Pull requests are essentially patches you have send (normally by email, here by GitHub webapp), and you wouldn't cancel an email either ;)

But since the GitHub Pull Request system also includes a discussion section, that would be there that you could voice your concern to the recipient of those changes, asking him/her to disregards 29 of your 30 commits.

Finally, remember:

  • a/ you have a preview section when making a pull request, allowing you to see the number of commits about to be included in it, and to review their diff.
  • b/ it is preferable to rebase the work you want to publish as pull request on top of the remote branch which will receive said work. Then you can make a pull request which could be safely applied in a fast forward manner by the recipient.

That being said, since January 2011 ("Refreshed Pull Request Discussions"), and mentioned in the answer above, you can close a pull request in the comments.
Look for that "Comment and Close" button at the bottom of the discussion page:

https://github-images.s3.amazonaws.com/blog/2011/pull-refresh.png

PHP array printing using a loop

foreach($array as $key => $value) echo $key, ' => ', $value;

How to remove all callbacks from a Handler?

If you don't have the Runnable references, on the first callback, get the obj of the message, and use removeCallbacksAndMessages() to remove all related callbacks.

Read a file one line at a time in node.js?

For such a simple operation there shouldn't be any dependency on third-party modules. Go easy.

var fs = require('fs'),
    readline = require('readline');

var rd = readline.createInterface({
    input: fs.createReadStream('/path/to/file'),
    output: process.stdout,
    console: false
});

rd.on('line', function(line) {
    console.log(line);
});

How to add colored border on cardview?

I solved this by putting two CardViews in a RelativeLayout. One with background of the border color and the other one with the image. (or whatever you wish to use)

Note the margin added to top and start for the second CardView. In my case I decided to use a 2dp thick border.

            <android.support.v7.widget.CardView
            android:id="@+id/user_thumb_rounded_background"
            android:layout_width="36dp"
            android:layout_height="36dp"
            app:cardCornerRadius="18dp"
            android:layout_marginEnd="6dp">

            <ImageView
                android:id="@+id/user_thumb_background"
                android:background="@color/colorPrimaryDark"
                android:layout_width="36dp"
                android:layout_height="36dp" />

        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            android:id="@+id/user_thumb_rounded"
            android:layout_width="32dp"
            android:layout_height="32dp"
            app:cardCornerRadius="16dp"
            android:layout_marginTop="2dp"
            android:layout_marginStart="2dp"
            android:layout_marginEnd="6dp">

        <ImageView
            android:id="@+id/user_thumb"
            android:src="@drawable/default_profile"
            android:layout_width="32dp"
            android:layout_height="32dp" />

        </android.support.v7.widget.CardView>

How do I make Visual Studio pause after executing a console application in debug mode?

Try to run the application with the Ctrl + F5 combination.

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

Here's a plugin which can list all event handlers for any given element/event:

$.fn.listHandlers = function(events, outputFunction) {
    return this.each(function(i){
        var elem = this,
            dEvents = $(this).data('events');
        if (!dEvents) {return;}
        $.each(dEvents, function(name, handler){
            if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
               $.each(handler, function(i,handler){
                   outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
               });
           }
        });
    });
};

Use it like this:

// List all onclick handlers of all anchor elements:
$('a').listHandlers('onclick', console.info);

// List all handlers for all events of all elements:
$('*').listHandlers('*', console.info);

// Write a custom output function:
$('#whatever').listHandlers('click',function(element,data){
    $('body').prepend('<br />' + element.nodeName + ': <br /><pre>' + data + '<\/pre>');
});

Src: (my blog) -> http://james.padolsey.com/javascript/debug-jquery-events-with-listhandlers/

How to set all elements of an array to zero or any same value?

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 };    // Will initialize all elements to 0
int myArray[10] = { 5 };    // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0
/************************************************************************************/
int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i;  // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
    myArray[i] = 5;
}
/************************************************************************************/
int myArray[10] = {[0 ... 9] = 5}; // This works only in GCC

HTML / CSS table with GRIDLINES

For internal gridlines, use the tag: td For external gridlines, use the tag: table

Char to int conversion in C

Since you're only converting one character, the function atoi() is overkill. atoi() is useful if you are converting string representations of numbers. The other posts have given examples of this. If I read your post correctly, you are only converting one numeric character. So, you are only going to convert a character that is the range 0 to 9. In the case of only converting one numeric character, your suggestion to subtract '0' will give you the result you want. The reason why this works is because ASCII values are consecutive (like you said). So, subtracting the ASCII value of 0 (ASCII value 48 - see ASCII Table for values) from a numeric character will give the value of the number. So, your example of c = c - '0' where c = '5', what is really happening is 53 (the ASCII value of 5) - 48 (the ASCII value of 0) = 5.

When I first posted this answer, I didn't take into consideration your comment about being 100% portable between different character sets. I did some further looking around around and it seems like your answer is still mostly correct. The problem is that you are using a char which is an 8-bit data type. Which wouldn't work with all character types. Read this article by Joel Spolsky on Unicode for a lot more information on Unicode. In this article, he says that he uses wchar_t for characters. This has worked well for him and he publishes his web site in 29 languages. So, you would need to change your char to a wchar_t. Other than that, he says that the character under value 127 and below are basically the same. This would include characters that represent numbers. This means the basic math you proposed should work for what you were trying to achieve.

Get rid of "The value for annotation attribute must be a constant expression" message

This is what a constant expression in Java looks like:

package com.mycompany.mypackage;

public class MyLinks {
  // constant expression
  public static final String GUESTBOOK_URL = "/guestbook";
}

You can use it with annotations as following:

import com.mycompany.mypackage.MyLinks;

@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
  // ...
}

android lollipop toolbar: how to hide/show the toolbar while scrolling?

The answer is straightforward. Just implement OnScrollListenerand hide/show your toolbar in the listener. For example, if you have listview/recyclerview/gridview, then follow the example.

In your MainActivity Oncreate method, initialize the toolbar.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
}

And then implement the OnScrollListener

public RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        boolean hideToolBar = false;
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (hideToolBar) {
                ((ActionBarActivity)getActivity()).getSupportActionBar().hide();
            } else {
                ((ActionBarActivity)getActivity()).getSupportActionBar().show();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (dy > 20) {
                hideToolBar = true;

            } else if (dy < -5) {
                hideToolBar = false;
            }
        }
    };

I got the idea from: https://stackoverflow.com/a/27063901/1079773

Add disabled attribute to input element using Javascript

$(element).prop('disabled', true); //true|disabled will work on all
$(element).attr('disabled', true); 
element.disabled = true;
element.setAttribute('disabled', true);

All of the above are perfectly valid solutions. Choose the one that fits your needs best.

how to stop a for loop

There are several ways to do it:

The simple Way: a sentinel variable

n = L[0][0]
m = len(A)
found = False
for i in range(m):
   if found:
      break
   for j in range(m):
     if L[i][j] != n: 
       found = True
       break

Pros: easy to understand Cons: additional conditional statement for every loop

The hacky Way: raising an exception

n = L[0][0]
m = len(A)

try:
  for x in range(3):
    for z in range(3):
     if L[i][j] != n: 
       raise StopIteration
except StopIteration:
   pass

Pros: very straightforward Cons: you use Exception outside of their semantic

The clean Way: make a function

def is_different_value(l, elem, size):
  for x in range(size):
    for z in range(size):
     if l[i][j] != elem: 
       return True
  return False

if is_different_value(L, L[0][0], len(A)):
  print "Doh"

pros: much cleaner and still efficient cons: yet feels like C

The pythonic way: use iteration as it should be

def is_different_value(iterable):
  first = iterable[0][0]
  for l in iterable:
    for elem in l:
       if elem != first: 
          return True
  return False

if is_different_value(L):
  print "Doh"

pros: still clean and efficient cons: you reinvdent the wheel

The guru way: use any():

def is_different_value(iterable):
  first = iterable[0][0]
  return  any(any((cell != first for cell in col)) for elem in iterable)):

if is_different_value(L):
  print "Doh"

pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you

How to prevent Screen Capture in Android

Just add this line:

getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);

Before your setContentView() method.

Cannot create PoolableConnectionFactory

I changed the driver version in pom.xml and helped me

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.2</version>
</dependency>

Finishing current activity from a fragment

Try this. There shouldn't be any warning...

            Activity thisActivity = getActivity();
            if (thisActivity != null) {
                startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
                thisActivity.finish();
            }

ImportError: No module named PyQt4

If you're using Anaconda to manage Python on your system, you can install it with:

$ conda install pyqt=4

Omit the =4 to install the most current version.

Answer from How to install PyQt4 in anaconda?

iPhone App Development on Ubuntu

I found one interesting site which seems pretty detailed on how you could setup a ubuntu for iPhone development. But it's a little old from November 2008 for the SDK 2.0.

Ubuntu 8.10 for iPhone open toolchain SDK2.0

The instructions also include something about the Android SDK/Emulator which you can leave out.

How to create border in UIButton?

Here's a UIButton subclass that supports the highlighted state animation without using images. It also updates the border color when the view's tint mode changes.

class BorderedButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)

        layer.borderColor = tintColor.CGColor
        layer.borderWidth = 1
        layer.cornerRadius = 5

        contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    override func tintColorDidChange() {
        super.tintColorDidChange()

        layer.borderColor = tintColor.CGColor
    }

    override var highlighted: Bool {
        didSet {
            let fadedColor = tintColor.colorWithAlphaComponent(0.2).CGColor

            if highlighted {
                layer.borderColor = fadedColor
            } else {
                layer.borderColor = tintColor.CGColor

                let animation = CABasicAnimation(keyPath: "borderColor")
                animation.fromValue = fadedColor
                animation.toValue = tintColor.CGColor
                animation.duration = 0.4
                layer.addAnimation(animation, forKey: "")
            }
        }
    }
}

Usage:

let button = BorderedButton(style: .System) //style .System is important

Appearance:

enter image description here

enter image description here

javac: invalid target release: 1.8

if you are going to step down, then change your project's source to 1.7 as well,

right click on your Project -> Properties -> Sources window and set 1.7 here" Jigar Joshi

Also go to the build-impl.xml and look for the property excludeFromCopy="${copylibs.excludes}" and delete this property on my code was at line 827 but I`ve seen it on other lines

for me was taking a code from MAC OS java 1.8 to WIN XP java 1.7

Extract a single (unsigned) integer from a string

If you just want to filter everything other than the numbers out, the easiest is to use filter_var:

$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);

How to draw rounded rectangle in Android UI?

Use CardView for Round Rectangle. CardView give more functionality like cardCornerRadius, cardBackgroundColor, cardElevation & many more. CardView make UI more suitable then Custom Round Rectangle drawable.

How to capture Curl output to a file?

For those of you want to copy the cURL output in the clipboard instead of outputting to a file, you can use pbcopy by using the pipe | after the cURL command.

Example: curl https://www.google.com/robots.txt | pbcopy. This will copy all the content from the given URL to your clipboard.

Pass parameter to EventHandler

If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:

myTimer.Elapsed += PlayMusicEvent;

where

public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
    music.player.Stop();
    System.Timers.Timer myTimer = (System.Timers.Timer)sender;
    myTimer.Stop();
}

But you need to think about where to store your note.

Truncate Decimal number not Round Off

What format are you wanting the output?

If you're happy with a string then consider the following C# code:

double num = 3.12345;
num.ToString("G3");

The result will be "3.12".

This link might be of use if you're using .NET. http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

I hope that helps....but unless you identify than language you are using and the format in which you want the output it is difficult to suggest an appropriate solution.

LaTeX Optional Arguments

All of the above show hard it can be to make a nice, flexible (or forbid an overloaded) function in LaTeX!!! (that TeX code looks like greek to me)

well, just to add my recent (albeit not as flexible) development, here's what I've recently used in my thesis doc, with

\usepackage{ifthen}  % provides conditonals...

Start the command, with the "optional" command set blank by default:

\newcommand {\figHoriz} [4] []  {

I then have the macro set a temporary variable, \temp{}, differently depending on whether or not the optional argument is blank. This could be extended to any passed argument.

\ifthenelse { \equal {#1} {} }  %if short caption not specified, use long caption (no slant)
    { \def\temp {\caption[#4]{\textsl{#4}}} }   % if #1 == blank
    { \def\temp {\caption[#1]{\textsl{#4}}} }   % else (not blank)

Then I run the macro using the \temp{} variable for the two cases. (Here it just sets the short-caption to equal the long caption if it wasn't specified by the user).

\begin{figure}[!]
    \begin{center}
        \includegraphics[width=350 pt]{#3}
        \temp   %see above for caption etc.
        \label{#2}
    \end{center}
\end{figure}
}

In this case I only check for the single, "optional" argument that \newcommand{} provides. If you were to set it up for, say, 3 "optional" args, you'd still have to send the 3 blank args... eg.

\MyCommand {first arg} {} {} {}

which is pretty silly, I know, but that's about as far as I'm going to go with LaTeX - it's just not that sensical once I start looking at TeX code... I do like Mr. Robertson's xparse method though, perhaps I'll try it...

Calculating arithmetic mean (one type of average) in Python

If you're using python >= 3.8, you can use the fmean function introduced in the statistics module which is part of the standard library:

>>> from statistics import fmean
>>> fmean([0, 1, 2, 3])
1.5

It's faster than the statistics.mean function, but it converts its data points to float beforehand, so it can be less accurate in some specific cases.

You can see its implementation here

What does the "__block" keyword mean?

Normally when you don't use __block, the block will copy(retain) the variable, so even if you modify the variable, the block has access to the old object.

NSString* str = @"hello";
void (^theBlock)() = ^void() {
    NSLog(@"%@", str);
};
str = @"how are you";
theBlock(); //prints @"hello"

In these 2 cases you need __block:

1.If you want to modify the variable inside the block and expect it to be visible outside:

__block NSString* str = @"hello";
void (^theBlock)() = ^void() {
    str = @"how are you";
};
theBlock();
NSLog(@"%@", str); //prints "how are you"

2.If you want to modify the variable after you have declared the block and you expect the block to see the change:

__block NSString* str = @"hello";
void (^theBlock)() = ^void() {
    NSLog(@"%@", str);
};
str = @"how are you";
theBlock(); //prints "how are you"

How to fix Invalid AES key length?

I was facing the same issue then i made my key 16 byte and it's working properly now. Create your key exactly 16 byte. It will surely work.

Case Statement Equivalent in R

I am using in those cases you are referring switch(). It looks like a control statement but actually, it is a function. The expression is evaluated and based on this value, the corresponding item in the list is returned.

switch works in two distinct ways depending whether the first argument evaluates to a character string or a number.

What follows is a simple string example which solves your problem to collapse old categories to new ones.

For the character-string form, have a single unnamed argument as the default after the named values.

newCat <- switch(EXPR = category,
       cat1   = catX,
       cat2   = catX,
       cat3   = catY,
       cat4   = catY,
       cat5   = catZ,
       cat6   = catZ,
       "not available")

c#: getter/setter

This means that the compiler defines a backing field at runtime. This is the syntax for auto-implemented properties.

More Information: Auto-Implemented Properties

How to put a tooltip on a user-defined function

Not a tooltip solution but an adequate workaround:

Start typing the UDF =MyUDF( then press CTRL + Shift + A and your function parameters will be displayed. So long as those parameters have meaningful names you at-least have a viable prompt

For example, this:

=MyUDF( + CTRL + Shift + A

Turns into this:

=MyUDF(sPath, sFileName)

Opening new window in HTML for target="_blank"

To open in a new windows with dimensions and everything, you will need to call a JavaScript function, as target="_blank" won't let you adjust sizes. An example would be:

<a href="http://www.facebook.com/sharer" onclick="window.open(this.href, 'mywin',
'left=20,top=20,width=500,height=500,toolbar=1,resizable=0'); return false;" >Share this</a>

Hope this helps you.

How to remove specific object from ArrayList in Java?

If you want to remove multiple objects that are matching to the property try this.

I have used following code to remove element from object array it helped me.

In general an object can be removed in two ways from an ArrayList (or generally any List), by index (remove(int)) and by object (remove(Object)).

some time for you arrayList.remove(index)or arrayList.remove(obj.get(index)) using these lines may not work try to use following code.

for (Iterator<DetailInbox> iter = detailInboxArray.iterator(); iter.hasNext(); ) {
    DetailInbox element = iter.next();
   if (element.isSelected()) {
      iter.remove();
   }
}

Clearing NSUserDefaults

All above answers are very relevant, but if someone still unable to reset the userdefaults for deleted app, then you can reset the content settings of you simulator, and it will work.enter image description here

How to remove unused C/C++ symbols with GCC and ld?

For GCC, this is accomplished in two stages:

First compile the data but tell the compiler to separate the code into separate sections within the translation unit. This will be done for functions, classes, and external variables by using the following two compiler flags:

-fdata-sections -ffunction-sections

Link the translation units together using the linker optimization flag (this causes the linker to discard unreferenced sections):

-Wl,--gc-sections

So if you had one file called test.cpp that had two functions declared in it, but one of them was unused, you could omit the unused one with the following command to gcc(g++):

gcc -Os -fdata-sections -ffunction-sections test.cpp -o test -Wl,--gc-sections

(Note that -Os is an additional compiler flag that tells GCC to optimize for size)

Swift convert unix time to date and time

In Swift 5

Using this implementation you just have to give epoch time as a parameter and you will the output as (1 second ago, 2 minutes ago, and so on).

func setTimestamp(epochTime: String) -> String {
    let currentDate = Date()
    let epochDate = Date(timeIntervalSince1970: TimeInterval(epochTime) as! TimeInterval)

    let calendar = Calendar.current

    let currentDay = calendar.component(.day, from: currentDate)
    let currentHour = calendar.component(.hour, from: currentDate)
    let currentMinutes = calendar.component(.minute, from: currentDate)
    let currentSeconds = calendar.component(.second, from: currentDate)

    let epochDay = calendar.component(.day, from: epochDate)
    let epochMonth = calendar.component(.month, from: epochDate)
    let epochYear = calendar.component(.year, from: epochDate)
    let epochHour = calendar.component(.hour, from: epochDate)
    let epochMinutes = calendar.component(.minute, from: epochDate)
    let epochSeconds = calendar.component(.second, from: epochDate)

    if (currentDay - epochDay < 30) {
        if (currentDay == epochDay) {
            if (currentHour - epochHour == 0) {
                if (currentMinutes - epochMinutes == 0) {
                    if (currentSeconds - epochSeconds <= 1) {
                        return String(currentSeconds - epochSeconds) + " second ago"
                    } else {
                        return String(currentSeconds - epochSeconds) + " seconds ago"
                    }

                } else if (currentMinutes - epochMinutes <= 1) {
                    return String(currentMinutes - epochMinutes) + " minute ago"
                } else {
                    return String(currentMinutes - epochMinutes) + " minutes ago"
                }
            } else if (currentHour - epochHour <= 1) {
                return String(currentHour - epochHour) + " hour ago"
            } else {
                return String(currentHour - epochHour) + " hours ago"
            }
        } else if (currentDay - epochDay <= 1) {
            return String(currentDay - epochDay) + " day ago"
        } else {
            return String(currentDay - epochDay) + " days ago"
        }
    } else {
        return String(epochDay) + " " + getMonthNameFromInt(month: epochMonth) + " " + String(epochYear)
    }
}


func getMonthNameFromInt(month: Int) -> String {
    switch month {
    case 1:
        return "Jan"
    case 2:
        return "Feb"
    case 3:
        return "Mar"
    case 4:
        return "Apr"
    case 5:
        return "May"
    case 6:
        return "Jun"
    case 7:
        return "Jul"
    case 8:
        return "Aug"
    case 9:
        return "Sept"
    case 10:
        return "Oct"
    case 11:
        return "Nov"
    case 12:
        return "Dec"
    default:
        return ""
    }
}

How to call?

setTimestamp(epochTime: time) and you'll get the desired output as a string.

How to use classes from .jar files?

Let's say we need to use the class Classname that is contained in the jar file org.example.jar

And your source is in the file mysource.java Like this:

import org.example.Classname;

public class mysource {
    public static void main(String[] argv) {
    ......
   }
}

First, as you see, in your code you have to import the classes. To do that you need import org.example.Classname;

Second, when you compile the source, you have to reference the jar file.

Please note the difference in using : and ; while compiling

  • If you are under a unix like operating system:

    javac -cp '.:org.example.jar' mysource.java
    
  • If you are under windows:

    javac -cp .;org.example.jar mysource.java
    

After this, you obtain the bytecode file mysource.class

Now you can run this :

  • If you are under a unix like operating system:

    java -cp '.:org.example.jar' mysource
    
  • If you are under windows:

    java -cp .;org.example.jar mysource
    

Open popup and refresh parent page on close popup

Following code will manage to refresh parent window post close :

function ManageQB_PopUp() {
            $(document).ready(function () {
                window.close();
            });
            window.onunload = function () {
                var win = window.opener;
                if (!win.closed) {
                    window.opener.location.reload();
                }
            };
        }

How do I resolve "Cannot find module" error using Node.js?

I was trying to publish my own package and then include it in another project. I had that issue because of how I've built the first module. Im using ES2015 export to create the module, e.g lets say the module looks like that:

export default function(who = 'world'){
    return `Hello ${who}`;
}

After compiled with Babel and before been published:

'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

exports.default = function () {
    var who = arguments.length <= 0 || arguments[0] === undefined ? 'world' : arguments[0];


    return 'Hello ' + who;
};

So after npm install module-name in another project (none ES2015) i had to do

var hello = require('module-name').default;

To actually got the package imported.

Hope that helps!

At least one JAR was scanned for TLDs yet contained no TLDs

For me I was getting the problem when deploying a geoserver WAR into tomcat 7

To fix it, I was on Java 7 and upgrading to Java 8.

This is running under a docker container. Tomcat 7.0.75 + Java 8 + Geos 2.10.2

how can I set visible back to true in jquery

Remove the visible="false" attribute and add a CSS class that is not visible by default. Then you should be able to reference the dropdown by the correct id, for example:

$("#ctl00_cphTest_test1").show();

Above ID you should serach for in the source of the rendered page in your browser.

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

Submitting the value of a disabled input field

Input elements have a property called disabled. When the form submits, just run some code like this:

var myInput = document.getElementById('myInput');
myInput.disabled = true;

How good is Java's UUID.randomUUID?

I'm not an expert, but I'd assume that enough smart people looked at Java's random number generator over the years. Hence, I'd also assume that random UUIDs are good. So you should really have the theoretical collision probability (which is about 1 : 3 × 10^38 for all possible UUIDs. Does anybody know how this changes for random UUIDs only? Is it 1/(16*4) of the above?)

From my practical experience, I've never seen any collisions so far. I'll probably have grown an astonishingly long beard the day I get my first one ;)

Remove all constraints affecting a UIView

Based on previous answers (swift 4)

You can use immediateConstraints when you don't want to crawl entire hierarchies.

extension UIView {
/**
 * Deactivates immediate constraints that target this view (self + superview)
 */
func deactivateImmediateConstraints(){
    NSLayoutConstraint.deactivate(self.immediateConstraints)
}
/**
 * Deactivates all constrains that target this view
 */
func deactiveAllConstraints(){
    NSLayoutConstraint.deactivate(self.allConstraints)
}
/**
 * Gets self.constraints + superview?.constraints for this particular view
 */
var immediateConstraints:[NSLayoutConstraint]{
    let constraints = self.superview?.constraints.filter{
        $0.firstItem as? UIView === self || $0.secondItem as? UIView === self
        } ?? []
    return self.constraints + constraints
}
/**
 * Crawls up superview hierarchy and gets all constraints that affect this view
 */
var allConstraints:[NSLayoutConstraint] {
    var view: UIView? = self
    var constraints:[NSLayoutConstraint] = []
    while let currentView = view {
        constraints += currentView.constraints.filter {
            return $0.firstItem as? UIView === self || $0.secondItem as? UIView === self
        }
        view = view?.superview
    }
    return constraints
}
}

How can I display an RTSP video stream in a web page?

Found a simple and working solution from VLC official documentation for web plugin

https://wiki.videolan.org/Documentation:WebPlugin/

Modified the code a little bit and got it working. Here is my code-

<embed type="application/x-vlc-plugin" pluginspage="http://www.videolan.org" autoplay="yes" loop="no" width="300" height="200" target="rtsp://10.20.50.15:554/0/888888:888888/main" />
<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" codebase="http://download.videolan.org/pub/videolan/vlc/last/win32/axvlc.cab" style="display:none;"></object>

Note: The above snippet uses the rtsp url format that is supported by my IP camera. So you need to get the same for your camera. You can get this information by consulting your camera vendor support. Also keep in mind that I tested it on Chrome (using an activeX plugin for Chrome) and other browsers (including mobile phone browsers) might not be supported.

POST Multipart Form Data using Retrofit 2.0 including image

Adding to the answer given by @insomniac. You can create a Map to put the parameter for RequestBody including image.

Code for Interface

public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser (@Header("Authorization") String authorization, @PartMap Map<String, RequestBody> map);
}

Code for Java class

File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));

Map<String, RequestBody> map = new HashMap<>();
map.put("file\"; filename=\"pp.png\" ", fbody);
map.put("FirstName", name);
map.put("Id", id);
Call<User> call = client.editUser(AZUtils.getToken(this), map);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response, Retrofit retrofit) 
{
    AZUtils.printObject(response.body());
}

@Override
public void onFailure(Throwable t) {
    t.printStackTrace();
 }
});

Fatal error: Class 'ZipArchive' not found in

For me work, first review

   php -m
   php -version

Later install the extension

apt-get update 
apt-get install php7.2-zip
systemctl restart apache2

MySQL 'Order By' - sorting alphanumeric correctly

This is a simple example.

SELECT HEX(some_col) h        
FROM some_table 
ORDER BY h

C# Reflection: How to get class reference from string?

A simple use:

Type typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName");

Sample:

Type dogClass = Type.GetType("Animals.Dog, Animals");

inherit from two classes in C#

Multitiple inheritance is not possible in C#, however it can be simulated using interfaces, see Simulated Multiple Inheritance Pattern for C#.

The basic idea is to define an interface for the members on class B that you wish to access (call it IB), and then have C inherit from A and implement IB by internally storing an instance of B, for example:

class C : A, IB
{
    private B _b = new B();

    // IB members
    public void SomeMethod()
    {
        _b.SomeMethod();
    }
}

There are also a couple of other alternaitve patterns explained on that page.

Why can't C# interfaces contain fields?

A lot has been said already, but to make it simple, here's my take. Interfaces are intended to have method contracts to be implemented by the consumers or classes and not to have fields to store values.

You may argue that then why properties are allowed? So the simple answer is - properties are internally defined as methods only.

What does the red exclamation point icon in Eclipse mean?

What I did was peculiar but somehow it fixed the problem. Pick any project and perform a fake edit of the build.properties file (e.g., add and remove a space and then save the file). Clean and rebuild the projects in your workspace.

Hope this solve some of your problems.

Comparing arrays in C#

Recommending SequenceEqual is ok, but thinking that it may ever be faster than usual for(;;) loop is too naive.

Here is the reflected code:

public static bool SequenceEqual<TSource>(this IEnumerable<TSource> first, 
    IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
    if (comparer == null)
    {
        comparer = EqualityComparer<TSource>.Default;
    }
    if (first == null)
    {
        throw Error.ArgumentNull("first");
    }
    if (second == null)
    {
        throw Error.ArgumentNull("second");
    }
    using (IEnumerator<TSource> enumerator = first.GetEnumerator())     
    using (IEnumerator<TSource> enumerator2 = second.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            if (!enumerator2.MoveNext() || !comparer.Equals(enumerator.Current, enumerator2.Current))
            {
                return false;
            }
        }
        if (enumerator2.MoveNext())
        {
            return false;
        }
    }
    return true;
}

As you can see it uses 2 enumerators and fires numerous method calls which seriously slow everything down. Also it doesn't check length at all, so in bad cases it can be ridiculously slower.

Compare moving two iterators with beautiful

if (a1[i] != a2[i])

and you will know what I mean about performance.

It can be used in cases where performance is really not so critical, maybe in unit test code, or in cases of some short list in rarely called methods.

How can I let a user download multiple files when a button is clicked?

You can either:

  1. Zip the selected files and return the one zipped file.
  2. Open multiple pop-ups each prompting for a download.

Note - option one is objectively better.

Edit Found an option three: https://stackoverflow.com/a/9425731/1803682

How to make cross domain request

Do a cross-domain AJAX call

Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Check the following for more information

Make cross-domain ajax JSONP request with jQuery

How to modify a specified commit?

If for some reason you don't like interactive editors, you can use git rebase --onto.

Say you want to modify Commit1. First, branch from before Commit1:

git checkout -b amending [commit before Commit1]

Second, grab Commit1 with cherry-pick:

git cherry-pick Commit1

Now, amend your changes, creating Commit1':

git add ...
git commit --amend -m "new message for Commit1"

And finally, after having stashed any other changes, transplant the rest of your commits up to master on top of your new commit:

git rebase --onto amending Commit1 master

Read: "rebase, onto the branch amending, all commits between Commit1 (non-inclusive) and master (inclusive)". That is, Commit2 and Commit3, cutting the old Commit1 out entirely. You could just cherry-pick them, but this way is easier.

Remember to clean up your branches!

git branch -d amending

How to change the color of text in javafx TextField?

The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.

.text-input {
    -fx-text-fill: -fx-text-inner-color;
    -fx-highlight-fill: derive(-fx-control-inner-background,-20%);
    -fx-highlight-text-fill: -fx-text-inner-color;
    -fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
    -fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: 0, 1;
    -fx-background-radius: 3, 2;
    -fx-cursor: text;
    -fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
    -fx-highlight-fill: -fx-accent;
    -fx-highlight-text-fill: white;
    -fx-background-color: 
        -fx-focus-color,
        -fx-control-inner-background,
        -fx-faint-focus-color,
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: -0.2, 1, -1.4, 3;
    -fx-background-radius: 3, 2, 4, 0;
    -fx-prompt-text-fill: transparent;
}

Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:

textField.setStyle("-fx-text-inner-color: red;");

Resize to fit image in div, and center horizontally and vertically

SOLUTION

<style>
.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
    background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;

}

</style>

<div class='container'>
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>

Adding custom radio buttons in android

I have updated accepted answer and removed unnecessary things.

I have created XML for following image.

enter image description here

Your XML code for RadioButton will be:

<RadioGroup
        android:id="@+id/daily_weekly_button_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="@dimen/_80sdp"
            android:gravity="center"
            android:layout_height="wrap_content"
            android:background="@drawable/radio_flat_selector"
            android:button="@android:color/transparent"
            android:checked="true"
            android:paddingLeft="@dimen/_16sdp"
            android:paddingTop="@dimen/_3sdp"
            android:paddingRight="@dimen/_16sdp"
            android:paddingBottom="@dimen/_3sdp"
            android:text="Daily"
            android:textColor="@color/radio_flat_text_selector" />

        <RadioButton
            android:id="@+id/radio1"
            android:gravity="center"
            android:layout_width="@dimen/_80sdp"
            android:layout_height="wrap_content"
            android:background="@drawable/radio_flat_selector"
            android:button="@android:color/transparent"
            android:paddingLeft="@dimen/_16sdp"
            android:paddingTop="@dimen/_3sdp"
            android:paddingRight="@dimen/_16sdp"
            android:paddingBottom="@dimen/_3sdp"
            android:text="Weekly"
            android:textColor="@color/radio_flat_text_selector" />

</RadioGroup>

radio_flat_selector.xml for background selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/radio_flat_selected" android:state_checked="true" />
    <item android:drawable="@drawable/radio_flat_regular" />
</selector>

radio_flat_selected.xml for selected button:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="1dp"
        />
    <solid android:color="@color/colorAccent" />
    <stroke
        android:width="1dp"
        android:color="@color/colorAccent" />
</shape>

radio_flat_regular.xml for regular selector:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="1dp" />
    <solid android:color="#fff" />
    <stroke
        android:width="1dp"
        android:color="@color/colorAccent" />
</shape>

All the above 3 file code will be in drawable/ folder.

Now we also need Text Color Selector to change color of text accordingly.

radio_flat_text_selector.xml for text color selector

(Use color/ folder for this file.)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorAccent" android:state_checked="false" />
    <item android:color="@color/colorWhite" android:state_checked="true" />
</selector>

Note: I refereed many answers for this type of solution but didn't found good solution so I make it.

Hope it will be helpful to you.

Thanks.

How to mount host volumes into docker containers in Dockerfile during build

There is a way to mount a volume during a build, but it doesn't involve Dockerfiles.

The technique would be to create a container from whatever base you wanted to use (mounting your volume(s) in the container with the -v option), run a shell script to do your image building work, then commit the container as an image when done.

Not only will this leave out the excess files you don't want (this is good for secure files as well, like SSH files), it also creates a single image. It has downsides: the commit command doesn't support all of the Dockerfile instructions, and it doesn't let you pick up when you left off if you need to edit your build script.

UPDATE:

For example,

CONTAINER_ID=$(docker run -dit ubuntu:16.04)
docker cp build.sh $CONTAINER_ID:/build.sh
docker exec -t $CONTAINER_ID /bin/sh -c '/bin/sh /build.sh'
docker commit $CONTAINER_ID $REPO:$TAG
docker stop $CONTAINER_ID

curl usage to get header

curl --head https://www.example.net

I was pointed to this by curl itself; when I issued the command with -X HEAD, it printed:

Warning: Setting custom HTTP method to HEAD with -X/--request may not work the 
Warning: way you want. Consider using -I/--head instead.

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

The issue here is that you just Added the reference to System.IO.Compression it is missing the reference to System.IO.Compression.Filesystem.dll

And you need to do it on .net 4.5 or later (because it doesn't exist on older versions).

I just posted a script on TechNet Maybe somebody would find it useful it requires .net 4.5 or 4.7

https://gallery.technet.microsoft.com/scriptcenter/Create-a-Zip-file-from-a-b23a7530

Codeigniter $this->db->get(), how do I return values for a specific row?

you can use row() instead of result().

$this->db->where('id', '3');
$q = $this->db->get('my_users_table')->row();

How to detect if URL has changed after hash in JavaScript

use this code

window.onhashchange = function() { 
     //code  
}

with jQuery

$(window).bind('hashchange', function() {
     //code
});

Should image size be defined in the img tag height/width attributes or in CSS?

While it's ok to use inline styles, your purposes may better be served by including an external CSS file on the page. This way you could define a class of image (i.e. 'Thumbnail', 'Photo', 'Large', etc) and assign it a constant size. This will help when you end up with images requiring the same placement across multiple pages.

Like this:

In your header:
<link type="text/css" rel="stylesheet" href="css/style.css" />

Your HTML:
<img class="thumbnail" src="images/academia_vs_business.png" alt="" />

In css/style.css:
img.thumbnail {
   width: 75px;
   height: 75px;
}

If you'd like to use inline styles though, it's probably best to set the width and height using the style attribute for the sake of readability.

How can I reset eclipse to default settings?

All the setting are stored in .metadata file in your workspace delete this and you are good to go

How to add a line to a multiline TextBox?

Try this

textBox1.Text += "SomeText\r\n" 

you can also try

textBox1.Text += "SomeText" + Environment.NewLine;

Where \r is carriage return and \n is new line

How to set String's font size, style in Java using the Font class?

Font myFont = new Font("Serif", Font.BOLD, 12);, then use a setFont method on your components like

JButton b = new JButton("Hello World");
b.setFont(myFont);

Need a query that returns every field that contains a specified letter

try this

Select * From Table
Where field like '%' + ltrValue1 + '%'
  And field like '%' + ltrValue2 + '%'
... etc.

and be prepared for a table scan as this functionality cannot use any existing indices

jquery function val() is not equivalent to "$(this).value="?

One thing you can do is this:

$(this)[0].value = "Something";

This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.

Parse JSON String into a Particular Object Prototype in JavaScript

I like adding an optional argument to the constructor and calling Object.assign(this, obj), then handling any properties that are objects or arrays of objects themselves:

constructor(obj) {
    if (obj != null) {
        Object.assign(this, obj);
        if (this.ingredients != null) {
            this.ingredients = this.ingredients.map(x => new Ingredient(x));
        }
    }
}

How to make a JFrame button open another JFrame class in Netbeans?

Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)

btnLogin.addActionListener(new ActionListener() 
{
    public void actionPerformed(ActionEvent e) {
        this.setVisible(false);
        new FrmMain().setVisible(true); // Main Form to show after the Login Form..
    }
});

How do I get the XML SOAP request of an WCF Web service request?

I am using below solution for IIS hosting in ASP.NET compatibility mode. Credits to Rodney Viana's MSDN blog.

Add following to your web.config under appSettings:

<add key="LogPath" value="C:\\logpath" />
<add key="LogRequestResponse" value="true" />

Replace your global.asax.cs with below (also fix namespace name):

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

using System.Text;
using System.IO;
using System.Configuration;

namespace Yournamespace
{
    public class Global : System.Web.HttpApplication
    {
        protected static bool LogFlag;
        protected static string fileNameBase;
        protected static string ext = "log";

        // One file name per day
        protected string FileName
        {
            get
            {
                return String.Format("{0}{1}.{2}", fileNameBase, DateTime.Now.ToString("yyyy-MM-dd"), ext);
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            LogFlag = bool.Parse(ConfigurationManager.AppSettings["LogRequestResponse"].ToString());
            fileNameBase = ConfigurationManager.AppSettings["LogPath"].ToString() + @"\C5API-";   
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (LogFlag) 
            {                
                // Creates a unique id to match Rquests with Responses
                string id = String.Format("Id: {0} Uri: {1}", Guid.NewGuid(), Request.Url);
                FilterSaveLog input = new FilterSaveLog(HttpContext.Current, Request.Filter, FileName, id);
                Request.Filter = input;
                input.SetFilter(false);
                FilterSaveLog output = new FilterSaveLog(HttpContext.Current, Response.Filter, FileName, id);
                output.SetFilter(true);
                Response.Filter = output;
            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }

    class FilterSaveLog : Stream
    {

        protected static string fileNameGlobal = null;
        protected string fileName = null;

        protected static object writeLock = null;
        protected Stream sinkStream;
        protected bool inDisk;
        protected bool isClosed;
        protected string id;
        protected bool isResponse;
        protected HttpContext context;

        public FilterSaveLog(HttpContext Context, Stream Sink, string FileName, string Id)
        {
            // One lock per file name
            if (String.IsNullOrWhiteSpace(fileNameGlobal) || fileNameGlobal.ToUpper() != fileNameGlobal.ToUpper())
            {
                fileNameGlobal = FileName;
                writeLock = new object();
            }
            context = Context;
            fileName = FileName;
            id = Id;
            sinkStream = Sink;
            inDisk = false;
            isClosed = false;
        }

        public void SetFilter(bool IsResponse)
        {


            isResponse = IsResponse;
            id = (isResponse ? "Reponse " : "Request ") + id;

            //
            // For Request only read the incoming stream and log it as it will not be "filtered" for a WCF request
            //
            if (!IsResponse)
            {
                AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
                AppendToFile(id);

                if (context.Request.InputStream.Length > 0)
                {
                    context.Request.InputStream.Position = 0;
                    byte[] rawBytes = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(rawBytes, 0, rawBytes.Length);
                    context.Request.InputStream.Position = 0;

                    AppendToFile(rawBytes);
                }
                else
                {
                    AppendToFile("(no body)");
                }
            }

        }

        public void AppendToFile(string Text)
        {
            byte[] strArray = Encoding.UTF8.GetBytes(Text);
            AppendToFile(strArray);

        }

        public void AppendToFile(byte[] RawBytes)
        {
            bool myLock = System.Threading.Monitor.TryEnter(writeLock, 100);


            if (myLock)
            {
                try
                {

                    using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        stream.Position = stream.Length;
                        stream.Write(RawBytes, 0, RawBytes.Length);
                        stream.WriteByte(13);
                        stream.WriteByte(10);

                    }

                }
                catch (Exception ex)
                {
                    string str = string.Format("Unable to create log. Type: {0} Message: {1}\nStack:{2}", ex, ex.Message, ex.StackTrace);
                    System.Diagnostics.Debug.WriteLine(str);
                    System.Diagnostics.Debug.Flush();


                }
                finally
                {
                    System.Threading.Monitor.Exit(writeLock);


                }
            }


        }


        public override bool CanRead
        {
            get { return sinkStream.CanRead; }
        }

        public override bool CanSeek
        {
            get { return sinkStream.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return sinkStream.CanWrite; }
        }

        public override long Length
        {
            get
            {
                return sinkStream.Length;
            }
        }

        public override long Position
        {
            get { return sinkStream.Position; }
            set { sinkStream.Position = value; }
        }

        //
        // For WCF this code will never be reached
        //
        public override int Read(byte[] buffer, int offset, int count)
        {
            int c = sinkStream.Read(buffer, offset, count);
            return c;
        }

        public override long Seek(long offset, System.IO.SeekOrigin direction)
        {
            return sinkStream.Seek(offset, direction);
        }

        public override void SetLength(long length)
        {
            sinkStream.SetLength(length);
        }

        public override void Close()
        {

            sinkStream.Close();
            isClosed = true;
        }

        public override void Flush()
        {

            sinkStream.Flush();
        }

        // For streamed responses (i.e. not buffered) there will be more than one Response (but the id will match the Request)
        public override void Write(byte[] buffer, int offset, int count)
        {
            sinkStream.Write(buffer, offset, count);
            AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
            AppendToFile(id);
            AppendToFile(buffer);
        }

    }
}

It should create log file in the folder LogPath with request and response XML.

Remove NaN from pandas series

If you have a pandas serie with NaN, and want to remove it (without loosing index):

serie = serie.dropna()

# create data for example
data = np.array(['g', 'e', 'e', 'k', 's']) 
ser = pd.Series(data)
ser.replace('e', np.NAN)
print(ser)

0      g
1    NaN
2    NaN
3      k
4      s
dtype: object

# the code
ser = ser.dropna()
print(ser)

0    g
3    k
4    s
dtype: object

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

Check if password you are using is correct one by running below command

keytool -keypasswd -new temp123 -keystore awsdemo-keystore.jks -storepass temp123 -alias movie-service -keypass changeit

If you are getting below error then your password is wrong

keytool error: java.security.UnrecoverableKeyException: Cannot recover key

SQL query for getting data for last 3 months

I'd use datediff, and not care about format conversions:

SELECT *
FROM   mytable
WHERE  DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3

Conditional Count on a field

IIF is not a standard SQL construct, but if it's supported by your database, you can achieve a more elegant statement producing the same result:

SELECT JobId, JobName,

COUNT(IIF (Priority=1, 1, NULL)) AS Priority1,
COUNT(IIF (Priority=2, 1, NULL)) AS Priority2,
COUNT(IIF (Priority=3, 1, NULL)) AS Priority3,
COUNT(IIF (Priority=4, 1, NULL)) AS Priority4,
COUNT(IIF (Priority=5, 1, NULL)) AS Priority5

FROM TableName
GROUP BY JobId, JobName

GitHub: invalid username or password

Just Try this:

# git remote set-url origin [email protected]:username/repository

Hope this help

R cannot be resolved - Android error

I tried most of the options on this thread (and many others) and nothing worked for me. Finally this one worked so I thought to share it with everyone...

I have multiple versions of Eclipse IDE on my machine (because I also work on non Android related projects). Accidentally I created my Android project using a workspace that was being used by another (non-Android) version of Eclipse. Due to this I guess something weird was going on and my R.java was never getting generated!

To fix this, all I did is created a new workspace and magically R.java started getting generated and everything went smoothly...

So while you are trying all other options, give this one a shot too. And hope it'll work for you...

Python - abs vs fabs

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In [2]: from math import fabs

In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop

In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop

So it seems abs() only has slight speed advantage over fabs() for integers. For floats, abs() and fabs() demonstrate similar speed.


In addition to what @aix has said, one more thing to consider is the speed difference:

In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop

In [2]: import math

In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop

So abs() is faster than math.fabs().

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

How to reset AUTO_INCREMENT in MySQL?

Simply like this:

ALTER TABLE tablename AUTO_INCREMENT = value;

reference: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Javascript Object push() function

I assume that REALLY you get object from server and want to get object on output

Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])

_x000D_
_x000D_
var data = { 5: { "ID": "0", "Status": "Valid" } }; // some OBJECT from server response_x000D_
_x000D_
data = { ...data,_x000D_
  0: { "ID": "1", "Status": "Valid" },_x000D_
  1: { "ID": "2", "Status": "Invalid" },_x000D_
  2: { "ID": "3", "Status": "Valid" }_x000D_
}_x000D_
_x000D_
// solution 1: where output is sorted filtred array_x000D_
let arr=Object.keys(data).filter(k=> data[k].Status!='Invalid').map(k=>data[k]).sort((a,b)=>+a.ID-b.ID);_x000D_
  _x000D_
// solution2: where output is filtered object_x000D_
Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])_x000D_
  _x000D_
// show_x000D_
console.log('Object',data);_x000D_
console.log('Array ',arr);
_x000D_
_x000D_
_x000D_

Link a .css on another folder

_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
_x000D_
.tree-view-com ul li {_x000D_
  position: relative;_x000D_
  list-style: none;_x000D_
}_x000D_
.tree-view-com .tree-view-child > li{_x000D_
  padding-bottom: 30px;_x000D_
}_x000D_
.tree-view-com .tree-view-child > li:last-of-type{_x000D_
  padding-bottom: 0px;_x000D_
}_x000D_
 _x000D_
.tree-view-com ul li a .c-icon {_x000D_
  margin-right: 10px;_x000D_
  position: relative;_x000D_
  top: 2px;_x000D_
}_x000D_
.tree-view-com ul > li > ul {_x000D_
  margin-top: 20px;_x000D_
  position: relative;_x000D_
}_x000D_
.tree-view-com > ul > li:before {_x000D_
  content: "";_x000D_
  border-left: 1px dashed #ccc;_x000D_
  position: absolute;_x000D_
  height: calc(100% - 30px - 5px);_x000D_
  z-index: 1;_x000D_
  left: 8px;_x000D_
  top: 30px;_x000D_
}_x000D_
.tree-view-com > ul > li > ul > li:before {_x000D_
  content: "";_x000D_
  border-top: 1px dashed #ccc;_x000D_
  position: absolute;_x000D_
  width: 25px;_x000D_
  left: -32px;_x000D_
  top: 12px;_x000D_
}
_x000D_
<div class="tree-view-com">_x000D_
    <ul class="tree-view-parent">_x000D_
        <li>_x000D_
            <a href=""><i class="fa fa-folder c-icon c-icon-list" aria-hidden="true"></i> folder</a>_x000D_
            <ul class="tree-view-child">_x000D_
                <li>_x000D_
                    <a href="" class="document-title">_x000D_
                        <i class="fa fa-folder c-icon" aria-hidden="true"></i>_x000D_
                        sub folder 1_x000D_
                    </a>_x000D_
                </li>_x000D_
                <li>_x000D_
                    <a href="" class="document-title">_x000D_
                        <i class="fa fa-folder c-icon" aria-hidden="true"></i>_x000D_
                        sub folder 2_x000D_
                    </a>_x000D_
                </li>_x000D_
                <li>_x000D_
                    <a href="" class="document-title">_x000D_
                        <i class="fa fa-folder c-icon" aria-hidden="true"></i>_x000D_
                        sub folder 3_x000D_
                    </a>_x000D_
                </li>_x000D_
            </ul>_x000D_
        </li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make the HTML link activated by clicking on the <li>?

Just to throw this option out there:

<ul id="menu">
    <a href="#"><li>Something1</li></a>
    <a href="#"><li>Something2</li></a>
    <a href="#"><li>Something3</li></a>
    <a href="#"><li>Something4</li></a>
</ul>

This is the style I use in my menus, it makes the list item itself a hyperlink (similar to how one would make an image a link).
For styling, I usually apply something like this:

nav ul a {
    color: inherit;
    text-decoration: none;
}

I can then apply whatever styling to the <li> that I wish.

Note: Validators will complain about this method, but if you're like me and do not base your life around them, this should work just fine.

File input 'accept' attribute - is it useful?

It's been a few years, and Chrome at least makes use of this attribute. This attribute is very useful from a usability standpoint as it will filter out the unnecessary files for the user, making their experience smoother. However, the user can still select "all files" from the type (or otherwise bypass the filter), thus you should always validate the file where it is actually used; If you're using it on the server, validate it there before using it. The user can always bypass any client-side scripting.

How to make div fixed after you scroll to that div?

Adding on to @Alexandre Aimbiré's answer - sometimes you may need to specify z-index:1 to have the element always on top while scrolling. Like this:

position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
z-index: 1;

How to map atan2() to degrees 0-360

theta_rad = Math.Atan2(y,x);
if(theta_rad < 0)
  theta_rad = theta_rad + 2 * Math.PI;    //if neg., add 2 PI to it
theta_deg = (theta_rad/M_PI*180) ;        //convert from radian to degree

//or
theta_rad = Math.Atan2(y,x);
theta_rad = (theta_rad < 0) ? theta_rad + 2 * Math.PI : theta_rad;
theta_deg = (theta_rad/M_PI*180) ;

-1 deg becomes (-1 + 360) = 359 deg
-179 deg becomes (-179 + 360) = 181 deg

What is an abstract class in PHP?

An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.

There is good explanation of that here.

Best way to define private methods for a class in Objective-C

You could try defining a static function below or above your implementation that takes a pointer to your instance. It will be able to access any of your instances variables.

//.h file
@interface MyClass : Object
{
    int test;
}
- (void) someMethod: anArg;

@end


//.m file    
@implementation MyClass

static void somePrivateMethod (MyClass *myClass, id anArg)
{
    fprintf (stderr, "MyClass (%d) was passed %p", myClass->test, anArg);
}


- (void) someMethod: (id) anArg
{
    somePrivateMethod (self, anArg);
}

@end

Select random lines from a file

seq 1 100 | python3 -c 'print(__import__("random").choice(__import__("sys").stdin.readlines()))'

Fixing a systemd service 203/EXEC failure (no such file or directory)

If that is a copy/paste from your script, you've permuted this line:

#!/usr/env/bin bash

There's no #!/usr/env/bin, you meant #!/usr/bin/env.

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1 is null or ConfigurationManager.AppSettings.Get("Url") is returning null.

json_encode() escaping forward slashes

On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -

my expected:

http://localhost/api/v1/admin/logs/testLog.log

would be encoded to:

http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log

If you need to do a comparison, transforming the url using:

addcslashes($url, '/')

allowed for the proper output during my comparisons.

Runnable with a parameter?

Since Java 8, the best answer is to use Consumer<T>:

https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html

It's one of the functional interfaces, which means you can call it as a lambda expression:

void doSomething(Consumer<String> something) {
    something.accept("hello!");
}

...

doSomething( (something) -> System.out.println(something) )

...

Where is SQL Profiler in my SQL Server 2008?

Also ensure that "client tools" are selected in the install options. However if SQL Managment Studio 2008 exists then it is likely that you installed the express edition.

How to submit an HTML form without redirection

You need Ajax to make it happen. Something like this:

$(document).ready(function(){
    $("#myform").on('submit', function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var contact = $("#contact").val();

        var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
        if(name=='' || email=='' || password=='' || contact=='')
        {
            alert("Please fill in all fields");
        }
        else
        {
            // Ajax code to submit form.
            $.ajax({
                type: "POST",
                url: "ajaxsubmit.php",
                data: dataString,
                cache: false,
                success: function(result){
                    alert(result);
                }
           });
        }
        return false;
    });
});

How can I draw vertical text with CSS cross-browser?

If you use Bootstrap 3, you can use one of it's mixins:

.rotate(degrees);

Example:

.rotate(-90deg);

How can I add JAR files to the web-inf/lib folder in Eclipse?

  1. add the jar to WEB-INF/lib from file structure
  2. refresh the project, you should see the jar now visible under the WEB-INF/lib folder.

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

Example #1:

class A{
 void met(){
   Class.forName("com.example.Class1");
 }
}

If com/example/Class1 doesn't exist in any of the classpaths, then It throws ClassNotFoundException.

Example #2:

Class B{
  void met(){
   com.example.Class2 c = new com.example.Class2();
 }
}

If com/example/Class2 existed while compiling B, but not found while execution, then It throws NoClassDefFoundError.

Both are run time exceptions.

Convert JavaScript string in dot notation into an object reference

Note if you're already using Lodash you can use the property or get functions:

var obj = { a: { b: '1', c: '2' } };
_.property('a.b')(obj); // => 1
_.get(obj, 'a.b'); // => 1

Underscore also has a property function but it doesn't support dot notation.

ImportError: No module named site on Windows

Locate site.py and add its path in PYTHONPATH. This will solve your problem.

Example using Hyperlink in WPF

Hope this help someone as well.

using System.Diagnostics;
using System.Windows.Documents;

namespace Helpers.Controls
{
    public class HyperlinkEx : Hyperlink
    {
        protected override void OnClick()
        {
            base.OnClick();

            Process p = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = this.NavigateUri.AbsoluteUri
                }
            };
            p.Start();
        }
    }
}

Removing element from array in component state

Here is a simple way to do it:

removeFunction(key){
  const data = {...this.state.data}; //Duplicate state.
  delete data[key];                  //remove Item form stateCopy.
  this.setState({data});             //Set state as the modify one.
}

Hope it Helps!!!

How to call a asp:Button OnClick event using JavaScript?

If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

How do I use the Tensorboard callback of Keras?

Change

keras.callbacks.TensorBoard(log_dir='/Graph', histogram_freq=0,  
          write_graph=True, write_images=True)

to

tbCallBack = keras.callbacks.TensorBoard(log_dir='Graph', histogram_freq=0,  
          write_graph=True, write_images=True)

and set your model

tbCallback.set_model(model)

Run in your terminal

tensorboard  --logdir Graph/

Python threading.timer - repeat function every 'n' seconds

This is an alternate implementation using function instead of class. Inspired by @Andrew Wilkins above.

Because wait is more accurate than sleep ( it takes function runtime into account ):

import threading

PING_ON = threading.Event()

def ping():
  while not PING_ON.wait(1):
    print("my thread %s" % str(threading.current_thread().ident))

t = threading.Thread(target=ping)
t.start()

sleep(5)
PING_ON.set()

How can I login to a website with Python?

Let me try to make it simple, suppose URL of the site is www.example.com and you need to sign up by filling username and password, so we go to the login page say http://www.example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like

 <form name="loginform" method="post" action="userinfo.php">

now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script

import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
          'password': 'pass'}

r = requests.post(url, data=values)
print r.content

I Hope that this helps someone somewhere someday.

Is there any kind of hash code function in JavaScript?

In addition to eyelidlessness's answer, here is a function that returns a reproducible, unique ID for any object:

var uniqueIdList = [];
function getConstantUniqueIdFor(element) {
    // HACK, using a list results in O(n), but how do we hash e.g. a DOM node?
    if (uniqueIdList.indexOf(element) < 0) {
        uniqueIdList.push(element);
    }
    return uniqueIdList.indexOf(element);
}

As you can see it uses a list for look-up which is very inefficient, however that's the best I could find for now.

Laravel-5 how to populate select box from database with id value and name value

For Laravel 5 :

$items = Items::lists('name', 'id');

Push an item onto the beginning of the collection.

$items->prepend($value, $key = null);

How can I find the number of years between two dates?

tl;dr

ChronoUnit.YEARS.between( 
    LocalDate.of( 2010 , 1 , 1 ) , 
    LocalDate.now( ZoneId.of( "America/Montreal" ) ) 
)

java.time

The old date-time classes really are bad, so bad that both Sun & Oracle agreed to supplant them with the java.time classes. If you do any significant work at all with date-time values, adding a library to your project is worthwhile. The Joda-Time library was highly successful and recommended, but is now in maintenance mode. The team advises migration to the java.time classes.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

LocalDate start = LocalDate.of( 2010 , 1 , 1 ) ;
LocalDate stop = LocalDate.now( ZoneId.of( "America/Montreal" ) );
long years = java.time.temporal.ChronoUnit.YEARS.between( start , stop );

Dump to console.

System.out.println( "start: " + start + " | stop: " + stop + " | years: " + years ) ;

start: 2010-01-01 | stop: 2016-09-06 | years: 6


Table of all date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

What is the purpose of mvnw and mvnw.cmd files?

Command mvnw uses Maven that is by default downloaded to ~/.m2/wrapper on the first use.

URL with Maven is specified in each project at .mvn/wrapper/maven-wrapper.properties:

distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

To update or change Maven version invoke the following (remember about --non-recursive for multi-module projects):

./mvnw io.takari:maven:wrapper -Dmaven=3.3.9 

or just modify .mvn/wrapper/maven-wrapper.properties manually.

To generate wrapper from scratch using Maven (you need to have it already in PATH run:

mvn io.takari:maven:wrapper -Dmaven=3.3.9 

Safari 3rd party cookie iframe trick no longer working?

I have also been suffering from this problem, but finally got the solution, Initially directly the load the iframe url in browser like small popup then only access the session values inside the iframe.

Add attribute 'checked' on click jquery

If .attr() isn't working for you (especially when checking and unchecking boxes in succession), use .prop() instead of .attr().

How to set <Text> text to upper case in react native

@Cherniv Thanks for the answer

<Text style={{}}> {'Test'.toUpperCase()} </Text>

How to compare DateTime without time via LINQ?

Try

var q = db.Games.Where(t => t.StartDate.Date >= DateTime.Now.Date).OrderBy(d => d.StartDate);

How can I use pickle to save a dict?

# Save a dictionary into a pickle file.
import pickle

favorite_color = {"lion": "yellow", "kitty": "red"}  # create a dictionary
pickle.dump(favorite_color, open("save.p", "wb"))  # save it into a file named save.p

# -------------------------------------------------------------
# Load the dictionary back from the pickle file.
import pickle

favorite_color = pickle.load(open("save.p", "rb"))
# favorite_color is now {"lion": "yellow", "kitty": "red"}

How to create table using select query in SQL Server?

select <column list> into <dest. table> from <source table>;

You could do this way.

SELECT windows_release, windows_service_pack_level, 
       windows_sku, os_language_version
into   new_table_name
FROM   sys.dm_os_windows_info OPTION (RECOMPILE);

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

How to use FormData in react-native?

Usage of formdata in react-native

I have used react-native-image-picker to select photo. In my case after choosing the photp from mobile. I'm storing it's info in component state. After, I'm sending POST request using fetch like below

const profile_pic = {
  name: this.state.formData.profile_pic.fileName,
  type: this.state.formData.profile_pic.type,
  path: this.state.formData.profile_pic.path,
  uri: this.state.formData.profile_pic.uri,
}
const formData = new FormData()
formData.append('first_name', this.state.formData.first_name);
formData.append('last_name', this.state.formData.last_name);
formData.append('profile_pic', profile_pic);
const Token = 'secret'

fetch('http://10.0.2.2:8000/api/profile/', {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "multipart/form-data",
      Authorization: `Token ${Token}`
    },
    body: formData
  })
  .then(response => console.log(response.json()))

RESTful call in Java

You can use Async Http Client (The library also supports the WebSocket Protocol) like that:

    String clientChannel = UriBuilder.fromPath("http://localhost:8080/api/{id}").build(id).toString();

    try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient())
    {
        BoundRequestBuilder postRequest = asyncHttpClient.preparePost(clientChannel);
        postRequest.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        postRequest.setBody(message.toString()); // returns JSON
        postRequest.execute().get();
    }

How to find if a native DLL file is compiled as x64 or x86?

There is an easy way to do this with CorFlags. Open the Visual Studio Command Prompt and type "corflags [your assembly]". You'll get something like this:

c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC>corflags "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll"

Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved.

Version : v2.0.50727 CLR Header: 2.5 PE : PE32 CorFlags : 24 ILONLY : 0 32BIT : 0 Signed : 1

You're looking at PE and 32BIT specifically.

  • Any CPU:

    PE: PE32
    32BIT: 0

  • x86:

    PE: PE32
    32BIT: 1

  • x64:

    PE: PE32+
    32BIT: 0

How to determine a user's IP address in node

Warning:

Don't just blindly use this for important rate-limiting:

let ip = request.headers['x-forwarded-for'].split(',')[0];

It's very easy to spoof:

curl --header "X-Forwarded-For: 1.2.3.4" "https://example.com"

In that case ther user's real IP address will be:

let ip = request.headers['x-forwarded-for'].split(',')[1];

I'm surprised that no other answers have mentioned this.

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Updating GUI (WPF) using a different thread

You have a couple of options here, I think.

One would be to use a BackgroundWorker. This is a common helper for multithreading in applications. It exposes a DoWork event which is handled on a background thread from the Thread Pool and a RunWorkerCompleted event which is invoked back on the main thread when the background thread completes. It also has the benefit of try/catching the code running on the background thread so that an unhandled exception doesn't kill the application.

If you don't want to go that route, you can use the WPF dispatcher object to invoke an action to update the GUI back onto the main thread. Random reference:

http://www.switchonthecode.com/tutorials/working-with-the-wpf-dispatcher

There are many other options around too, but these are the two most common that come to mind.

What resources are shared between threads?

Something that really needs to be pointed out is that there are really two aspects to this question - the theoretical aspect and the implementations aspect.

First, let's look at the theoretical aspect. You need to understand what a process is conceptually to understand the difference between a process and a thread and what's shared between them.

We have the following from section 2.2.2 The Classical Thread Model in Modern Operating Systems 3e by Tanenbaum:

The process model is based on two independent concepts: resource grouping and execution. Sometimes it is use­ful to separate them; this is where threads come in....

He continues:

One way of looking at a process is that it is a way to group related resources together. A process has an address space containing program text and data, as well as other resources. These resource may include open files, child processes, pending alarms, signal handlers, accounting information, and more. By putting them together in the form of a process, they can be managed more easily. The other concept a process has is a thread of execution, usually shortened to just thread. The thread has a program counter that keeps track of which instruc­tion to execute next. It has registers, which hold its current working variables. It has a stack, which contains the execution history, with one frame for each proce­dure called but not yet returned from. Although a thread must execute in some process, the thread and its process are different concepts and can be treated sepa­rately. Processes are used to group resources together; threads are the entities scheduled for execution on the CPU.

Further down he provides the following table:

Per process items             | Per thread items
------------------------------|-----------------
Address space                 | Program counter
Global variables              | Registers
Open files                    | Stack
Child processes               | State
Pending alarms                |
Signals and signal handlers   |
Accounting information        |

The above is what you need for threads to work. As others have pointed out, things like segments are OS dependant implementation details.

From io.Reader to string in Go

func copyToString(r io.Reader) (res string, err error) {
    var sb strings.Builder
    if _, err = io.Copy(&sb, r); err == nil {
        res = sb.String()
    }
    return
}

Scala: what is the best way to append an element to an Array?

val array2 = array :+ 4
//Array(1, 2, 3, 4)

Works also "reversed":

val array2 = 4 +: array
Array(4, 1, 2, 3)

There is also an "in-place" version:

var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)

What are the most common font-sizes for H1-H6 tags

It would depend on the browser's default stylesheet. You can view an (unofficial) table of CSS2.1 User Agent stylesheet defaults here.

Based on the page listed above, the default sizes look something like this:

    IE7     IE8     FF2         FF3         Opera   Safari 3.1
H1  24pt    2em     32px        32px        32px    32px       
H2  18pt    1.5em   24px        24px        24px    24px
H3  13.55pt 1.17em  18.7333px   18.7167px   18px    19px
H4  n/a     n/a     n/a         n/a         n/a     n/a
H5  10pt    0.83em  13.2667px   13.2833px   13px    13px
H6  7.55pt  0.67em  10.7333px   10.7167px   10px    11px

Also worth taking a look at is the default stylesheet for HTML 4. The W3C recommends using these styles as the default. An abridged excerpt:

h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.17em; }
h4 { font-size: 1.12em; }
h5 { font-size: .83em; }
h6 { font-size: .75em; }

Hope this information is helpful.

How do you switch pages in Xamarin.Forms?

In App.Xaml.Cs:

MainPage = new NavigationPage( new YourPage());

When you wish to navigate from YourPage to the next page you do:

await Navigation.PushAsync(new YourSecondPage());

You can read more about Xamarin Forms navigation here: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/hierarchical

Microsoft has quite good docs on this.

There is also the newer concept of the Shell. It allows for a new way of structuring your application and simplifies navigation in some cases.

Intro: https://devblogs.microsoft.com/xamarin/shell-xamarin-forms-4-0-getting-started/

Video on basics of Shell: https://www.youtube.com/watch?v=0y1bUAcOjZY&t=3112s

Docs: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/

Copy from one workbook and paste into another

You copied using Cells.
If so, no need to PasteSpecial since you are copying data at exactly the same format.
Here's your code with some fixes.

Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet

Set x = Workbooks.Open("path to copying book")
Set y = Workbooks.Open("path to pasting book")

Set ws1 = x.Sheets("Sheet you want to copy from")
Set ws2 = y.Sheets("Sheet you want to copy to")

ws1.Cells.Copy ws2.cells
y.Close True
x.Close False

If however you really want to paste special, use a dynamic Range("Address") to copy from.
Like this:

ws1.Range("Address").Copy: ws2.Range("A1").PasteSpecial xlPasteValues
y.Close True
x.Close False

Take note of the : colon after the .Copy which is a Statement Separating character.
Using Object.PasteSpecial requires to be executed in a new line.
Hope this gets you going.

How to get current time in milliseconds in PHP?

As other have stated, you can use microtime() to get millisecond precision on timestamps.

From your comments, you seem to want it as a high-precision UNIX Timestamp. Something like DateTime.Now.Ticks in the .NET world.

You may use the following function to do so:

function millitime() {
  $microtime = microtime();
  $comps = explode(' ', $microtime);

  // Note: Using a string here to prevent loss of precision
  // in case of "overflow" (PHP converts it to a double)
  return sprintf('%d%03d', $comps[1], $comps[0] * 1000);
}

Javascript: getFullyear() is not a function

You are overwriting the start date object with the value of a DOM Element with an id of Startdate.

This should work:

var start = new Date(document.getElementById('Stardate').value);

var y = start.getFullYear();

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

Do the following changes in servlet-context.xml

    <beans:property name="hibernateProperties">
        <beans:props>

            <beans:prop key="hibernate.enable_lazy_load_no_trans">true</beans:prop>

        </beans:props>
    </beans:property>

Check if table exists in SQL Server

You can use this :

     IF OBJECT_ID (N'dbo.T', N'U') IS NOT NULL 
        BEGIN 
            print 'deleted table';
            drop table t 
        END
     else 
        begin 
            print 'table not found' 
        end

 Create table t (id int identity(1,1) not null, name varchar(30) not null, lastname varchar(25) null)
 insert into t( name, lastname) values('john','doe');
 insert into t( name, lastname) values('rose',NULL);

 Select * from t
1   john    doe
2   rose    NULL

 -- clean
 drop table t

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

If the "Customer don't want to install and buy MS Office on a server not at any price", then you cannot use Excel ... But I cannot get the trick: it's all about one basic Office licence which costs something like 150 USD ... And I guess that spending time finding an alternative will cost by far more than this amount!

Find CRLF in Notepad++

Go to View--> Show symbol-->Show all character // Its worked for me

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

How to round a numpy array?

It is worth noting that the accepted answer will round small floats down to zero.

>>> import numpy as np 
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03  4.82011728e-08  1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0.  ,  0.  ,  0.  ]) 

You can use set_printoptions and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:

>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]  

This way, you get the full versatility of format and maintain the full precision of numpy's datatypes.

Also note that this only affects printing, not the actual precision of the stored values used for computation.

Handling identity columns in an "Insert Into TABLE Values()" statement?

Since it isn't practical to put code in a comment, in response to your comment in Eric's answer that it's not working for you...

I just ran the following on a SQL 2005 box (sorry, no 2000 handy) with default settings and it worked without error:

CREATE TABLE dbo.Test_Identity_Insert
(
    id  INT IDENTITY NOT NULL,
    my_string   VARCHAR(20) NOT NULL,
    CONSTRAINT PK_Test_Identity_Insert PRIMARY KEY CLUSTERED (id)
)
GO

INSERT INTO dbo.Test_Identity_Insert VALUES ('test')
GO

SELECT * FROM dbo.Test_Identity_Insert
GO

Are you perhaps sending the ID value over in your values list? I don't think that you can make it ignore the column if you actually pass a value for it. For example, if your table has 6 columns and you want to ignore the IDENTITY column you can only pass 5 values.

why windows 7 task scheduler task fails with error 2147942667

For me it was the "Start In" - I accidentally left in the '.py' at the end of the name of my program. And I forgot to capitalize the name of the folder it was in ('Apps').

How to pass a variable from Activity to Fragment, and pass it back?

Sending data from Activity into Fragments linked by XML

If you create a fragment in Android Studio using one of the templates e.g. File > New > Fragment > Fragment (List), then the fragment is linked via XML. The newInstance method is created in the fragment but is never called so can't be used to pass arguments.

Instead in the Activity override the method onAttachFragment

@Override
public void onAttachFragment(Fragment fragment) {
    if (fragment instanceof DetailsFragment) {
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);        
     }
}

Then read the arguments in the fragment onCreate method as per the other answers

Where's my invalid character (ORA-00911)

One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .

JOIN queries vs multiple queries

For inner joins, a single query makes sense, since you only get matching rows. For left joins, multiple queries is much better... look at the following benchmark I did:

  1. Single query with 5 Joins

    query: 8.074508 seconds

    result size: 2268000

  2. 5 queries in a row

    combined query time: 0.00262 seconds

    result size: 165 (6 + 50 + 7 + 12 + 90)

.

Note that we get the same results in both cases (6 x 50 x 7 x 12 x 90 = 2268000)

left joins use exponentially more memory with redundant data.

The memory limit might not be as bad if you only do a join of two tables, but generally three or more and it becomes worth different queries.

As a side note, my MySQL server is right beside my application server... so connection time is negligible. If your connection time is in the seconds, then maybe there is a benefit

Frank

How to style icon color, size, and shadow of Font Awesome Icons

Wrap the i tag in p or span, then you can use bootstrap css class

<p class="text-success"><i class="fa fa-check"></i></p>

How to resolve the "ADB server didn't ACK" error?

I've got a kind of botch for the old ADB server didn't ACK * failed to start daemon * issue which might help, though i haven't seen anyone else with my problem so maybe not. Anyway...

I changed the default install location for my HTC sensation to 2 (SD card), but when trying to revert back to 0 (internal) i was getting this error. Looking in task manager showed there were 2 instances of adb.exe running, one of which kept stopping and starting and was impossible to kill, the other could be killed but then a new instance would start almost immediately.

The only way i could get adb to start successfully was to get my command ready in the command window, go to task manager to end the adb.exe, then when the window came up saying 'are you sure you want to kill adb.exe' dragged that over the command window, clicked OK then immediately pressed Enter to run the command. It seems that the short window between adb.exe being killed and restarting itself is sufficient to run a command, though if you try to do something else it won't work and you have to repeat this process each time you want to run a command.

PITA but it's the only way an uneducated numpty like myself could get round it - hopefully it'll help someone...

Creating a 3D sphere in Opengl using Visual C++

I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:

inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
    int curRow = r * sectors;
    int nextRow = (r+1) * sectors;

    indices.push_back(curRow + s);
    indices.push_back(nextRow + s);
    indices.push_back(nextRow + (s+1));

    indices.push_back(curRow + s);
    indices.push_back(nextRow + (s+1));
    indices.push_back(curRow + (s+1));
}

void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
             float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);

    for(int r = 0; r < rings; ++r) {
        for(int s = 0; s < sectors; ++s) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

            texcoords.push_back(vec2(s*S, r*R));
            vertices.push_back(vec3(x,y,z) * radius);
            push_indices(indices, sectors, r, s);
        }
    }
}

How do I get a div to float to the bottom of its container?

I know that this stuff is old, but I recently ran into this problem.

use absolute position divs advice is really silly, because the whole float thing kind of loses point with absolute positions..

now, I did not find an universal solution, but in a lot of cases prople use floating divs just to display something in a row, like a series of span elements. and you can't vertically align that.

to achieve a similar effect you can do this: do not make the div float, but set it's display property to inline-block. then you can align it vertically however it pleases you. you just need to set parent's div property vertical-align to either top, bottom, middle or baseline

i hope that helps someone

Best way to find the intersection of multiple sets?

Clearly set.intersection is what you want here, but in case you ever need a generalisation of "take the sum of all these", "take the product of all these", "take the xor of all these", what you are looking for is the reduce function:

from operator import and_
from functools import reduce
print(reduce(and_, [{1,2,3},{2,3,4},{3,4,5}])) # = {3}

or

print(reduce((lambda x,y: x&y), [{1,2,3},{2,3,4},{3,4,5}])) # = {3}

Using getline() in C++

If you're using getline() after cin >> something, you need to flush the newline character out of the buffer in between. You can do it by using cin.ignore().

It would be something like this:

string messageVar;
cout << "Type your message: ";
cin.ignore(); 
getline(cin, messageVar);

This happens because the >> operator leaves a newline \n character in the input buffer. This may become a problem when you do unformatted input, like getline(), which reads input until a newline character is found. This happening, it will stop reading immediately, because of that \n that was left hanging there in your previous operation.

ISO time (ISO 8601) in Python

Here is what I use to convert to the XSD datetime format:

from datetime import datetime
datetime.now().replace(microsecond=0).isoformat()
# You get your ISO string

I came across this question when looking for the XSD date time format (xs:dateTime). I needed to remove the microseconds from isoformat.

Dilemma: when to use Fragments vs Activities:

Why I prefer Fragment over Activity in ALL CASES.

  • Activity is expensive. In Fragment, views and property states are separated - whenever a fragment is in backstack, its views will be destroyed. So you can stack much more Fragments than Activity.

  • Backstack manipulation. With FragmentManager, it's easy to clear all the Fragments, insert more than on Fragments and etcs. But for Activity, it will be a nightmare to manipulate those stuff.

  • A much predictable lifecycle. As long as the host Activity is not recycled. the Fragments in the backstack will not be recycled. So it's possible to use FragmentManager::getFragments() to find specific Fragment (not encouraged).

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

CustomErrors mode="Off"

You can also try bringing up the website in a browser on the server machine. I don't do a lot of ASP.NET development, but I remember the custom errors thing has a setting for only displaying full error text on the server, as a security measure.

JAVA_HOME directory in Linux

On Linux you can run $(dirname $(dirname $(readlink -f $(which javac))))

On Mac you can run $(dirname $(readlink $(which javac)))/java_home

I'm not sure about windows but I imagine where javac would get you pretty close

How to determine the number of days in a month in SQL Server?

SELECT DAY(SUBDATE(ADDDATE(CONCAT(YEAR(NOW()), '-', MONTH(NOW()), '-1'), INTERVAL 1 MONTH), INTERVAL 1 DAY))

Nice 'n' Simple and does not require creating any functions

React js change child component's state from parent component

You can use the createRef to change the state of the child component from the parent component. Here are all the steps.

  1. Create a method to change the state in the child component.

    2 - Create a reference for the child component in parent component using React.createRef().

    3 - Attach reference with the child component using ref={}.

    4 - Call the child component method using this.yor-reference.current.method.

Parent component


class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
  render() {
    return (
      <div>
        <button onClick={this.changeChild.current.toggleMenu()}>
          Toggle Menu from Parent
        </button>
        <ChildComponent ref={this.changeChild} />
      </div>
    );
  }
}

Child Component


class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false;
    }
  }

  toggleMenu=() => {
    this.setState({
      open: !this.state.open
    });
  }

  render() {
    return (
      <Drawer open={this.state.open}/>
    );
  }
}



File URL "Not allowed to load local resource" in the Internet Browser

For people do not like to modify chrome's security options, we can simply start a python http server from directory which contains your local file:

python -m SimpleHTTPServer

and for python 3:

python3 -m http.server

Now you can reach any local file directly from your js code or externally with http://127.0.0.1:8000/some_file.txt

How to pass multiple checkboxes using jQuery ajax post

This would be better and easy

var arr = $('input[name="user_ids[]"]').map(function(){
  return $(this).val();
}).get();

console.log(arr);

Copying files into the application folder at compile time

You want to use a Post-Build event on your project. You can specify the output there and there are macro values for frequently used things like project path, item name, etc.

A project with an Output Type of Class Library cannot be started directly

Just needs to go:

Solution Explorer-->Go to Properties --->change(Single Startup project) from.dll to .web

Then try to debug it.

Surely your problem will be solved.

How to zip a whole folder using PHP

I assume this is running on a server where the zip application is in the search path. Should be true for all unix-based and I guess most windows-based servers.

exec('zip -r archive.zip "My folder"');
unlink('My\ folder/index.html');
unlink('My\ folder/picture.jpg');

The archive will reside in archive.zip afterwards. Keep in mind that blanks in file or folder names are a common cause of errors and should be avoided where possible.

Is there a way to get a list of all current temporary tables in SQL Server?

Is this what you are after?

select * from tempdb..sysobjects
--for sql-server 2000 and later versions

select * from tempdb.sys.objects
--for sql-server 2005 and later versions

Why catch and rethrow an exception in C#?

One possible reason to catch-throw is to disable any exception filters deeper up the stack from filtering down (random old link). But of course, if that was the intention, there would be a comment there saying so.

Load jQuery with Javascript and use jQuery

There's a working JSFiddle with a small example here, that demonstrates exactly what you are looking for (unless I've misunderstood your request): http://jsfiddle.net/9N7Z2/188/

There are a few issues with that method of loading javascript dynamically. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework...

You could use some of the existing JavaScript loaders, or write your own by watching for window.jQuery to get defined.

// Immediately-invoked function expression
(function() {
    // Load the script
    var script = document.createElement("SCRIPT");
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    script.type = 'text/javascript';
    script.onload = function() {
        var $ = window.jQuery;
        // Use $ here...
    };
    document.getElementsByTagName("head")[0].appendChild(script);
})();

Just remember that if you need to support really old browsers, like IE8, load event handlers do not execute. In that case, you would need to poll for the existance of window.jQuery using repeated window.setTimeout. There is a working JSFiddle with that method here: http://jsfiddle.net/9N7Z2/3/

There are lots of people who have already done what you need to do. Check out some of the existing JavaScript Loader frameworks, like:

Determining complexity for recursive functions (Big O notation)

The time complexity, in Big O notation, for each function:


int recursiveFun1(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun1(n-1);
}

This function is being called recursively n times before reaching the base case so its O(n), often called linear.


int recursiveFun2(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun2(n-5);
}

This function is called n-5 for each time, so we deduct five from n before calling the function, but n-5 is also O(n). (Actually called order of n/5 times. And, O(n/5) = O(n) ).


int recursiveFun3(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun3(n/5);
}

This function is log(n) base 5, for every time we divide by 5 before calling the function so its O(log(n))(base 5), often called logarithmic and most often Big O notation and complexity analysis uses base 2.


void recursiveFun4(int n, int m, int o)
{
    if (n <= 0)
    {
        printf("%d, %d\n",m, o);
    }
    else
    {
        recursiveFun4(n-1, m+1, o);
        recursiveFun4(n-1, m, o+1);
    }
}

Here, it's O(2^n), or exponential, since each function call calls itself twice unless it has been recursed n times.



int recursiveFun5(int n)
{
    for (i = 0; i < n; i += 2) {
        // do something
    }

    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun5(n-5);
}

And here the for loop takes n/2 since we're increasing by 2, and the recursion takes n/5 and since the for loop is called recursively, therefore, the time complexity is in

(n/5) * (n/2) = n^2/10,

due to Asymptotic behavior and worst-case scenario considerations or the upper bound that big O is striving for, we are only interested in the largest term so O(n^2).


Good luck on your midterms ;)

Create a List of primitive int?

This is not possible. The java specification forbids the use of primitives in generics. However, you can create ArrayList<Integer> and call add(i) if i is an int thanks to boxing.

How to hide 'Back' button on navigation bar on iPhone?

It wasn't working for me in all cases when I set

self.navigationItem.hidesBackButton = YES;

in viewWillAppear or ViewDidLoad, but worked perfectly when I set it in init of the viewController.

Can I set an unlimited length for maxJsonLength in web.config?

Just ran into this. I'm getting over 6,000 records. Just decided I'd just do some paging. As in, I accept a page number in my MVC JsonResult endpoint, which is defaulted to 0 so it's not necessary, like so:

public JsonResult MyObjects(int pageNumber = 0)

Then instead of saying:

return Json(_repository.MyObjects.ToList(), JsonRequestBehavior.AllowGet);

I say:

return Json(_repository.MyObjects.OrderBy(obj => obj.ID).Skip(1000 * pageNumber).Take(1000).ToList(), JsonRequestBehavior.AllowGet);

It's very simple. Then, in JavaScript, instead of this:

function myAJAXCallback(items) {
    // Do stuff here
}

I instead say:

var pageNumber = 0;
function myAJAXCallback(items) {
    if(items.length == 1000)
        // Call same endpoint but add this to the end: '?pageNumber=' + ++pageNumber
    }
    // Do stuff here
}

And append your records to whatever you were doing with them in the first place. Or just wait until all the calls finish and cobble the results together.

Why would I use dirname(__FILE__) in an include or include_once statement?

I might have even a simpler explanation to this question compared to the accepted answer so I'm going to give it a go: Assume this is the structure of the files and directories of a project:

Project root directory:
                       file1.php
                       file3.php
                       dir1/
                            file2.php

(dir1 is a directory and file2.php is inside it)

And this is the content of each of the three files above:

//file1.php:
<?php include "dir1/file2.php"

//file2.php:
<?php include "../file3.php"

//file3.php:
<?php echo "Hello, Test!";

Now run file1.php and try to guess what should happen. You might expect to see "Hello, Test!", however, it won't be shown! What you'll get instead will be an error indicating that the file you have requested(file3.php) does not exist!

The reason is that, inside file1.php when you include file2.php, the content of it is getting copied and then pasted back directly into file1.php which is inside the root directory, thus this part "../file3.php" runs from the root directory and thus goes one directory up the root! (and obviously it won't find the file3.php).

Now, what should we do ?!

Relative paths of course have the problem above, so we have to use absolute paths. However, absolute paths have also one problem. If you (for example) copy the root folder (containing your whole project) and paste it in anywhere else on your computer, the paths will be invalid from that point on! And that'll be a REAL MESS!

So we kind of need paths that are both absolute and dynamic(Each file dynamically finds the absolute path of itself wherever we place it)!

The way we do that is by getting help from PHP, and dirname() is the function to go for, which gives the absolute path to the directory in which a file exists in. And each file name could also be easily accessed using the __FILE__ constant. So dirname(__FILE__) would easily give you the absolute (while dynamic!) path to the file we're typing in the above code. Now move your whole project to a new place, or even a new system, and tada! it works!

So now if we turn the project above to this:

//file1.php:
<?php include(dirname(__FILE__)."/dir1/file2.php");

//file2.php:
<?php include(dirname(__FILE__)."/../file3.php");

//file3.php:
<?php echo "Hello, Test!";

if you run it, you'll see the almighty Hello, Test!! (hopefully, if you've not done anything else wrong).

It's also worth mentioning that from PHP5, a nicer way(with regards to readability and preventing eye boilage!) has been provided by PHP as well which is the constant __DIR__ which does exactly the same thing as dirname(__FILE__)!

Hope that helps.

Split a python list into other "sublists" i.e smaller lists

I'd say

chunks = [data[x:x+100] for x in range(0, len(data), 100)]

If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange(), changing the above code to:

chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]

Server is already running in Rails

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

What is the benefit of zerofill in MySQL?

ZEROFILL

This essentially means that if the integer value 23 is inserted into an INT column with the width of 8 then the rest of the available position will be automatically padded with zeros.

Hence

23

becomes:

00000023

How to print environment variables to the console in PowerShell?

The following is works best in my opinion:

Get-Item Env:PATH
  1. It's shorter and therefore a little bit easier to remember than Get-ChildItem. There's no hierarchy with environment variables.
  2. The command is symmetrical to one of the ways that's used for setting environment variables with Powershell. (EX: Set-Item -Path env:SomeVariable -Value "Some Value")
  3. If you get in the habit of doing it this way you'll remember how to list all Environment variables; simply omit the entry portion. (EX: Get-Item Env:)

I found the syntax odd at first, but things started making more sense after I understood the notion of Providers. Essentially PowerShell let's you navigate disparate components of the system in a way that's analogous to a file system.

What's the point of the trailing colon in Env:? Try listing all of the "drives" available through Providers like this:

PS> Get-PSDrive

I only see a few results... (Alias, C, Cert, D, Env, Function, HKCU, HKLM, Variable, WSMan). It becomes obvious that Env is simply another "drive" and the colon is a familiar syntax to anyone who's worked in Windows.

You can navigate the drives and pick out specific values:

Get-ChildItem C:\Windows
Get-Item C:
Get-Item Env:
Get-Item HKLM:
Get-ChildItem HKLM:SYSTEM

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Why aren't python nested functions called closures?

I'd like to offer another simple comparison between python and JS example, if this helps make things clearer.

JS:

function make () {
  var cl = 1;
  function gett () {
    console.log(cl);
  }
  function sett (val) {
    cl = val;
  }
  return [gett, sett]
}

and executing:

a = make(); g = a[0]; s = a[1];
s(2); g(); // 2
s(3); g(); // 3

Python:

def make (): 
  cl = 1
  def gett ():
    print(cl);
  def sett (val):
    cl = val
  return gett, sett

and executing:

g, s = make()
g() #1
s(2); g() #1
s(3); g() #1

Reason: As many others said above, in python, if there is an assignment in the inner scope to a variable with the same name, a new reference in the inner scope is created. Not so with JS, unless you explicitly declare one with the var keyword.

@Autowired - No qualifying bean of type found for dependency

My guess is that here

<context:component-scan base-package="pl.com.radzikowski.webmail" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

all annotations are first disabled by use-default-filters="false" and then only @Controller annotation enabled. Thus, your @Component annotation is not enabled.

Android, How to limit width of TextView (and add three dots at the end of text)?

The following is what I learned by playing around with various options for forcing a TextView to a single line (with and without the three dots).

enter image description here

android:maxLines="1"

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:text="one two three four five six seven eight nine ten" />

This just forces the text to one line. Any extra text is hidden.

Related:

ellipsize="end"

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:ellipsize="end"
    android:text="one two three four five six seven eight nine ten" />

This cuts off the text that doesn't fit but lets users know that the text has been truncated by adding an ellipsis (the three dots).

Related:

ellipsize="marquee"

<TextView
    android:id="@+id/MarqueeText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:text="one two three four five six seven eight nine ten" />

This makes the text scroll automatically across the TextView. Note that sometimes it needs to be set in code:

textView.setSelected(true);

Supposedly android:maxLines="1" and android:singleLine="true" should do basically the same thing and since singleLine is apparently deprecated I would prefer not to use it, but when I take it out, the marquee doesn't scroll anymore. Taking maxLines out doesn't affect it, though.

Related:

HorizontalScrollView with scrollHorizontally

<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/horizontalScrollView">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:scrollHorizontally="true"
        android:text="one two three four five six seven eight nine ten" />
</HorizontalScrollView>

This allows the user to manually scroll to see the whole line of text.

Protect .NET code from reverse engineering?

Unfortunately, you are not going to run away from this. Your best bet is to write your code in C and P/Invoke it.

There is a small catch-22, someone could just decompile your application to CIL and kill any verification/activation code (for example, the call to your C library). Remember that applications that are written in C are also reverse-engineered by the more persistent hackers (just look at how fast games are cracked these days). Nothing will protect your application.

In the end it works a lot like your home, protect it well enough so that it is too much effort (spaghetti code would help here) and so that the assailant just moves onto your next door neighbor (competition :) ). Look at Windows Vista, there must be 10 different ways to crack it.

There are packages out there that will encrypt your EXE file and decrypt it when the user is allowed to use it, but once again, that is using a generic solution that has no doubt been cracked.

Activation and registration mechanisms are aimed at the 'average Joe:' people who don't have enough tech savvy to bypass it (or for that matter know that they can bypass it). Don't bother with crackers, they have far too much time on their hands.

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

Docker compose, running containers in net:host

Those documents are outdated. I'm guessing the 1.6 in the URL is for Docker 1.6, not Compose 1.6. Check out the correct syntax here: https://docs.docker.com/compose/compose-file/#network_mode. You are looking for network_mode when using the v2 YAML format.

Sass - Converting Hex to RGBa for background opacity

The rgba() function can accept a single hex color as well decimal RGB values. For example, this would work just fine:

@mixin background-opacity($color, $opacity: 0.3) {
    background: $color; /* The Fallback */
    background: rgba($color, $opacity);
}

element {
     @include background-opacity(#333, 0.5);
}

If you ever need to break the hex color into RGB components, though, you can use the red(), green(), and blue() functions to do so:

$red: red($color);
$green: green($color);
$blue: blue($color);

background: rgb($red, $green, $blue); /* same as using "background: $color" */

How to initialize an array in angular2 and typescript

You can use this construct:

export class AppComponent {

    title:string;
    myHero:string;
    heroes: any[];

    constructor() {
       this.title = 'Tour of Heros';
       this.heroes=['Windstorm','Bombasto','Magneta','Tornado']
       this.myHero = this.heroes[0];
    }
}

Mixing C# & VB In The Same Project

Well, actually I inherited a project some years ago from a colleague who had decided to mix VB and C# webforms within the same project. That worked but is far from fun to maintain.

I decided that new code should be C# classes and to get them to work I had to add a subnode to the compilation part of web.config

        <codeSubDirectories>
            <add directoryName="VB"/>
            <add directoryName="CS"/>
        </codeSubDirectories>

The all VB code goes into a subfolder in the App_Code called VB and the C# code into the CS subfolder. This will produce two .dll files. It works, but code is compiled in the same order as listed in "codeSubDirectories" and therefore i.e Interfaces should be in the VB folder if used in both C# and VB.

I have both a reference to a VB and a C# compiler in

<system.codedom>
    <compilers>

The project is currently updated to framework 3.5 and it still works (but still no fun to maintain..)