Programs & Examples On #Jquery address

A JQuery plugin that provides an API to add deep linking capabilities to the web application and allows the creation of unique URLs that can point to a website section or an application state.

Laravel 5 – Clear Cache in Shared Hosting Server

This command will clear all kinds of cache at once. :

$ php artisan optimize:clear

This is an alias of :

$ php artisan view:clear
$ php artisan config:clear
$ php artisan route:clear
$ php artisan cache:clear
$ php artisan clear-compiled

In an array of objects, fastest way to find the index of an object whose attributes match a search

Maybe you would like to use higher-order functions such as "map". Assuming you want search by 'field' attribute:

var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];

showing that a date is greater than current date

For those that want a nice conditional:

DECLARE @MyDate DATETIME  = 'some date in future' --example  DateAdd(day,5,GetDate())

IF @MyDate < DATEADD(DAY,1,GETDATE())
    BEGIN
        PRINT 'Date NOT greater than today...'
END
ELSE 
    BEGIN
       PRINT 'Date greater than today...'
END 

What is the difference between a data flow diagram and a flow chart?

Between the above answers its been explained but I will try to expand slightly...

The point about the cup of tea is a good one. A flow chart is concerned with the physical aspects of a task and as such is used to represent something as it is currently. This is useful in developing understanding about a situation/communication/training etc etc..You will likley have come across these in your work places, certainly if they have adopted the ISO9000 standards.

A data flow diagram is concerned with the logical aspects of an activity so again the cup of tea analogy is a good one. If you use a data flow diagram in conjunction with a process flow your data flow would only be concerned with the flow of data/information regarding a process, to the exclusion of the physical aspects. If you wonder why that would be useful then its because data flow diagrams allow us to move from the 'as it is' situation and see it that something as it could/will be. These two modelling approaches are common in structured analysis and design and typically used by systems/business analysts as part of business process improvement/re-engineering.

Checking if a field contains a string

How to ignore HTML tags in a RegExp match:

var text = '<p>The <b>tiger</b> (<i>Panthera tigris</i>) is the largest <a href="/wiki/Felidae" title="Felidae">cat</a> <a href="/wiki/Species" title="Species">species</a>, most recognizable for its pattern of dark vertical stripes on reddish-orange fur with a lighter underside. The species is classified in the genus <i><a href="/wiki/Panthera" title="Panthera">Panthera</a></i> with the <a href="/wiki/Lion" title="Lion">lion</a>, <a href="/wiki/Leopard" title="Leopard">leopard</a>, <a href="/wiki/Jaguar" title="Jaguar">jaguar</a>, and <a href="/wiki/Snow_leopard" title="Snow leopard">snow leopard</a>. It is an <a href="/wiki/Apex_predator" title="Apex predator">apex predator</a>, primarily preying on <a href="/wiki/Ungulate" title="Ungulate">ungulates</a> such as <a href="/wiki/Deer" title="Deer">deer</a> and <a href="/wiki/Bovid" class="mw-redirect" title="Bovid">bovids</a>.</p>';
var searchString = 'largest cat species';

var rx = '';
searchString.split(' ').forEach(e => {
  rx += '('+e+')((?:\\s*(?:<\/?\\w[^<>]*>)?\\s*)*)';
});

rx = new RegExp(rx, 'igm');

console.log(text.match(rx));

This is probably very easy to turn into a MongoDB aggregation filter.

Converting a string to a date in a cell

I was struggling with this for some time and after some help on a post I was able to come up with this formula =(DATEVALUE(LEFT(XX,10)))+(TIMEVALUE(MID(XX,12,5))) where XX is the cell in reference.

I've come across many other forums with people asking the same thing and this, to me, seems to be the simplest answer. What this will do is return text that is copied in from this format 2014/11/20 11:53 EST and turn it in to a Date/Time format so it can be sorted oldest to newest. It works with short date/long date and if you want the time just format the cell to display time and it will show. Hope this helps anyone who goes searching around like I did.

concat scope variables into string in angular directive expression

It's not very clear what the problem is and what you are trying to accomplish from the code you posted, but I'll take a stab at it.

In general, I suggest calling a function on ng-click like so:

<a ng-click="navigateToPath()">click me</a>

obj.val1 & obj.val2 should be available on your controller's $scope, you dont need to pass those into a function from the markup.

then, in your controller:

$scope.navigateToPath = function(){
   var path = '/somePath/' + $scope.obj.val1 + '/' + $scope.obj.val2; //dont need the '#'
   $location.path(path)       
}

How do I set the rounded corner radius of a color drawable using xml?

Use the <shape> tag to create a drawable in XML with rounded corners. (You can do other stuff with the shape tag like define a color gradient as well).

Here's a copy of a XML file I'm using in one of my apps to create a drawable with a white background, black border and rounded corners:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#ffffffff"/>    
             
    <stroke android:width="3dp"
            android:color="#ff000000" />

    <padding android:left="1dp"
             android:top="1dp"
             android:right="1dp"
             android:bottom="1dp" /> 
             
    <corners android:radius="7dp" /> 
</shape>

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

How to write a comment in a Razor view?

Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.

Server side Comments:

Razor .cshtml

Like so:

@* Comment goes here *@

.aspx
For those looking for the older .aspx view (and Asp.Net WebForms) server side comment syntax:

<%-- Comment goes here --%>

Client Side Comments

HTML Comment

<!-- Comment goes here -->

Javascript Comment

// One line Comment goes Here
/* Multiline comment
   goes here */

As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).

Calculate mean and standard deviation from a vector of samples in C++ using Boost

My answer is similar as Josh Greifer but generalised to sample covariance. Sample variance is just sample covariance but with the two inputs identical. This includes Bessel's correlation.

    template <class Iter> typename Iter::value_type cov(const Iter &x, const Iter &y)
    {
        double sum_x = std::accumulate(std::begin(x), std::end(x), 0.0);
        double sum_y = std::accumulate(std::begin(y), std::end(y), 0.0);

        double mx =  sum_x / x.size();
        double my =  sum_y / y.size();

        double accum = 0.0;

        for (auto i = 0; i < x.size(); i++)
        {
            accum += (x.at(i) - mx) * (y.at(i) - my);
        }

        return accum / (x.size() - 1);
    }

What is the difference between a function expression vs declaration in JavaScript?

Though the complete difference is more complicated, the only difference that concerns me is when the machine creates the function object. Which in the case of declarations is before any statement is executed but after a statement body is invoked (be that the global code body or a sub-function's), and in the case of expressions is when the statement it is in gets executed. Other than that for all intents and purposes browsers treat them the same.

To help you understand, take a look at this performance test which busted an assumption I had made of internally declared functions not needing to be re-created by the machine when the outer function is invoked. Kind of a shame too as I liked writing code that way.

PHP: If internet explorer 6, 7, 8 , or 9

This is what I ended up using a variation of, which checks for IE8 and below:

if (preg_match('/MSIE\s(?P<v>\d+)/i', @$_SERVER['HTTP_USER_AGENT'], $B) && $B['v'] <= 8) {
    // Browsers IE 8 and below
} else {
    // All other browsers
}

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

What you have is EXTRATERRESTRIAL ALIEN (U+1F47D) and BROKEN HEART (U+1F494) which are not in the basic multilingual plane. They cannot be even represented in java as one char, "".length() == 4. They are definitely not null characters and one will see squares if you are not using fonts that support them.

MySQL's utf8 only supports basic multilingual plane, and you need to use utf8mb4 instead:

For a supplementary character, utf8 cannot store the character at all, while utf8mb4 requires four bytes to store it. Since utf8 cannot store the character at all, you do not have any supplementary characters in utf8 columns and you need not worry about converting characters or losing data when upgrading utf8 data from older versions of MySQL.

So to support these characters, your MySQL needs to be 5.5+ and you need to use utf8mb4 everywhere. Connection encoding needs to be utf8mb4, character set needs to be utf8mb4 and collaction needs to be utf8mb4. For java it's still just "utf-8", but MySQL needs a distinction.

I don't know what driver you are using but a driver agnostic way to set connection charset is to send the query:

SET NAMES 'utf8mb4'

Right after making the connection.

See also this for Connector/J:

14.14: How can I use 4-byte UTF8, utf8mb4 with Connector/J?

To use 4-byte UTF8 with Connector/J configure the MySQL server with character_set_server=utf8mb4. Connector/J will then use that setting as long as characterEncoding has not been set in the connection string. This is equivalent to autodetection of the character set.

Adjust your columns and database as well:

var1 varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL

Again, your MySQL version needs to be relatively up-to-date for utf8mb4 support.

CSS position:fixed inside a positioned element

I know this is an old post but I had the same question but didn't find an answer that set the element fixed relative to a parent div. The scroll bar on medium.com is a great pure CSS solution for setting something position: fixed; relative to a parent element instead of the viewport (kinda*). It is achieved by setting the parent div to position: relative; and having a button wrapper with position: absolute; and the button of course is position: fixed; as follows:

<div class="wrapper">
  <div class="content">
    Your long content here
  </div>

  <div class="button-wrapper">
    <button class="button">This is your button</button>
  </div>
</div>

<style>
  .wrapper {
    position: relative;
  }

  .button-wrapper {
    position: absolute;
    right: 0;
    top: 0;
    width: 50px;
  }

  .button {
    position: fixed;
    top: 0;
    width: 50px;
  }
</style>

working example

*Since fixed elements don't scroll with the page the vertical position will still be relative to the viewport but the horizontal position is relative to the parent with this solution.

Fixed header, footer with scrollable content

If you're targeting browsers supporting flexible boxes you could do the following.. http://jsfiddle.net/meyertee/AH3pE/

HTML

<div class="container">
    <header><h1>Header</h1></header>
    <div class="body">Body</div>
    <footer><h3>Footer</h3></footer>
</div>

CSS

.container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
}

header {
    flex-shrink: 0;
}
.body{
    flex-grow: 1;
    overflow: auto;
    min-height: 2em;
}
footer{
    flex-shrink: 0;
}

Update:
See "Can I use" for browser support of flexible boxes.

Android basics: running code in the UI thread

As of Android P you can use getMainExecutor():

getMainExecutor().execute(new Runnable() {
  @Override public void run() {
    // Code will run on the main thread
  }
});

From the Android developer docs:

Return an Executor that will run enqueued tasks on the main thread associated with this context. This is the thread used to dispatch calls to application components (activities, services, etc).

From the CommonsBlog:

You can call getMainExecutor() on Context to get an Executor that will execute its jobs on the main application thread. There are other ways of accomplishing this, using Looper and a custom Executor implementation, but this is simpler.

Is there a way to suppress JSHint warning for one given line?

The "evil" answer did not work for me. Instead, I used what was recommended on the JSHints docs page. If you know the warning that is thrown, you can turn it off for a block of code. For example, I am using some third party code that does not use camel case functions, yet my JSHint rules require it, which led to a warning. To silence it, I wrote:

/*jshint -W106 */
save_state(id);
/*jshint +W106 */

java.util.NoSuchElementException - Scanner reading user input

You need to remove the scanner closing lines: scan.close();

It happened to me before and that was the reason.

fastest MD5 Implementation in JavaScript

I wrote tests to compare several JavaScript hash implementations, including most MD5 implementations mentioned here. To run the tests, go to http://brillout.github.io/test-javascript-hash-implementations/ and wait a bit.

It seems that the YaMD5 implementation of R. Hill's answer is the fastest.

Formula to determine brightness of RGB color

I was solving a similar task today in javascript. I've settled on this getPerceivedLightness(rgb) function for a HEX RGB color. It deals with Helmholtz-Kohlrausch effect via Fairchild and Perrotta formula for luminance correction.

/**
 * Converts RGB color to CIE 1931 XYZ color space.
 * https://www.image-engineering.de/library/technotes/958-how-to-convert-between-srgb-and-ciexyz
 * @param  {string} hex
 * @return {number[]}
 */
export function rgbToXyz(hex) {
    const [r, g, b] = hexToRgb(hex).map(_ => _ / 255).map(sRGBtoLinearRGB)
    const X =  0.4124 * r + 0.3576 * g + 0.1805 * b
    const Y =  0.2126 * r + 0.7152 * g + 0.0722 * b
    const Z =  0.0193 * r + 0.1192 * g + 0.9505 * b
    // For some reason, X, Y and Z are multiplied by 100.
    return [X, Y, Z].map(_ => _ * 100)
}

/**
 * Undoes gamma-correction from an RGB-encoded color.
 * https://en.wikipedia.org/wiki/SRGB#Specification_of_the_transformation
 * https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
 * @param  {number}
 * @return {number}
 */
function sRGBtoLinearRGB(color) {
    // Send this function a decimal sRGB gamma encoded color value
    // between 0.0 and 1.0, and it returns a linearized value.
    if (color <= 0.04045) {
        return color / 12.92
    } else {
        return Math.pow((color + 0.055) / 1.055, 2.4)
    }
}

/**
 * Converts hex color to RGB.
 * https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
 * @param  {string} hex
 * @return {number[]} [rgb]
 */
function hexToRgb(hex) {
    const match = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    if (match) {
        match.shift()
        return match.map(_ => parseInt(_, 16))
    }
}

/**
 * Converts CIE 1931 XYZ colors to CIE L*a*b*.
 * The conversion formula comes from <http://www.easyrgb.com/en/math.php>.
 * https://github.com/cangoektas/xyz-to-lab/blob/master/src/index.js
 * @param   {number[]} color The CIE 1931 XYZ color to convert which refers to
 *                           the D65/2° standard illuminant.
 * @returns {number[]}       The color in the CIE L*a*b* color space.
 */
// X, Y, Z of a "D65" light source.
// "D65" is a standard 6500K Daylight light source.
// https://en.wikipedia.org/wiki/Illuminant_D65
const D65 = [95.047, 100, 108.883]
export function xyzToLab([x, y, z]) {
  [x, y, z] = [x, y, z].map((v, i) => {
    v = v / D65[i]
    return v > 0.008856 ? Math.pow(v, 1 / 3) : v * 7.787 + 16 / 116
  })
  const l = 116 * y - 16
  const a = 500 * (x - y)
  const b = 200 * (y - z)
  return [l, a, b]
}

/**
 * Converts Lab color space to Luminance-Chroma-Hue color space.
 * http://www.brucelindbloom.com/index.html?Eqn_Lab_to_LCH.html
 * @param  {number[]}
 * @return {number[]}
 */
export function labToLch([l, a, b]) {
    const c = Math.sqrt(a * a + b * b)
    const h = abToHue(a, b)
    return [l, c, h]
}

/**
 * Converts a and b of Lab color space to Hue of LCH color space.
 * https://stackoverflow.com/questions/53733379/conversion-of-cielab-to-cielchab-not-yielding-correct-result
 * @param  {number} a
 * @param  {number} b
 * @return {number}
 */
function abToHue(a, b) {
    if (a >= 0 && b === 0) {
        return 0
    }
    if (a < 0 && b === 0) {
        return 180
    }
    if (a === 0 && b > 0) {
        return 90
    }
    if (a === 0 && b < 0) {
        return 270
    }
    let xBias
    if (a > 0 && b > 0) {
        xBias = 0
    } else if (a < 0) {
        xBias = 180
    } else if (a > 0 && b < 0) {
        xBias = 360
    }
    return radiansToDegrees(Math.atan(b / a)) + xBias
}

function radiansToDegrees(radians) {
    return radians * (180 / Math.PI)
}

function degreesToRadians(degrees) {
    return degrees * Math.PI / 180
}

/**
 * Saturated colors appear brighter to human eye.
 * That's called Helmholtz-Kohlrausch effect.
 * Fairchild and Pirrotta came up with a formula to
 * calculate a correction for that effect.
 * "Color Quality of Semiconductor and Conventional Light Sources":
 * https://books.google.ru/books?id=ptDJDQAAQBAJ&pg=PA45&lpg=PA45&dq=fairchild+pirrotta+correction&source=bl&ots=7gXR2MGJs7&sig=ACfU3U3uIHo0ZUdZB_Cz9F9NldKzBix0oQ&hl=ru&sa=X&ved=2ahUKEwi47LGivOvmAhUHEpoKHU_ICkIQ6AEwAXoECAkQAQ#v=onepage&q=fairchild%20pirrotta%20correction&f=false
 * @return {number}
 */
