Programs & Examples On #Ogg theora

Questions related to Theora video codec, encapsulated in Ogg Container format. Theora is a free lossy video compression format. It is developed by the Xiph.Org Foundation and distributed without licensing fees alongside their other free and open media projects, including the Vorbis audio format and the Ogg container.

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

Just remove the inner quotes - they confuse Firefox. You can just use "video/ogg; codecs=theora,vorbis".

Also, that markup works in my Minefiled 3.7a5pre, so if your ogv file doesn't play, it may be a bogus file. How did you create it? You might want to register a bug with Firefox.

Parsing ISO 8601 date in Javascript

According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date methods and formatting to accomplish your goal:

function dateToString (date) {
  // Use an array to format the month numbers
  var months = [
    "January",
    "February",
    "March",
    ...
  ];

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",
    ...
  };

  var month = months[date.getMonth()];
  var day = date.getDate();
  var year = date.getFullYear();

  var hours = date.getHours();
  var minutes = date.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[date.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;
}

var date = new Date("2011-01-28T19:30:00-05:00");

alert(dateToString(date));

You could even take it one step further and override the Date.toString() method:

function dateToString () { // No date argument this time
  // Use an array to format the month numbers
  var months = [
    "January",
    "February",
    "March",
    ...
  ];

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",
    ...
  };

  var month = months[*this*.getMonth()];
  var day = *this*.getDate();
  var year = *this*.getFullYear();

  var hours = *this*.getHours();
  var minutes = *this*.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[*this*.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;
}

var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;

alert(date.toString());

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

Check image width and height before upload with Javascript

This is the easiest way to check the size

let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
   alert(img.width + " " + img.height);
}

Check for specific size. Using 100 x 100 as example

let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
   if(img.width === 100 && img.height === 100){
        alert(`Nice, image is the right size. It can be uploaded`)
        // upload logic here
        } else {
        alert(`Sorry, this image doesn't look like the size we wanted. It's 
   ${img.width} x ${img.height} but we require 100 x 100 size image.`);
   }                
}

Allow only numbers and dot in script

This is a great place to use regular expressions.

By using a regular expression, you can replace all that code with just one line.

You can use the following regex to validate your requirements:

[0-9]*\.?[0-9]*

In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.

You can replace your code with this:

function validate(s) {
    var rgx = /^[0-9]*\.?[0-9]*$/;
    return s.match(rgx);
}

That code can replace your entire function!

Note that you have to escape the period with a backslash (otherwise it stands for 'any character').

For more reading on using regular expressions with javascript, check this out:

You can also test the above regex here:


Explanation of the regex used above:

  • The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.

  • The * means "zero or more of the previous expression."

  • [0-9]* means "zero or more numbers"

  • The backslash is used as an escape character for the period, because period usually stands for "any character."

  • The ? means "zero or one of the previous character."

  • The ^ represents the beginning of a string.

  • The $ represents the end of a string.

  • Starting the regex with ^ and ending it with $ ensures that the entire string adheres to the regex pattern.

Hope this helps!

Git list of staged files

You can Try using :- git ls-files -s

Bootstrap 3 Carousel Not Working

For me, the carousel wasn't working in the DreamWeaver CC provided the code in the "template" page I am playing with. I needed to add the data-ride="carousel" attribute to the carousel div in order for it to start working. Thanks to Adarsh for his code snippet which highlighted the missing attribute.

Different class for the last element in ng-repeat

You could use limitTo filter with -1 for find the last element

Example :

<div ng-repeat="friend in friends | limitTo: -1">
    {{friend.name}}
</div>

How to zoom div content using jquery?

@Gadde - your answer was very helpful. Thank you! I needed a "Maps"-like zoom for a div and was able to produce the feel I needed with your post. My criteria included the need to have the click repeat and continue to zoom out/in with each click. Below is my final result.

    var currentZoom = 1.0;

    $(document).ready(function () {
        $('#btn_ZoomIn').click(
            function () {
                $('#divName').animate({ 'zoom': currentZoom += .1 }, 'slow');
            })
        $('#btn_ZoomOut').click(
            function () {
                $('#divName').animate({ 'zoom': currentZoom -= .1 }, 'slow');
            })
        $('#btn_ZoomReset').click(
            function () {
                currentZoom = 1.0
                $('#divName').animate({ 'zoom': 1 }, 'slow');
            })
    });

django no such table:

. first step delete db.sqlite3 file . go to terminal and run commands:

  • python manage.py makemigrations
  • python manage.py migrate
  • python manage.py createsuperuser
  • python manage.py runserver . go to admin page every thing ok now.

Bootstrap dropdown menu not working (not dropping down when clicked)

Just Remove the type="text/javascript"

<script src="JavaScript/jquery.js" />
<script src="JavaScript/bootstrap-min.js" />

Here is the update - http://jsfiddle.net/andieje/kRX6n/

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

I resolved this problem by change application.properties of

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

to

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Hope it help

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

In my case the tensorflow install was looking for cudart64_101.dll

enter image description here

The 101 part of cudart64_101 is the Cuda version - here 101 = 10.1

I had downloaded 11.x, so the version of cudart64 on my system was cudart64_110.dll

enter image description here

This is the wrong file!! cudart64_101.dll ? cudart64_110.dll

Solution

Download Cuda 10.1 from https://developer.nvidia.com/

Install (mine crashes with NSight Visual Studio Integration, so I switched that off)

enter image description here

When the install has finished you should have a Cuda 10.1 folder, and in the bin the dll the system was complaining about being missing

enter image description here

Check that the path to the 10.1 bin folder is registered as a system environmental variable, so it will be checked when loading the library

enter image description here

You may need a reboot if the path is not picked up by the system straight away

enter image description here

Iterating through populated rows

I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.

This code will:

  1. Find the last row in column A that has data
  2. Loop through each row
  3. Find the last column in current row with data
  4. Loop through each cell in current row up to last column found.

This is not a fast method but will iterate through each one individually as you suggested is your intention.


Sub iterateThroughAll()
    ScreenUpdating = False
    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim rowRange As Range
    Dim colRange As Range

    Dim LastCol As Long
    Dim LastRow As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A1:A" & LastRow)

    'Loop through each row
    For Each rrow In rowRange
        'Find Last column in current row
        LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
        Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))

        'Loop through all cells in row up to last col
        For Each cell In colRange
            'Do something to each cell
            Debug.Print (cell.Value)
        Next cell
    Next rrow
    ScreenUpdating = True
End Sub

Preloading CSS Images

Preloading images using HTML <link> Tag

I believe most of the visitors of this question are looking for the answer of "How can I preload an image before the page's render starts?" and the best solution for this problem is using <link> tag because <link> tag is capable to block the further rendering of the page. See preemptive

These two value options of rel (relationship between the current document and the linked document) attribute are most relevant with the issue:

  • prefetch : load the given resource while page rendering
  • preload : load the given resource before page rendering starts

So if you want to load a resource (in this case it's an image) before the rendering process of <body> tag starts, use:

<link rel="preload" as="image" href="IMAGE_URL">

and if you want to load a resource while <body> is rendering but you are planning to use it later on dynamically and don't wanna bother the user with loading time, use:

<link rel="prefetch" href="RESOURCE_URL">

Download Excel file via AJAX MVC

I used the solution posted by CSL but I would recommend you dont store the file data in Session during the whole session. By using TempData the file data is automatically removed after the next request (which is the GET request for the file). You could also manage removal of the file data in Session in download action.

Session could consume much memory/space depending on SessionState storage and how many files are exported during the session and if you have many users.

I've updated the serer side code from CSL to use TempData instead.

public ActionResult PostReportPartial(ReportVM model){

   // Validate the Model is correct and contains valid data
   // Generate your report output based on the model parameters
   // This can be an Excel, PDF, Word file - whatever you need.

   // As an example lets assume we've generated an EPPlus ExcelPackage

   ExcelPackage workbook = new ExcelPackage();
   // Do something to populate your workbook

   // Generate a new unique identifier against which the file can be stored
   string handle = Guid.NewGuid().ToString()

   using(MemoryStream memoryStream = new MemoryStream()){
        workbook.SaveAs(memoryStream);
        memoryStream.Position = 0;
        TempData[handle] = memoryStream.ToArray();
   }      

   // Note we are returning a filename as well as the handle
   return new JsonResult() { 
         Data = new { FileGuid = handle, FileName = "TestReportOutput.xlsx" }
   };

}

[HttpGet]
public virtual ActionResult Download(string fileGuid, string fileName)
{   
   if(TempData[fileGuid] != null){
        byte[] data = TempData[fileGuid] as byte[];
        return File(data, "application/vnd.ms-excel", fileName);
   }   
   else{
        // Problem - Log the error, generate a blank file,
        //           redirect to another controller action - whatever fits with your application
        return new EmptyResult();
   }
}

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Prevent redirect after form is submitted

Since it is bypassing CORS and CSP, this is to keep in the toolbox. Here is a variation.

This will POST a base64 encoded object at localhost:8080, and will clean up the DOM after usage.

_x000D_
_x000D_
const theOBJECT = {message: 'Hello world!', target: 'local'}_x000D_
_x000D_
document.body.innerHTML += '<iframe id="postframe" name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe><form id="dynForm" target="hiddenFrame" action="http://localhost:8080/" method="post"><input type="hidden" name="somedata" value="'+btoa(JSON.stringify(theOBJECT))+'"></form>';_x000D_
document.getElementById("dynForm").submit();_x000D_
dynForm.outerHTML = ""_x000D_
postframe.outerHTML = ""
_x000D_
_x000D_
_x000D_

From the network debugger tab, we can observe a successful POST to a http:// unencrypted server from a tls/https page.

enter image description here

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Instead of thinking of it as 'extracting', I like to think of it as 'isolating'. Once the desired bits are isolated, you can do what you will with them.

To isolate any set of bits, apply an AND mask.

If you want the last X bits of a value, there is a simple trick that can be used.

unsigned  mask;
mask = (1 << X) - 1;
lastXbits = value & mask;

If you want to isolate a run of X bits in the middle of 'value' starting at 'startBit' ...

unsigned  mask;
mask = ((1 << X) - 1) << startBit;
isolatedXbits = value & mask;

Hope this helps.

iReport not starting using JRE 8

I have installed IReport 5.6 with Java 7: not working

I tried to install Java 6 and added the path to "ireport.conf" file like the attached screenshot and it worked fine :Denter image description here

So the steps is :

 Install IReport 5.6
 Install JDK 6
 Edit "ireport.conf" file like the below image and Enjoy ;)

How to config Tomcat to serve images from an external folder outside webapps?

This is very simple and straight forward to server the static content from outside webapps folder in tomcat.

Simply edit the server.xml under $CATALINA_HOME/config/server.xml as below and restart the tomcat.

<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        **<Context docBase="C:\Ankur\testFiles"  path="/companyLogo" />**

       <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

</Host>

Add the context element inside the host element with two attribute docBase and path.

1) docBase: represents the hard drive directory 2) path: represents the uri on which you want to serve the static content.

For example:If you have 7.png inside the C:\Ankur\testFiles directory then you can access the 7.png file like below:

http://localhost:8081/companyLogo/7.png

For more details, check the blog