function getLightnessUsingFairchildPirrottaCorrection([l, c, h]) {
    const l_ = 2.5 - 0.025 * l
    const g = 0.116 * Math.abs(Math.sin(degreesToRadians((h - 90) / 2))) + 0.085
    return l + l_ * g * c
}

export function getPerceivedLightness(hex) {
    return getLightnessUsingFairchildPirrottaCorrection(labToLch(xyzToLab(rgbToXyz(hex))))
}

jQuery AJAX cross domain

I know 3 way to resolve your problem:

  1. First if you have access to both domains you can allow access for all other domain using :

    header("Access-Control-Allow-Origin: *");

    or just a domain by adding code bellow to .htaccess file:

    <FilesMatch "\.(ttf|otf|eot|woff)$"> <IfModule mod_headers.c> SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.net|dev02.otherdomain.net)$" AccessControlAllowOrigin=$0 Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin </IfModule> </FilesMatch>

  2. you can have ajax request to a php file in your server and handle request to another domain using this php file.

  3. you can use jsonp , because it doesn't need permission. for this you can read our friend @BGerrissen answer.

Finding the handle to a WPF window

If you want window handles for ALL of your application's Windows for some reason, you can use the Application.Windows property to get at all the Windows and then use WindowInteropHandler to get at their handles as you have already demonstrated.

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

In my case it was due to adding requireSSL=true to httpcookies in webconfig which made the AntiForgeryToken stop working. Example:

<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true"/>
</system.web>

To make both requireSSL=true and @Html.AntiForgeryToken() work I added this line inside the Application_BeginRequest in Global.asax

    protected void Application_BeginRequest(object sender, EventArgs e)
  {
    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
  }

How is a CRC32 checksum calculated?

For IEEE802.3, CRC-32. Think of the entire message as a serial bit stream, append 32 zeros to the end of the message. Next, you MUST reverse the bits of EVERY byte of the message and do a 1's complement the first 32 bits. Now divide by the CRC-32 polynomial, 0x104C11DB7. Finally, you must 1's complement the 32-bit remainder of this division bit-reverse each of the 4 bytes of the remainder. This becomes the 32-bit CRC that is appended to the end of the message.

The reason for this strange procedure is that the first Ethernet implementations would serialize the message one byte at a time and transmit the least significant bit of every byte first. The serial bit stream then went through a serial CRC-32 shift register computation, which was simply complemented and sent out on the wire after the message was completed. The reason for complementing the first 32 bits of the message is so that you don't get an all zero CRC even if the message was all zeros.

Best practice: PHP Magic Methods __set and __get

I do a mix of edem's answer and your second code. This way, I have the benefits of common getter/setters (code completion in your IDE), ease of coding if I want, exceptions due to inexistent properties (great for discovering typos: $foo->naem instead of $foo->name), read only properties and compound properties.

class Foo
{
    private $_bar;
    private $_baz;

    public function getBar()
    {
        return $this->_bar;
    }

    public function setBar($value)
    {
        $this->_bar = $value;
    }

    public function getBaz()
    {
        return $this->_baz;
    }

    public function getBarBaz()
    {
        return $this->_bar . ' ' . $this->_baz;
    }

    public function __get($var)
    {
        $func = 'get'.$var;
        if (method_exists($this, $func))
        {
            return $this->$func();
        } else {
            throw new InexistentPropertyException("Inexistent property: $var");
        }
    }

    public function __set($var, $value)
    {
        $func = 'set'.$var;
        if (method_exists($this, $func))
        {
            $this->$func($value);
        } else {
            if (method_exists($this, 'get'.$var))
            {
                throw new ReadOnlyException("property $var is read-only");
            } else {
                throw new InexistentPropertyException("Inexistent property: $var");
            }
        }
    }
}

Generating Random Number In Each Row In Oracle Query

Something like?

select t.*, round(dbms_random.value() * 8) + 1 from foo t;

Edit: David has pointed out this gives uneven distribution for 1 and 9.

As he points out, the following gives a better distribution:

select t.*, floor(dbms_random.value(1, 10)) from foo t;

How to select all records from one table that do not exist in another table?

SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.name = t1.name
WHERE t2.name IS NULL

Q: What is happening here?

A: Conceptually, we select all rows from table1 and for each row we attempt to find a row in table2 with the same value for the name column. If there is no such row, we just leave the table2 portion of our result empty for that row. Then we constrain our selection by picking only those rows in the result where the matching row does not exist. Finally, We ignore all fields from our result except for the name column (the one we are sure that exists, from table1).

While it may not be the most performant method possible in all cases, it should work in basically every database engine ever that attempts to implement ANSI 92 SQL

Swift presentViewController

Just use this : Make sure using nibName otherwise preloaded views of xib will not show :

var vc : ViewController = ViewController(nibName: "ViewController", bundle: nil) //change this to your class name

 self.presentViewController(vc, animated: true, completion: nil)

An established connection was aborted by the software in your host machine

On a Windows box, I wanted to avoid reboot and these did not work: * /android/adt-bundle-windows/sdk/platform-tools/adb kill-server * /android/adt-bundle-windows/sdk/platform-tools/adb start-server

So what did work to get adb running again without this error was

  1. wait for the TIME WAIT to complete, which took multiple minutes. You can view the state of the ports and watch when to restart the debugger with this command: "PortQryV2/PortQry.exe -local" This tools is downloaded here: http://support.microsoft.com/?id=832919

  2. force closing ports with "netsh int tcp reset"

'NoneType' object is not subscriptable?

Don't use list as a variable name for it shadows the builtin.

And there is no need to determine the length of the list. Just iterate over it.

def printer(data):
    for element in data:
        print(element[0])

Just an addendum: Looking at the contents of the inner lists I think they might be the wrong data structure. It looks like you want to use a dictionary instead.

VB.NET - Click Submit Button on Webbrowser page

This seems to work easily.


Public Function LoginAsTech(ByVal UserID As String, ByVal Pass As String) As Boolean
        Dim MyDoc As New mshtml.HTMLDocument
        Dim DocElements As mshtml.IHTMLElementCollection = Nothing
        Dim LoginForm As mshtml.HTMLFormElement = Nothing

        ASPComplete = 0
        WB.Navigate(VitecLoginURI)
        BrowserLoop()

        MyDoc = WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each i As mshtml.IHTMLElement In DocElements

            Select Case i.name
                Case "seLogin$UserName"
                    i.value = UserID
                Case "seLogin$Password"
                    i.value = Pass
                Case Else
                    Exit Select
            End Select

            frmServiceCalls.txtOut.Text &= i.name & " : " & i.value & " : " & i.type & vbCrLf
        Next i

        'Old Method for Clicking submit
        'WB.Document.Forms("form1").InvokeMember("submit")


        'Better Method to click submit
        LoginForm = MyDoc.forms.item("form1")
        LoginForm.item("seLogin$LoginButton").click()
        ASPComplete = 0
        BrowserLoop()



        MyDoc= WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each j As mshtml.IHTMLElement In DocElements
            frmServiceCalls.txtOut.Text &= j.name & " : " & j.value & " : " & j.type & vbCrLf

        Next j

        frmServiceCalls.txtOut.Text &= vbCrLf & vbCrLf & WB.Url.AbsoluteUri & vbCrLf
        Return 1
End Function

Sort arrays of primitive types in descending order

You cannot use Comparators for sorting primitive arrays.

Your best bet is to implement (or borrow an implementation) of a sorting algorithm that is appropriate for your use case to sort the array (in reverse order in your case).

Reading a JSP variable from JavaScript

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

    <title>JSP Page</title>
    <script>
       $(document).ready(function(){
          <% String name = "phuongmychi.github.io" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html

       });
    </script>
</head>
<body>
    <h1 id='id'>!</h1>
</body>

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

Basic True / False Declaration

$is_admin = ($user['permissions'] == 'admin' ? true : false);

Conditional Welcome Message

echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Conditional Items Message

echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.';

ref: https://davidwalsh.name/php-ternary-examples

How to use random in BATCH script?

You could do it this way, which does not require EnableDelayedExpansion

:choosenamea
cls
set /a choosemname=%random%

if %choosemname% GTR %max% goto choosenameb
if %choosemname% LSS %min% goto choosenameb
goto gotnamenow

where max is your max and min is your minimum. This is not very efficient since might take a lot of rounds if your range is too small. Also, this will not work for numbers larger than 32767.

Regular Expression to match string starting with a specific word

If you wish to match only lines beginning with stop use

^stop

If you wish to match lines beginning with the word stop followed by a space

^stop\s

Or, if you wish to match lines beginning with the word stop but followed by either a space or any other non word character you can use (your regex flavor permitting)

^stop\W

On the other hand, what follows matches a word at the beginning of a string on most regex flavors (in these flavors \w matches the opposite of \W)

^\w

If your flavor does not have the \w shortcut, you can use

^[a-zA-Z0-9]+

Be wary that this second idiom will only match letters and numbers, no symbol whatsoever.

Check your regex flavor manual to know what shortcuts are allowed and what exactly do they match (and how do they deal with Unicode.)

Delete a row in Excel VBA

Something like this will do it:

Rows("12:12").Select
Selection.Delete

So in your code it would look like something like this:

Rows(CStr(rand) & ":" & CStr(rand)).Select
Selection.Delete

MongoDB distinct aggregation

SQL Query: (group by & count of distinct)

select city,count(distinct(emailId)) from TransactionDetails group by city;

Equivalent mongo query would look like this:

db.TransactionDetails.aggregate([ 
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} } 
]);

How to remove a package from Laravel using composer?

Normally composer remove used like this is enough:

$ composer remove vendor/package

but if composer package is removed and config cache is not cleaned you cannot clean it, when you try like so

php artisan config:clear

you can get an error In ProviderRepository.php line 208:

Class 'Laracasts\Flash\FlashServiceProvider' not found

this is a dead end, unless you go deleting files

$rm bootstrap/cache/config.php

And this is Laravel 5.6 I'm talking about, not some kind of very old stuff.

It happens usually on automated deployment, when you copy files of a new release on top of old cache. Even if you cleared cache before copying. You end up with old cache and a new composer.json.

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

What is the use of DesiredCapabilities in Selenium WebDriver?

I know I am very late to answer this question.
But would like to add for further references to the give answers.
DesiredCapabilities are used like setting your config with key-value pair.
Below is an example related to Appium used for Automating Mobile platforms like Android and IOS.
So we generally set DesiredCapabilities for conveying our WebDriver for specific things we will be needing to run our test to narrow down the performance and to increase the accuracy.

So we set our DesiredCapabilities as:

// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();

// Set android deviceName desired capability. Set your device name.
capabilities.setCapability("deviceName", "your Device Name");

// Set BROWSER_NAME desired capability.
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");

// Set android VERSION desired capability. Set your mobile device's OS version.
capabilities.setCapability(CapabilityType.VERSION, "5.1");

// Set android platformName desired capability. It's Android in our case here.
capabilities.setCapability("platformName", "Android");

// Set android appPackage desired capability.

//You need to check for your appPackage Name for your app, you can use this app for that APK INFO

// Set your application's appPackage if you are using any other app. 
capabilities.setCapability("appPackage", "com.android.appPackageName");

// Set android appActivity desired capability. You can use the same app for finding appActivity of your app
capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

This DesiredCapabilities are very specific to Appium on Android Platform. For more you can refer to the official site of Selenium desiredCapabilities class

How do I read and parse an XML file in C#?

LINQ to XML Example:

// Loading from a file, you can also load from a stream
var xml = XDocument.Load(@"C:\contacts.xml");


// Query the data and write out a subset of contacts
var query = from c in xml.Root.Descendants("contact")
            where (int)c.Attribute("id") < 4
            select c.Element("firstName").Value + " " +
                   c.Element("lastName").Value;


foreach (string name in query)
{
    Console.WriteLine("Contact's Full Name: {0}", name);
}

Reference: LINQ to XML at MSDN

How to use variables in a command in sed?

This might work for you:

sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1

How to get just numeric part of CSS property with jQuery?

parseInt($(this).css('marginBottom'), 10);

parseInt will automatically ignore the units.

For example:

var marginBottom = "10px";
marginBottom = parseInt(marginBottom, 10);
alert(marginBottom); // alerts: 10

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

How to hide a mobile browser's address bar?

create host file = manifest.json

html tag head

<link rel="manifest" href="/manifest.json">

file

manifest.json

{
"name": "news",
"short_name": "news",
"description": "des news application day",
"categories": [
"news",
"business"
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone",
"orientation": "natural",
"lang": "fa",
"dir": "rtl",
"start_url": "/?application=true",
"gcm_sender_id": "482941778795",
"DO_NOT_CHANGE_GCM_SENDER_ID": "Do not change the GCM Sender ID",
"icons": [
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"related_applications": [
{
"platform": "play",
"url": "https://play.google.com/store/apps/details?id=ir.divar"
}
],
"prefer_related_applications": true
}

How to parse unix timestamp to time.Time

According to the go documentation, Unix returns a local time.

Unix returns the local Time corresponding to the given Unix time

This means the output would depend on the machine your code runs on, which, most often is what you need, but sometimes, you may want to have the value in UTC.

To do so, I adapted the snippet to make it return a time in UTC:

i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
    panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm.UTC())

This prints on my machine (in CEST)

2014-07-16 20:55:46 +0000 UTC

Add image in pdf using jspdf

No need to add any extra base64 library. Simple 5 line solution -

var img = new Image();
img.src = path.resolve('sample.jpg');

var doc = new jsPDF('p', 'mm', 'a3');  // optional parameters
doc.addImage(img, 'JPEG', 1, 2);
doc.save("new.pdf");

Java: how to convert HashMap<String, Object> to array

HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);

How to reliably open a file in the same directory as a Python script

Ok here is what I do

sys.argv is always what you type into the terminal or use as the file path when executing it with python.exe or pythonw.exe

For example you can run the file text.py several ways, they each give you a different answer they always give you the path that python was typed.

    C:\Documents and Settings\Admin>python test.py
    sys.argv[0]: test.py
    C:\Documents and Settings\Admin>python "C:\Documents and Settings\Admin\test.py"
    sys.argv[0]: C:\Documents and Settings\Admin\test.py

Ok so know you can get the file name, great big deal, now to get the application directory you can know use os.path, specifically abspath and dirname

    import sys, os
    print os.path.dirname(os.path.abspath(sys.argv[0]))

That will output this:

   C:\Documents and Settings\Admin\

it will always output this no matter if you type python test.py or python "C:\Documents and Settings\Admin\test.py"

The problem with using __file__ Consider these two files test.py

import sys
import os

def paths():
        print "__file__: %s" % __file__
        print "sys.argv: %s" % sys.argv[0]

        a_f = os.path.abspath(__file__)
        a_s = os.path.abspath(sys.argv[0])

        print "abs __file__: %s" % a_f
        print "abs sys.argv: %s" % a_s

if __name__ == "__main__":
    paths()

import_test.py

import test
import sys

test.paths()

print "--------"
print __file__
print sys.argv[0]

Output of "python test.py"

C:\Documents and Settings\Admin>python test.py
__file__: test.py
sys.argv: test.py
abs __file__: C:\Documents and Settings\Admin\test.py
abs sys.argv: C:\Documents and Settings\Admin\test.py

Output of "python test_import.py"

C:\Documents and Settings\Admin>python test_import.py
__file__: C:\Documents and Settings\Admin\test.pyc
sys.argv: test_import.py
abs __file__: C:\Documents and Settings\Admin\test.pyc
abs sys.argv: C:\Documents and Settings\Admin\test_import.py
--------
test_import.py
test_import.py

So as you can see file gives you always the python file it is being run from, where as sys.argv[0] gives you the file that you ran from the interpreter always. Depending on your needs you will need to choose which one best fits your needs.

Getting MAC Address

One other thing that you should note is that uuid.getnode() can fake the MAC addr by returning a random 48-bit number which may not be what you are expecting. Also, there's no explicit indication that the MAC address has been faked, but you could detect it by calling getnode() twice and seeing if the result varies. If the same value is returned by both calls, you have the MAC address, otherwise you are getting a faked address.

>>> print uuid.getnode.__doc__
Get the hardware address as a 48-bit positive integer.

    The first time this runs, it may launch a separate program, which could
    be quite slow.  If all attempts to obtain the hardware address fail, we
    choose a random 48-bit number with its eighth bit set to 1 as recommended
    in RFC 4122.

Bind a function to Twitter Bootstrap Modal Close

Bootstrap 4:

$('#myModal').on('hidden.bs.modal', function (e) {
   // call your method
})

hide.bs.modal: This event is fired immediately when the hide instance method has been called.

hidden.bs.modal: This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).

Confirm postback OnClientClick button ASP.NET

I know this is old and there are so many answers, some are really convoluted, can be quick and inline:

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton" OnClick="BtnUserDelete_Click" OnClientClick="return confirm('Are you sure you want to delete this user?');" meta:resourcekey="BtnUserDeleteResource1" />
                       

Table column sizing

As of Alpha 6 you can create the following sass file:

@each $breakpoint in map-keys($grid-breakpoints) {
  $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

  col, td, th {
    @for $i from 1 through $grid-columns {
        &.col#{$infix}-#{$i} {
          flex: none;
          position: initial;
        }
    }

    @include media-breakpoint-up($breakpoint, $grid-breakpoints) {
      @for $i from 1 through $grid-columns {
        &.col#{$infix}-#{$i} {
          width: 100% / $grid-columns * $i;
        }
      }
    }
  }
}

How to convert a full date to a short date in javascript?

The getDay() method returns a number to indicate the day in week (0=Sun, 1=Mon, ... 6=Sat). Use getDate() to return a number for the day in month:

var day = convertedStartDate.getDate();

If you like, you can try to add a custom format function to the prototype of the Date object:

Date.prototype.formatMMDDYYYY = function(){
    return (this.getMonth() + 1) + 
    "/" +  this.getDate() +
    "/" +  this.getFullYear();
}

After doing this, you can call formatMMDDYYY() on any instance of the Date object. Of course, this is just a very specific example, and if you really need it, you can write a generic formatting function that would do this based on a formatting string, kinda like java's SimpleDateeFormat (http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html)

(tangent: the Date object always confuses me... getYear() vs getFullYear(), getDate() vs getDay(), getDate() ranges from 1..31, but getMonth() from 0..11

It's a mess, and I always need to take a peek. http://www.w3schools.com/jsref/jsref_obj_date.asp)

Is there a way to 'pretty' print MongoDB shell output to a file?

Put your query (e.g. db.someCollection.find().pretty()) to a javascript file, let's say query.js. Then run it in your operating system's shell using command:

mongo yourDb < query.js > outputFile

Query result will be in the file named 'outputFile'.

By default Mongo prints out first 20 documents IIRC. If you want more you can define new value to batch size in Mongo shell, e.g.

DBQuery.shellBatchSize = 100.

How do I trim whitespace from a string?

I could not find a solution to what I was looking for so I created some custom functions. You can try them out.

def cleansed(s: str):
    """:param s: String to be cleansed"""
    assert s is not (None or "")
    # return trimmed(s.replace('"', '').replace("'", ""))
    return trimmed(s)


def trimmed(s: str):
    """:param s: String to be cleansed"""
    assert s is not (None or "")
    ss = trim_start_and_end(s).replace('  ', ' ')
    while '  ' in ss:
        ss = ss.replace('  ', ' ')
    return ss


def trim_start_and_end(s: str):
    """:param s: String to be cleansed"""
    assert s is not (None or "")
    return trim_start(trim_end(s))


def trim_start(s: str):
    """:param s: String to be cleansed"""
    assert s is not (None or "")
    chars = []
    for c in s:
        if c is not ' ' or len(chars) > 0:
            chars.append(c)
    return "".join(chars).lower()


def trim_end(s: str):
    """:param s: String to be cleansed"""
    assert s is not (None or "")
    chars = []
    for c in reversed(s):
        if c is not ' ' or len(chars) > 0:
            chars.append(c)
    return "".join(reversed(chars)).lower()


s1 = '  b Beer '
s2 = 'Beer  b    '
s3 = '      Beer  b    '
s4 = '  bread butter    Beer  b    '

cdd = trim_start(s1)
cddd = trim_end(s2)
clean1 = cleansed(s3)
clean2 = cleansed(s4)

print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s1, len(s1), cdd, len(cdd)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s2, len(s2), cddd, len(cddd)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s3, len(s3), clean1, len(clean1)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s4, len(s4), clean2, len(clean2)))

What exactly does += do in python?

+= adds another value with the variable's value and assigns the new value to the variable.

>>> x = 3
>>> x += 2
>>> print x
5

-=, *=, /= does similar for subtraction, multiplication and division.

"No X11 DISPLAY variable" - what does it mean?

For those who are trying to get an X Window application working from Windows from Linux:

What worked for me was to setup xming server on my windows machine, set X11 forwarding option in putty when I connect to the linux host and put in my windows ip address with the display port and then the display variable with my windows IP address:0.0

Dont forget to add the linux hosts IP address to the X0.hosts file to ensure that the xming server accepts traffic from that host. Took me a while to figure that out.

What languages are Windows, Mac OS X and Linux written in?

As an addition about the core of Mac OS X, Finder had not been written in Objective-C prior to Snow Leopard. In Snow Leopard it was written in Cocoa, Objective-C

How do I delay a function call for 5 seconds?

var rotator = function(){
  widget.Rotator.rotate();
  setTimeout(rotator,5000);
};
rotator();

Or:

setInterval(
  function(){ widget.Rotator.rotate() },
  5000
);

Or:

setInterval(
  widget.Rotator.rotate.bind(widget.Rotator),
  5000
);

How do you run a command for each line of a file?

Read a file line by line and execute commands: 4 answers

This is because there is not only 1 answer...

  1. shell command line expansion
  2. xargs dedicated tool
  3. while read with some remarks
  4. while read -u using dedicated fd, for interactive processing (sample)

Regarding the OP request: running chmod on all targets listed in file, xargs is the indicated tool. But for some other applications, small amount of files, etc...

  1. Read entire file as command line argument.

    If your file is not too big and all files are well named (without spaces or other special chars like quotes), you could use shell command line expansion. Simply:

    chmod 755 $(<file.txt)
    

    For small amount of files (lines), this command is the lighter one.

  2. xargs is the right tool

    For bigger amount of files, or almost any number of lines in your input file...

    For many binutils tools, like chown, chmod, rm, cp -t ...

    xargs chmod 755 <file.txt
    

    If you have special chars and/or a lot of lines in file.txt.

    xargs -0 chmod 755 < <(tr \\n \\0 <file.txt)
    

    if your command need to be run exactly 1 time by entry:

    xargs -0 -n 1 chmod 755 < <(tr \\n \\0 <file.txt)
    

    This is not needed for this sample, as chmod accept multiple files as argument, but this match the title of question.

    For some special case, you could even define location of file argument in commands generateds by xargs:

    xargs -0 -I '{}' -n 1 myWrapper -arg1 -file='{}' wrapCmd < <(tr \\n \\0 <file.txt)
    

    Test with seq 1 5 as input

    Try this:

    xargs -n 1 -I{} echo Blah {} blabla {}.. < <(seq 1 5)
    Blah 1 blabla 1..
    Blah 2 blabla 2..
    Blah 3 blabla 3..
    Blah 4 blabla 4..
    Blah 5 blabla 5..
    

    Where commande is done once per line.

  3. while read and variants.

    As OP suggest cat file.txt | while read in; do chmod 755 "$in"; done will work, but there is 2 issues:

    • cat | is an useless fork, and

    • | while ... ;done will become a subshell where environment will disapear after ;done.

    So this could be better written:

    while read in; do chmod 755 "$in"; done < file.txt
    

    But,

    • You may be warned about $IFS and read flags:

      help read
      
      read: read [-r] ... [-d delim] ... [name ...]
          ...
          Reads a single line from the standard input... The line is split
          into fields as with word splitting, and the first word is assigned
          to the first NAME, the second word to the second NAME, and so on...
          Only the characters found in $IFS are recognized as word delimiters.
          ...
          Options:
            ...
            -d delim   continue until the first character of DELIM is read, 
                       rather than newline
            ...
            -r do not allow backslashes to escape any characters
          ...
          Exit Status:
          The return code is zero, unless end-of-file is encountered...
      

      In some case, you may need to use

      while IFS= read -r in;do chmod 755 "$in";done <file.txt
      

      For avoiding problems with stranges filenames. And maybe if you encouter problems with UTF-8:

      while LANG=C IFS= read -r in ; do chmod 755 "$in";done <file.txt
      
    • While you use STDIN for reading file.txt, your script could not be interactive (you cannot use STDIN anymore).

  4. while read -u, using dedicated fd.

    Syntax: while read ...;done <file.txt will redirect STDIN to file.txt. That mean, you won't be able to deal with process, until they finish.

    If you plan to create interactive tool, you have to avoid use of STDIN and use some alternative file descriptor.

    Constants file descriptors are: 0 for STDIN, 1 for STDOUT and 2 for STDERR. You could see them by:

    ls -l /dev/fd/
    

    or

    ls -l /proc/self/fd/
    

    From there, you have to choose unused number, between 0 and 63 (more, in fact, depending on sysctl superuser tool) as file descriptor:

    For this demo, I will use fd 7:

    exec 7<file.txt      # Without spaces between `7` and `<`!
    ls -l /dev/fd/
    

    Then you could use read -u 7 this way:

    while read -u 7 filename;do
        ans=;while [ -z "$ans" ];do
            read -p "Process file '$filename' (y/n)? " -sn1 foo
            [ "$foo" ]&& [ -z "${foo/[yn]}" ]&& ans=$foo || echo '??'
        done
        if [ "$ans" = "y" ] ;then
            echo Yes
            echo "Processing '$filename'."
        else
            echo No
        fi
    done 7<file.txt
    

    done
    

    To close fd/7:

    exec 7<&-            # This will close file descriptor 7.
    ls -l /dev/fd/
    

    Nota: I let striked version because this syntax could be usefull, when doing many I/O with parallels process:

    mkfifo sshfifo
    exec 7> >(ssh -t user@host sh >sshfifo)
    exec 6<sshfifo
    

Return in Scala

It's not as simple as just omitting the return keyword. In Scala, if there is no return then the last expression is taken to be the return value. So, if the last expression is what you want to return, then you can omit the return keyword. But if what you want to return is not the last expression, then Scala will not know that you wanted to return it.

An example:

def f() = {
  if (something)
    "A"
  else
    "B"
}

Here the last expression of the function f is an if/else expression that evaluates to a String. Since there is no explicit return marked, Scala will infer that you wanted to return the result of this if/else expression: a String.

Now, if we add something after the if/else expression:

def f() = {
  if (something)
    "A"
  else
    "B"

  if (somethingElse)
    1
  else
    2
}

Now the last expression is an if/else expression that evaluates to an Int. So the return type of f will be Int. If we really wanted it to return the String, then we're in trouble because Scala has no idea that that's what we intended. Thus, we have to fix it by either storing the String to a variable and returning it after the second if/else expression, or by changing the order so that the String part happens last.

Finally, we can avoid the return keyword even with a nested if-else expression like yours:

def f() = {
  if(somethingFirst) {
    if (something)      // Last expression of `if` returns a String
     "A"
    else
     "B"
  }
  else {
    if (somethingElse)
      1
    else
      2

    "C"                // Last expression of `else` returns a String
  }

}

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

To post JSON, you will need to stringify it. JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Where can I set path to make.exe on Windows?

Why don't you create a bat file makedos.bat containing the following line?

c:\DOS\make.exe %1 %2 %5

and put it in C:\DOS (or C:\Windowsè or make sure that it is in your %path%)

You can run from cmd, SET and it displays all environment variables, including PATH.

In registry you can find environment variables under:

  • HKEY_CURRENT_USER\Environment
  • HKEY_CURRENT_USER\Volatile Environment
  • HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment

What is the difference between Serializable and Externalizable in Java?

There are so many difference exist between Serializable and Externalizable but when we compare difference between custom Serializable(overrided writeObject() & readObject()) and Externalizable then we find that custom implementation is tightly bind with ObjectOutputStream class where as in Externalizable case , we ourself provide an implementation of ObjectOutput which may be ObjectOutputStream class or it could be some other like org.apache.mina.filter.codec.serialization.ObjectSerializationOutputStream

In case of Externalizable interface

@Override
public void writeExternal(ObjectOutput out) throws IOException {
    out.writeUTF(key);
    out.writeUTF(value);
    out.writeObject(emp);
}

@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    this.key = in.readUTF();
    this.value = in.readUTF();
    this.emp = (Employee) in.readObject();
}





**In case of Serializable interface**


        /* 
             We can comment below two method and use default serialization process as well
             Sequence of class attributes in read and write methods MUST BE same.
        // below will not work it will not work . 
        // Exception = java.io.StreamCorruptedException: invalid type code: 00\
              private void writeObject(java.io.ObjectOutput stream) 
              */
            private void writeObject(java.io.ObjectOutputStream Outstream)
                    throws IOException {

                System.out.println("from writeObject()");
                /*     We can define custom validation or business rules inside read/write methods.
 This way our validation methods will be automatically 
    called by JVM, immediately after default serialization 
    and deserialization process 
    happens.
                 checkTestInfo();
                */

                stream.writeUTF(name);
                stream.writeInt(age);
                stream.writeObject(salary);
                stream.writeObject(address);
            }

            private void readObject(java.io.ObjectInputStream Instream)
                    throws IOException, ClassNotFoundException {
                System.out.println("from readObject()");
                name = (String) stream.readUTF();
                age = stream.readInt();
                salary = (BigDecimal) stream.readObject();
                address = (Address) stream.readObject();
                // validateTestInfo();
            }

I have added sample code to explain better. please check in/out object case of Externalizable. These are not bound to any implementation directly.
Where as Outstream/Instream are tightly bind to classes. We can extends ObjectOutputStream/ObjectInputStream but it will a bit difficult to use.

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue today. I added the user to:

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log on as a batch job

But was still getting the error. I found this post, and it turns out there's also this setting that I had to remove the user from (not sure how it got in there):

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Deny log on as a batch job

So just be aware that you may need to check both policies for the user.

FPDF utf-8 encoding (HOW-TO)

just edit the function cell in the fpdf.php file, look for the line that looks like this

function cell ($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '')
{ 

after finding the line

write after the {,

$txt = utf8_decode($txt);

save the file and ready, the accents and the utf8 encoding will be working :)

Deleting all files from a folder using PHP?

I updated the answer of @Stichoza to remove files through subfolders.

function glob_recursive($pattern, $flags = 0) {
    $fileList = glob($pattern, $flags);
    foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
        $subPattern = $dir.'/'.basename($pattern);
        $subFileList = glob_recursive($subPattern, $flags);
        $fileList = array_merge($fileList, $subFileList);
    }
    return $fileList;
}

function glob_recursive_unlink($pattern, $flags = 0) {
    array_map('unlink', glob_recursive($pattern, $flags));
}

Get Date in YYYYMMDD format in windows batch file

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

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

Refresh DataGridView when updating data source

This is copy my answer from THIS place.

Only need to fill datagrid again like this:

this.XXXTableAdapter.Fill(this.DataSet.XXX);

If you use automaticlly connect from dataGridView this code create automaticlly in Form_Load()

OPTION (RECOMPILE) is Always Faster; Why?

The very first actions before tunning queries is to defrag/rebuild the indexes and statistics, otherway you're wasting your time.

You must check the execution plan to see if it's stable (is the same when you change the parameters), if not, you might have to create a cover index (in this case for each table) (knowing th system you can create one that is usefull for other queries too).

as an example : create index idx01_datafeed_trans On datafeed_trans ( feedid, feedDate) INCLUDE( acctNo, tradeDate)

if the plan is stable or you can stabilize it you can execute the sentence with sp_executesql('sql sentence') to save and use a fixed execution plan.

if the plan is unstable you have to use an ad-hoc statement or EXEC('sql sentence') to evaluate and create an execution plan each time. (or a stored procedure "with recompile").

Hope it helps.

What is the difference between #import and #include in Objective-C?

#include it used to get "things" from another file to the one the #include is used in. Ex:

in file: main.cpp

#include "otherfile.h"

// some stuff here using otherfile.h objects,
// functions or classes declared inside

Header guard is used on the top of each header file (*.h) to prevent including the same file more then once (if it happens you will get compile errors).

in file: otherfile.h

#ifndef OTHERFILE
#define OTHERFILE

// declare functions, classes or objects here

#endif

even if you put #include "otherfile.h" n time in your code, this inside it will not be redeclared.