Create a text file for download on-the-fly

Use below code to generate files on fly..

<? //Generate text file on the fly

   header("Content-type: text/plain");
   header("Content-Disposition: attachment; filename=savethis.txt");

   // do your Db stuff here to get the content into $content
   print "This is some text...\n";
   print $content;
 ?>

What is the string length of a GUID?

It depends on how you format the Guid:

  • Guid.NewGuid().ToString() => 36 characters (Hyphenated)
    outputs: 12345678-1234-1234-1234-123456789abc

  • Guid.NewGuid().ToString("D") => 36 characters (Hyphenated, same as ToString())
    outputs: 12345678-1234-1234-1234-123456789abc

  • Guid.NewGuid().ToString("N") => 32 characters (Digits only)
    outputs: 12345678123412341234123456789abc

  • Guid.NewGuid().ToString("B") => 38 characters (Braces)
    outputs: {12345678-1234-1234-1234-123456789abc}

  • Guid.NewGuid().ToString("P") => 38 characters (Parentheses)
    outputs: (12345678-1234-1234-1234-123456789abc)

  • Guid.NewGuid().ToString("X") => 68 characters (Hexadecimal)
    outputs: {0x12345678,0x1234,0x1234,{0x12,0x34,0x12,0x34,0x56,0x78,0x9a,0xbc}}

How can I add private key to the distribution certificate?

For Developer certificate, you need to create a developer .mobileprovision profile and install add it to your XCode. In case you want to distribute the app using an adhoc distribution profile you will require AdHoc Distribution certificate and private key installed in your keychain.

If you have not created the cert, here are steps to create it. Incase it has already been created by someone in your team, ask him to share the cert and private key. If that someone is no longer in your team then you can revoke the cert from developer account and create new.

Bootstrap 4 Change Hamburger Toggler Color

Yes, just delete this span from your code: <span class="navbar-toggler-icon"></span> , then paste this font awesome icon that called bars: <i class="fas fa-bars"></i>, add a class to this icon, then put any color you want.

Then, the second step is to hide this icon from the devices that have width more than 992px (desktops width), due to this icon will appear in your interface at any device if you won't add this @media in your css code:

 /* Large devices (desktops, 992px and up) */
@media (min-width: 992px) { 
    /* the class you gave of the bars icon ? */
    .iconClass{
        display: none;
    }
    /* the bootstrap toogler button class */
    .navbar-toggler{
        display: none;
    }
}

It worked for me as well and I found it so easy.

Java: random long number in 0 <= x < n range

Use the '%' operator

resultingNumber = (r.nextLong() % (maximum - minimum)) + minimum;

By using the '%' operator, we take the remainder when divided by your maximum value. This leaves us with only numbers from 0 (inclusive) to the divisor (exclusive).

For example:

public long randLong(long min, long max) {
    return (new java.util.Random().nextLong() % (max - min)) + min;
}

How to find substring inside a string (or how to grep a variable)?

LIST="some string with a substring you want to match"
SOURCE="substring"
if echo "$LIST" | grep -q "$SOURCE"; then
  echo "matched";
else
  echo "no match";
fi

Android ClassNotFoundException: Didn't find class on path

This happens if we change Build Path of the APP, this can be in any case of Adding or Removing or Changing Libraries or .jar file. The Best solution is to Restart the Eclipse.

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

Ok, I figured it out. The issue was that I didn't have the correct permissions set for myrepo.git and the parent directory git.

As root I logged into the server and used:

$ chown username /home/username/git

This then returns drwxrwxr-x 4 username root 4096 2012-10-30 15:51 /home/username/git with the following:

$ ls -ld /home/username/git

I then make a new directory for myrepo.git inside git:

$ mkdir myrepo.git
$ ls -ld myrepo.git/
drwxr-xr-x 2 root root 4096 2012-10-30 18:41 myrepo.git/

but it has the user set to root, so I change it to username the same way as before.

$ chown username myrepo.git/
$ ls -ld myrepo.git/
drwxr-xr-x 2 username root 4096 2012-10-30 18:41 myrepo.git/

I then sign out of root and sign into server as username:

Inside git directory:

$ cd myrepo.git/
$ git --bare init
Initialized empty Git repository in /home/username/git/myrepo.git/

On local machine:

$ git remote add origin      
ssh://[email protected]/home/username/git/myrepo.git
$ git push origin master

SUCCESS!

Hopefully this comes in handy for anyone else that runs into the same issue in the future!

Resources

How to echo text during SQL script execution in SQLPLUS

The prompt command will echo text to the output:

prompt A useful comment.
select(*) from TableA;

Will be displayed as:

SQL> A useful comment.
SQL> 
  COUNT(*)
----------
     0

javascript - pass selected value from popup window to parent window input box

My approach: use a div instead of a pop-up window.

See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/

Or save the code below as test.html and try it locally.

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(window).load(function(){
            $('.btnChoice').on('click', function(){
                $('#divChoices').show()
                thefield = $(this).prev()
                $('.btnselect').on('click', function(){
                    theselected = $(this).prev()
                    thefield.val( theselected.val() )
                    $('#divChoices').hide()
                })
            })

            $('#divChoices').css({
                'border':'2px solid red',
                'position':'fixed',
                'top':'100',
                'left':'200',
                'display':'none'
            })
        });
    </script>
</head>

<body>

<div class="divform">
    <input type="checkbox" name="kvi1" id="kvi1" value="1">
    <label>Field 1: </label>
    <input size="10" type="number" id="sku1" name="sku1">
    <button id="choice1" class="btnChoice">?</button>
    <br>
    <input type="checkbox" name="kvi2" id="kvi2" value="2">
    <label>Field 2: </label>
    <input size="10"  type="number" id="sku2" name="sku2">
    <button id="choice2" class="btnChoice">?</button>
</div>

<div id="divChoices">
    Select something: 
    <br>
    <input size="10" type="number" id="ch1" name="ch1" value="11">
    <button id="btnsel1" class="btnselect">Select</button>
    <label for="ch1">bla bla bla</label>
    <br>
    <input size="10" type="number" id="ch2" name="ch2" value="22">
    <button id="btnsel2" class="btnselect">Select</button>
    <label for="ch2">ble ble ble</label>
</div>

</body>

</html>

clean and simple.

How to apply shell command to each line of a command output?

You actually can use sed to do it, provided it is GNU sed.

... | sed 's/match/command \0/e'

How it works:

  1. Substitute match with command match
  2. On substitution execute command
  3. Replace substituted line with command output.

adb not finding my device / phone (MacOS X)

Its damn strange but just plugging to the USB port located next to Thunderbolt port on my mid-2014 MBP with Retina worked!

The other USB port would simply not recognise the device.

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

Any future date in JavaScript (postman test uses JavaScript) can be retrieved as:

var dateNow = new Date();  
var twoWeeksFutureDate = new Date(dateNow.setDate(dateNow.getDate() + 14)).toISOString();

postman.setEnvironmentVariable("future-date", twoWeeksFutureDate);

How to pull remote branch from somebody else's repo

If the forked repo is protected so you can't push directly into it, and your goal is to make changes to their foo, then you need to get their branch foo into your repo like so:

git remote add protected_repo https://github.com/theirusername/their_repo.git
git fetch protected_repo 
git checkout --no-track protected_repo/foo

Now you have a local copy of foo with no upstream associated to it. You can commit changes to it (or not) and then push your foo to your own remote repo.

git push --set-upstream origin foo

Now foo is in your repo on GitHub and your local foo is tracking it. If they continue to make changes to foo you can fetch theirs and merge into your foo.

git checkout foo 
git fetch protected_repo
git merge protected_repo/foo

SQLite error 'attempt to write a readonly database' during insert?

I got this in my browser when I changed from using http://localhost to http://145.900.50.20 (where 145.900.50.20 is my local IP address) and then changed back to localhost -- it was necessary to stay with the IP address once I had changed to that once

Cloning a private Github repo

This worked for me on mac git clone https://[email protected]:username/repo_name

Python, HTTPS GET with basic authentication

using only standard modules and no manual header encoding

...which seems to be the intended and most portable way

the concept of python urllib is to group the numerous attributes of the request into various managers/directors/contexts... which then process their parts:

import urllib.request, ssl

# to avoid verifying ssl certificates
httpsHa = urllib.request.HTTPSHandler(context= ssl._create_unverified_context())

# setting up realm+urls+user-password auth
# (top_level_url may be sequence, also the complete url, realm None is default)
top_level_url = 'https://ip:port_or_domain'
# of the std managers, this can send user+passwd in one go,
# not after HTTP req->401 sequence
password_mgr = urllib.request.HTTPPasswordMgrWithPriorAuth()
password_mgr.add_password(None, top_level_url, "user", "password", is_authenticated=True)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
# create OpenerDirector
opener = urllib.request.build_opener(handler, httpsHa)

url = top_level_url + '/some_url?some_query...'
response = opener.open(url)

print(response.read())

How can I open the interactive matplotlib window in IPython notebook?

You can use

%matplotlib qt

If you got the error ImportError: Failed to import any qt binding then install PyQt5 as: pip install PyQt5 and it works for me.

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

To resolve this issue:

  1. The jstl jar should be in your classpath. If you are using maven, add a dependency to jstl in your pom.xml using the snippet provided here. If you are not using maven, download the jstl jar from here and deploy it into your WEB-INF/lib.

  2. Make sure you have the following taglib directive at the top of your jsp:

     <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Make a DIV fill an entire table cell

Try putting display:table block inside a cell

Python: Adding element to list while iterating

I had a similar problem today. I had a list of items that needed checking; if the objects passed the check, they were added to a result list. If they didn't pass, I changed them a bit and if they might still work (size > 0 after the change), I'd add them on to the back of the list for rechecking.

I went for a solution like

items = [...what I want to check...]
result = []
while items:
    recheck_items = []
    for item in items:
        if check(item):
            result.append(item)
        else:
            item = change(item)  # Note that this always lowers the integer size(),
                                 # so no danger of an infinite loop
            if item.size() > 0:
                recheck_items.append(item)
    items = recheck_items  # Let the loop restart with these, if any

My list is effectively a queue, should probably have used some sort of queue. But my lists are small (like 10 items) and this works too.

Insert some string into given string at given index in Python

An important point that often bites new Python programmers but the other posters haven't made explicit is that strings in Python are immutable -- you can't ever modify them in place.

You need to retrain yourself when working with strings in Python so that instead of thinking, "How can I modify this string?" instead you're thinking "how can I create a new string that has some pieces from this one I've already gotten?"

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

If using maven, usually you put log4j.properties under java or resources?

Some "data mining" accounts for that src/main/resources is the typical place.

Results on Google Code Search:

  • src/main/resources/log4j.properties: 4877
  • src/main/java/log4j.properties: 215

Check if value exists in column in VBA

Try adding WorksheetFunction:

If Not IsError(Application.WorksheetFunction.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
' String is in range

Dump a mysql database to a plaintext (CSV) backup from the command line

If you can cope with table-at-a-time, and your data is not binary, use the -B option to the mysql command. With this option it'll generate TSV (tab separated) files which can import into Excel, etc, quite easily:

% echo 'SELECT * FROM table' | mysql -B -uxxx -pyyy database

Alternatively, if you've got direct access to the server's file system, use SELECT INTO OUTFILE which can generate real CSV files:

SELECT * INTO OUTFILE 'table.csv'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM table

How to properly create an SVN tag from trunk?

@victor hugo and @unwind are correct, and victor's solution is by far the simplest. However BEWARE of externals in your SVN project. If you reference external libraries, the external's revision reference (whether a tag, or HEAD, or number) will remain unchanged when you tag directories that have external references.

It is possible to create a script to handle this aspect of tagging, for a discussion on that topic, see this SO article: Tagging an SVN checkout with externals

Select all elements with a "data-xxx" attribute without using jQuery

While not as pretty as querySelectorAll (which has a litany of issues), here's a very flexible function that recurses the DOM and should work in most browsers (old and new). As long as the browser supports your condition (ie: data attributes), you should be able to retrieve the element.

To the curious: Don't bother testing this vs. QSA on jsPerf. Browsers like Opera 11 will cache the query and skew the results.

Code:

function recurseDOM(start, whitelist)
{
    /*
    *    @start:        Node    -    Specifies point of entry for recursion
    *    @whitelist:    Object  -    Specifies permitted nodeTypes to collect
    */

    var i = 0, 
    startIsNode = !!start && !!start.nodeType, 
    startHasChildNodes = !!start.childNodes && !!start.childNodes.length,
    nodes, node, nodeHasChildNodes;
    if(startIsNode && startHasChildNodes)
    {       
        nodes = start.childNodes;
        for(i;i<nodes.length;i++)
        {
            node = nodes[i];
            nodeHasChildNodes = !!node.childNodes && !!node.childNodes.length;
            if(!whitelist || whitelist[node.nodeType])
            {
                //condition here
                if(!!node.dataset && !!node.dataset.foo)
                {
                    //handle results here
                }
                if(nodeHasChildNodes)
                {
                    recurseDOM(node, whitelist);
                }
            }
            node = null;
            nodeHasChildNodes = null;
        }
    }
}

You can then initiate it with the following:

recurseDOM(document.body, {"1": 1}); for speed, or just recurseDOM(document.body);

Example with your specification: http://jsbin.com/unajot/1/edit

Example with differing specification: http://jsbin.com/unajot/2/edit

LINQ Orderby Descending Query

I think this first failed because you are ordering value which is null. If Delivery is a foreign key associated table then you should include this table first, example below:

var itemList = from t in ctn.Items.Include(x=>x.Delivery)
                    where !t.Items && t.DeliverySelection
                    orderby t.Delivery.SubmissionDate descending
                    select t;

open existing java project in eclipse

Eclipse does not have internal Subversion connectivity. After you've downloaded and unzipped Eclipse, you have to install a Subversion plug-in. Check with the other developers as to which Subversion plug-in you're using. Subclipse is one Subversion plug-in.

After you've installed the Subversion plug-in, you have to give Eclipse the repository information in the SVN Repositories view of the SVN Repositories perspective. One of the other developers should have that information.

Finally, you check out the project from Subversion, by left clicking on the Package Explorer, selecting New -> Project, and in the New Project wizard,left clicking on SVN -> Checkout projects from SVN.

Open existing file, append a single line

We can use

public StreamWriter(string path, bool append);

while opening the file

string path="C:\\MyFolder\\Notes.txt"
StreamWriter writer = new StreamWriter(path, true);

First parameter is a string to hold a full file path Second parameter is Append Mode, that in this case is made true

Writing to the file can be done with:

writer.Write(string)

or

writer.WriteLine(string)

Sample Code

private void WriteAndAppend()
{
            string Path = Application.StartupPath + "\\notes.txt";
            FileInfo fi = new FileInfo(Path);
            StreamWriter SW;
            StreamReader SR;
            if (fi.Exists)
            {
                SR = new StreamReader(Path);
                string Line = "";
                while (!SR.EndOfStream) // Till the last line
                {
                    Line = SR.ReadLine();
                }
                SR.Close();
                int x = 0;
                if (Line.Trim().Length <= 0)
                {
                    x = 0;
                }
                else
                {
                    x = Convert.ToInt32(Line.Substring(0, Line.IndexOf('.')));
                }
                x++;
                SW = new StreamWriter(Path, true);
                SW.WriteLine("-----"+string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
                SW.WriteLine(x.ToString() + "." + textBox1.Text);

            }
            else
            {
                SW = new StreamWriter(Path);
                SW.WriteLine("-----" + string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
                SW.WriteLine("1." + textBox1.Text);
            }
            SW.Flush();
            SW.Close();
        }

OAuth: how to test with local URLs?

You can edit the hosts file on windows or linux Windows : C:\Windows\System32\Drivers\etc\hosts Linux : /etc/hosts

localhost name resolution is handled within DNS itself.

127.0.0.1 mywebsite.com

after you finish your tests you just comment the line you add to disable it

127.0.0.1 mywebsite.com

Dynamically access object property using variable

You can achieve this in quite a few different ways.

let foo = {
    bar: 'Hello World'
};

foo.bar;
foo['bar'];

The bracket notation is specially powerful as it let's you access a property based on a variable:

let foo = {
    bar: 'Hello World'
};

let prop = 'bar';

foo[prop];

This can be extended to looping over every property of an object. This can be seem redundant due to newer JavaScript constructs such as for ... of ..., but helps illustrate a use case:

let foo = {
    bar: 'Hello World',
    baz: 'How are you doing?',
    last: 'Quite alright'
};

for (let prop in foo.getOwnPropertyNames()) {
    console.log(foo[prop]);
}

Both dot and bracket notation also work as expected for nested objects:

let foo = {
    bar: {
        baz: 'Hello World'
    }
};

foo.bar.baz;
foo['bar']['baz'];
foo.bar['baz'];
foo['bar'].baz;

Object destructuring

We could also consider object destructuring as a means to access a property in an object, but as follows:

let foo = {
    bar: 'Hello World',
    baz: 'How are you doing?',
    last: 'Quite alright'
};

let prop = 'last';
let { bar, baz, [prop]: customName } = foo;

// bar = 'Hello World'
// baz = 'How are you doing?'
// customName = 'Quite alright'

Setting a spinner onClickListener() in Android

The following works how you want it, but it is not ideal.

public class Tester extends Activity {

    String[] vals = { "here", "are", "some", "values" };
    Spinner spinner;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        spinner = (Spinner) findViewById(R.id.spin);
        ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, vals);
        spinner.setAdapter(ad);
        Log.i("", "" + spinner.getChildCount());
        Timer t = new Timer();
        t.schedule(new TimerTask() {

            @Override
            public void run() {
                int a = spinner.getCount();
                int b = spinner.getChildCount();
                System.out.println("Count =" + a);
                System.out.println("ChildCount =" + b);
                for (int i = 0; i < b; i++) {
                    View v = spinner.getChildAt(i);
                    if (v == null) {
                        System.out.println("View not found");
                    } else {
                        v.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                        Log.i("","click");
                                        }
                        });
                    }
                }
            }
        }, 500);
    }
}

Let me know exactly how you need the spinner to behave, and we can work out a better solution.

Pattern matching using a wildcard

glob2rx() converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.

If you want to match "blue*" where * has the usual wildcard, not regular expression, meaning we use glob2rx() to convert the wildcard pattern into a useful regular expression:

> glob2rx("blue*")
[1] "^blue"

The returned object is a regular expression.

Given your data:

x <- c('red','blue1','blue2', 'red2')

we can pattern match using grep() or similar tools:

> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE  TRUE  TRUE FALSE

As for the selecting rows problem you posted