How to use font-family lato?

Download it from here and extract LatoOFL.rar then go to TTF and open this font-face-generator click at Choose File choose font which you want to use and click at generate then download it and then go html file open it and you see the code like this

@font-face {
        font-family: "Lato Black";
        src: url('698242188-Lato-Bla.eot');
        src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
        url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
        url('698242188-Lato-Bla.woff') format('woff'),
        url('698242188-Lato-Bla.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}
body{
    font-family: "Lato Black";
    direction: ltr;
}

change the src code and give the url where your this font directory placed, now you can use it at your website...

If you don't want to download it use this

<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />

How to have conditional elements and keep DRY with Facebook React's JSX?

&& + code-style + small components

This simple test syntax + code-style convention + small focused components is for me the most readable option out there. You just need to take special care of falsy values like false, 0 or "".

render: function() {
    var person= ...; 
    var counter= ...; 
    return (
       <div className="component">
          {person && (
            <Person person={person}/>
          )}
          {(typeof counter !== 'undefined') && (
            <Counter value={counter}/>
          )}
       </div>
    );
}

do notation

ES7 stage-0 do notation syntax is also very nice and I'll definitively use it when my IDE supports it correctly:

const Users = ({users}) => (
  <div>
    {users.map(user =>
      <User key={user.id} user={user}/>
    )}
  </div>
)  

const UserList = ({users}) => do {
  if (!users) <div>Loading</div>
  else if (!users.length) <div>Empty</div>
  else <Users users={users}/>
}

More details here: ReactJs - Creating an "If" component... a good idea?

How do I get countifs to select all non-blank cells in Excel?

In Excel 2010, You have the countifS function.

I was having issues if I was trying to count the number of cells in a range that have a non0 value.

e.g. If you had a worksheet that in the range A1:A10 had values 1, 0, 2, 3, 0 and you wanted the answer 3.

The normal function =COUNTIF(A1:A10,"<>0") would give you 8 as it is counting the blank cells as 0s.

My solution to this is to use the COUNTIFS function with the same range but multiple criteria e.g.

=COUNTIFS(A1:A10,"<>0",A1:A10,"<>")

This effectively checks if the range is non 0 and is non blank.

delete_all vs destroy_all?

delete_all is a single SQL DELETE statement and nothing more. destroy_all calls destroy() on all matching results of :conditions (if you have one) which could be at least NUM_OF_RESULTS SQL statements.

If you have to do something drastic such as destroy_all() on large dataset, I would probably not do it from the app and handle it manually with care. If the dataset is small enough, you wouldn't hurt as much.

Import PEM into Java Key Store

In my case I had a pem file which contained two certificates and an encrypted private key to be used in mutual SSL authentication. So my pem file looked like this:

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

-----BEGIN RSA PRIVATE KEY-----

Proc-Type: 4,ENCRYPTED

DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9

...

-----END RSA PRIVATE KEY-----

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

Here is what I did

Split the file into three separate files, so that each one contains just one entry, starting with ---BEGIN.. and ending with ---END.. lines. Lets assume we now have three files: cert1.pem, cert2.pem, and pkey.pem.

Convert pkey.pem into DER format using openssl and the following syntax:

openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER

Note, that if the private key is encrypted you need to supply a password( obtain it from the supplier of the original pem file ) to convert to DER format, openssl will ask you for the password like this: "enter a passphrase for pkey.pem: ".

If conversion is successful, you will get a new file called pkey.der.

Create a new java keystore and import the private key and the certificates:

String keypass = "password";  // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");

// this section does not make much sense to me, 
// but I will leave it intact as this is how it was in the original example I found on internet:   
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore"  ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ),    keypass.toCharArray());
// end of section..


// read the key file from disk and create a PrivateKey

FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();

PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);


// read the certificates from the files and load them into the key store:

Collection  col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection  col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));

Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };

String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();

ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);

// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );

// save the key store to a file         
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());

(optional) Verify the content of your new key store:

$ keytool -list -keystore mykeystore -storepass password

Keystore type: JKS Keystore provider: SUN

Your keystore contains 3 entries:

  • cn=...,ou=...,o=.., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 2C:B8: ...

  • importkey, Sep 2, 2014, PrivateKeyEntry, Certificate fingerprint (SHA1): 9C:B0: ...

  • cn=...,o=...., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 83:63: ...

(optional) Test your certificates and private key from your new key store against your SSL server: ( You may want to enable debugging as an VM option: -Djavax.net.debug=all )

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        SSLSocketFactory factory = sclx.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
        socket.startHandshake();

        //if no exceptions are thrown in the startHandshake method, then everything is fine..

Finally register your certificates with HttpsURLConnection if plan to use it:

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        HostnameVerifier hv = new HostnameVerifier()
        {
            public boolean verify(String urlHostName, SSLSession session)
            {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
                {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

If System.IO.File.Exists(FilePath) Then
    MsgBox("The file exists")
Else
    MsgBox("the file doesn't exist")
End If

regex match any whitespace

Your regex should work 'as-is'. Assuming that it is doing what you want it to.

wordA(\s*)wordB(?! wordc)

This means match wordA followed by 0 or more spaces followed by wordB, but do not match if followed by wordc. Note the single space between ?! and wordc which means that wordA wordB wordc will not match, but wordA wordB wordc will.

Here are some example matches and the associated replacement output:

enter image description here

Note that all matches are replaced no matter how many spaces. There are a couple of other points: -

  • (?! wordc) is a negative lookahead, so you wont match lines wordA wordB wordc which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?! to match the whitespace. You may want to be more precise and use (?!\swordc). If you want to match against more than one space before wordc you can use (?!\s*wordc) for 0 or more spaces or (?!\s*+wordc) for 1 or more spaces depending on what your intention is. Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.

  • * will match 0 or more spaces so it will match wordAwordB. You may want to consider + if you want at least one space.

  • (\s*) - the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s.

Update based on comment

Hello the problem is not the expression but the HTML out put   that are not considered as whitespace. it's a Joomla website.

Preserving your original regex you can use:

wordA((?:\s|&nbsp;)*)wordB(?!(?:\s|&nbsp;)wordc)

The only difference is that not the regex matches whitespace OR &nbsp;. I replaced wordc with \swordc since that is more explicit. Note as I have already pointed out that the negative lookahead ?! will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.

Example matches:

enter image description here

How to NodeJS require inside TypeScript file?

Use typings to access node functions from TypeScript:

typings install env~node --global

If you don't have typings install it:

npm install typings --global

from jquery $.ajax to angular $http

We can implement ajax request by using http service in AngularJs, which helps to read/load data from remote server.

$http service methods are listed below,

 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

One of the Example:

    $http.get("sample.php")
        .success(function(response) {
            $scope.getting = response.data; // response.data is an array
    }).error(){

        // Error callback will trigger
    });

http://www.drtuts.com/ajax-requests-angularjs/

Combine two or more columns in a dataframe into a new column with a new name

Some examples with NAs and their removal using apply

n = c(2, NA, NA) 
s = c("aa", "bb", NA) 
b = c(TRUE, FALSE, NA) 
c = c(2, 3, 5) 
d = c("aa", NA, "cc") 
e = c(TRUE, NA, TRUE) 
df = data.frame(n, s, b, c, d, e)

paste_noNA <- function(x,sep=", ") {
gsub(", " ,sep, toString(x[!is.na(x) & x!="" & x!="NA"] ) ) }

sep=" "
df$x <- apply( df[ , c(1:6) ] , 1 , paste_noNA , sep=sep)
df

(Excel) Conditional Formatting based on Adjacent Cell Value

I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:

Under Conditional Formatting > Manage Rules:

  1. Make a new rule with "Use a formula to determine which cells to format"
  2. Make your rule, but put a dollar sign only in front of the letter: $A2<$B2
  3. Under "Applies to", Manually select the second column (It would not work for me if I changed the value in the box, it just kept snapping back to what was already there), so it looks like $B$2:$B$100 (assuming you have 100 rows)

This worked for me in Excel 2016.

How do I create a comma delimited string from an ArrayList?

Something like:

String.Join(",", myArrayList.toArray(string.GetType()) );

Which basically loops ya know...

EDIT

how about:

string.Join(",", Array.ConvertAll<object, string>(a.ToArray(), Convert.ToString));

Generate random numbers uniformly over an entire range

You should look at RAND_MAX for your particular compiler/environment. I think you would see these results if rand() is producing a random 16-bit number. (you seem to be assuming it will be a 32-bit number).

I can't promise this is the answer, but please post your value of RAND_MAX, and a little more detail on your environment.

Bootstrap Datepicker - Months and Years Only

I am using bootstrap calender for future date not allow with allow change in months & year only..

var j = jQuery.noConflict();
        j(function () {
            j(".datepicker").datepicker({ dateFormat: "dd-M-yy" }).val()
        });

        j(function () {
            j(".Futuredatenotallowed").datepicker({
                changeMonth: true,
                maxDate: 0,
                changeYear: true,
                dateFormat: 'dd-M-yy',
                language: "tr"
            }).on('changeDate', function (ev) {
                $(this).blur();
                $(this).datepicker('hide');
            }).val()
        });

C# Creating and using Functions

This code gives you an error because your Add function needs to be static:

static public int Add(int x, int y)

In C# there is a distinction between functions that operate on instances (non-static) and functions that do not operate on instances (static). Instance functions can call other instance functions and static functions because they have an implicit reference to the instance. In contrast, static functions can call only static functions, or else they must explicitly provide an instance on which to call a non-static function.

Since public static void Main(string[] args) is static, all functions that it calls need to be static as well.

How to change color of ListView items on focus and on click

Here's a good article on how to use selectors with lists.

Instead of setting it to be the android:background of the ListView, I believe you want to set android:listSelector as shown below:

<ListView android:id="@+id/list" 
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" 
  android:layout_gravity="center"
  android:divider="@null" 
  android:dividerHeight="0dip"
  android:listSelector="@drawable/list_selector" />

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

If the answers must be constrained to Google Sheets, this answer works but it has limitations and is clumsy enough UX that it may be hard to get others to adopt. In trying to solve this problem I've found that, for many applications, Airtable solves this by allowing for multi-select columns and the UX is worlds better.

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config/> <!-- is used to activate the annotation for beans -->
<context:component-scan base-package="x.y.MyClass" /> <!-- is for the Spring IOC container to look for the beans in the base package. -->

The other important point to note is that context:component-scan implicitly calls the context:annotation-config to activate the annotations on beans. Well if you don't want context:component-scan to implicitly activate annotations for you, you can go on setting the annotation-config element of the context:component-scan to false.

To summarize:

<context:annotation-config/> <!-- activates the annotations --> 
<context:component-scan base-package="x.y.MyClass" /> <!-- activates the annotations + register the beans by looking inside the base-package -->

Can you have multiple $(document).ready(function(){ ... }); sections?

You can use multiple. But you can also use multiple functions inside one document.ready as well:

$(document).ready(function() {
    // Jquery
    $('.hide').hide();
    $('.test').each(function() {
       $(this).fadeIn();
    });

    // Reqular JS
    function test(word) {
       alert(word);
    }
    test('hello!');
});

How to automatically convert strongly typed enum into int?

An extension to the answers from R. Martinho Fernandes and Class Skeleton: Their answers show how to use typename std::underlying_type<EnumType>::type or std::underlying_type_t<EnumType> to convert your enumeration value with a static_cast to a value of the underlying type. Compared to a static_cast to some specific integer type, like, static_cast<int> this has the benefit of being maintenance friendly, because when the underlying type changes, the code using std::underlying_type_t will automatically use the new type.

This, however, is sometimes not what you want: Assume you wanted to print out enumeration values directly, for example to std::cout, like in the following example:

enum class EnumType : int { Green, Blue, Yellow };
std::cout << static_cast<std::underlying_type_t<EnumType>>(EnumType::Green);

If you later change the underlying type to a character type, like, uint8_t, then the value of EnumType::Green will not be printed as a number, but as a character, which is most probably not what you want. Thus, you sometimes would rather convert the enumeration value into something like "underlying type, but with integer promotion where necessary".

It would be possible to apply the unary operator+ to the result of the cast to force integer promotion if necessary. However, you can also use std::common_type_t (also from header file <type_traits>) to do the following:

enum class EnumType : int { Green, Blue, Yellow };
std::cout << static_cast<std::common_type_t<int, std::underlying_type_t<EnumType>>>(EnumType::Green);

Preferrably you would wrap this expression in some helper template function:

template <class E>
constexpr std::common_type_t<int, std::underlying_type_t<E>>
enumToInteger(E e) {
    return static_cast<std::common_type_t<int, std::underlying_type_t<E>>>(e);
}

Which would then be more friendly to the eyes, be maintenance friendly with respect to changes to the underlying type, and without need for tricks with operator+:

std::cout << enumToInteger(EnumType::Green);

How to Replace Multiple Characters in SQL?

declare @testVal varchar(20)

set @testVal = '?t/es?ti/n*g 1*2?3*'

select @testVal = REPLACE(@testVal, item, '') from (select '?' item union select '*' union select '/') list

select @testVal;

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Converting VARCHAR2 to CLOB

In PL/SQL a CLOB can be converted to a VARCHAR2 with a simple assignment, SUBSTR, and other methods. A simple assignment will only work if the CLOB is less then or equal to the size of the VARCHAR2. The limit is 32767 in PL/SQL and 4000 in SQL (although 12c allows 32767 in SQL).

For example, this code converts a small CLOB through a simple assignment and then coverts the beginning of a larger CLOB.

declare
    v_small_clob clob := lpad('0', 1000, '0');
    v_large_clob clob := lpad('0', 32767, '0') || lpad('0', 32767, '0');
    v_varchar2   varchar2(32767);
begin
    v_varchar2 := v_small_clob;
    v_varchar2 := substr(v_large_clob, 1, 32767);
end;

LONG?

The above code does not convert the value to a LONG. It merely looks that way because of limitations with PL/SQL debuggers and strings over 999 characters long.

For example, in PL/SQL Developer, open a Test window and add and debug the above code. Right-click on v_varchar2 and select "Add variable to Watches". Step through the code and the value will be set to "(Long Value)". There is a ... next to the text but it does not display the contents. PLSQL Developer Long Value

C#?

I suspect the real problem here is with C# but I don't know how enough about C# to debug the problem.

How to parse month full form string using DateFormat in Java?

val currentTime = Calendar.getInstance().time
SimpleDateFormat("MMMM", Locale.getDefault()).format(date.time)

Checking if an object is a given type in Swift

Why not use the built in functionality built especially for this task?

let myArray: [Any] = ["easy", "as", "that"]
let type = type(of: myArray)

Result: "Array<Any>"

MySQL Query GROUP BY day / month / year

GROUP BY YEAR(record_date), MONTH(record_date)

Check out the date and time functions in MySQL.

Run Android studio emulator on AMD processor

I am using the AMD processor and had the same issue. To solve this go to control panel-> turn windows features on or off -> check the hyper-V checkbox and click Ok and restart your computer. Now you can create virtual device

Dump a NumPy array into a csv file

If you want to save your numpy array (e.g. your_array = np.array([[1,2],[3,4]])) to one cell, you could convert it first with your_array.tolist().

Then save it the normal way to one cell, with delimiter=';' and the cell in the csv-file will look like this [[1, 2], [2, 4]]

Then you could restore your array like this: your_array = np.array(ast.literal_eval(cell_string))

How to force 'cp' to overwrite directory instead of creating another one inside?

If you want to ensure bar/ ends up identical to foo/, use rsync instead:

rsync -a --delete foo/ bar/

If just a few things have changed, this will execute much faster than removing and re-copying the whole directory.

  • -a is 'archive mode', which copies faithfully files in foo/ to bar/
  • --delete removes extra files not in foo/ from bar/ as well, ensuring bar/ ends up identical
  • If you want to see what it's doing, add -vh for verbose and human-readable
  • Note: the slash after foo is required, otherwise rsync will copy foo/ to bar/foo/ rather than overwriting bar/ itself.
    • (Slashes after directories in rsync are confusing; if you're interested, here's the scoop. They tell rsync to refer to the contents of the directory, rather than the directory itself. So to overwrite from the contents of foo/ onto the contents of bar/, we use a slash on both. It's confusing because it won't work as expected with a slash on neither, though; rsync sneakily always interprets the destination path as though it has a slash, even though it honors an absence of a slash on the source path. So we need a slash on the source path to make it match the auto-added slash on the destination path, if we want to copy the contents of foo/ into bar/, rather than the directory foo/ itself landing into bar/ as bar/foo.)

rsync is very powerful and useful, if you're curious look around for what else it can do (such as copying over ssh).

C# how to wait for a webpage to finish loading before continuing

I think the DocumentCompleted event of the WebBrowser control should get you where you need to go.

How to set a value for a span using jQuery

Syntax:

$(selector).text() returns the text content.

$(selector).text(content) sets the text content.

$(selector).text(function(index, curContent)) sets text content using a function.

kaynak: https://www.geeksforgeeks.org/jquery-change-the-text-of-a-span-element/

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

Random "Element is no longer attached to the DOM" StaleElementReferenceException

I think I found convenient approach to handle StaleElementReferenceException. Usually you have to write wrappers for every WebElement method to retry actions, which is frustrating and wastes lots of time.

Adding this code

webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete")));

if ((Boolean) ((JavascriptExecutor) webDriver).executeScript("return window.jQuery != undefined")) {
    webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return jQuery.active == 0")));
}

before every WebElement action can increase stability of your tests but you still can get StaleElementReferenceException from time to time.

So this is what I came up with (using AspectJ):

package path.to.your.aspects;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.pagefactory.DefaultElementLocator;
import org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Aspect
public class WebElementAspect {
    private static final Logger LOG = LogManager.getLogger(WebElementAspect.class);
    /**
     * Get your WebDriver instance from some kind of manager
     */
    private WebDriver webDriver = DriverManager.getWebDriver();
    private WebDriverWait webDriverWait = new WebDriverWait(webDriver, 10);

    /**
     * This will intercept execution of all methods from WebElement interface
     */
    @Pointcut("execution(* org.openqa.selenium.WebElement.*(..))")
    public void webElementMethods() {}

    /**
     * @Around annotation means that you can insert additional logic
     * before and after execution of the method
     */
    @Around("webElementMethods()")
    public Object webElementHandler(ProceedingJoinPoint joinPoint) throws Throwable {
        /**
         * Waiting until JavaScript and jQuery complete their stuff
         */
        waitUntilPageIsLoaded();

        /**
         * Getting WebElement instance, method, arguments
         */
        WebElement webElement = (WebElement) joinPoint.getThis();
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Object[] args = joinPoint.getArgs();

        /**
         * Do some logging if you feel like it
         */
        String methodName = method.getName();

        if (methodName.contains("click")) {
            LOG.info("Clicking on " + getBy(webElement));
        } else if (methodName.contains("select")) {
            LOG.info("Selecting from " + getBy(webElement));
        } else if (methodName.contains("sendKeys")) {
            LOG.info("Entering " + args[0].toString() + " into " + getBy(webElement));
        }

        try {
            /**
             * Executing WebElement method
             */
            return joinPoint.proceed();
        } catch (StaleElementReferenceException ex) {
            LOG.debug("Intercepted StaleElementReferenceException");

            /**
             * Refreshing WebElement
             * You can use implementation from this blog
             * http://www.sahajamit.com/post/mystery-of-stale-element-reference-exception/
             * but remove staleness check in the beginning (if(!isElementStale(elem))), because we already caught exception
             * and it will result in an endless loop
             */
            webElement = StaleElementUtil.refreshElement(webElement);

            /**
             * Executing method once again on the refreshed WebElement and returning result
             */
            return method.invoke(webElement, args);
        }
    }

    private void waitUntilPageIsLoaded() {
        webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete")));

        if ((Boolean) ((JavascriptExecutor) webDriver).executeScript("return window.jQuery != undefined")) {
            webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return jQuery.active == 0")));
        }
    }

    private static String getBy(WebElement webElement) {
        try {
            if (webElement instanceof RemoteWebElement) {
                try {
                    Field foundBy = webElement.getClass().getDeclaredField("foundBy");
                    foundBy.setAccessible(true);
                    return (String) foundBy.get(webElement);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            } else {
                LocatingElementHandler handler = (LocatingElementHandler) Proxy.getInvocationHandler(webElement);

                Field locatorField = handler.getClass().getDeclaredField("locator");
                locatorField.setAccessible(true);

                DefaultElementLocator locator = (DefaultElementLocator) locatorField.get(handler);

                Field byField = locator.getClass().getDeclaredField("by");
                byField.setAccessible(true);

                return byField.get(locator).toString();
            }
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }

        return null;
    }
}

To enable this aspect create file src\main\resources\META-INF\aop-ajc.xml and write

<aspectj>
    <aspects>
        <aspect name="path.to.your.aspects.WebElementAspect"/>
    </aspects>
</aspectj>

Add this to your pom.xml

<properties>
    <aspectj.version>1.9.1</aspectj.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.0</version>
            <configuration>
                <argLine>
                    -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                </argLine>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
        </plugin>
</build>

And thats all. Hope it helps.

How can I compare two lists in python and return matches

Also you can try this,by keeping common elements in a new list.

new_list = []
for element in a:
    if element in b:
        new_list.append(element)

How to change or add theme to Android Studio?

You can use CTRL + SHIFT + A and then simply type theme to go directly to the theme settings. Same goes for pretty much any setting, refactoring or action you're looking for.

AWK to print field $2 first, then field $1

A couple of general tips (besides the DOS line ending issue):

cat is for concatenating files, it's not the only tool that can read files! If a command doesn't read files then use redirection like command < file.

You can set the field separator with the -F option so instead of:

cat foo | awk 'BEGIN{FS="|"} {print $2 " " $1}' 

Try:

awk -F'|' '{print $2" "$1}' foo 

This will output:

com.emailclient.account [email protected]
com.socialsite.auth.accoun [email protected]

To get the desired output you could do a variety of things. I'd probably split() the second field:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file
emailclient [email protected]
socialsite [email protected]

Finally to get the first character converted to uppercase is a bit of a pain in awk as you don't have a nice built in ucfirst() function:

awk -F'|' '{split($2,a,".");print toupper(substr(a[2],1,1)) substr(a[2],2),$1}' file
Emailclient [email protected]
Socialsite [email protected]

If you want something more concise (although you give up a sub-process) you could do:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file | sed 's/^./\U&/'
Emailclient [email protected]
Socialsite [email protected]

How to write an inline IF statement in JavaScript?

Isn't the question essentially: can I write the following?

if (foo)
  console.log(bar)
else
  console.log(foo + bar)

the answer is, yes, the above will translate.

however, be wary of doing the following

if (foo)
  if (bar)
    console.log(foo)
  else 
    console.log(bar)
else 
  console.log(foobar)

be sure to wrap ambiguous code in braces as the above will throw an exception (and similar permutations will produce undesired behaviour.)

error: ‘NULL’ was not declared in this scope

NULL can also be found in:

#include <string.h>

String.h will pull in the NULL from somewhere else.

What is the difference between user and kernel modes in operating systems?

  1. Kernel Mode

    In Kernel mode, the executing code has complete and unrestricted access to the underlying hardware. It can execute any CPU instruction and reference any memory address. Kernel mode is generally reserved for the lowest-level, most trusted functions of the operating system. Crashes in kernel mode are catastrophic; they will halt the entire PC.

  2. User Mode

    In User mode, the executing code has no ability to directly access hardware or reference memory. Code running in user mode must delegate to system APIs to access hardware or memory. Due to the protection afforded by this sort of isolation, crashes in user mode are always recoverable. Most of the code running on your computer will execute in user mode.

Read more

Understanding User and Kernel Mode

Boolean.parseBoolean("1") = false...?

How about this?

boolean uses_votes =
  ( "|1|yes|on|true|"
      .indexOf("|"+o.get("uses_votes").toLowerCase()+"|")
      > -1
  );

ActiveRecord OR query

I just extracted this plugin from client work that lets you combine scopes with .or., ex. Post.published.or.authored_by(current_user). Squeel (newer implementation of MetaSearch) is also great, but doesn't let you OR scopes, so query logic can get a bit redundant.

remove objects from array by object property

If you like short and self descriptive parameters or if you don't want to use splice and go with a straight forward filter or if you are simply a SQL person like me:

function removeFromArrayOfHash(p_array_of_hash, p_key, p_value_to_remove){
    return p_array_of_hash.filter((l_cur_row) => {return l_cur_row[p_key] != p_value_to_remove});
}

And a sample usage:

l_test_arr = 
[
    {
         post_id: 1,
        post_content: "Hey I am the first hash with id 1"
    },
    {
        post_id: 2,
        post_content: "This is item 2"
    },
    {
        post_id: 1,
        post_content: "And I am the second hash with id 1"
    },
    {
        post_id: 3,
        post_content: "This is item 3"
    },
 ];



 l_test_arr = removeFromArrayOfHash(l_test_arr, "post_id", 2); // gives both of the post_id 1 hashes and the post_id 3
 l_test_arr = removeFromArrayOfHash(l_test_arr, "post_id", 1); // gives only post_id 3 (since 1 was removed in previous line)

Get the filePath from Filename using Java

Correct solution with "File" class to get the directory - the "path" of the file:

String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();

which will return:

path = "C:\\Temp\\your directory"

Use LINQ to get items in one List<>, that are not in another List<>

If you override the equality of People then you can also use:

peopleList2.Except(peopleList1)

Except should be significantly faster than the Where(...Any) variant since it can put the second list into a hashtable. Where(...Any) has a runtime of O(peopleList1.Count * peopleList2.Count) whereas variants based on HashSet<T> (almost) have a runtime of O(peopleList1.Count + peopleList2.Count).

Except implicitly removes duplicates. That shouldn't affect your case, but might be an issue for similar cases.

Or if you want fast code but don't want to override the equality:

var excludedIDs = new HashSet<int>(peopleList1.Select(p => p.ID));
var result = peopleList2.Where(p => !excludedIDs.Contains(p.ID));

This variant does not remove duplicates.

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I got the same error in 1.10.2. In my case, I wanted to make clicking on the background overlay hide the currently visible dialog, regardless of which element it was based upon. Therefore I had this:

$('body').on("click", ".ui-widget-overlay", function () {
    $(".ui-dialog").dialog('destroy');
});

This used to be working, so I think they must have removed support in JQUI for calling .dialog() on the popup itself at some point.

My workaround looks like this:

$('body').on("click", ".ui-widget-overlay", function () {
    $('#' + $(".ui-dialog").attr('aria-describedby')).dialog('destroy');
});

BeanFactory not initialized or already closed - call 'refresh' before

In my case, the error was valid and it was due to using try with resource

 try (ConfigurableApplicationContext cxt = new ClassPathXmlApplicationContext(
                    "classpath:application-main-config.xml")) {..
}

It auto closes the stream which should not happen if I want to reuse this context in other beans.

Bash: infinite sleep (infinite blocking)

tail does not block

As always: For everything there is an answer which is short, easy to understand, easy to follow and completely wrong. Here tail -f /dev/null falls into this category ;)

If you look at it with strace tail -f /dev/null you will notice, that this solution is far from blocking! It's probably even worse than the sleep solution in the question, as it uses (under Linux) precious resources like the inotify system. Also other processes which write to /dev/null make tail loop. (On my Ubuntu64 16.10 this adds several 10 syscalls per second on an already busy system.)

The question was for a blocking command

Unfortunately, there is no such thing ..

Read: I do not know any way to archive this with the shell directly.

Everything (even sleep infinity) can be interrupted by some signal. So if you want to be really sure it does not exceptionally return, it must run in a loop, like you already did for your sleep. Please note, that (on Linux) /bin/sleep apparently is capped at 24 days (have a look at strace sleep infinity), hence the best you can do probably is:

while :; do sleep 2073600; done

(Note that I believe sleep loops internally for higher values than 24 days, but this means: It is not blocking, it is very slowly looping. So why not move this loop to the outside?)

.. but you can come quite near with an unnamed fifo

You can create something which really blocks as long as there are no signals send to the process. Following uses bash 4, 2 PIDs and 1 fifo:

bash -c 'coproc { exec >&-; read; }; eval exec "${COPROC[0]}<&-"; wait'

You can check that this really blocks with strace if you like:

strace -ff bash -c '..see above..'

How this was constructed

read blocks if there is no input data (see some other answers). However, the tty (aka. stdin) usually is not a good source, as it is closed when the user logs out. Also it might steal some input from the tty. Not nice.

To make read block, we need to wait for something like a fifo which will never return anything. In bash 4 there is a command which can exactly provide us with such a fifo: coproc. If we also wait the blocking read (which is our coproc), we are done. Sadly this needs to keep open two PIDs and a fifo.

Variant with a named fifo

If you do not bother using a named fifo, you can do this as follows:

mkfifo "$HOME/.pause.fifo" 2>/dev/null; read <"$HOME/.pause.fifo"

Not using a loop on the read is a bit sloppy, but you can reuse this fifo as often as you like and make the reads terminat using touch "$HOME/.pause.fifo" (if there are more than a single read waiting, all are terminated at once).

Or use the Linux pause() syscall

For the infinite blocking there is a Linux kernel call, called pause(), which does what we want: Wait forever (until a signal arrives). However there is no userspace program for this (yet).

C

Create such a program is easy. Here is a snippet to create a very small Linux program called pause which pauses indefinitely (needs diet, gcc etc.):

printf '#include <unistd.h>\nint main(){for(;;)pause();}' > pause.c;
diet -Os cc pause.c -o pause;
strip -s pause;
ls -al pause

python

If you do not want to compile something yourself, but you have python installed, you can use this under Linux:

python -c 'while 1: import ctypes; ctypes.CDLL(None).pause()'

(Note: Use exec python -c ... to replace the current shell, this frees one PID. The solution can be improved with some IO redirection as well, freeing unused FDs. This is up to you.)

How this works (I think): ctypes.CDLL(None) loads the standard C library and runs the pause() function in it within some additional loop. Less efficient than the C version, but works.

My recommendation for you:

Stay at the looping sleep. It's easy to understand, very portable, and blocks most of the time.

How to create named and latest tag in Docker?

You can have multiple tags when building the image:

$ docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 .

Reference: https://docs.docker.com/engine/reference/commandline/build/#tag-image-t

POST data in JSON format

Another example is available here:

Sending a JSON to server and retrieving a JSON in return, without JQuery

Which is the same as jans answer, but also checks the servers response by setting a onreadystatechange callback on the XMLHttpRequest.

Reading numbers from a text file into an array in C

5623125698541159 is treated as a single number (out of range of int on most architecture). You need to write numbers in your file as

5 6 2 3 1 2 5  6 9 8 5 4 1 1 5 9  

for 16 numbers.

If your file has input

5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9 

then change %d specifier in your fscanf to %d,.

  fscanf(myFile, "%d,", &numberArray[i] );  

Here is your full code after few modifications:

#include <stdio.h>
#include <stdlib.h>

int main(){

    FILE *myFile;
    myFile = fopen("somenumbers.txt", "r");

    //read file into array
    int numberArray[16];
    int i;

    if (myFile == NULL){
        printf("Error Reading File\n");
        exit (0);
    }

    for (i = 0; i < 16; i++){
        fscanf(myFile, "%d,", &numberArray[i] );
    }

    for (i = 0; i < 16; i++){
        printf("Number is: %d\n\n", numberArray[i]);
    }

    fclose(myFile);

    return 0;
}

Move / Copy File Operations in Java

Check out: http://commons.apache.org/io/

It has copy, and as stated the JDK already has move.

Don't implement your own copy method. There are so many floating out there...

Differences between cookies and sessions?

Google JSESSIONID. This will explain how the Servlet API initially uses URL re-writing and then, if cookies are enabled, cookies to manage sessions.

HTTP is stateless so the client browser must send the id of its session to the server with each request. The server, through whatever means, uses this id to retrieve any data for that session making it available for the lifetime of the request.

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

  1. Spring is an IoC container (at least the core of Spring) and is used to wire things using dependency injection. Spring provides additional services like transaction management and seamless integration of various other technologies.
  2. Struts is an action-based presentation framework (but don't use it for a new development).
  3. Struts 2 is an action-based presentation framework, the version 2 of the above (created from a merge of WebWork with Struts).
  4. Hibernate is an object-relational mapping tool, a persistence framework.
  5. JavaServer Faces is component-based presentation framework.
  6. JavaServer Pages is a view technology used by all mentioned presentation framework for the view.
  7. Tapestry is another component-based presentation framework.

So, to summarize:

  • Struts 2, JSF, Tapestry (and Wicket, Spring MVC, Stripes) are presentation frameworks. If you use one of them, you don't use another.
  • Hibernate is a persistence framework and is used to persist Java objects in a relational database.
  • Spring can be used to wire all this together and to provide declarative transaction management.

I don't want to make things more confusing but note that Java EE 6 provides modern, standardized and very nice equivalent of the above frameworks: JSF 2.0 and Facelets for the presentation, JPA 2.0 for the persistence, Dependency Injection, etc. For a new development, this is IMO a serious option, Java EE 6 is a great stack.

See also

In C# check that filename is *possibly* valid (not that it exists)

Even if the filename is valid, you may still want to touch it to be sure the user has permission to write.

If you won't be thrashing the disk with hundreds of files in a short period of time, I think creating an empty file is a reasonable approach.

If you really want something lighter, like just checking for invalid chars, then compare your filename against Path.GetInvalidFileNameChars().

Java, return if trimmed String in List contains String

You can use your own code. You don't need to use the looping structure, if you don't want to use the looping structure as you said above. Only you have to focus to remove space or trim the String of the list.

If you are using java8 you can simply trim the String using the single line of the code:

myList = myList.stream().map(String :: trim).collect(Collectors.toList());

The importance of the above line is, in the future, you can use a List or set as well. Now you can use your own code:

if(myList.contains("A")){
    //true
}else{
    // false
}

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

Field 'id' doesn't have a default value?

To detect run:

select @@sql_mode
-- It will give something like:
-- STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

To fix, run:

set global sql_mode = ''

How to convert string values from a dictionary, into int/float datatypes?

For python 3,

    for d in list:
        d.update((k, float(v)) for k, v in d.items())

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

Wouldn't you be better off with

<asp:HyperLink ID="HyperLink1" runat="server" 
            NavigateUrl="CMS_1.aspx" 
            Target="_blank">
    Click here
</asp:HyperLink>

Because, to replicate your desired behavior on an asp:Button, you have to call window.open on the OnClientClick event of the button which looks a lot less cleaner than the above solution. Plus asp:HyperLink is there to handle scenarios like this.

If you want to replicate this using an asp:Button, do this.

<asp:Button ID="btn" runat="Server" 
        Text="SUBMIT"
        OnClientClick="javascript:return openRequestedPopup();"/>

JavaScript function.

var windowObjectReference;

function openRequestedPopup() {
    windowObjectReference = window.open("CMS_1.aspx",
              "DescriptiveWindowName",
              "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
}

Where can I view Tomcat log files in Eclipse?

Double click and open the server. Go to 'Arguments'. -Dcatalina.base= .. something. Go to that something. Your logs are there.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Confirm deletion using Bootstrap 3 modal box

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

https://getbootstrap.com/docs/4.0/components/modal/

NodeJS / Express: what is "app.use"?

app.use is woks as middleware for app request. syntax

app.use('pass request format',function which contain request response onject)

example

app.use('/',funtion(req,res){
 console.log(all request pass through it);
// here u can check your authentication and other activities.
})

also you can use it in case of routing your request.

app.use('/', roting_object);

Remove columns from DataTable in C#

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);

How to see what privileges are granted to schema of another user

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

Express-js can't GET my static files, why?

This work for me:

app.use('*/css',express.static('public/css'));
app.use('*/js',express.static('public/js'));
app.use('*/images',express.static('public/images'));

Find records with a date field in the last 24 hours

There are so many ways to do this. The listed ones work great, but here's another way if you have a datetime field:

SELECT [fields] 
FROM [table] 
WHERE timediff(now(), my_datetime_field) < '24:00:00'

timediff() returns a time object, so don't make the mistake of comparing it to 86400 (number of seconds in a day), or your output will be all kinds of wrong.

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

Had a similar issue, and tried lots of things. Ultimately what worked for me, was to have Gnu on Windows installed (https://github.com/bmatzelle/gow/releases) , and ensure that it was using the ssh tool inside that directory and not the one with Git. Once installed test with (ensure if its in your environment PATH that it preceds Git\bin)

C:\Git\htest2>which ssh
C:\Program Files (x86)\Gow\bin\ssh.BAT

I used putty and pageant as described here:http://rubyonrailswin.wordpress.com/2010/03/08/getting-git-to-work-on-heroku-on-windows-using-putty-plink-pageant/

Once the keys had been sent to heroku (heroku keys:add c:\Users\Person.ssh\id_rsa.pub), use

ssh -v <username>@heroku.com 

and ensure that your stack is showing use of Putty - ie a working stack:

Looking up host "heroku.com"
Connecting to 50.19.85.132 port 22
Server version: SSH-2.0-Twisted
Using SSH protocol version 2
**We claim version: SSH-2.0-PuTTY_Release_0.62**
Using Diffie-Hellman with standard group "group1"
Doing Diffie-Hellman key exchange with hash SHA-1
Host key fingerprint is:
ssh-rsa 2048 8b:48:5e:67:0e:c9:16:47:32:f2:87:0c:1f:c8:60:ad
Initialised AES-256 SDCTR client->server encryption
Initialised HMAC-SHA1 client->server MAC algorithm
Initialised AES-256 SDCTR server->client encryption
Initialised HMAC-SHA1 server->client MAC algorithm
Pageant is running. Requesting keys.
Pageant has 1 SSH-2 keys
Using username "*--ommitted for security--*".
**Trying Pageant key #0**
Authenticating with public key "rsa-key-20140401" from agent
Sending Pageant's response
Access granted
Opened channel for session
Server refused to allocate pty
Server refused to start a shell/command
FATAL ERROR: Server refused to start a shell/command

One that was running previously and failed:

C:\Git\htest2>ssh -v <username>@[email protected]
OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007
debug1: Connecting to heroku.com [50.19.85.156] port 22.
debug1: Connection established.
debug1: identity file /c/Users/Person/.ssh/identity type -1
debug1: identity file /c/Users/Person/.ssh/id_rsa type 1
debug1: identity file /c/Users/Person/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version Twisted
debug1: no match: Twisted
debug1: Enabling compatibility mode for protocol 2.0
**debug1: Local version string SSH-2.0-OpenSSH_4.6**
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: sending SSH2_MSG_KEXDH_INIT
debug1: expecting SSH2_MSG_KEXDH_REPLY
debug1: Host 'heroku.com' is known and matches the RSA host key.
debug1: Found key in /c/Users/Person/.ssh/known_hosts:1
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Users/Person/.ssh/identity
debug1: Offering public key: /c/Users/Person/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: Trying private key: /c/Users/Person/.ssh/id_dsa
debug1: No more authentication methods to try.
Permission denied (publickey).

Generate war file from tomcat webapp folder

Create the war file in a different directory to where the content is otherwise the jar command might try to zip up the file it is creating.

#!/bin/bash

set -euo pipefail

war=app.war
src=contents

# Clean last war build
if [ -e ${war} ]; then
    echo "Removing old war ${war}"
    rm -rf ${war}
fi

# Build war
if [ -d ${src} ]; then
    echo "Found source at ${src}"
    cd ${src}
    jar -cvf ../${war} *
    cd ..
fi

# Show war details
ls -la ${war}

What is the meaning of "POSIX"?

Posix is more as an OS, it is an "OS standard". You can imagine it as an imaginary OS, which actually doesn't exist, but it has a documentation. These papers are the "posix standard", defined by the IEEE, which is the big standard organization of the USA. The OSes implementing this specification are "Posix-compliant".

Government regulations prefer Posix-compliant solutions in their investments, thus being Posix-compliant has a significant financial advantage, particularly for the big IT companies of the USA.

The reward for an OS being fully posix compliant, that it is a guarantee that it will compile and run all Posix-compliant applications seamlessly.

Linux is the most well-known one. OSX, Solaris, NetBSD and Windows NT play here as well. Free- and OpenBSD are only "nearly" Posix-compliant. The posix-compliance of the WinNT is only a pseudo-solution to avoid this government regulation above.

Where is the correct location to put Log4j.properties in an Eclipse project?

The best way is to create special source folder named resources and use it for all resource including log4j.properties. So, just put it there.

On the Java Resources folder that was automatically created by the Dynamic Web Project, right click and add a new Source Folder and name it 'resources'. Files here will then be exported to the war file to the classes directory

MySQL date formats - difficulty Inserting a date

When using a string-typed variable in PHP containing a date, the variable must be enclosed in single quotes:

$NEW_DATE = '1997-07-15';
$sql = "INSERT INTO tbl (NEW_DATE, ...) VALUES ('$NEW_DATE', ...)";

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

In your css add folllowing

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
    display: none !important;
 }

And then in you code you can add ng-cloak directive. For example,

<div ng-cloak>
   Welcome {{data.name}}
</div>

Thats it!

Pip Install not installing into correct directory?

I've tried this and it worked for me,

curl -O  https://files.pythonhosted.org/packages/c0/4d/d2cd1171f93245131686b67d905f38cab53bf0edc3fd1a06b9c667c9d046/boto3-1.14.29.tar.gz

tar -zxvf boto3-1.14.29.tar.gz

cd boto3-1.14.29/

Replace X with your required python interpreter, for mine it was python3

sudo pythonX setup.py install

docker: "build" requires 1 argument. See 'docker build --help'

You can build docker image from a file called docker file and named Dockerfile by default. It has set of command/instruction that you need in your docker container. Below command creates image with tag latest, Dockerfile should present on that location (. means present direcotry)

docker build . -t <image_name>:latest

You can specify the Dockerfile via -f if the file name in not default (Dockerfile) Sameple Docker file contents.

FROM busybox
RUN echo "hello world"

Laravel: How to Get Current Route Name? (v5 ... v7)

Laravel 5.2 You can use

$request->route()->getName()

It will give you current route name.

Understanding Chrome network log "Stalled" state

My case is the page is sending multiple requests with different parameters when it was open. So most are being "stalled". Following requests immediately sent gets "stalled". Avoiding unnecessary requests would be better (to be lazy...).

Convert timestamp to readable date/time PHP

$timestamp = 1465298940;
$datetimeFormat = 'Y-m-d H:i:s';

$date = new \DateTime();
// If you must have use time zones
// $date = new \DateTime('now', new \DateTimeZone('Europe/Helsinki'));
$date->setTimestamp($timestamp);
echo $date->format($datetimeFormat);

result: 2016-06-07 14:29:00

Other time zones:

How can I get CMake to find my alternative Boost installation?

I had a similar issue, CMake finding a vendor-installed Boost only, but my cluster had a locally installed version which is what I wanted it to use. Red Hat Linux 6.

Anyway, it looks like all the BOOSTROOT, BOOST_ROOT, and Boost_DIR stuff would get annoyed unless one also sets Boost_NO_BOOST_CMAKE (e.g add to cmd line -DBoost_NO_BOOST_CMAKE=TRUE).

(I will concede the usefulness of CMake for multiplatform, but I can still hate it.)

Jquery change background color

This is how it should be:

Code:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

Demo: http://jsfiddle.net/p7w9W/2/

Explanation:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p> there you shouldn't include a class in your selector.

I also enhanced your code (caching of the jQuery object, chaining, etc.)

Update: As suggested by VKolev the color is now changing when the item is hidden.

JavaScript null check

The simple way to do your test is :

function (data) {
    if (data) { // check if null, undefined, empty ...
        // some code here
    }
}

What strategies and tools are useful for finding memory leaks in .NET?

We've used Ants Profiler Pro by Red Gate software in our project. It works really well for all .NET language-based applications.

We found that the .NET Garbage Collector is very "safe" in its cleaning up of in-memory objects (as it should be). It would keep objects around just because we might be using it sometime in the future. This meant we needed to be more careful about the number of objects that we inflated in memory. In the end, we converted all of our data objects over to an "inflate on-demand" (just before a field is requested) in order to reduce memory overhead and increase performance.

EDIT: Here's a further explanation of what I mean by "inflate on demand." In our object model of our database we use Properties of a parent object to expose the child object(s). For example if we had some record that referenced some other "detail" or "lookup" record on a one-to-one basis we would structure it like this:

class ParentObject
   Private mRelatedObject as New CRelatedObject
   public Readonly property RelatedObject() as CRelatedObject
      get
         mRelatedObject.getWithID(RelatedObjectID)
         return mRelatedObject
      end get
   end property
End class

We found that the above system created some real memory and performance problems when there were a lot of records in memory. So we switched over to a system where objects were inflated only when they were requested, and database calls were done only when necessary:

class ParentObject
   Private mRelatedObject as CRelatedObject
   Public ReadOnly Property RelatedObject() as CRelatedObject
      Get
         If mRelatedObject is Nothing
            mRelatedObject = New CRelatedObject
         End If
         If mRelatedObject.isEmptyObject
            mRelatedObject.getWithID(RelatedObjectID)
         End If
         return mRelatedObject
      end get
   end Property
end class

This turned out to be much more efficient because objects were kept out of memory until they were needed (the Get method was accessed). It provided a very large performance boost in limiting database hits and a huge gain on memory space.

In C#, what is the difference between public, private, protected, and having no access modifier?

Reposting the awesome diagrams from this answer.

Here are all access modifiers in Venn diagrams, from more limiting to more promiscuous:

private:
enter image description here

private protected: - added in C# 7.2
enter image description here

internal:
enter image description here

protected:
enter image description here

protected internal:
enter image description here

public:
enter image description here

How to make an image center (vertically & horizontally) inside a bigger div

You can set position of image is align center horizontal by this

#imageId {
   display: block;
   margin-left: auto;
   margin-right:auto;
}

Playing m3u8 Files with HTML Video Tag

<html>
<body>
    <video width="600" height="400" controls>
        <source src="index.m3u8" type="application/x-mpegURL">
    </video>
</body> 

Stream HLS or m3u8 files using above code. it works for desktop: ms edge browser (not working with desktop chrome) and mobile: chrome,opera mini browser.

To play on all browser use flash based media player. media player to support all browser

Why would you use Expression<Func<T>> rather than Func<T>?

An extremely important consideration in the choice of Expression vs Func is that IQueryable providers like LINQ to Entities can 'digest' what you pass in an Expression, but will ignore what you pass in a Func. I have two blog posts on the subject:

More on Expression vs Func with Entity Framework and Falling in Love with LINQ - Part 7: Expressions and Funcs (the last section)

Getting full JS autocompletion under Sublime Text

There are three approaches

  • Use SublimeCodeIntel plug-in

  • Use CTags plug-in

  • Generate .sublime-completion file manually

Approaches are described in detail in this blog post (of mine): http://opensourcehacker.com/2013/03/04/javascript-autocompletions-and-having-one-for-sublime-text-2/

How to load a resource from WEB-INF directory of a web archive

Here is how it works for me with no Servlet use.

Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml

  1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )

  2. Now let's use class loader:

    InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
    

Escape regex special characters in a Python string

Use repr()[1:-1]. In this case, the double quotes don't need to be escaped. The [-1:1] slice is to remove the single quote from the beginning and the end.

>>> x = raw_input()
I'm "stuck" :\
>>> print x
I'm "stuck" :\
>>> print repr(x)[1:-1]
I\'m "stuck" :\\

Or maybe you just want to escape a phrase to paste into your program? If so, do this:

>>> raw_input()
I'm "stuck" :\
'I\'m "stuck" :\\'

What is the fastest way to transpose a matrix in C++?

If the size of the arrays are known prior then we could use the union to our help. Like this-

#include <bits/stdc++.h>
using namespace std;

union ua{
    int arr[2][3];
    int brr[3][2];
};

int main() {
    union ua uav;
    int karr[2][3] = {{1,2,3},{4,5,6}};
    memcpy(uav.arr,karr,sizeof(karr));
    for (int i=0;i<3;i++)
    {
        for (int j=0;j<2;j++)
            cout<<uav.brr[i][j]<<" ";
        cout<<'\n';
    }

    return 0;
}

How to make a .jar out from an Android Studio project

If you use

apply plugin: 'com.android.library'

You can convert .aar -> .jar

If you run a gradle task from AndroidStudio[More]

assembleRelease 
//or
bundleReleaseAar

or via terminal

./gradlew <moduleName>:assembleRelease
//or
./gradlew <moduleName>:bundleReleaseAar

then you will able to find .aar in

<project_path>/build/outputs/aar/<module_name>.aar
//if you do not see it try to remove this folder and repeat the command

.aar[About] file is a zip file with aar extension that is why you can replace .aar with .zip or run

unzip "<path_to/module_name>.aar"

Can't update data-attribute value

For myself, using Jquery lib 2.1.1 the following did NOT work the way I expected:

Set element data attribute value:

$('.my-class').data('num', 'myValue');
console.log($('#myElem').data('num'));// as expected = 'myValue'

BUT the element itself remains without the attribute:

<div class="my-class"></div>

I needed the DOM updated so I could later do $('.my-class[data-num="myValue"]') //current length is 0

So I had to do

$('.my-class').attr('data-num', 'myValue');

To get the DOM to update:

<div class="my-class" data-num="myValue"></div>

Whether the attribute exists or not $.attr will overwrite.

Can I use multiple versions of jQuery on the same page?

You can have as many different jQuery versions on your page as you want.

Use jQuery.noConflict():

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script>
    var $i = jQuery.noConflict();
    alert($i.fn.jquery);
</script> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    var $j = jQuery.noConflict();
    alert($j.fn.jquery);
</script> 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
    var $k = jQuery.noConflict();
    alert($k.fn.jquery);
</script> 

DEMO | Source

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

Removing duplicate rows from table in Oracle

5. solution

delete from emp where rowid in 
    (
      select  rid from
       (
         select rowid rid,rank() over (partition by emp_id order by rowid)rn from emp     
       )
     where rn > 1
    );

postgres default timezone

In addition to the previous answers, if you use the tool pgAdmin III you can set the time zone as follows:

  1. Open Postgres config via Tools > Server Configuration > postgresql.conf
  2. Look for the entry timezone and double click to open
  3. Change the Value
  4. Reload Server to apply configuration changes (Play button on top or via services)

Postgres config in pgAdmin III

How to change port number in vue-cli project

In my vue project in visual studio code, I had to set this in /config/index.js. Change it in the:

module.exports = {
    dev: {
          // Paths
          assetsSubDirectory: 'static',
          assetsPublicPath: '/',
          proxyTable: {},

          host: 'localhost', // can be overwritten by process.env.HOST
          port: 8090, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
          autoOpenBrowser: false,
          errorOverlay: true,
          notifyOnErrors: true,
          poll: false    
         }
}

Get individual query parameters from Uri

This should work:

string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters = 
   System.Web.HttpUtility.ParseQueryString(querystring);

According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.

Edit: Apparently, if you supply the complete url to ParseQueryString it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.

How to handle screen orientation change when progress dialog and background thread active?

I going to contribute my approach to handling this rotation issue. This may not be relevant to OP as he's not using AsyncTask, but maybe others will find it useful. It's pretty simple but it seems to do the job for me:

I have a login activity with a nested AsyncTask class called BackgroundLoginTask.

In my BackgroundLoginTask I don't do anything out of the ordinary except to add a null check upon calling ProgressDialog's dismiss:

@Override
protected void onPostExecute(Boolean result)
{    
if (pleaseWaitDialog != null)
            pleaseWaitDialog.dismiss();
[...]
}

This is to handle the case where the background task finishes while the Activity is not visible and, therefore, the progress dialog has already been dismissed by the onPause() method.

Next, in my parent Activity class, I create global static handles to my AsyncTask class and my ProgressDialog (the AsyncTask, being nested, can access these variables):

private static BackgroundLoginTask backgroundLoginTask;
private static ProgressDialog pleaseWaitDialog;

This serves two purposes: First, it allows my Activity to always access the AsyncTask object even from a new, post-rotated activity. Second, it allows my BackgroundLoginTask to access and dismiss the ProgressDialog even after a rotate.

Next, I add this to onPause(), causing the progress dialog to disappear when our Activity is leaving the foreground (preventing that ugly "force close" crash):

    if (pleaseWaitDialog != null)
    pleaseWaitDialog.dismiss();

Finally, I have the following in my onResume() method:

if ((backgroundLoginTask != null) && (backgroundLoginTask.getStatus() == Status.RUNNING))
        {
           if (pleaseWaitDialog != null)
             pleaseWaitDialog.show();
        }

This allows the Dialog to reappear after the Activity is recreated.

Here is the entire class:

public class NSFkioskLoginActivity extends NSFkioskBaseActivity {
    private static BackgroundLoginTask backgroundLoginTask;
    private static ProgressDialog pleaseWaitDialog;
    private Controller cont;

    // This is the app entry point.
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (CredentialsAvailableAndValidated())
        {
        //Go to main menu and don't run rest of onCreate method.
            gotoMainMenu();
            return;
        }
        setContentView(R.layout.login);
        populateStoredCredentials();   
    }

    //Save current progress to options when app is leaving foreground
    @Override
    public void onPause()
    {
        super.onPause();
        saveCredentialsToPreferences(false);
        //Get rid of progress dialog in the event of a screen rotation. Prevents a crash.
        if (pleaseWaitDialog != null)
        pleaseWaitDialog.dismiss();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        if ((backgroundLoginTask != null) && (backgroundLoginTask.getStatus() == Status.RUNNING))
        {
           if (pleaseWaitDialog != null)
             pleaseWaitDialog.show();
        }
    }

    /**
     * Go to main menu, finishing this activity
     */
    private void gotoMainMenu()
    {
        startActivity(new Intent(getApplicationContext(), NSFkioskMainMenuActivity.class));
        finish();
    }

    /**
     * 
     * @param setValidatedBooleanTrue If set true, method will set CREDS_HAVE_BEEN_VALIDATED to true in addition to saving username/password.
     */
    private void saveCredentialsToPreferences(boolean setValidatedBooleanTrue)
    {
        SharedPreferences settings = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);
        SharedPreferences.Editor prefEditor = settings.edit();
        EditText usernameText = (EditText) findViewById(R.id.editTextUsername);
        EditText pswText = (EditText) findViewById(R.id.editTextPassword);
        prefEditor.putString(USERNAME, usernameText.getText().toString());
        prefEditor.putString(PASSWORD, pswText.getText().toString());
        if (setValidatedBooleanTrue)
        prefEditor.putBoolean(CREDS_HAVE_BEEN_VALIDATED, true);
        prefEditor.commit();
    }

    /**
     * Checks if user is already signed in
     */
    private boolean CredentialsAvailableAndValidated() {
        SharedPreferences settings = getSharedPreferences(APP_PREFERENCES,
                MODE_PRIVATE);
        if (settings.contains(USERNAME) && settings.contains(PASSWORD) && settings.getBoolean(CREDS_HAVE_BEEN_VALIDATED, false) == true)
         return true;   
        else
        return false;
    }

    //Populate stored credentials, if any available
    private void populateStoredCredentials()
    {
        SharedPreferences settings = getSharedPreferences(APP_PREFERENCES,
            MODE_PRIVATE);
        settings.getString(USERNAME, "");
       EditText usernameText = (EditText) findViewById(R.id.editTextUsername);
       usernameText.setText(settings.getString(USERNAME, ""));
       EditText pswText = (EditText) findViewById(R.id.editTextPassword);
       pswText.setText(settings.getString(PASSWORD, ""));
    }

    /**
     * Validate credentials in a seperate thread, displaying a progress circle in the meantime
     * If successful, save credentials in preferences and proceed to main menu activity
     * If not, display an error message
     */
    public void loginButtonClick(View view)
    {
        if (phoneIsOnline())
        {
        EditText usernameText = (EditText) findViewById(R.id.editTextUsername);
        EditText pswText = (EditText) findViewById(R.id.editTextPassword);
           //Call background task worker with username and password params
           backgroundLoginTask = new BackgroundLoginTask();
           backgroundLoginTask.execute(usernameText.getText().toString(), pswText.getText().toString());
        }
        else
        {
        //Display toast informing of no internet access
        String notOnlineMessage = getResources().getString(R.string.noNetworkAccessAvailable);
        Toast toast = Toast.makeText(getApplicationContext(), notOnlineMessage, Toast.LENGTH_SHORT);
        toast.show();
        }
    }

    /**
     * 
     * Takes two params: username and password
     *
     */
    public class BackgroundLoginTask extends AsyncTask<Object, String, Boolean>
    {       
       private Exception e = null;

       @Override
       protected void onPreExecute()
       {
           cont = Controller.getInstance();
           //Show progress dialog
           String pleaseWait = getResources().getString(R.string.pleaseWait);
           String commWithServer = getResources().getString(R.string.communicatingWithServer);
            if (pleaseWaitDialog == null)
              pleaseWaitDialog= ProgressDialog.show(NSFkioskLoginActivity.this, pleaseWait, commWithServer, true);

       }

        @Override
        protected Boolean doInBackground(Object... params)
        {
        try {
            //Returns true if credentials were valid. False if not. Exception if server could not be reached.
            return cont.validateCredentials((String)params[0], (String)params[1]);
        } catch (Exception e) {
            this.e=e;
            return false;
        }
        }

        /**
         * result is passed from doInBackground. Indicates whether credentials were validated.
         */
        @Override
        protected void onPostExecute(Boolean result)
        {
        //Hide progress dialog and handle exceptions
        //Progress dialog may be null if rotation has been switched
        if (pleaseWaitDialog != null)
             {
            pleaseWaitDialog.dismiss();
                pleaseWaitDialog = null;
             }

        if (e != null)
        {
         //Show toast with exception text
                String networkError = getResources().getString(R.string.serverErrorException);
                Toast toast = Toast.makeText(getApplicationContext(), networkError, Toast.LENGTH_SHORT);
            toast.show();
        }
        else
        {
            if (result == true)
            {
            saveCredentialsToPreferences(true);
            gotoMainMenu();
            }
            else
            {
            String toastText = getResources().getString(R.string.invalidCredentialsEntered);
                Toast toast = Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT);
            toast.show();
            } 
        }
        }

    }
}