> a <- data.frame(x =  c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2

or via subset():

> with(a, subset(a, subset = grepl(grx, x)))
      x
2 blue1
3 blue2

Hope that explains what grob2rx() does and how to use it?

Declaring array of objects

Using forEach we can store data in case we have already data we want to do some business login on data.

var sample = new Array();
var x = 10;
var sample = [1,2,3,4,5,6,7,8,9];
var data = [];

sample.forEach(function(item){
    data.push(item);
})

document.write(data);

Example by using simple for loop

var data = [];
for(var i = 0 ; i < 10 ; i++){
   data.push(i);
}
document.write(data);

Convert string to decimal, keeping fractions

Hello i was have the same issue, but it is easly, just do this:

string cadena="96.23";

decimal NoDecimal=decimal.parse(cadena.replace(".",","))

I think this is beacuse the notation that accept C# on decimal numbers are with a ","

Get Android Device Name

 static String getDeviceName() {
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method getMethod = systemPropertiesClass.getMethod("get", String.class);
            Object object = new Object();
            Object obj = getMethod.invoke(object, "ro.product.device");
            return (obj == null ? "" : (String) obj);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

enter image description here

you can get 'idol3' by this way.

How to create the branch from specific commit in different branch

Try

git checkout <commit hash>
git checkout -b new_branch

The commit should only exist once in your tree, not in two separate branches.

This allows you to check out that specific commit and name it what you will.

How to reference image resources in XAML?

One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.

Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images" 

Set your Image source like this:

<Image Source={Binding {x:Static UI:Resources.Search}} /> where 'Search' is name of the resource.

How do I convert a string to a number in PHP?

I got the question "say you were writing the built in function for casting an integer to a string in PHP, how would you write that function" in a programming interview. Here's a solution.

$nums = ["0","1","2","3","4","5","6","7","8","9"];
$int = 15939; 
$string = ""; 
while ($int) { 
    $string .= $nums[$int % 10]; 
    $int = (int)($int / 10); 
} 
$result = strrev($string);

How to display an unordered list in two columns?

The legacy solution in the top answer didn't work for me because I wanted to affect multiple lists on the page and the answer assumes a single list plus it uses a fair bit of global state. In this case I wanted to alter every list inside a <section class="list-content">:

const columns = 2;
$("section.list-content").each(function (index, element) {
    let section = $(element);
    let items = section.find("ul li").detach();
    section.find("ul").detach();
    for (let i = 0; i < columns; i++) {
        section.append("<ul></ul>");
    }
    let lists = section.find("ul");
    for (let i = 0; i < items.length; i++) {
        lists.get(i % columns).append(items[i]);
    }
});

C: socket connection timeout

On Linux you can also use:

struct timeval timeout;
timeout.tv_sec  = 7;  // after 7 seconds connect() will timeout
timeout.tv_usec = 0;
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
connect(...)

Don't forget to clear SO_SNDTIMEO after connect() if you don't need it.

Visual Studio replace tab with 4 spaces?

If you don't see the formatting option, you can do Tools->Import and Export settings to import the missing one.

How do I find out what License has been applied to my SQL Server installation?

I presume you mean via SSMS?

For a SQL Server Instance:

SELECT SERVERPROPERTY('productversion'), 
       SERVERPROPERTY ('productlevel'), 
       SERVERPROPERTY ('edition')

For a SQL Server Installation:

Select @@Version

IntelliJ IDEA "The selected directory is not a valid home for JDK"

for me ,with JDK11 and IntelliJ 2016.3 , I kept getting the same message so I decided to uninstall JDK11 and installed JDK8 instead and it immediately worked!

How to check cordova android version of a cordova/phonegap project?

Run

cordova -v 

to see the currently running version. Run the npm info command

npm info cordova

for a longer listing that includes the current version along with other available version numbers

how to get last insert id after insert query in codeigniter active record

**Inside Model**
function add_info($data){
   $this->db->insert('tbl_user_info',$data);
   $last_id = $this->db->insert_id();
   return  $last_id;
}

**Inside Controller**
public function save_user_record() {
  $insertId =  $this->welcome_model->save_user_info($data);
  echo $insertId->id;
}

Complex CSS selector for parent of active child

According to Wikipedia:

Selectors are unable to ascend

CSS offers no way to select a parent or ancestor of element that satisfies certain criteria. A more advanced selector scheme (such as XPath) would enable more sophisticated stylesheets. However, the major reasons for the CSS Working Group rejecting proposals for parent selectors are related to browser performance and incremental rendering issues.

And for anyone searching SO in future, this might also be referred to as an ancestor selector.

Update:

The Selectors Level 4 Spec allows you to select which part of the select is the subject:

The subject of the selector can be explicitly identified by prepending a dollar sign ($) to one of the compound selectors in a selector. Although the element structure that the selector represents is the same with or without the dollar sign, indicating the subject in this way can change which compound selector represents the subject in that structure.

Example 1:

For example, the following selector represents a list item LI unique child of an ordered list OL:

OL > LI:only-child

However the following one represents an ordered list OL having a unique child, that child being a LI:

$OL > LI:only-child

The structures represented by these two selectors are the same, but the subjects of the selectors are not.

Although this isn't available (currently, November 2011) in any browser or as a selector in jQuery.

How can I get a JavaScript stack trace when I throw an exception?

function stacktrace(){
  return (new Error()).stack.split('\n').reverse().slice(0,-2).reverse().join('\n');
}

How can I use a local image as the base image with a dockerfile?

Verified: it works well in Docker 1.7.0.

Don't specify --pull=true when running the docker build command

From this thread on reference locally-built image using FROM at dockerfile:

If you want use the local image as the base image, pass without the option --pull=true
--pull=true will always attempt to pull a newer version of the image.

Illegal Character when trying to compile java code

I solved this by right clicking in my textEdit program file and selecting [substitutions] and un-checking smart quotes.

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

The first matches any number of digits within your string (allows other characters too, i.e.: "039330a29"). The second allows only 45 digits (and not less). So just take the better from both:

^\d{1,45}$

where \d is the same like [0-9].

How can I git stash a specific file?

I usually add to index changes I don't want to stash and then stash with --keep-index option.

git add app/controllers/cart_controller.php
git stash --keep-index
git reset

Last step is optional, but usually you want it. It removes changes from index.


Warning As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.

How to use aria-expanded="true" to change a css property

You could use querySelector() with attribute selector '[attribute="value"]', then affect css rule using .style, as you can see in the example below:

_x000D_
_x000D_
document.querySelector('a[aria-expanded="true"]').style.backgroundColor = "#42DCA3";
_x000D_
<ul><li class="active">_x000D_
  <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> <span class="network-name">Google+ with aria expanded true</span></a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> <span class="network-name">Google+ with aria expanded false</span></a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

jQuery solution :

If you want to use a jQuery solution you could simply use css() method :

$('a[aria-expanded="true"]').css('background-color','#42DCA3');

Hope this helps.

How to convert a timezone aware string to datetime in Python without dateutil?

Here is the Python Doc for datetime object using dateutil package..

from dateutil.parser import parse

get_date_obj = parse("2012-11-01T04:16:13-04:00")
print get_date_obj

Javascript to stop HTML5 video playback on modal window close

When you close the video you just need to pause it.

$("#closeSimple").click(function() {
    $("div#simpleModal").removeClass("show");
    $("#videoContainer")[0].pause();
    return false;                   
});

<video id="videoContainer" width="320" height="240" src="Davis_5109iPadFig3.m4v" controls="controls"> </video>

Also, for reference, here's the Opera documentation for scripting video controls.

Google Chrome: This setting is enforced by your administrator

On Linux, you can get rid of "Managed by your organization" Chrome policies, by removing these directories (as sudo probably):

/etc/opt/chrome/policies
/etc/opt/chrome/policies/managed
/etc/opt/chrome/policies/recommended

ASP.NET MVC - Extract parameter of an URL

I'm not familiar with ASP.NET but I guess you could use a split function to split it in an array using the / as delimiter, then grab the last element in the array (usually the array length -1) to get the extract you want.

Ok this does not seem to work for all the examples.

What about a regex?

.*(/|[a-zA-Z]+\?)(.*)

then get that last subexpression (.*), I believe it's $+ in .Net, I'm not sure

Why is this HTTP request not working on AWS Lambda?

Simple Working Example of Http request using node.

const http = require('https')
exports.handler = async (event) => {
    return httprequest().then((data) => {
        const response = {
            statusCode: 200,
            body: JSON.stringify(data),
        };
    return response;
    });
};
function httprequest() {
     return new Promise((resolve, reject) => {
        const options = {
            host: 'jsonplaceholder.typicode.com',
            path: '/todos',
            port: 443,
            method: 'GET'
        };
        const req = http.request(options, (res) => {
          if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        req.on('error', (e) => {
          reject(e.message);
        });
        // send the request
       req.end();
    });
}

convert '1' to '0001' in JavaScript

String.prototype.padZero= function(len, c){
    var s= this, c= c || '0';
    while(s.length< len) s= c+ s;
    return s;
}

dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.

warning: incompatible implicit declaration of built-in function ‘xyz’

In the case of some programs, these errors are normal and should not be fixed.

I get these error messages when compiling the program phrap (for example). This program happens to contain code that modifies or replaces some built in functions, and when I include the appropriate header files to fix the warnings, GCC instead generates a bunch of errors. So fixing the warnings effectively breaks the build.

If you got the source as part of a distribution that should compile normally, the errors might be normal. Consult the documentation to be sure.

How to set background color of view transparent in React Native

Use rgba value for the backgroundColor.

For example,

backgroundColor: 'rgba(52, 52, 52, 0.8)'

This sets it to a grey color with 80% opacity, which is derived from the opacity decimal, 0.8. This value can be anything from 0.0 to 1.0.

How to replace special characters in a string?

Here is a function I used to remove all possible special characters from the string

let name = name.replace(/[&\/\\#,+()$~%!.„'":*‚^_¤?<>|@ª{«»§}©®™ ]/g, '').toLowerCase();

How to change Format of a Cell to Text using VBA

Well this should change your format to text.

Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"

How do I sort a vector of pairs based on the second element of the pair?

You can use boost like this:

std::sort(a.begin(), a.end(), 
          boost::bind(&std::pair<int, int>::second, _1) <
          boost::bind(&std::pair<int, int>::second, _2));

I don't know a standard way to do this equally short and concise, but you can grab boost::bind it's all consisting of headers.

SELECT last id, without INSERT

In MySQL, this does return the highest value from the id column:

SELECT MAX(id) FROM tablename;

However, this does not put that id into $n:

$n = mysql_query("SELECT max(id) FROM tablename");

To get the value, you need to do this:

$result = mysql_query("SELECT max(id) FROM tablename");

if (!$result) {
    die('Could not query:' . mysql_error());
}

$id = mysql_result($result, 0, 'id');

If you want to get the last insert ID from A, and insert it into B, you can do it with one command:

INSERT INTO B (col) SELECT MAX(id) FROM A;

Create a dropdown component

I would say that it depends on what you want to do.

If your dropdown is a component for a form that manages a state, I would leverage the two-way binding of Angular2. For this, I would use two attributes: an input one to get the associated object and an output one to notify when the state changes.

Here is a sample:

export class DropdownValue {
  value:string;
  label:string;

  constructor(value:string,label:string) {
    this.value = value;
    this.label = label;
  }
}

@Component({
  selector: 'dropdown',
  template: `
    <ul>
      <li *ngFor="let value of values" (click)="select(value.value)">{{value.label}}</li>
    </ul>
  `
})
export class DropdownComponent {
  @Input()
  values: DropdownValue[];

  @Input()
  value: string[];

  @Output()
  valueChange: EventEmitter;

  constructor(private elementRef:ElementRef) {
    this.valueChange = new EventEmitter();
  }

  select(value) {
    this.valueChange.emit(value);
  }
}

This allows you to use it this way:

<dropdown [values]="dropdownValues" [(value)]="value"></dropdown>

You can build your dropdown within the component, apply styles and manage selections internally.

Edit

You can notice that you can either simply leverage a custom event in your component to trigger the selection of a dropdown. So the component would now be something like this:

export class DropdownValue {
  value:string;
  label:string;

  constructor(value:string,label:string) {
    this.value = value;
    this.label = label;
  }
}

@Component({
  selector: 'dropdown',
  template: `
    <ul>
      <li *ngFor="let value of values" (click)="selectItem(value.value)">{{value.label}}</li>
    </ul>
  `
})
export class DropdownComponent {
  @Input()
  values: DropdownValue[];

  @Output()
  select: EventEmitter;

  constructor() {
    this.select = new EventEmitter();
  }

  selectItem(value) {
    this.select.emit(value);
  }
}

Then you can use the component like this:

<dropdown [values]="dropdownValues" (select)="action($event.value)"></dropdown>

Notice that the action method is the one of the parent component (not the dropdown one).

Docker: How to delete all local Docker images

Adding to techtabu's accepted answer, If you're using docker on windows, you can use the following command

for /F "delims=" %A in ('docker ps -a -q') do docker rm %A

here, the command docker ps -a -q lists all the images and this list is passed to docker rm one by one

see this for more details on how this type of command format works in windows cmd.

Moving x-axis to the top of a plot in matplotlib

You want set_ticks_position rather than set_label_position:

ax.xaxis.set_ticks_position('top') # the rest is the same

This gives me:

enter image description here

how to get html content from a webview?

Actually this question has many answers. Here are 2 of them :

  • This first is almost the same as yours, I guess we got it from the same tutorial.

public class TestActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        final WebView webview = (WebView) findViewById(R.id.browser);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                webview.loadUrl("javascript:window.HtmlViewer.showHTML" +
                        "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
            }
        });

        webview.loadUrl("http://android-in-action.com/index.php?post/" +
                "Common-errors-and-bugs-and-how-to-solve-avoid-them");
    }

    class MyJavaScriptInterface {

        private Context ctx;

        MyJavaScriptInterface(Context ctx) {
            this.ctx = ctx;
        }

        public void showHTML(String html) {
            new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
                    .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
        }

    }
}

This way your grab the html through javascript. Not the prettiest way but when you have your javascript interface, you can add other methods to tinker it.


  • An other way is using an HttpClient like there.

The option you choose also depends, I think, on what you intend to do with the retrieved html...

GitHub: How to make a fork of public repository private?

There is one more option now ( January-2015 )

  1. Create a new private repo
  2. On the empty repo screen there is an "import" option/button enter image description here
  3. click it and put the existing github repo url There is no github option mention but it works with github repos too. enter image description here
  4. DONE

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

Add 'x' number of hours to date

for add 2 hours to "now"

$date = new DateTime('now +2 hours');

or

$date = date("Y-m-d H:i:s", strtotime('+2 hours', $now)); // as above in example

or

$now = new DateTime();

$now->add(new DateInterval('PT2H')); // as above in example

CSS Layout - Dynamic width DIV

try

<div style="width:100%;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>

or

<div style="width:100%; border:2px solid #dadada;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>    
</div>

Determine number of pages in a PDF file

Docotic.Pdf library may be used to accomplish the task.

Here is sample code:

PdfDocument document = new PdfDocument();
document.Open("file.pdf");
int pageCount = document.PageCount;

The library will parse as little as possible so performance should be ok.

Disclaimer: I work for Bit Miracle.

how to release localhost from Error: listen EADDRINUSE

If you like UI more, find the process Node.js in windows task manager and kill it.

How do I create a table based on another table

select * into newtable from oldtable

How to view/delete local storage in Firefox?

From Firefox 34 onwards you now have an option for Storage Inspector, which you can enable it from developer tools settings

Once there, you can enable the Storage options under Default Firefox Developer tools

Updated 27-3-16

Firefox 48.0a1 now supports Cookies editing.

Updated 3-4-16

Firefox 48.0a1 now supports localStorage and sessionStorage editing.

Updated 02-08-16

Firefox 48 (stable release) and onward supports editing of all storage types, except IndexedDB

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

I assume you are using gcc, to simply link object files do:

$ gcc -o output file1.o file2.o

To get the object-files simply compile using

$ gcc -c file1.c

this yields file1.o and so on.

If you want to link your files to an executable do

$ gcc -o output file1.c file2.c

What does "The APR based Apache Tomcat Native library was not found" mean?

On Mac OS X:

$ brew install tomcat-native
==> tomcat-native
In order for tomcat's APR lifecycle listener to find this library, you'll
need to add it to java.library.path. This can be done by adding this line
to $CATALINA_HOME/bin/setenv.sh

  CATALINA_OPTS="$CATALINA_OPTS -Djava.library.path=/usr/local/opt/tomcat-native/lib"

If $CATALINA_HOME/bin/setenv.sh doesn't exist, create it and make it executable.

Then add it to the eclipse's tomcat arguments (double-click Server > Open Launch Configuration > Arguments tab > VM arguments)

-Djava.library.path=/usr/local/opt/tomcat-native/lib

how can I debug a jar at runtime?

With IntelliJ IDEA you can create a Jar Application runtime configuration, select the JAR, the sources, the JRE to run the Jar with and start debugging. Here is the documentation.

Is there a way to collapse all code blocks in Eclipse?

Collapse all : CTRL + SHIFT + /

Expand all code blocks : CTRL + *

How do I install Keras and Theano in Anaconda Python on Windows?

Anaconda with Windows

  • Run anaconda prompt with administrator privilages
  • conda update conda
  • conda update --all
  • conda install mingw libpython
  • conda install theano

After conda commands it's required to accept process - Proceed ([y]/n)?

TypeError: a bytes-like object is required, not 'str'

Simply replace message parameter passed in clientSocket.sendto(message,(serverName, serverPort)) to clientSocket.sendto(message.encode(),(serverName, serverPort)). Then you would successfully run in in python3

What is the difference between URI, URL and URN?

Below I sum up Prateek Joshi's awesome explanation.

The theory:

  • URI (uniform resource identifier) identifies a resource (text document, image file, etc)
  • URL (uniform resource locator) is a subset of the URIs that include a network location
  • URN (uniform resource name) is a subset of URIs that include a name within a given space, but no location

That is:

enter image description here

And for an example:

enter image description here

Also, if you haven't already, I suggest reading Roger Pate's answer.

Simulating ENTER keypress in bash script

You might find the yes command useful.

See man yes

Easy way to export multiple data.frame to multiple Excel worksheets

I do this all the time, all I do is

WriteXLS::WriteXLS(
    all.dataframes,
    ExcelFileName = xl.filename,
    AdjWidth = T,
    AutoFilter = T,
    FreezeRow = 1,
    FreezeCol = 2,
    BoldHeaderRow = T,
    verbose = F,
    na = '0'
  )

and all those data frames come from here

all.dataframes <- vector()
for (obj.iter in all.objects) {
  obj.name <- obj.iter
  obj.iter <- get(obj.iter)
  if (class(obj.iter) == 'data.frame') {
      all.dataframes <- c(all.dataframes, obj.name)
}

obviously sapply routine would be better here

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Calling stored procedure with return value

I had a similar problem with the SP call returning an error that an expected parameter was not included. My code was as follows.
Stored Procedure:

@Result int OUTPUT

And C#:

            SqlParameter result = cmd.Parameters.Add(new SqlParameter("@Result", DbType.Int32));
            result.Direction = ParameterDirection.ReturnValue;

In troubleshooting, I realized that the stored procedure was ACTUALLY looking for a direction of "InputOutput" so the following change fixed the problem.

            r

Result.Direction = ParameterDirection.InputOutput;

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

If you are using SQL Server 2012+ you can use CONCAT function in which we don't have to do any explicit conversion

SET @ActualWeightDIMS = Concat(@Actual_Dims_Lenght, 'x', @Actual_Dims_Width, 'x' 
                        , @Actual_Dims_Height) 

Parse JSON String into List<string>

Seems like a bad way to do it (creating two correlated lists) but I'm assuming you have your reasons.

I'd parse the JSON string (which has a typo in your example, it's missing a comma between the two objects) into a strongly-typed object and then use a couple of LINQ queries to get the two lists.

void Main()
{
    string json = "{\"People\":[{\"FirstName\":\"Hans\",\"LastName\":\"Olo\"},{\"FirstName\":\"Jimmy\",\"LastName\":\"Crackedcorn\"}]}";

    var result = JsonConvert.DeserializeObject<RootObject>(json);

    var firstNames = result.People.Select (p => p.FirstName).ToList();
    var lastNames = result.People.Select (p => p.LastName).ToList();
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class RootObject
{
    public List<Person> People { get; set; }
}

a href link for entire div in HTML/CSS

put display:block on the anchor element. and/or zoom:1;

but you should just really do this.

a#parentdivimage{position:relative; width:184px; height:235px; 
                 border:2px solid #000; text-align:center; 
                 background-image:url("myimage.jpg"); 
                 background-position: 50% 50%; 
                 background-repeat:no-repeat; display:block; 
                 text-indent:-9999px}

<a id="parentdivimage">whatever your alt attribute was</a>

How do I remove  from the beginning of a file?

Open the PHP file under question, in Notepad++.

Click on Encoding at the top and change from "Encoding in UTF-8 without BOM" to just "Encoding in UTF-8". Save and overwrite the file on your server.

How to split elements of a list?

Something like:

>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']

Microsoft SQL Server 2005 service fails to start

I had similar problem while installing SQL Server 2005 on Windows 7 Professional and got error SQL server failed to start. I logged in as a Administrator (my user id is administrator) in windows.

SOLUTION

  1. Go to services, from control panel -> Administrative Tools

  2. Click on properties of "SQL Server (MSSQLSERVER)"

  3. Go to Log On Tab, Select "This Account"

  4. Enter your windows login detail (administrator and password)

  5. Start the service manually, it should work fine..

Hope this too helps..

How to check if a table contains an element in Lua?

You can put the values as the table's keys. For example:

function addToSet(set, key)
    set[key] = true
end

function removeFromSet(set, key)
    set[key] = nil
end

function setContains(set, key)
    return set[key] ~= nil
end

There's a more fully-featured example here.

Java's L number (long) specification

There are specific suffixes for long (e.g. 39832L), float (e.g. 2.4f) and double (e.g. -7.832d).

If there is no suffix, and it is an integral type (e.g. 5623), it is assumed to be an int. If it is not an integral type (e.g. 3.14159), it is assumed to be a double.

In all other cases (byte, short, char), you need the cast as there is no specific suffix.

The Java spec allows both upper and lower case suffixes, but the upper case version for longs is preferred, as the upper case L is less easy to confuse with a numeral 1 than the lower case l.

See the JLS section 3.10 for the gory details (see the definition of IntegerTypeSuffix).

PHP foreach loop through multidimensional array

<?php
$first = reset($arr_nav); // Get the first element
$last  = end($arr_nav);   // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) { 
   $first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
   $last['class'] = 'last';
}

Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.

Where can I find error log files?

I am using Cent OS 6.6 with Apache and for me error log files are in

/usr/local/apache/log

Create Hyperlink in Slack

Recently it became possible (but with an odd workaround).

To do this you must first create text with the desired hyperlink in an editor that supports rich text formatting. This can be an advanced text editor, web browser, email client, web-development IDE, etc.). Then copypaste the text from the editor or rendered HTML from browser (or other). E.g. in the example below I copypasted the head of this StackOverflow page. As you may see, the hyperlink have been copied correctly and is clickable in the message (checked on Mac Desktop, browser, and iOS apps).

Message in Slack

On Mac

I was able to compose the desired link in the native Pages app as shown below. When you are done, copypaste your text into Slack app. This is the probably easiest way on Mac OS.

Link creation in Pages

On Windows

I have a strong suspicion that MS Word will do the same trick, but unfortunately I don't have an installed instance to check.

Universal

Create text in an online editor, such as Google Documents. Use Insert -> Link, modify the text and web URL, then copypaste into Slack.

enter image description here

Is there an opposite to display:none?

The best answer for display: none is

display:inline

or

display:normal

How can I solve a connection pool problem between ASP.NET and SQL Server?

Make sure you set up the correct settings for connection pool. This is very important as I have explained in the following article: https://medium.com/@dewanwaqas/configurations-that-significantly-improves-your-app-performance-built-using-sql-server-and-net-ed044e53b60 You will see a drastic improvement in your application's performance if you follow it.

Hiding a password in a python script (insecure obfuscation only)

A way that I have done this is as follows:

At the python shell:

>>> from cryptography.fernet import Fernet
>>> key = Fernet.generate_key()
>>> print(key)
b'B8XBLJDiroM3N2nCBuUlzPL06AmfV4XkPJ5OKsPZbC4='
>>> cipher = Fernet(key)
>>> password = "thepassword".encode('utf-8')
>>> token = cipher.encrypt(password)
>>> print(token)
b'gAAAAABe_TUP82q1zMR9SZw1LpawRLHjgNLdUOmW31RApwASzeo4qWSZ52ZBYpSrb1kUeXNFoX0tyhe7kWuudNs2Iy7vUwaY7Q=='

Then, create a module with the following code:

from cryptography.fernet import Fernet

# you store the key and the token
key = b'B8XBLJDiroM3N2nCBuUlzPL06AmfV4XkPJ5OKsPZbC4='
token = b'gAAAAABe_TUP82q1zMR9SZw1LpawRLHjgNLdUOmW31RApwASzeo4qWSZ52ZBYpSrb1kUeXNFoX0tyhe7kWuudNs2Iy7vUwaY7Q=='

# create a cipher and decrypt when you need your password
cipher = Fernet(key)

mypassword = cipher.decrypt(token).decode('utf-8')

Once you've done this, you can either import mypassword directly or you can import the token and cipher to decrypt as needed.

Obviously, there are some shortcomings to this approach. If someone has both the token and the key (as they would if they have the script), they can decrypt easily. However it does obfuscate, and if you compile the code (with something like Nuitka) at least your password won't appear as plain text in a hex editor.