I am by no means a seasoned Android developer, so feel free to comment.

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

Delete bin and obj folders in all projects of that solution.

Seems like those folders were having old files generated by some older version of visual studio, which are not compatible with new version of visual studio.

Karma: Running a single test file from command line

Even though --files is no longer supported, you can use an env variable to provide a list of files:

// karma.conf.js
function getSpecs(specList) {
  if (specList) {
    return specList.split(',')
  } else {
    return ['**/*_spec.js'] // whatever your default glob is
  }
}

module.exports = function(config) {
  config.set({
    //...
    files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))
  });
});

Then in CLI:

$ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run

"implements Runnable" vs "extends Thread" in Java

Moral of the story:

Inherit only if you want to override some behavior.

Or rather it should be read as:

Inherit less, interface more.

Check if selected dropdown value is empty using jQuery

You need to use .change() event as well as using # to target element by id:

$('#EventStartTimeMin').change(function() {
    if($(this).val()===""){ 
        console.log('empty');    
    }
});

Fiddle Demo

Adding an img element to a div with javascript

function image()
{
    //dynamically add an image and set its attribute
    var img=document.createElement("img");
    img.src="p1.jpg"
    img.id="picture"
    var foo = document.getElementById("fooBar");
    foo.appendChild(img);
}

<span id="fooBar">&nbsp;</span>