make a phone call click on a button

Have you given the permission in the manifest file

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

and inside your activity

  Intent callIntent = new Intent(Intent.ACTION_CALL);
    callIntent.setData(Uri.parse("tel:123456789"));
    startActivity(callIntent);

Let me know if you find any issue.

How do I get list of all tables in a database using TSQL?

SQL Server 2000, 2005, 2008, 2012, 2014, 2016, 2017 or 2019:

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

To show only tables from a particular database

SELECT TABLE_NAME 
FROM [<DATABASE_NAME>].INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE'

Or,

SELECT TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE' 
    AND TABLE_CATALOG='dbName' --(for MySql, use: TABLE_SCHEMA='dbName' )

PS: For SQL Server 2000:

SELECT * FROM sysobjects WHERE xtype='U' 

New warnings in iOS 9: "all bitcode will be dropped"

Method canOpenUrl is in iOS 9 (due to privacy) changed and is not free to use any more. Your banner provider checks for installed apps so that they do not show banners for an app that is already installed.

That gives all the log statements like

-canOpenURL: failed for URL: "kindle://home" - error: "This app is not allowed to query for scheme kindle"

The providers should update their logic for this.

If you need to query for installed apps/available schemes you need to add them to your info.plist file.

Add the key 'LSApplicationQueriesSchemes' to your plist as an array. Then add strings in that array like 'kindle'.

Of course this is not really an option for the banner ads (since those are dynamic), but you can still query that way for your own apps or specific other apps like Twitter and Facebook.

Documentation of the canOpenUrl: method canOpenUrl:

Documentation about the LSApplicationQueriesSchemes key

Image change every 30 seconds - loop

setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.

CODE:

var im = document.getElementById("img");

var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;

function changeImage()
{
  im.setAttribute("src", images[index]);
  index++;
  if(index >= images.length)
  {
    index=0;
  }
}

setInterval(changeImage, 30000);

How to read specific lines from a file (by line number)?

You can do a seek() call which positions your read head to a specified byte within the file. This won't help you unless you know exactly how many bytes (characters) are written in the file before the line you want to read. Perhaps your file is strictly formatted (each line is X number of bytes?) or, you could count the number of characters yourself (remember to include invisible characters like line breaks) if you really want the speed boost.

Otherwise, you do have to read every line prior to the line you desire, as per one of the many solutions already proposed here.

SQL Server: Database stuck in "Restoring" state

Have you tried running a VERIFY ONLY? Just to make sure it's a sound backup.

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

Netbeans how to set command line arguments in Java

I am guessing that you are running the file using Run | Run File (or shift-F6) rather than Run | Run Main Project. The NetBeans 7.1 help file (F1 is your friend!) states for the Arguments parameter:

Add arguments to pass to the main class during application execution. Note that arguments cannot be passed to individual files.

I verified this with a little snippet of code:

public class Junk
{
    public static void main(String[] args)
    {
        for (String s : args)
            System.out.println("arg -> " + s);
    }
}

I set Run -> Arguments to x y z. When I ran the file by itself I got no output. When I ran the project the output was:

arg -> x
arg -> y
arg -> z

editing PATH variable on mac

use

~/.bash_profile

or

~/.MacOSX/environment.plist

(see Runtime Configuration Guidelines)

Prime numbers between 1 to 100 in C Programming Language

#include<stdio.h>
main()
{
    int i,j,k;
    for(i=2;i<=100;i++)
    {
        k=0;
        for(j=2;j<=i;j++)
        {
            if(i%j==0)
            k++;
        }
        if(k==1)
        printf("%d\t",i);
    }
}

Laravel 5.4 redirection to custom url after login

Path Customization (tested in laravel 7) When a user is successfully authenticated, they will be redirected to the /home URI. You can customize the post-authentication redirect path using the HOME constant defined in your RouteServiceProvider:

public const HOME = '/home';

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

You don't have write permissions for the /var/lib/gems/2.3.0 directory

Rather than changing owners, which might lock out other local users, or –some day– your own ruby server/deployment-things... running under a different user...

I would rather simply extend rights of that particular folder to... well, everybody:

cd /var/lib
sudo chmod -R a+w gems/

(I did encounter your error as well. So this is fairly verified.)

Android ViewPager with bottom dots

Following is my proposed solution.

  • Since we need to show only some images in the view pagers so have avoided the cumbersome use of fragments.
    • Implemented the view page indicators (the bottom dots without any extra library or plugin)
    • On the touch of the view page indicators(the dots) also the page navigation is happening.
    • Please don"t forget to add your own images in the resources.
    • Feel free to comment and improve upon it.

A) Following is my activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="schneider.carouseladventure.MainActivity">

    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/viewpager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:id="@+id/viewPagerIndicator"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="5dp"
        android:gravity="center">

        <LinearLayout
            android:id="@+id/viewPagerCountDots"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:orientation="horizontal" />

    </RelativeLayout>


</RelativeLayout>

B) pager_item.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imageView" />
</LinearLayout>

C) MainActivity.java

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {

    int[] mResources = {R.drawable.nature1, R.drawable.nature2, R.drawable.nature3, R.drawable.nature4,
            R.drawable.nature5, R.drawable.nature6
    };

    ViewPager mViewPager;
    private CustomPagerAdapter mAdapter;
    private LinearLayout pager_indicator;
    private int dotsCount;
    private ImageView[] dots;


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

        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        pager_indicator = (LinearLayout) findViewById(R.id.viewPagerCountDots);
        mAdapter = new CustomPagerAdapter(this, mResources);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(0);
        mViewPager.setOnPageChangeListener(this);

        setPageViewIndicator();

    }

    private void setPageViewIndicator() {

        Log.d("###setPageViewIndicator", " : called");
        dotsCount = mAdapter.getCount();
        dots = new ImageView[dotsCount];

        for (int i = 0; i < dotsCount; i++) {
            dots[i] = new ImageView(this);
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );

            params.setMargins(4, 0, 4, 0);

            final int presentPosition = i;
            dots[presentPosition].setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mViewPager.setCurrentItem(presentPosition);
                    return true;
                }

            });


            pager_indicator.addView(dots[i], params);
        }

        dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        Log.d("###onPageSelected, pos ", String.valueOf(position));
        for (int i = 0; i < dotsCount; i++) {
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
        }

        dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));

        if (position + 1 == dotsCount) {

        } else {

        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

D) CustomPagerAdapter.java

 import android.content.Context;
    import android.support.v4.view.PagerAdapter;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.LinearLayout;

    public class CustomPagerAdapter extends PagerAdapter {
        private Context mContext;
        LayoutInflater mLayoutInflater;
        private int[] mResources;

        public CustomPagerAdapter(Context context, int[] resources) {
            mContext = context;
            mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mResources = resources;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            View itemView = mLayoutInflater.inflate(R.layout.pager_item,container,false);
            ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
            imageView.setImageResource(mResources[position]);
           /* LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(950, 950);
            imageView.setLayoutParams(layoutParams);*/
            container.addView(itemView);
            return itemView;
        }

        @Override
        public void destroyItem(ViewGroup collection, int position, Object view) {
            collection.removeView((View) view);
        }

        @Override
        public int getCount() {
            return mResources.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

E) selecteditem_dot.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" android:useLevel="true"
    android:dither="true">

    <size android:height="12dip" android:width="12dip"/>

    <solid android:color="#7e7e7e"/>
</shape>

F) nonselecteditem_dot.xml

 <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval" android:useLevel="true"
        android:dither="true">        
        <size android:height="12dip" android:width="12dip"/>        
        <solid android:color="#d3d3d3"/>
    </shape>

first image

enter image description here

Subtracting Number of Days from a Date in PL/SQL

Use sysdate-1 to subtract one day from system date.

select sysdate, sysdate -1 from dual;

Output:

SYSDATE  SYSDATE-1
-------- ---------
22-10-13 21-10-13 

Is there a way for non-root processes to bind to "privileged" ports on Linux?

Answer at 2015/Sep:

ip6tables now supports IPV6 NAT: http://www.netfilter.org/projects/iptables/files/changes-iptables-1.4.17.txt

You will need kernel 3.7+

Proof:

[09:09:23] root@X:~ ip6tables -t nat -vnL
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 REDIRECT   tcp      eth0   *       ::/0                 ::/0                 tcp dpt:80 redir ports 8080
    0     0 REDIRECT   tcp      eth0   *       ::/0                 ::/0                 tcp dpt:443 redir ports 1443

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 6148 packets, 534K bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 6148 packets, 534K bytes)
 pkts bytes target     prot opt in     out     source               destination

datetimepicker is not a function jquery

Place your scripts in this order:   

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>   
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

Pass a JavaScript function as parameter

I chopped all my hair off with that issue. I couldn't make the examples above working, so I ended like :

function foo(blabla){
    var func = new Function(blabla);
    func();
}
// to call it, I just pass the js function I wanted as a string in the new one...
foo("alert('test')");

And that's working like a charm ... for what I needed at least. Hope it might help some.

Undefined reference to 'vtable for xxx'

One or more of your .cpp files is not being linked in, or some non-inline functions in some class are not defined. In particular, takeaway::textualGame()'s implementation can't be found. Note that you've defined a textualGame() at toplevel, but this is distinct from a takeaway::textualGame() implementation - probably you just forgot the takeaway:: there.

What the error means is that the linker can't find the "vtable" for a class - every class with virtual functions has a "vtable" data structure associated with it. In GCC, this vtable is generated in the same .cpp file as the first listed non-inline member of the class; if there's no non-inline members, it will be generated wherever you instantiate the class, I believe. So you're probably failing to link the .cpp file with that first-listed non-inline member, or never defining that member in the first place.

What is the advantage of using REST instead of non-REST HTTP?

Simply put, REST means using HTTP the way it's meant to be.

Have a look at Roy Fielding's dissertation about REST. I think that every person that is doing web development should read it.

As a note, Roy Fielding is one of the key drivers behind the HTTP protocol, as well.

To name some of the advandages:

  • Simple.
  • You can make good use of HTTP cache and proxy server to help you handle high load.
  • It helps you organize even a very complex application into simple resources.
  • It makes it easy for new clients to use your application, even if you haven't designed it specifically for them (probably, because they weren't around when you created your app).

How to view DLL functions?

For native code it's probably best to use Dependency Walker. It also possible to use dumpbin command line utility that comes with Visual Studio.

The VMware Authorization Service is not running

This problem was solved for me by running VMware workstation as Windows administrator. From the start menu right click on the VMware workstation, then select "Run as Administrator"

PostgreSQL query to list all table names?

Open up the postgres terminal with the databse you would like:

psql dbname (run this line in a terminal)

then, run this command in the postgres environment

\d

This will describe all tables by name. Basically a list of tables by name ascending.

Then you can try this to describe a table by fields:

\d tablename.

Hope this helps.

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

First do this either in Build Phase of Jenkins if using or set in /etc/profile:

unset DISPLAY
export DISPLAY=:0

then set this property either in java code or using maven: -Djava.awt.headless=false

Linux / Bash, using ps -o to get process by specific name?