jQuery - prevent default, then continue default

With jQuery and a small variation of @Joepreludian's answer above:

Important points to keep in mind:

  • .one(...) instead on .on(...) or .submit(...)
  • named function instead of anonymous function since we will be referring it within the callback.

$('form#my-form').one('submit', function myFormSubmitCallback(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    var $this = $(this);
    if (allIsWell) {
        $this.submit(); // submit the form and it will not re-enter the callback because we have worked with .one(...)
    } else {
        $this.one('submit', myFormSubmitCallback); // lets get into the callback 'one' more time...
    }
});

You can change the value of allIsWell variable in the below snippet to true or false to test the functionality:

_x000D_
_x000D_
$('form#my-form').one('submit', function myFormSubmitCallback(evt){_x000D_
  evt.stopPropagation();_x000D_
  evt.preventDefault();_x000D_
  var $this = $(this);_x000D_
  var allIsWell = $('#allIsWell').get(0).checked;_x000D_
  if(allIsWell) {_x000D_
    $this.submit();_x000D_
  } else {_x000D_
    $this.one('submit', myFormSubmitCallback);_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="/" id="my-form">_x000D_
  <input name="./fname" value="John" />_x000D_
  <input name="./lname" value="Smith" />_x000D_
  <input type="submit" value="Lets Do This!" />_x000D_
  <br>_x000D_
  <label>_x000D_
    <input type="checkbox" value="true" id="allIsWell" />_x000D_
    All Is Well_x000D_
  </label>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Good Luck...

jQuery find and replace string

You could do something like this:

$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

It will be better to mark all tags with text that needs to be examined with a suitable class name.

Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

Remove all pods and install again.

Steps:

  1. comment all pods and run pod install
  2. uncomment all pods and run pod install

What does the explicit keyword mean?

The explicit keyword makes a conversion constructor to non-conversion constructor. As a result, the code is less error prone.

Formatting a float to 2 decimal places

The first thing you need to do is use the decimal type instead of float for the prices. Using float is absolutely unacceptable for that because it cannot accurately represent most decimal fractions.

Once you have done that, Decimal.Round() can be used to round to 2 places.

How do I add space between two variables after a print in Python

A quick warning, this a pretty wordy answer.

print is tricky sometimes, I had some problems with it when I first started. What you want is a few spaces in between two variables after you print them right? There's many ways to do this, as shown in the above answers.

This is your code:

count = 1
conv = count * 2.54
print count, conv

It's output is this:

1 2.54

If you want spaces in between, you can do it the naive way by sticking a string of spaces in between them. The variables count and conv need to be converted to string types to concatenate(join) them together. This is done with str().

print (str(count) + "           " + str(conv))
### Provides an output of:
1           2.54

To do this is the newer, more pythonic way, we use the % sign in conjunction with a letter to denote the kind of value we're using. Here I use underscores instead of spaces to show how many there are. The modulo before the last values just tells python to insert the following values in, in the order we provided.

print ('%i____%s' % (count, conv))
### provides an output of:
1____2.54

I used %i for count because it is a whole number, and %s for conv, because using %i in that instance would provide us with "2" instead of "2.54" Technically, I could've used both %s, but it's all good.

I hope this helps!

-Joseph

P.S. if you want to get complicated with your formatting, you should look at prettyprint for large amounts of text such as dictionaries and tuple lists(imported as pprint) as well as which does automatic tabs, spacing and other cool junk.

Here's some more information about strings in the python docs. http://docs.python.org/library/string.html#module-string

Push eclipse project to GitHub with EGit

The key lies in when you create the project in eclipse.

First step, you create the Java project in eclipse. Right click on the project and choose Team > Share>Git.

In the Configure Git Repository dialog, ensure that you select the option to create the Repository in the parent folder of the project.. enter image description here Then you can push to github.

N.B: Eclipse will give you a warning about putting git repositories in your workspace. So when you create your project, set your project directory outside the default workspace.

How to add a changed file to an older (not last) commit in Git

To "fix" an old commit with a small change, without changing the commit message of the old commit, where OLDCOMMIT is something like 091b73a:

git add <my fixed files>
git commit --fixup=OLDCOMMIT
git rebase --interactive --autosquash OLDCOMMIT^

You can also use git commit --squash=OLDCOMMIT to edit the old commit message during rebase.

See documentation for git commit and git rebase. As always, when rewriting git history, you should only fixup or squash commits you have not yet published to anyone else (including random internet users and build servers).


Detailed explanation

  • git commit --fixup=OLDCOMMIT copies the OLDCOMMIT commit message and automatically prefixes fixup! so it can be put in the correct order during interactive rebase. (--squash=OLDCOMMIT does the same but prefixes squash!.)
  • git rebase --interactive will bring up a text editor (which can be configured) to confirm (or edit) the rebase instruction sequence. There is info for rebase instruction changes in the file; just save and quit the editor (:wq in vim) to continue with the rebase.
  • --autosquash will automatically put any --fixup=OLDCOMMIT commits in the correct order. Note that --autosquash is only valid when the --interactive option is used.
  • The ^ in OLDCOMMIT^ means it's a reference to the commit just before OLDCOMMIT. (OLDCOMMIT^ is the first parent of OLDCOMMIT.)

Optional automation

The above steps are good for verification and/or modifying the rebase instruction sequence, but it's also possible to skip/automate the interactive rebase text editor by:

Comparing two vectors in an if statement

I'd probably use all.equal and which to get the information you want. It's not recommended to use all.equal in an if...else block for some reason, so we wrap it in isTRUE(). See ?all.equal for more:

foo <- function(A,B){
  if (!isTRUE(all.equal(A,B))){
    mismatches <- paste(which(A != B), collapse = ",")
    stop("error the A and B does not match at the following columns: ", mismatches )
  } else {
    message("Yahtzee!")
  }
}

And in use:

> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) : 
  error the A and B does not match at the following columns: 2,4

How to check "hasRole" in Java Code with Spring Security?

I'm using this:

@RequestMapping(method = RequestMethod.GET)
public void welcome(SecurityContextHolderAwareRequestWrapper request) {
    boolean b = request.isUserInRole("ROLE_ADMIN");
    System.out.println("ROLE_ADMIN=" + b);

    boolean c = request.isUserInRole("ROLE_USER");
    System.out.println("ROLE_USER=" + c);
}

How to print VARCHAR(MAX) using Print Statement?

Here's another version. This one extracts each substring to print from the main string instead of taking reducing the main string by 4000 on each loop (which might create a lot of very long strings under the hood - not sure).

CREATE PROCEDURE [Internal].[LongPrint]
    @msg nvarchar(max)
AS
BEGIN

    -- SET NOCOUNT ON reduces network overhead
    SET NOCOUNT ON;

    DECLARE @MsgLen int;
    DECLARE @CurrLineStartIdx int = 1;
    DECLARE @CurrLineEndIdx int;
    DECLARE @CurrLineLen int;   
    DECLARE @SkipCount int;

    -- Normalise line end characters.
    SET @msg = REPLACE(@msg, char(13) + char(10), char(10));
    SET @msg = REPLACE(@msg, char(13), char(10));

    -- Store length of the normalised string.
    SET @MsgLen = LEN(@msg);        

    -- Special case: Empty string.
    IF @MsgLen = 0
    BEGIN
        PRINT '';
        RETURN;
    END

    -- Find the end of next substring to print.
    SET @CurrLineEndIdx = CHARINDEX(CHAR(10), @msg);
    IF @CurrLineEndIdx BETWEEN 1 AND 4000
    BEGIN
        SET @CurrLineEndIdx = @CurrLineEndIdx - 1
        SET @SkipCount = 2;
    END
    ELSE
    BEGIN
        SET @CurrLineEndIdx = 4000;
        SET @SkipCount = 1;
    END     

    -- Loop: Print current substring, identify next substring (a do-while pattern is preferable but TSQL doesn't have one).
    WHILE @CurrLineStartIdx < @MsgLen
    BEGIN
        -- Print substring.
        PRINT SUBSTRING(@msg, @CurrLineStartIdx, (@CurrLineEndIdx - @CurrLineStartIdx)+1);

        -- Move to start of next substring.
        SET @CurrLineStartIdx = @CurrLineEndIdx + @SkipCount;

        -- Find the end of next substring to print.
        SET @CurrLineEndIdx = CHARINDEX(CHAR(10), @msg, @CurrLineStartIdx);
        SET @CurrLineLen = @CurrLineEndIdx - @CurrLineStartIdx;

        -- Find bounds of next substring to print.              
        IF @CurrLineLen BETWEEN 1 AND 4000
        BEGIN
            SET @CurrLineEndIdx = @CurrLineEndIdx - 1
            SET @SkipCount = 2;
        END
        ELSE
        BEGIN
            SET @CurrLineEndIdx = @CurrLineStartIdx + 4000;
            SET @SkipCount = 1;
        END
    END
END

current/duration time of html5 video?

This page might help you out. Everything you need to know about HTML5 video and audio

var video = document.createElement('video');
var curtime = video.currentTime;

If you already have the video element, .currentTime should work. If you need more details, that webpage should be able to help.

How to print / echo environment variables?

To bring the existing answers together with an important clarification:

As stated, the problem with NAME=sam echo "$NAME" is that $NAME gets expanded by the current shell before assignment NAME=sam takes effect.

Solutions that preserve the original semantics (of the (ineffective) solution attempt NAME=sam echo "$NAME"):

Use either eval[1] (as in the question itself), or printenv (as added by Aaron McDaid to heemayl's answer), or bash -c (from Ljm Dullaart's answer), in descending order of efficiency:

NAME=sam eval 'echo "$NAME"'  # use `eval` only if you fully control the command string
NAME=sam printenv NAME
NAME=sam bash -c 'echo "$NAME"'

printenv is not a POSIX utility, but it is available on both Linux and macOS/BSD.

What this style of invocation (<var>=<name> cmd ...) does is to define NAME:

  • as an environment variable
  • that is only defined for the command being invoked.

In other words: NAME only exists for the command being invoked, and has no effect on the current shell (if no variable named NAME existed before, there will be none after; a preexisting NAME variable remains unchanged).

POSIX defines the rules for this kind of invocation in its Command Search and Execution chapter.


The following solutions work very differently (from heemayl's answer):

NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"

While they produce the same output, they instead define:

  • a shell variable NAME (only) rather than an environment variable
    • if echo were a command that relied on environment variable NAME, it wouldn't be defined (or potentially defined differently from earlier).
  • that lives on after the command.

Note that every environment variable is also exposed as a shell variable, but the inverse is not true: shell variables are only visible to the current shell and its subshells, but not to child processes, such as external utilities and (non-sourced) scripts (unless they're marked as environment variables with export or declare -x).


[1] Technically, bash is in violation of POSIX here (as is zsh): Since eval is a special shell built-in, the preceding NAME=sam assignment should cause the the variable $NAME to remain in scope after the command finishes, but that's not what happens.
However, when you run bash in POSIX compatibility mode, it is compliant.
dash and ksh are always compliant.
The exact rules are complicated, and some aspects are left up to the implementations to decide; again, see Command Search and Execution.
Also, the usual disclaimer applies: Use eval only on input you fully control or implicitly trust.

Algorithm for solving Sudoku

Hi I've blogged about writing a sudoku solver from scratch in Python and currently writing a whole series about writing a constraint programming solver in Julia (another high level but faster language) You can read the sudoku problem from a file which seems to be easier more handy than a gui or cli way. The general idea it uses is constraint programming. I use the all different / unique constraint but I coded it myself instead of using a constraint programming solver.

If someone is interested:

Mocking a class: Mock() or patch()?

I've got a YouTube video on this.

Short answer: Use mock when you're passing in the thing that you want mocked, and patch if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.

Silly example:

# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
    sentence.replace('cks','x')   # We're cool and hip.
    twitter_api.send(sentence)

# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class 
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
    twitter_api = Twitter(user="XXX", password="YYY")
    sentence.replace('cks','x') 
    twitter_api.send(sentence)

Batch file: Find if substring is in string (not in a file)

You can pipe the source string to findstr and check the value of ERRORLEVEL to see if the pattern string was found. A value of zero indicates success and the pattern was found. Here is an example:

::
: Y.CMD - Test if pattern in string
: P1 - the pattern
: P2 - the string to check
::
@echo off

echo.%2 | findstr /C:"%1" 1>nul

if errorlevel 1 (
  echo. got one - pattern not found
) ELSE (
  echo. got zero - found pattern
)

When this is run in CMD.EXE, we get:

C:\DemoDev>y pqrs "abc def pqr 123"
 got one - pattern not found

C:\DemoDev>y pqr "abc def pqr 123" 
 got zero - found pattern

Deserialize JSON array(or list) in C#

I was having the similar issue and solved by understanding the Classes in asp.net C#

I want to read following JSON string :

[
    {
        "resultList": [
            {
                "channelType": "",
                "duration": "2:29:30",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1204,
                "language": "Hindi",
                "name": "The Great Target",
                "productId": 1204,
                "productMasterId": 1203,
                "productMasterName": "The Great Target",
                "productName": "The Great Target",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2005",
                "showGoodName": "Movies ",
                "views": 8333
            },
            {
                "channelType": "",
                "duration": "2:30:30",
                "episodeno": 0,
                "genre": "Romance",
                "genreList": [
                    "Romance"
                ],
                "genres": [
                    {
                        "personName": "Romance"
                    }
                ],
                "id": 1144,
                "language": "Hindi",
                "name": "Mere Sapnon Ki Rani",
                "productId": 1144,
                "productMasterId": 1143,
                "productMasterName": "Mere Sapnon Ki Rani",
                "productName": "Mere Sapnon Ki Rani",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "1997",
                "showGoodName": "Movies ",
                "views": 6482
            },
            {
                "channelType": "",
                "duration": "2:34:07",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1520,
                "language": "Telugu",
                "name": "Satyameva Jayathe",
                "productId": 1520,
                "productMasterId": 1519,
                "productMasterName": "Satyameva Jayathe",
                "productName": "Satyameva Jayathe",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2004",
                "showGoodName": "Movies ",
                "views": 9910
            }
        ],
        "resultSize": 1171,
        "pageIndex": "1"
    }
]

My asp.net c# code looks like following

First, Class3.cs page created in APP_Code folder of Web application

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;

/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{

    public List<ListWrapper_Main> ResultList_Main { get; set; }

    public class ListWrapper_Main
    {
        public List<ListWrapper> ResultList { get; set; }

        public string resultSize { get; set; }
        public string pageIndex { get; set; }
    }

    public class ListWrapper
    {
        public string channelType { get; set; }
        public string duration { get; set; }
        public int episodeno { get; set; }
        public string genre { get; set; }
        public string[] genreList { get; set; }
        public List<genres_cls> genres { get; set; }
        public int id { get; set; }
        public string imageUrl { get; set; }
        //public string imageurl { get; set; }
        public string language { get; set; }
        public string name { get; set; }
        public int productId { get; set; }
        public int productMasterId { get; set; }
        public string productMasterName { get; set; }
        public string productName { get; set; }
        public int productTypeId { get; set; }
        public string productTypeName { get; set; }
        public decimal rating { get; set; }
        public string releaseYear { get; set; }
        //public string releaseyear { get; set; }
        public string showGoodName { get; set; }
        public string views { get; set; }
    }
    public class genres_cls
    {
        public string personName { get; set; }
    }

}

Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data

JavaScriptSerializer ser = new JavaScriptSerializer();


        string final_sb = sb.ToString();

        List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());

        foreach (var itemdetail in movieInfos)
        {

            foreach (var itemdetail2 in itemdetail.ResultList)
            {
                Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
                Response.Write("duration=" + itemdetail2.duration + "<br/>");
                Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
                Response.Write("genre=" + itemdetail2.genre + "<br/>");

                string[] genreList_arr = itemdetail2.genreList;
                for (int i = 0; i < genreList_arr.Length; i++)
                    Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");

                foreach (var genres1 in itemdetail2.genres)
                {
                    Response.Write("genres1=" + genres1.personName + "<br>");
                }

                Response.Write("id=" + itemdetail2.id + "<br/>");
                Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
                //Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
                Response.Write("language=" + itemdetail2.language + "<br/>");
                Response.Write("name=" + itemdetail2.name + "<br/>");
                Response.Write("productId=" + itemdetail2.productId + "<br/>");
                Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
                Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
                Response.Write("productName=" + itemdetail2.productName + "<br/>");
                Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
                Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
                Response.Write("rating=" + itemdetail2.rating + "<br/>");
                Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
                //Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
                Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
                Response.Write("views=" + itemdetail2.views + "<br/><br>");
                //Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
                //  Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");


            }



            Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
            Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");

        }

'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply

This is basically - web application asp.net c# code....

N joy...

What is the simplest way to convert array to vector?

You're asking the wrong question here - instead of forcing everything into a vector ask how you can convert test to work with iterators instead of a specific container. You can provide an overload too in order to retain compatibility (and handle other containers at the same time for free):

void test(const std::vector<int>& in) {
  // Iterate over vector and do whatever
}

becomes:

template <typename Iterator>
void test(Iterator begin, const Iterator end) {
    // Iterate over range and do whatever
}

template <typename Container>
void test(const Container& in) {
    test(std::begin(in), std::end(in));
}

Which lets you do:

int x[3]={1, 2, 3};
test(x); // Now correct

(Ideone demo)

From inside of a Docker container, how do I connect to the localhost of the machine?

Several solutions come to mind:

  1. Move your dependencies into containers first
  2. Make your other services externally accessible and connect to them with that external IP
  3. Run your containers without network isolation
  4. Avoid connecting over the network, use a socket that is mounted as a volume instead

The reason this doesn't work out of the box is that containers run with their own network namespace by default. That means localhost (or 127.0.0.1 pointing to the loopback interface) is unique per container. Connecting to this will connect to the container itself, and not services running outside of docker or inside of a different docker container.

Option 1: If your dependency can be moved into a container, I would do this first. It makes your application stack portable as others try to run your container on their own environment. And you can still publish the port on your host where other services that have not been migrated can still reach it. You can even publish the port to the localhost interface on your docker host to avoid it being externally accessible with a syntax like: -p 127.0.0.1:3306:3306 for the published port.

Option 2: There are a variety of ways to detect the host IP address from inside of the container, but each have a limited number of scenarios where they work (e.g. requiring Docker for Mac). The most portable option is to inject your host IP into the container with something like an environment variable or configuration file, e.g.:

docker run --rm -e "HOST_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')" ...

This does require that your service is listening on that external interface, which could be a security concern. For other methods to get the host IP address from inside of the container, see this post.

Slightly less portable is to use host.docker.internal. This works in current versions of Docker for Windows and Docker for Mac. And in 20.10, the capability has been added to Docker for Linux when you pass a special host entry with:

docker run --add-host host.docker.internal:host-gateway ...

The host-gateway is a special value added in Docker 20.10 that automatically expands to a host IP. For more details see this PR.

Option 3: Running without network isolation, i.e. running with --net host, means your application is running on the host network namespace. This is less isolation for the container, and it means you cannot access other containers over a shared docker network with DNS (instead, you need to use published ports to access other containerized applications). But for applications that need to access other services on the host that are only listening on 127.0.0.1 on the host, this can be the easiest option.

Option 4: Various services also allow access over a filesystem based socket. This socket can be mounted into the container as a bind mounted volume, allowing you to access the host service without going over the network. For access to the docker engine, you often see examples of mounting /var/run/docker.sock into the container (giving that container root access to the host). With mysql, you can try something like -v /var/run/mysqld/mysqld.sock:/var/run/mysqld/mysql.sock and then connect to localhost which mysql converts to using the socket.

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

if ($name )
{
    #since undef and '' both evaluate to false 
    #this should work only when string is defined and non-empty...
    #unless you're expecting someting like $name="0" which is false.
    #notice though that $name="00" is not false
}

Web API Put Request generates an Http 405 Method Not Allowed error

WebDav-SchmebDav.. ..make sure you create the url with the ID correctly. Don't send it like http://www.fluff.com/api/Fluff?id=MyID, send it like http://www.fluff.com/api/Fluff/MyID.

Eg.

PUT http://www.fluff.com/api/Fluff/123 HTTP/1.1
Host: www.fluff.com
Content-Length: 11

{"Data":"1"}

This was busting my balls for a small eternity, total embarrassment.

How can I render a list select box (dropdown) with bootstrap?

I'm currently fighting with dropdowns and I'd like to share my experiences:

There are specific situations where <select> can't be used and must be 'emulated' with dropdown.

For example if you want to create bootstrap input groups, like Buttons with dropdowns (see http://getbootstrap.com/components/#input-groups-buttons-dropdowns). Unfortunately <select> is not supported in input groups, it will not be rendered properly.

Or does anybody solved this already? I would be very interested on the solution.

And to make it even more complicated, you can't use so simply $(this).text() to catch what user selected in dropdown if you're using glypicons or font awesome icons as content for dropdown. For example: <li id="someId"><a href="#0"><i class="fa fa-minus"></i></a></li> Because in this case there is no text and if you will add some then it will be also displayed in dropdown element and this is unwanted.

I found two possible solutions:

1) Use $(this).html() to get content of the selected <li> element and then to examine it, but you will get something like <a href="#0"><i class="fa fa-minus"></i></a> so you need to play with this to extract what you need.

2) Use $(this).text() and hide the text in element in hidden span: <li id="someId"><a href="#0"><i class="fa fa-minus"><span class="hidden">text</span></i></a></li>. For me this is simple and elegant solution, you can put any text you need, text will be hidden, and you don't need to do any transformations of $(this).html() result like in option 1) to get what you need.

I hope it's clear and can help somebody :-)