Sometimes you need to grep the process by name - in that case:

ps aux | grep simple-scan

Example output:

simple-scan  1090  0.0  0.1   4248  1432 ?        S    Jun11   0:00

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

We've just come across a very similar issue and I'm now very much a +1 for never using Money except in top level presentation. We have multiple tables (effectively a sales voucher and sales invoice) each of which contains one or more Money fields for historical reasons, and we need to perform a pro-rata calculation to work out how much of the total invoice Tax is relevant to each line on the sales voucher. Our calculation is

vat proportion = total invoice vat x (voucher line value / total invoice value)

This results in a real world money / money calculation which causes scale errors on the division part, which then multiplies up into an incorrect vat proportion. When these values are subsequently added, we end up with a sum of the vat proportions which do not add up to the total invoice value. Had either of the values in the brackets been a decimal (I'm about to cast one of them as such) the vat proportion would be correct.

When the brackets weren't there originally this used to work, I guess because of the larger values involved, it was effectively simulating a higher scale. We added the brackets because it was doing the multiplication first, which was in some rare cases blowing the precision available for the calculation, but this has now caused this much more common error.

Python: For each list element apply a function across the list

Some readable python:

def JoeCalimar(l):
    masterList = []
    for i in l:
        for j in l:
            masterList.append(1.*i/j)
    pos = masterList.index(min(masterList))
    a = pos/len(masterList)
    b = pos%len(masterList)
    return (l[a],l[b])

Let me know if something is not clear.

Windows batch: echo without new line

Using: echo | set /p= or <NUL set /p= will both work to suppress the newline.

However, this can be very dangerous when writing more advanced scripts when checking the ERRORLEVEL becomes important as setting set /p= without specifying a variable name will set the ERRORLEVEL to 1.

A better approach would be to just use a dummy variable name like so:
echo | set /p dummyName=Hello World

This will produce exactly what you want without any sneaky stuff going on in the background as I had to find out the hard way, but this only works with the piped version; <NUL set /p dummyName=Hello will still raise the ERRORLEVEL to 1.

Radio buttons not checked in jQuery

This works too. It seems shortest working notation: !$('#selector:checked')

How to get milliseconds from LocalDateTime in Java 8

To avoid ZoneId you can do:

LocalDateTime date = LocalDateTime.of(1970, 1, 1, 0, 0);

System.out.println("Initial Epoch (TimeInMillis): " + date.toInstant(ZoneOffset.ofTotalSeconds(0)).toEpochMilli());

Getting 0 as value, that's right!

collapse cell in jupyter notebook

Create custom.js file inside ~/.jupyter/custom/ with following contents:

$("<style type='text/css'> .cell.code_cell.collapse { max-height:30px; overflow:hidden;} </style>").appendTo("head");
$('.prompt.input_prompt').on('click', function(event) {
    console.log("CLICKED", arguments)   
    var c = $(event.target.closest('.cell.code_cell'))
    if(c.hasClass('collapse')) {
        c.removeClass('collapse');
    } else {
        c.addClass('collapse');
    }
});

After saving, restart the server and refresh the notebook. You can collapse any cell by clicking on the input label (In[]).

How to Get True Size of MySQL Database?

If you are using MySql Workbench, its very easy to get all details of Database size, each table size, index size etc.

  1. Right Click on Schema
  2. Select Schema Inspector option

    enter image description here

  3. It Shows all details of Schema size

  4. Select Tables Tab to see size of each table.

    enter image description here

  5. Table size diplayed in Data Lenght column

Unit testing click event in Angular

I had a similar problem (detailed explanation below), and I solved it (in jasmine-core: 2.52) by using the tick function with the same (or greater) amount of milliseconds as in original setTimeout call.

For example, if I had a setTimeout(() => {...}, 2500); (so it will trigger after 2500 ms), I would call tick(2500), and that would solve the problem.

What I had in my component, as a reaction on a Delete button click:

delete() {
    this.myService.delete(this.id)
      .subscribe(
        response => {
          this.message = 'Successfully deleted! Redirecting...';
          setTimeout(() => {
            this.router.navigate(['/home']);
          }, 2500); // I wait for 2.5 seconds before redirect
        });
  }

Her is my working test:

it('should delete the entity', fakeAsync(() => {
    component.id = 1; // preparations..
    component.getEntity(); // this one loads up the entity to my component
    tick(); // make sure that everything that is async is resolved/completed
    expect(myService.getMyThing).toHaveBeenCalledWith(1);
    // more expects here..
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    const deleteButton = fixture.debugElement.query(By.css('.btn-danger')).nativeElement;
    deleteButton.click(); // I've clicked the button, and now the delete function is called...

    tick(2501); // timeout for redirect is 2500 ms :)  <-- solution

    expect(myService.delete).toHaveBeenCalledWith(1);
    // more expects here..
  }));

P.S. Great explanation on fakeAsync and general asyncs in testing can be found here: a video on Testing strategies with Angular 2 - Julie Ralph, starting from 8:10, lasting 4 minutes :)

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

How to get char from string by index?

Python.org has an excellent section on strings here. Scroll down to where it says "slice notation".

make *** no targets specified and no makefile found. stop

If after ./configure Makefile.in and Makefile.am are generated and make fail (by showing this following make: *** No targets specified and no makefile found. Stop.) so there is something not configured well, to solve it, first run "autoconf" commande to solve wrong configuration then re-run "./configure" commande and finally "make"

How to make a Qt Widget grow with the window size?

I found it was impossible to assign a layout to the centralwidget until I had added at least one child beneath it. Then I could highlight the tiny icon with the red 'disabled' mark and then click on a layout in the Designer toolbar at top.

make sounds (beep) with c++

alternatively in c or c++ after including stdio.h

char d=(char)(7);
printf("%c\n",d);

(char)7 is called the bell character.

SQL distinct for 2 fields in a database

How about simply:

select distinct c1, c2 from t

or

select c1, c2, count(*)
from t
group by c1, c2

What is javax.inject.Named annotation supposed to be used for?

Use @Named to differentiate between different objects of the same type bound in the same scope.

@Named("maxWaitTime")
public long maxWaitTimeMs;

@Named("minWaitTime")
public long minWaitTimeMs;

Without the @Named qualifier, the injector would not know which long to bind to which variable.

  • If you want to create annotations that act like @Named, use the @Qualifier annotation when creating them.

  • If you look at @Named, it is itself annotated with @Qualifier.

Run text file as commands in Bash

You can use something like this:

for i in `cat foo.txt`
do
    sudo $i
done

Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo as a command. But it gives you an idea on how to start.

Decoding base64 in batch

Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL

I'm not sure what version of Windows introduced this command.

To encode a file:

certutil -encode inputFileName encodedOutputFileName

To decode a file:

certutil -decode encodedInputFileName decodedOutputFileName

There are a number of available verbs and options available to CERTUTIL.

To get a list of nearly all available verbs:

certutil -?

To get help on a particular verb (-encode for example):

certutil -encode -?

To get complete help for nearly all verbs:

certutil -v -?

Mysteriously, the -encodehex verb is not listed with certutil -? or certutil -v -?. But it is described using certutil -encodehex -?. It is another handy function :-)

Update

Regarding David Morales' comment, there is a poorly documented type option to the -encodehex verb that allows creation of base64 strings without header or footer lines.

certutil [Options] -encodehex inFile outFile [type]

A type of 1 will yield base64 without the header or footer lines.

See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.

Not investigated, but the -decodehex verb also has an optional trailing type argument.

What does this thread join code mean?

Hope it helps!

package join;

public class ThreadJoinApp {

    Thread th = new Thread("Thread 1") {
        public void run() {
            System.out.println("Current thread execution - " + Thread.currentThread().getName());
            for (int i = 0; i < 10; i++) {
                System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
            }
        }
    };

    Thread th2 = new Thread("Thread 2") {
        public void run() {
            System.out.println("Current thread execution - " + Thread.currentThread().getName());

            //Thread 2 waits until the thread 1 successfully completes.
            try {
            th.join();
            } catch( InterruptedException ex) {
                System.out.println("Exception has been caught");
            }

            for (int i = 0; i < 10; i++) {
                System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
            }
        }
    };

    public static void main(String[] args) {
        ThreadJoinApp threadJoinApp = new ThreadJoinApp();
        threadJoinApp.th.start();
        threadJoinApp.th2.start();
    }

    //Happy coding -- Parthasarathy S
}

How to create JSON string in C#

You can also try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContracts, any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.

Basic Example

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json); 

Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.

How to group subarrays by a column value?

There is no native one, just use a loop.

$result = array();
foreach ($data as $element) {
    $result[$element['id']][] = $element;
}

Creating object with dynamic keys

You can't define an object literal with a dynamic key. Do this :

var o = {};
o[key] = value;
return o;

There's no shortcut (edit: there's one now, with ES6, see the other answer).

Uncaught ReferenceError: $ is not defined error in jQuery

Include the jQuery file first:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
 <script type="text/javascript" src="./javascript.js"></script>
    <script
        src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
    </script>

How to deep copy a list?

If you are not allowed to directly import modules you can define your own deepcopy function as -

def copyList(L):
if type(L[0]) != list:
    return [i for i in L]
else:
    return [copyList(L[i]) for i in range(len(L))]

It's working can be seen easily as -

>>> x = [[1,2,3],[3,4]]
>>> z = copyList(x)
>>> x
[[1, 2, 3], [3, 4]]
>>> z
[[1, 2, 3], [3, 4]]
>>> id(x)
2095053718720
>>> id(z)
2095053718528
>>> id(x[0])
2095058990144
>>> id(z[0])
2095058992192
>>>

How can I close a login form and show the main form without my application closing?

The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.

The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:

static void Main()
{
    LoginForm fLogin = new LoginForm();
    if (fLogin.ShowDialog() == DialogResult.OK)
    {
        Application.Run(new MainForm());
    }
    else
    {
        Application.Exit();
    }
}

How to connect android wifi to adhoc wifi?

If you have a Microsoft Virtual WiFi Miniport Adapter as one of the available network adapters, you may do the following:

  • Run Windows Command Processor (cmd) as Administrator
  • Type: netsh wlan set hostednetwork mode=allow ssid=NAME key=PASSWORD
  • Then: netsh wlan start hostednetwork
  • Open "Control Panel\Network and Internet\Network Connections"
  • Right-click on your active network adapter (the one that you use to connect on the internet) and then click Properties
  • Then open Sharing tab
  • Check "Allow other network users to connect..." and select your WiFi Miniport Adapter
  • Once finished, type: netsh wlan stop hostednetwork

That's it!

Source: How to connect android phone to an ad-hoc network without softwares.

SQL Query for Logins

Select * From Master..SysUsers Where IsSqlUser = 1

Is it correct to use alt tag for an anchor link?

I'm surprised to see all answers stating the use of alt attribute in a tag is not valid. This is absolutely wrong.

Html does not block you using any attributes:

<a your-custom-attribute="value">Any attribute can be used</a>

If you ask if it is semantically correct to use alt attribute in a then I will say:

NO. It is used to set image description <img alt="image description" />.

It is a matter of what you'd do with the attributes. Here's an example:

_x000D_
_x000D_
a::after {_x000D_
  content: attr(color); /* attr can be used as content */_x000D_
  display: block;_x000D_
  color: white;_x000D_
  background-color: blue;_x000D_
  background-color: attr(color); /* This won't work */_x000D_
  display: none;_x000D_
}_x000D_
a:hover::after {_x000D_
  display: block;_x000D_
}_x000D_
[hidden] {_x000D_
  display: none;_x000D_
}
_x000D_
<a href="#" color="red">Hover me!</a>_x000D_
<a href="#" color="red" hidden>In some cases, it can be used to hide it!</a>
_x000D_
_x000D_
_x000D_

Again, if you ask if it is semantically correct to use custom attribute then I will say:

No. Use data-* attributes for its semantic use.


Oops, question was asked in 2013.

How to get the client IP address in PHP

This function should work as expected

function Get_User_Ip()
{
    $IP = false;
    if (getenv('HTTP_CLIENT_IP'))
    {
        $IP = getenv('HTTP_CLIENT_IP');
    }
    else if(getenv('HTTP_X_FORWARDED_FOR'))
    {
        $IP = getenv('HTTP_X_FORWARDED_FOR');
    }
    else if(getenv('HTTP_X_FORWARDED'))
    {
        $IP = getenv('HTTP_X_FORWARDED');
    }
    else if(getenv('HTTP_FORWARDED_FOR'))
    {
        $IP = getenv('HTTP_FORWARDED_FOR');
    }
    else if(getenv('HTTP_FORWARDED'))
    {
        $IP = getenv('HTTP_FORWARDED');
    }
    else if(getenv('REMOTE_ADDR'))
    {
        $IP = getenv('REMOTE_ADDR');
    }

    //If HTTP_X_FORWARDED_FOR == server ip
    if((($IP) && ($IP == getenv('SERVER_ADDR')) && (getenv('REMOTE_ADDR')) || (!filter_var($IP, FILTER_VALIDATE_IP))))
    {
        $IP = getenv('REMOTE_ADDR');
    }

    if($IP)
    {
        if(!filter_var($IP, FILTER_VALIDATE_IP))
        {
            $IP = false;
        }
    }
    else
    {
        $IP = false;
    }
    return $IP;
}

Get device token for push notification

To get Token Device you can do by some steps:

1) Enable APNS (Apple Push Notification Service) for both Developer Certification and Distribute Certification, then redownload those two file.

2) Redownload both Developer Provisioning and Distribute Provisioning file.

3) In Xcode interface: setting provisioning for PROJECT and TARGETS with two file provisioning have download.

4) Finally, you need to add the code below in AppDelegate file to get Token Device (note: run app in real device).

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
     [self.window addSubview:viewController.view];
     [self.window makeKeyAndVisible];

     NSLog(@"Registering for push notifications...");    
     [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
 (UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
     return YES;
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
     NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
     NSLog(@"%@", str);
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 
     NSString *str = [NSString stringWithFormat: @"Error: %@", err];
     NSLog(@"%@",str);
}

Jquery, set value of td in a table?

You can try below code:

$("Your button id or class").live("click", function(){

    $('#detailInfo').html('set your value as you want');

});

Good Luck...

How to add a WiX custom action that happens only on uninstall (via MSI)?

Here's a set of properties i made that feel more intuitive to use than the built in stuff. The conditions are based off of the truth table supplied above by ahmd0.

<!-- truth table for installer varables (install vs uninstall vs repair vs upgrade) https://stackoverflow.com/a/17608049/1721136 -->
 <SetProperty Id="_INSTALL"   After="FindRelatedProducts" Value="1"><![CDATA[Installed="" AND PREVIOUSVERSIONSINSTALLED=""]]></SetProperty>
 <SetProperty Id="_UNINSTALL" After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED="" AND REMOVE="ALL"]]></SetProperty>
 <SetProperty Id="_CHANGE"    After="FindRelatedProducts" Value="1"><![CDATA[Installed<>"" AND REINSTALL="" AND PREVIOUSVERSIONSINSTALLED<>"" AND REMOVE=""]]></SetProperty>
 <SetProperty Id="_REPAIR"    After="FindRelatedProducts" Value="1"><![CDATA[REINSTALL<>""]]></SetProperty>
 <SetProperty Id="_UPGRADE"   After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED<>"" ]]></SetProperty>

Here's some sample usage:

  <Custom Action="CaptureExistingLocalSettingsValues" After="InstallInitialize">NOT _UNINSTALL</Custom>
  <Custom Action="GetConfigXmlToPersistFromCmdLineArgs" After="InstallInitialize">_INSTALL OR _UPGRADE</Custom>
  <Custom Action="ForgetProperties" Before="InstallFinalize">_UNINSTALL OR _UPGRADE</Custom>
  <Custom Action="SetInstallCustomConfigSettingsArgs" Before="InstallCustomConfigSettings">NOT _UNINSTALL</Custom>
  <Custom Action="InstallCustomConfigSettings" Before="InstallFinalize">NOT _UNINSTALL</Custom>

Issues:

How would I find the second largest salary from the employee table?

Try something like:

SELECT TOP 1 compensation FROM (
  SELECT TOP 2 compensation FROM employees
  ORDER BY compensation DESC
) AS em ORDER BY compensation ASC

Essentially:

  • Find the top 2 salaries in descending order.
  • Of those 2, find the top salary in ascending order.
  • The selected value is the second-highest salary.

If the salaries aren't distinct, you can use SELECT DISTINCT TOP ... instead.

Setting a minimum/maximum character count for any character using a regular expression

It's usually the metacharacter . when not inside a character class.

So use ^.{1,35}$. However, dot does not include newlines unless the dot-all modifier is applied against it.

You can use ^[\S\s]{1,35}$ without any modifiers, and this includes newlines as well.

Change Oracle port from port 8080

There are many Oracle components that run a web service, so it's not clear which you are referring to.

For example, the web site port for standalone OC4J is configured in the j2ee/home/config/default-web-site.xml file:

<web-site xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/web-site-10_0.xsd"
port="8888" display-name="OC4J 10g (10.1.3) Default Web Site"
schema-major-version="10" schema-minor-version="0" > 

Hot deploy on JBoss - how do I make JBoss "see" the change?

In case you are working with the Eclipse IDE there is a free plugin Manik-Hotdeploy.

This plugin allows you to connect your eclipse workspace with your wildfly deployment folder. After a maven build your artifact (e.g. war or ear) will be automatically pushed into the deployment folder of your server. Also web content files (e.g. .xhtml .jsf ...) will be hot deployed.

The plugin runs for wildfly, glassfish and payara.

Read the section JBoss/Wildfly Support for more details.

A more useful statusline in vim?

Here's mine:

set statusline=
set statusline +=%1*\ %n\ %*            "buffer number
set statusline +=%5*%{&ff}%*            "file format
set statusline +=%3*%y%*                "file type
set statusline +=%4*\ %<%F%*            "full path
set statusline +=%2*%m%*                "modified flag
set statusline +=%1*%=%5l%*             "current line
set statusline +=%2*/%L%*               "total lines
set statusline +=%1*%4v\ %*             "virtual column number
set statusline +=%2*0x%04B\ %*          "character under cursor

vim statusline

And here's the colors I used:

hi User1 guifg=#eea040 guibg=#222222
hi User2 guifg=#dd3333 guibg=#222222
hi User3 guifg=#ff66ff guibg=#222222
hi User4 guifg=#a0ee40 guibg=#222222
hi User5 guifg=#eeee40 guibg=#222222

getString Outside of a Context or Activity

The best approach from the response of Khemraj:

App class

class App : Application() {

    companion object {
        lateinit var instance: Application
        lateinit var resourses: Resources
    }


    // MARK: - Lifecycle

    override fun onCreate() {
        super.onCreate()
        instance = this
        resourses = resources
    }

}

Declaration in the manifest

<application
        android:name=".App"
        ...>
</application>     

Constants class

class Localizations {

    companion object {
        val info = App.resourses.getString(R.string.info)
    }

}

Using

textView.text = Localizations.info

Reminder - \r\n or \n\r?

if you are using C#, why not using Environment.NewLine ? (i assume you use some file writer objects... just pass it the Environment.NewLine and it will handle the right terminators.

How to Change Font Size in drawString Java

All you need to do is this: click on (window) on the dropdown manue on top of your screen. click on (Editor). click on (zoom in) as many times as you need to.

App not setup: This app is still in development mode

This is an answer I haven't seen much around (this it was in a comment somewhere) although yes taking the app off development mode will work this can be bad for security or really annoying if the app isn't ready yet but you need to submit the app for review on account of needing access to special permissions (e.g. user_birthday).

What I did instead to fix the error was go to https://developers.facebook.com/sa/apps/{appId}/roles/ or from the app dashboard click roles on the left side

Then add the user account(s) to either developer or tester. Developers will need to be verified by mobile and will get access to the app to make changes but a tester will only need to be verified by email (not sure if even this is necessary but it probably is) and will only be able to use the API instead of make changes to settings.

If the app is ready for the public, obviously just take the app off development mode.

Removing empty rows of a data file in R

Here are some dplyr options:

# sample data
df <- data.frame(a = c('1', NA, '3', NA), b = c('a', 'b', 'c', NA), c = c('e', 'f', 'g', NA))

library(dplyr)

# remove rows where all values are NA:
df %>% filter_all(any_vars(!is.na(.)))
df %>% filter_all(any_vars(complete.cases(.)))  


# remove rows where only some values are NA:
df %>% filter_all(all_vars(!is.na(.)))
df %>% filter_all(all_vars(complete.cases(.)))  

# or more succinctly:
df %>% filter(complete.cases(.))  
df %>% na.omit

# dplyr and tidyr:
library(tidyr)
df %>% drop_na

Remove last item from array

Array.prototype.pop() by JavaScript convention.

let fruit = ['apple', 'orange', 'banana', 'tomato'];
let popped = fruit.pop();

console.log(popped); // "tomato"
console.log(fruit); // ["apple", "orange", "banana"]

SQL order string as number

The column I'm sorting with has any combination of alpha and numeric, so I used the suggestions in this post as a starting point and came up with this.

DECLARE @tmp TABLE (ID VARCHAR(50));
INSERT INTO @tmp VALUES ('XYZ300');
INSERT INTO @tmp VALUES ('XYZ1002');
INSERT INTO @tmp VALUES ('106');
INSERT INTO @tmp VALUES ('206');
INSERT INTO @tmp VALUES ('1002');
INSERT INTO @tmp VALUES ('J206');
INSERT INTO @tmp VALUES ('J1002');

SELECT ID, (CASE WHEN ISNUMERIC(ID) = 1 THEN 0 ELSE 1 END) IsNum
FROM @tmp
ORDER BY IsNum, LEN(ID), ID;

Results

ID
------------------------
106
206
1002
J206
J1002
XYZ300
XYZ1002

Hope this helps

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

Matplotlib: "Unknown projection '3d'" error

I encounter the same problem, and @Joe Kington and @bvanlew's answer solve my problem.

but I should add more infomation when you use pycharm and enable auto import.

when you format the code, the code from mpl_toolkits.mplot3d import Axes3D will auto remove by pycharm.

so, my solution is

from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D  # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

and it works well!