Programs & Examples On #My.resources

VB.Net: Dynamically Select Image from My.Resources

Dim resources As Object = My.Resources.ResourceManager
PictureBoxName.Image = resources.GetObject("Company_Logo")

Insert multiple values using INSERT INTO (SQL Server 2005)

You can also use the following syntax:-

INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

From here

What's the use of session.flush() in Hibernate

Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you:

  • before some query executions
  • when a transaction is committed

Allowing to explicitly flush the Session gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session,...).

How to execute a stored procedure within C# program

using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI")) {
    conn.Open();

    // 1.  create a command object identifying the stored procedure
    SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);

    // 2. set the command object so it knows to execute a stored procedure
    cmd.CommandType = CommandType.StoredProcedure;

    // 3. add parameter to command, which will be passed to the stored procedure
    cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

    // execute the command
    using (SqlDataReader rdr = cmd.ExecuteReader()) {
        // iterate through results, printing each to console
        while (rdr.Read())
        {
            Console.WriteLine("Product: {0,-35} Total: {1,2}",rdr["ProductName"],rdr["Total"]);
        }
    }
}

Here are some interesting links you could read:

Range with step of type float

One explanation might be floating point rounding issues. For example, if you could call

range(0, 0.4, 0.1)

you might expect an output of

[0, 0.1, 0.2, 0.3]

but you in fact get something like

[0, 0.1, 0.2000000001, 0.3000000001]

due to rounding issues. And since range is often used to generate indices of some sort, it's integers only.

Still, if you want a range generator for floats, you can just roll your own.

def xfrange(start, stop, step):
    i = 0
    while start + i * step < stop:
        yield start + i * step
        i += 1

The entity name must immediately follow the '&' in the entity reference

All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.

Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:

  • < the start of a tag.
  • > the end of a tag.
  • " the start and end of an attribute value.
  • ' the alternative start and end of an attribute value.
  • & the start of an entity (which ends with ;).

In case of & which is not followed by # (e.g. &#160;, &#xA0;, etc), the XML parser is implicitly looking for one of the five predefined entity names lt, gt, amp, quot and apos, or any manually defined entity name. However, in your particular case, you was using & as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:

The entity name must immediately follow the '&' in the entity reference

In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The & must be escaped as &amp;.

So, in your particular case, the

if (Modernizr.canvas && Modernizr.localstorage && 

must become

if (Modernizr.canvas &amp;&amp; Modernizr.localstorage &amp;&amp;

to make it XML-valid.

However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:

<h:outputScript>
    <![CDATA[
        // ...
    ]]>
</h:outputScript>

The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".

But, much better is to just put the JS code in its own JS file which you include by <script src>, or in JSF terms, the <h:outputScript>.

<h:outputScript name="onload.js" target="body" />

(note the target="body"; this way JSF will automatically render the <script> at the very end of <body>, regardless of where <h:outputScript> itself is located, hereby achieving the same effect as with window.onload and $(document).ready(); so you don't need to use those anymore in that script)

This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.

See also:

How to open an external file from HTML

<a href="file://server/directory/file.xlsx" target="_blank"> if I remember correctly.

What does LINQ return when the results are empty

In Linq-to-SQL if you try to get the first element on a query with no results you will get sequence contains no elements error. I can assure you that the mentioned error is not equal to object reference not set to an instance of an object. in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;)

jQuery: Check if special characters exists in string

var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
var check = function(string){
    for(i = 0; i < specialChars.length;i++){
        if(string.indexOf(specialChars[i]) > -1){
            return true
        }
    }
    return false;
}

if(check($('#Search').val()) == false){
    // Code that needs to execute when none of the above is in the string
}else{
    alert('Your search string contains illegal characters.');
}

How to affect other elements when one element is hovered

Only this worked for me:

#container:hover .cube { background-color: yellow; }

Where .cube is CssClass of the #cube.

Tested in Firefox, Chrome and Edge.

Why boolean in Java takes only true or false? Why not 1 or 0 also?

Even though there is a bool (short for boolean) data type in C++. But in C++, any nonzero value is a true value including negative numbers. A 0 (zero) is treated as false. Where as in JAVA there is a separate data type boolean for true and false.

How to find list intersection?

Make a set out of the larger one:

_auxset = set(a)

Then,

c = [x for x in b if x in _auxset]

will do what you want (preserving b's ordering, not a's -- can't necessarily preserve both) and do it fast. (Using if x in a as the condition in the list comprehension would also work, and avoid the need to build _auxset, but unfortunately for lists of substantial length it would be a lot slower).

If you want the result to be sorted, rather than preserve either list's ordering, an even neater way might be:

c = sorted(set(a).intersection(b))

How do I check if an array includes a value in JavaScript?

Solution that works in all modern browsers:

function contains(arr, obj) {
  const stringifiedObj = JSON.stringify(obj); // Cache our object to not call `JSON.stringify` on every iteration
  return arr.some(item => JSON.stringify(item) === stringifiedObj);
}

Usage:

contains([{a: 1}, {a: 2}], {a: 1}); // true

IE6+ solution:

function contains(arr, obj) {
  var stringifiedObj = JSON.stringify(obj)
  return arr.some(function (item) {
    return JSON.stringify(item) === stringifiedObj;
  });
}

// .some polyfill, not needed for IE9+
if (!('some' in Array.prototype)) {
  Array.prototype.some = function (tester, that /*opt*/) {
    for (var i = 0, n = this.length; i < n; i++) {
      if (i in this && tester.call(that, this[i], i, this)) return true;
    } return false;
  };
}

Usage:

contains([{a: 1}, {a: 2}], {a: 1}); // true

Why to use JSON.stringify?

Array.indexOf and Array.includes (as well as most of the answers here) only compare by reference and not by value.

[{a: 1}, {a: 2}].includes({a: 1});
// false, because {a: 1} is a new object

Bonus

Non-optimized ES6 one-liner:

[{a: 1}, {a: 2}].some(item => JSON.stringify(item) === JSON.stringify({a: 1));
// true

Note: Comparing objects by value will work better if the keys are in the same order, so to be safe you might sort the keys first with a package like this one: https://www.npmjs.com/package/sort-keys


Updated the contains function with a perf optimization. Thanks itinance for pointing it out.

SSH to AWS Instance without key pairs

Recently, AWS added a feature called Sessions Manager to the Systems Manager service that allows one to SSH into an instance without needing to setup a private key or opening up port 22. I believe authentication is done with IAM and optionally MFA.

You can find out more about it here:

https://aws.amazon.com/blogs/aws/new-session-manager/

Oracle query execution time

Use:

set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );

Or possibly:

SET TIMING ON;

-- do stuff

SET TIMING OFF;

...to get the hundredths of seconds that elapsed.

In either case, time elapsed can be impacted by server load/etc.

Reference:

PHP Undefined Index

I don't see php file, but that could be that -
replace in your php file:

$query_age = $_GET['query_age'];

with:

$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

Most probably, at first time you running your script without ?query_age=[something] and $_GET has no key like query_age.

Applying an ellipsis to multiline text

I have just been playing around a little bit with this concept. Basically, if you are ok with potentially having a pixel or so cut off from your last character, here is a pure css and html solution:

The way this works is by absolutely positioning a div below the viewable region of a viewport. We want the div to offset up into the visible region as our content grows. If the content grows too much, our div will offset too high, so upper bound the height our content can grow.

HTML:

<div class="text-container">
  <span class="text-content">
    PUT YOUR TEXT HERE
    <div class="ellipsis">...</div> // You could even make this a pseudo-element
  </span>
</div>

CSS:

.text-container {
    position: relative;
    display: block;
    color: #838485;
    width: 24em;
    height: calc(2em + 5px); // This is the max height you want to show of the text. A little extra space is for characters that extend below the line like 'j'
    overflow: hidden;
    white-space: normal;
}

.text-content {
  word-break: break-all;
  position: relative;
  display: block;
  max-height: 3em;       // This prevents the ellipsis element from being offset too much. It should be 1 line height greater than the viewport 
}

.ellipsis {
  position: absolute;
  right: 0;
  top: calc(4em + 2px - 100%); // Offset grows inversely with content height. Initially extends below the viewport, as content grows it offsets up, and reaches a maximum due to max-height of the content
  text-align: left;
  background: white;
}

I have tested this in Chrome, FF, Safari, and IE 11.

You can check it out here: http://codepen.io/puopg/pen/vKWJwK

You might even be able to alleviate the abrupt cut off of the character with some CSS magic.

EDIT: I guess one thing that this imposes is word-break: break-all since otherwise the content would not extend to the very end of the viewport. :(

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

Well... I had a similar problem... I want an incremental / step search with RegExp (eg: start search... do some processing... continue search until last match)

After lots of internet search... like always (this is turning an habit now) I end up in StackOverflow and found the answer...

Whats is not referred and matters to mention is "lastIndex" I now understand why the RegExp object implements the "lastIndex" property

How to return a value from pthread threads in C?

#include<stdio.h>
#include<pthread.h>
void* myprint(void *x)
{
 int k = *((int *)x);
 printf("\n Thread created.. value of k [%d]\n",k);
 //k =11;
 pthread_exit((void *)k);

}
int main()
{
 pthread_t th1;
 int x =5;
 int *y;
 pthread_create(&th1,NULL,myprint,(void*)&x);
 pthread_join(th1,(void*)&y);
 printf("\n Exit value is [%d]\n",y);
}  

How to update record using Entity Framework Core?

It's super simple

using (var dbContext = new DbContextBuilder().BuildDbContext())
{
    dbContext.Update(entity);
    await dbContext.SaveChangesAsync();
}

Matching exact string with JavaScript

If you do not use any placeholders (as the "exactly" seems to imply), how about string comparison instead?

If you do use placeholders, ^ and $ match the beginning and the end of a string, respectively.

How to access the GET parameters after "?" in Express?

Use req.query, for getting he value in query string parameter in the route. Refer req.query. Say if in a route, http://localhost:3000/?name=satyam you want to get value for name parameter, then your 'Get' route handler will go like this :-

app.get('/', function(req, res){
    console.log(req.query.name);
    res.send('Response send to client::'+req.query.name);

});

Detecting IE11 using CSS Capability/Feature Detection

Perhaps Layout Engine v0.7.0 is a good solution for your situation. It uses browser feature detection and can detect not only IE11 and IE10, but also IE9, IE8, and IE7. It also detects other popular browsers, including some mobile browsers. It adds a class to the html tag, is easy to use, and it's performed well under some fairly deep testing.

http://mattstow.com/layout-engine.html

Classes vs. Modules in VB.NET

I think it's a good idea to keep avoiding modules unless you stick them into separate namespaces. Because in Intellisense methods in modules will be visible from everywhere in that namespace.

So instead of ModuleName.MyMethod() you end up with MyMethod() popups in anywhere and this kind of invalidates the encapsulation. (at least in the programming level).

That's why I always try to create Class with shared methods, seems so much better.

How to install python3 version of package via pip on Ubuntu?

You may want to build a virtualenv of python3, then install packages of python3 after activating the virtualenv. So your system won't be messed up :)

This could be something like:

virtualenv -p /usr/bin/python3 py3env
source py3env/bin/activate
pip install package-name

How to make a redirection on page load in JSF 1.x

Set the GET query parameters as managed properties in faces-config.xml so that you don't need to gather them manually:

<managed-bean>
    <managed-bean-name>forward</managed-bean-name>
    <managed-bean-class>com.example.ForwardBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>action</property-name>
        <value>#{param.action}</value>
    </managed-property>
    <managed-property>
        <property-name>actionParam</property-name>
        <value>#{param.actionParam}</value>
    </managed-property>
</managed-bean>

This way the request forward.jsf?action=outcome1&actionParam=123 will let JSF set the action and actionParam parameters as action and actionParam properties of the ForwardBean.

Create a small view forward.xhtml (so small that it fits in default response buffer (often 2KB) so that it can be resetted by the navigationhandler, otherwise you've to increase the response buffer in the servletcontainer's configuration), which invokes a bean method on beforePhase of the f:view:

<!DOCTYPE html>
<html xmlns:f="http://java.sun.com/jsf/core">
    <f:view beforePhase="#{forward.navigate}" />
</html>

The ForwardBean can look like this:

public class ForwardBean {
    private String action;
    private String actionParam;

    public void navigate(PhaseEvent event) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String outcome = action; // Do your thing?
        facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);
    }

    // Add/generate the usual boilerplate.
}

The navigation-rule speaks for itself (note the <redirect /> entries which would do ExternalContext#redirect() instead of ExternalContext#dispatch() under the covers):

<navigation-rule>
    <navigation-case>
        <from-outcome>outcome1</from-outcome>
        <to-view-id>/outcome1.xhtml</to-view-id>
        <redirect />
    </navigation-case>
    <navigation-case>
        <from-outcome>outcome2</from-outcome>
        <to-view-id>/outcome2.xhtml</to-view-id>
        <redirect />
    </navigation-case>
</navigation-rule>

An alternative is to use forward.xhtml as

<!DOCTYPE html>
<html>#{forward}</html>

and update the navigate() method to be invoked on @PostConstruct (which will be invoked after bean's construction and all managed property setting):

@PostConstruct
public void navigate() {
    // ...
}    

It has the same effect, however the view side is not really self-documenting. All it basically does is printing ForwardBean#toString() (and hereby implicitly constructing the bean if not present yet).


Note for the JSF2 users, there is a cleaner way of passing parameters with <f:viewParam> and more robust way of handling the redirect/navigation by <f:event type="preRenderView">. See also among others:

How can I fill a column with random numbers in SQL? I get the same value in every row

If you are on SQL Server 2008 you can also use

 CRYPT_GEN_RANDOM(2) % 10000

Which seems somewhat simpler (it is also evaluated once per row as newid is - shown below)

DECLARE @foo TABLE (col1 FLOAT)

INSERT INTO @foo SELECT 1 UNION SELECT 2

UPDATE @foo
SET col1 =  CRYPT_GEN_RANDOM(2) % 10000

SELECT *  FROM @foo

Returns (2 random probably different numbers)

col1
----------------------
9693
8573

Mulling the unexplained downvote the only legitimate reason I can think of is that because the random number generated is between 0-65535 which is not evenly divisible by 10,000 some numbers will be slightly over represented. A way around this would be to wrap it in a scalar UDF that throws away any number over 60,000 and calls itself recursively to get a replacement number.

CREATE FUNCTION dbo.RandomNumber()
RETURNS INT
AS
  BEGIN
      DECLARE @Result INT

      SET @Result = CRYPT_GEN_RANDOM(2)

      RETURN CASE
               WHEN @Result < 60000
                     OR @@NESTLEVEL = 32 THEN @Result % 10000
               ELSE dbo.RandomNumber()
             END
  END  

Make HTML5 video poster be same size as video itself

Or you can use simply preload="none" attribute to make VIDEO background visible. And you can use background-size: cover; here.

 video {
   background: transparent url('video-image.jpg') 50% 50% / cover no-repeat ;
 }

 <video preload="none" controls>
   <source src="movie.mp4" type="video/mp4">
   <source src="movie.ogg" type="video/ogg">
 </video>

Compare a string using sh shell

-eq is used to compare integers. Use = instead.

jQuery rotate/transform

Simply remove the line that rotates it one degree at a time and calls the script forever.

// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);

Then pass the desired value into the function... in this example 45 for 45 degrees.

$(function() {

    var $elie = $("#bkgimg");
    rotate(45);

        function rotate(degree) {
      // For webkit browsers: e.g. Chrome
           $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
      // For Mozilla browser: e.g. Firefox
           $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
        }

});

Change .css() to .animate() in order to animate the rotation with jQuery. We also need to add a duration for the animation, 5000 for 5 seconds. And updating your original function to remove some redundancy and support more browsers...

$(function() {

    var $elie = $("#bkgimg");
    rotate(45);

        function rotate(degree) {
            $elie.animate({
                        '-webkit-transform': 'rotate(' + degree + 'deg)',
                        '-moz-transform': 'rotate(' + degree + 'deg)',
                        '-ms-transform': 'rotate(' + degree + 'deg)',
                        '-o-transform': 'rotate(' + degree + 'deg)',
                        'transform': 'rotate(' + degree + 'deg)',
                        'zoom': 1
            }, 5000);
        }
});

EDIT: The standard jQuery CSS animation code above is not working because apparently, jQuery .animate() does not yet support the CSS3 transforms.

This jQuery plugin is supposed to animate the rotation:

http://plugins.jquery.com/project/QTransform

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

What column type/length should I use for storing a Bcrypt hashed password in a Database?

I don't think that there are any neat tricks you can do storing this as you can do for example with an MD5 hash.

I think your best bet is to store it as a CHAR(60) as it is always 60 chars long

How can I detect keydown or keypress event in angular.js?

You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress (also Enter key, backspace key, alter key ,control key)

<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>

How to add an existing folder with files to SVN?

I don't use commands. You should be able to do this using the GUI:

  • Right-click an empty space in your My Documents folder, select TortoiseSVN > Repo-browser.
  • Enter http://subversion... (your URL path to your Subversion server/directory you will save to) as your path and select OK
  • Right-click the root directory in Repo and select Add folder. Give it the name of your project and create it.
  • Right-click the project folder in the Repo-browser and select Checkout. The Checkout directory will be your Visual Studio\Projects\{your project} folder. Select OK.
  • You will receive a warning that the folder is not empty. Say Yes to checkout/export to that folder - it will not overwrite your project files.
  • Open your project folder. You will see question marks on folders that are associated with your VS project that have not yet been added to Subversion. Select those folders using Ctrl + Click, then right-click one of the selected items and select TortoiseSVN > Add
  • Select OK on the prompt
  • Your files should add. Select OK on the Add Finished! dialog
  • Right-click in an empty area of the folder and select Refresh. You’ll see “+” icons on the folders/files, now
  • Right-click an empty area in the folder once again and select SVN Commit
  • Add a message regarding what you are committing and click OK

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

Writing String to Stream and reading it back does not work

You're using message.Length which returns the number of characters in the string, but you should be using the nubmer of bytes to read. You should use something like:

byte[] messageBytes = uniEncoding.GetBytes(message);
stringAsStream.Write(messageBytes, 0, messageBytes.Length);

You're then reading a single byte and expecting to get a character from it just by casting to char. UnicodeEncoding will use two bytes per character.

As Justin says you're also not seeking back to the beginning of the stream.

Basically I'm afraid pretty much everything is wrong here. Please give us the bigger picture and we can help you work out what you should really be doing. Using a StreamWriter to write and then a StreamReader to read is quite possibly what you want, but we can't really tell from just the brief bit of code you've shown.

Calculate distance between 2 GPS coordinates

This is version from "Henry Vilinskiy" adapted for MySQL and Kilometers:

CREATE FUNCTION `CalculateDistanceInKm`(
  fromLatitude float,
  fromLongitude float,
  toLatitude float, 
  toLongitude float
) RETURNS float
BEGIN
  declare distance float;

  select 
    6367 * ACOS(
            round(
              COS(RADIANS(90-fromLatitude)) *
                COS(RADIANS(90-toLatitude)) +
                SIN(RADIANS(90-fromLatitude)) *
                SIN(RADIANS(90-toLatitude)) *
                COS(RADIANS(fromLongitude-toLongitude))
              ,15)
            )
    into distance;

  return  round(distance,3);
END;

How to force table cell <td> content to wrap?

Just add: word-break: break-word; to you table class.

Why is there no String.Empty in Java?

For those claiming "" and String.Empty are interchangeable or that "" is better, you are very wrong.

Each time you do something like myVariable = ""; you are creating an instance of an object. If Java's String object had an EMPTY public constant, there would only be 1 instance of the object ""

E.g: -

String.EMPTY = ""; //Simply demonstrating. I realize this is invalid syntax

myVar0 = String.EMPTY;
myVar1 = String.EMPTY;
myVar2 = String.EMPTY;
myVar3 = String.EMPTY;
myVar4 = String.EMPTY;
myVar5 = String.EMPTY;
myVar6 = String.EMPTY;
myVar7 = String.EMPTY;
myVar8 = String.EMPTY;
myVar9 = String.EMPTY;

10 (11 including String.EMPTY) Pointers to 1 object

Or: -

myVar0 = "";
myVar1 = "";
myVar2 = "";
myVar3 = "";
myVar4 = "";
myVar5 = "";
myVar6 = "";
myVar7 = "";
myVar8 = "";
myVar9 = "";

10 pointers to 10 objects

This is inefficient and throughout a large application, can be significant.

Perhaps the Java compiler or run-time is efficient enough to automatically point all instances of "" to the same instance, but it might not and takes additional processing to make that determination.

How to set JAVA_HOME in Mac permanently?

You can use /usr/libexec/java_home -v <version you want> to get the path you need for JAVA_HOME. For instance, to get the path to the 1.7 JDK you can run /usr/libexec/java_home -v 1.7 and it will return the path to the JDK. In your .profile or .bash_profile just add

export JAVA_HOME=`/usr/libexec/java_home -v <version>`

and you should be good. Alternatively, try and convince the maintainers of java tools you use to make use of this method to get the version they need.

To open '.bash_profile' type the following in terminal :

nano ~/.bash_profile 

and add the following line to the file:

export JAVA_HOME=`/usr/libexec/java_home -v <version>`

Press CTRL+X to exit the bash. Press 'Y' to save changes.

To check whether the path has been added, type following in terminal:

source ~/.bash_profile
echo $JAVA_HOME

Get loop count inside a Python FOR loop

Agree with Nick. Here is more elaborated code.

#count=0
for idx, item in enumerate(list):
    print item
    #count +=1
    #if count % 10 == 0:
    if (idx+1) % 10 == 0:
        print 'did ten'

I have commented out the count variable in your code.

Get and Set Screen Resolution

Answer from different solutions to get Display Resolution

  1. Get the scaling factor

  2. Get Screen.PrimaryScreen.Bounds.Width and Screen.PrimaryScreen.Bounds.Height multiple by scaling factor result

    #region Display Resolution
    
     [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
     public static extern int GetDeviceCaps(IntPtr hDC, int nIndex);
    
     public enum DeviceCap
     {
         VERTRES = 10,
         DESKTOPVERTRES = 117
     }
    
    
     public static double GetWindowsScreenScalingFactor(bool percentage = true)
     {
         //Create Graphics object from the current windows handle
         Graphics GraphicsObject = Graphics.FromHwnd(IntPtr.Zero);
         //Get Handle to the device context associated with this Graphics object
         IntPtr DeviceContextHandle = GraphicsObject.GetHdc();
         //Call GetDeviceCaps with the Handle to retrieve the Screen Height
         int LogicalScreenHeight = GetDeviceCaps(DeviceContextHandle, (int)DeviceCap.VERTRES);
         int PhysicalScreenHeight = GetDeviceCaps(DeviceContextHandle, (int)DeviceCap.DESKTOPVERTRES);
         //Divide the Screen Heights to get the scaling factor and round it to two decimals
         double ScreenScalingFactor = Math.Round(PhysicalScreenHeight / (double)LogicalScreenHeight, 2);
         //If requested as percentage - convert it
         if (percentage)
         {
             ScreenScalingFactor *= 100.0;
         }
         //Release the Handle and Dispose of the GraphicsObject object
         GraphicsObject.ReleaseHdc(DeviceContextHandle);
         GraphicsObject.Dispose();
         //Return the Scaling Factor
         return ScreenScalingFactor;
     }
    
     public static Size GetDisplayResolution()
     {
         var sf = GetWindowsScreenScalingFactor(false);
         var screenWidth = Screen.PrimaryScreen.Bounds.Width * sf;
         var screenHeight = Screen.PrimaryScreen.Bounds.Height * sf;
         return new Size((int)screenWidth, (int)screenHeight);
     }
    
     #endregion
    

to check display resolution

var size = GetDisplayResolution();
Console.WriteLine("Display Resoluton: " + size.Width + "x" + size.Height);

vertical-align: middle doesn't work

You should set a fixed value to your span's line-height property:

.float, .twoline {
    line-height: 100px;
}

Stop an input field in a form from being submitted

_x000D_
_x000D_
$('#serialize').click(function () {_x000D_
  $('#out').text(_x000D_
    $('form').serialize()_x000D_
  );_x000D_
});_x000D_
_x000D_
$('#exclude').change(function () {_x000D_
  if ($(this).is(':checked')) {_x000D_
    $('[name=age]').attr('form', 'fake-form-id');_x000D_
  } else {_x000D_
    $('[name=age]').removeAttr('form');    _x000D_
  }_x000D_
  _x000D_
  $('#serialize').click();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="/">_x000D_
  <input type="text" value="John" name="name">_x000D_
  <input type="number" value="100" name="age">_x000D_
</form>_x000D_
_x000D_
<input type="button" value="serialize" id="serialize">_x000D_
<label for="exclude">  _x000D_
  <input type="checkbox" value="exclude age" id="exclude">_x000D_
  exlude age_x000D_
</label>_x000D_
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

What is setContentView(R.layout.main)?

You can set content view (or design) of an activity. For example you can do it like this too :

public void onCreate(Bundle savedinstanceState) {
    super.onCreate(savedinstanceState);

    Button testButon = new Button(this);

    setContentView(testButon);   
}

Also watch this tutorial too.

How to make 'submit' button disabled?

Here is a working example (you'll have to trust me that there's a submit() method on the controller - it prints an Object, like {user: 'abc'} if 'abc' is entered in the input field):

<form #loginForm="ngForm" (ngSubmit)="submit(loginForm.value)">
    <input type="text" name="user" ngModel required>
    <button  type="submit"  [disabled]="loginForm.invalid">
        Submit
    </button>
</form>

As you can see:

  • don't use loginForm.form, just use loginForm
  • loginForm.invalid works as well as !loginForm.valid
  • if you want submit() to be passed the correct value(s), the input element should have name and ngModel attributes

Also, this is when you're NOT using the new FormBuilder, which I recommend. Things are very different when using FormBuilder.

Center/Set Zoom of Map to cover all visible Markers?

To extend the given answer with few useful tricks:

var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
   bounds.extend(markers[i].getPosition());
}

//center the map to a specific spot (city)
map.setCenter(center); 

//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());

map.fitBounds(bounds);

//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1); 

// set a minimum zoom 
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
  map.setZoom(15);
}

//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
    map.setMaxZoom(15);
    map.fitBounds(bounds);
    map.setMaxZoom(Null)
}

UPDATE:
Further research in the topic show that fitBounds() is a asynchronic and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  this.setZoom(map.getZoom()-1);

  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});
map.fitBounds(bounds);

Remove NaN from pandas series

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

serie = serie.dropna()

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

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

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

0    g
3    k
4    s
dtype: object

Bootstrap 3 panel header with buttons wrong position

You are part right. with <b>title</b> it looks fine, but I would like to use <h4>.

I have put <h4 style="display: inline;"> and it seams to work.

Now, I only need to add some vertival align.

Proper way to return JSON using node or Express

Older version of Express use app.use(express.json()) or bodyParser.json() read more about bodyParser middleware

On latest version of express we could simply use res.json()

const express = require('express'),
    port = process.env.port || 3000,
    app = express()

app.get('/', (req, res) => res.json({key: "value"}))

app.listen(port, () => console.log(`Server start at ${port}`))

Show and hide a View with a slide up/down animation

Here is my solution. Just get a reference to your view and call this method:

public static void animateViewFromBottomToTop(final View view){

    view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {

            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);

            final int TRANSLATION_Y = view.getHeight();
            view.setTranslationY(TRANSLATION_Y);
            view.setVisibility(View.GONE);
            view.animate()
                .translationYBy(-TRANSLATION_Y)
                .setDuration(500)
                .setStartDelay(200)
                .setListener(new AnimatorListenerAdapter() {

                    @Override
                    public void onAnimationStart(final Animator animation) {

                        view.setVisibility(View.VISIBLE);
                    }
                })
                .start();
        }
    });
}

No need to do anything else =)

Simple JavaScript Checkbox Validation

If your checkbox has an ID of 'checkbox':

 if(document.getElementById('checkbox').checked == true){ // code here }

HTH

Unit Testing: DateTime.Now

An old question, but still valid.

My approach is to create a new interface and class to wrap the System.DateTime.Now call

public interface INow
{
    DateTime Execute();
}

public sealed class Now : INow
{
    public DateTime Execute()
    {
        return DateTime.Now
    }
}

This interface can be injected into any class that needs to get the current date and time. In this example, I have a class that adds a timespan to the current date and time (a unit testable System.DateTime.Now.Add(TimeSpan))

public interface IAddTimeSpanToCurrentDateAndTime
{
    DateTime Execute(TimeSpan input);
}

public class AddTimeSpanToCurrentDateAndTime : IAddTimeSpanToCurrentDateAndTime
{
    private readonly INow _now;

    public AddTimeSpanToCurrentDateAndTime(INow now)
    {
        this._now = now;
    }

    public DateTime Execute(TimeSpan input)
    {
        var currentDateAndTime = this._now.Execute();

        return currentDateAndTime.Add(input);
    }
}

And tests can be written to ensure that it functions correctly. I'm using NUnit and Moq but any test framework will do

public class Execute
{
    private Moq.Mock<INow> _nowMock;

    private AddTimeSpanToCurrentDateAndTime _systemUnderTest;

    [SetUp]
    public void Initialize()
    {
        this._nowMock = new Moq.Mock<INow>(Moq.MockBehavior.Strict);

        this._systemUnderTest = AddTimeSpanToCurrentDateAndTime(
            this._nowMock.Object);
    }

    [Test]
    public void AddTimeSpanToCurrentDateAndTimeExecute0001()
    {
        // arrange

        var input = new TimeSpan(911252);

        // arrange : mocks

        this._nowMock
            .Setup(a => a.Execute())
            .Returns(new DateTime(348756););

        // arrange : expected

        var expected = new DateTime(911252 + 348756);

        // act

        var actual = this._systemUnderTest.Execute(input).Result;

        // assert

        Assert.Equals(actual, expected);
    }
}

This pattern will work for any functions which depend on external factors, like System.Random.Next(), System.DateTime.Now.UtcNow, System.Guid.NewGuid() etc.

See https://loadlimited.visualstudio.com/Stamina/_git/Stamina.Core for further examples or get the https://www.nuget.org/packages/Stamina.Core nuget package.

Creating a URL in the controller .NET MVC

I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:

var urlHelper = new UrlHelper(this.ControllerContext);

Or, you could just use the Controller.Url property if you inherit from Controller.

Spring Boot yaml configuration for a list of strings

My guess is, that the @Value can not cope with "complex" types. You can go with a prop class like this:

@Component
@ConfigurationProperties('ignore')
class IgnoreSettings {
    List<String> filenames
}

Please note: This code is Groovy - not Java - to keep the example short! See the comments for tips how to adopt.

See the complete example https://github.com/christoph-frick/so-springboot-yaml-string-list

Limit the length of a string with AngularJS

If you have two bindings {{item.name}} and {{item.directory}}.

And want to show the data as a directory followed by the name, assuming '/root' as the directory and 'Machine' as the name (/root-machine).

{{[item.directory]+[isLast ? '': '/'] + [ item.name]  | limitTo:5}}

How to make a <ul> display in a horizontal row

You could also set them to float to the right.

#ul_top_hypers li {
    float: right;
}

This allows them to still be block level, but will appear on the same line.

How do I list all cron jobs for all users?

Depends on your version of cron. Using Vixie cron on FreeBSD, I can do something like this:

(cd /var/cron/tabs && grep -vH ^# *) 

if I want it more tab deliminated, I might do something like this:

(cd /var/cron/tabs && grep -vH ^# * | sed "s/:/      /")

Where that's a literal tab in the sed replacement portion.

It may be more system independent to loop through the users in /etc/passwd and do crontab -l -u $user for each of them.

jQuery: more than one handler for same event

jquery will execute both handler since it allows multiple event handlers. I have created sample code. You can try it

demo

CURL Command Line URL Parameters

Felipsmartins is correct.

It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.

Which means you can do this:

curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'

Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.

I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.

curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros

This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)

Hope it helps.

SQL Server Insert Example

To insert a single row of data:

INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');

To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');

To insert multiple rows of data in SQL Server 2008 or later:

INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'

Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

Bootstrap Columns Not Working

Try this:

DEMO

<div class="container-fluid"> <!-- If Needed Left and Right Padding in 'md' and 'lg' screen means use container class -->
            <div class="row">
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#">About</a>
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <img src="image.png" />
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>

define a List like List<int,string>?

Depending on your needs, you have a few options here.

If you don't need to do key/value lookups and want to stick with a List<>, you can make use of Tuple<int, string>:

List<Tuple<int, string>> mylist = new List<Tuple<int, string>>();

// add an item
mylist.Add(new Tuple<int, string>(someInt, someString));

If you do want key/value lookups, you could move towards a Dictionary<int, string>:

Dictionary<int, string> mydict = new Dictionary<int, string>();

// add an item
mydict.Add(someInt, someString);

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

For GCC, this is accomplished in two stages:

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

-fdata-sections -ffunction-sections

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

-Wl,--gc-sections

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

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

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

Why am I getting string does not name a type Error?

Your using declaration is in game.cpp, not game.h where you actually declare string variables. You intended to put using namespace std; into the header, above the lines that use string, which would let those lines find the string type defined in the std namespace.

As others have pointed out, this is not good practice in headers -- everyone who includes that header will also involuntarily hit the using line and import std into their namespace; the right solution is to change those lines to use std::string instead

You don't have permission to access / on this server

Edit httpd.conf file, which is in /etc/httpd/conf/httpd.conf. Add the below code.

<Directory "/">
#Options FollowSymLinks
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride None
Allow from all
</Directory>

<Directory "/home/">
 #Options FollowSymLinks
 Options Indexes FollowSymLinks Includes ExecCGI
 AllowOverride None
 Allow from all
</Directory>

After the line no. 555 (in my case) . Check for the file permissions and restart the server.

service httpd restart   

Now, it will work . Still you are facing the same problem, disable the seLinux in /etc/selinux/config change SELINUX=disabled and restart the server as mentioned above and try it.

Hope this helps

"import datetime" v.s. "from datetime import datetime"

datetime is a module which contains a type that is also called datetime. You appear to want to use both, but you're trying to use the same name to refer to both. The type and the module are two different things and you can't refer to both of them with the name datetime in your program.

If you need to use anything from the module besides the datetime type (as you apparently do), then you need to import the module with import datetime. You can then refer to the "date" type as datetime.date and the datetime type as datetime.datetime.

You could also do this:

from datetime import datetime, date
today_date = date.today()
date_time = datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

Here you import only the names you need (the datetime and date types) and import them directly so you don't need to refer to the module itself at all.

Ultimately you have to decide what names from the module you need to use, and how best to use them. If you are only using one or two things from the module (e.g., just the date and datetime types), it may be okay to import those names directly. If you're using many things, it's probably better to import the module and access the things inside it using dot syntax, to avoid cluttering your global namespace with date-specific names.

Note also that, if you do import the module name itself, you can shorten the name to ease typing:

import datetime as dt
today_date = dt.date.today()
date_time = dt.datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

Powershell folder size of folders without listing Subdirectories

This simple solution worked for me as well.

powershell -c "Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum"

How to check existence of user-define table type in SQL Server 2008?

You can use also system table_types view

IF EXISTS (SELECT *
           FROM   [sys].[table_types]
           WHERE  user_type_id = Type_id(N'[dbo].[UdTableType]'))
  BEGIN
      PRINT 'EXISTS'
  END 

How should the ViewModel close the form?

I was inspired by Thejuan's answer to write a simpler attached property. No styles, no triggers; instead, you can just do this:

<Window ...
        xmlns:xc="clr-namespace:ExCastle.Wpf"
        xc:DialogCloser.DialogResult="{Binding DialogResult}">

This is almost as clean as if the WPF team had gotten it right and made DialogResult a dependency property in the first place. Just put a bool? DialogResult property on your ViewModel and implement INotifyPropertyChanged, and voilà, your ViewModel can close the Window (and set its DialogResult) just by setting a property. MVVM as it should be.

Here's the code for DialogCloser:

using System.Windows;

namespace ExCastle.Wpf
{
    public static class DialogCloser
    {
        public static readonly DependencyProperty DialogResultProperty =
            DependencyProperty.RegisterAttached(
                "DialogResult",
                typeof(bool?),
                typeof(DialogCloser),
                new PropertyMetadata(DialogResultChanged));

        private static void DialogResultChanged(
            DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            var window = d as Window;
            if (window != null)
                window.DialogResult = e.NewValue as bool?;
        }
        public static void SetDialogResult(Window target, bool? value)
        {
            target.SetValue(DialogResultProperty, value);
        }
    }
}

I've also posted this on my blog.

Selenium IDE - Command to wait for 5 seconds

The pause command can be used directly in the ide in the html format.

If using java or C you could use Thread.sleep(5000). Time is in milliseconds. Other languages support "sleep 5" or time.sleep(5). you have multiple options for just waiting for a set time.

Getting query parameters from react-router hash fragment

"react-router-dom": "^5.0.0",

you do not need to add any additional module, just in your component that has a url address like this:

http://localhost:3000/#/?authority'

you can try the following simple code:

    const search =this.props.location.search;
    const params = new URLSearchParams(search);
    const authority = params.get('authority'); //

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

How to change HTML Object element data attribute value in javascript

In JavaScript, you can assign values to data attributes through Element.dataset.

For example:

avatar.dataset.id = 12345;

Reference: https://developer.mozilla.org/en/docs/Web/API/HTMLElement/dataset

Using Default Arguments in a Function

<?php
function info($name="George",$age=18) {
echo "$name is $age years old.<br>";
}
info();     // prints default values(number of values = 2)
info("Nick");   // changes first default argument from George to Nick
info("Mark",17);    // changes both default arguments' values

?>

Ansible: how to get output to display

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

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

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

    - debug:
        var: shell_result.stdout_lines

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

An example run would look like the this:

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

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

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

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

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

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

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

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

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

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

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

  - debug:
      var: jenkins_result.output

Negative list index?

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

Same Navigation Drawer in different Activities

Create Navigation drawer in your MainActivity using fragment.
Initialize the Navigation Drawer in MainActivity
now in all other activities you want to use same Navigation Drawer put DrawerLayout as base and fragment as navigation drawer. Just set android:name in your fragment pointing to your fragment Java file. You won't need to initialize the fragment in other Activities.
You can access Nav Drawer by swipe in other activities like in Google Play Store app

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.

    { 'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'} 
   };

User $resource("apiUrl").query();

How to "perfectly" override a dict?

All you will have to do is

class BatchCollection(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(*args, **kwargs)

OR

class BatchCollection(dict):
    def __init__(self, inpt={}):
        super(BatchCollection, self).__init__(inpt)

A sample usage for my personal use

### EXAMPLE
class BatchCollection(dict):
    def __init__(self, inpt={}):
        dict.__init__(*args, **kwargs)

    def __setitem__(self, key, item):
        if (isinstance(key, tuple) and len(key) == 2
                and isinstance(item, collections.Iterable)):
            # self.__dict__[key] = item
            super(BatchCollection, self).__setitem__(key, item)
        else:
            raise Exception(
                "Valid key should be a tuple (database_name, table_name) "
                "and value should be iterable")

Note: tested only in python3

What is the difference between Amazon SNS and Amazon SQS?

From the AWS documentation:

Amazon SNS allows applications to send time-critical messages to multiple subscribers through a “push” mechanism, eliminating the need to periodically check or “poll” for updates.

Amazon SQS is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components—without requiring each component to be concurrently available.

Fanout to Amazon SQS queues

How do you append an int to a string in C++?

Here a small working conversion/appending example, with some code I needed before.

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}

the output will be:

/dev/video
/dev/video456
/dev/video321
/dev/video123

Note that in the last two lines you save the modified string before it's actually printed out, and you could use it later if needed.

How to fix broken paste clipboard in VNC on Windows

http://rreddy.blogspot.com/2009/07/vncviewer-clipboard-operations-like.html

Many times you must have observed that clipboard operations like copy/cut and paste suddenly stops workings with the vncviewer. The main reason for this there is a program called as vncconfig responsible for these clipboard transfers. Some times the program may get closed because of some bug in vnc or some other reasons like you closed that window.

To get those clipboard operations back you need to run the program "vncconfig &".

After this your clipboard actions should work fine with out any problems.

Run "vncconfig &" on the client.

How to call URL action in MVC with javascript function?

Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:

 <input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />

Then you just get the value in your ajax call:

var path = $("#GetIndexDataPath").val();
$.ajax({
        type: "GET",
        url: path,
        data: { id = e.value},  
        dataType: "html",
        success : function (data) {
            $('div#theNewView').html(data);
        }
    });
}

I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.

how to display employee names starting with a and then b in sql

select * 
from stores 
where name like 'a%' or 
name like 'b%' 
order by name

Best way to remove the last character from a string built with stringbuilder

You should use the string.Join method to turn a collection of items into a comma delimited string. It will ensure that there is no leading or trailing comma, as well as ensure the string is constructed efficiently (without unnecessary intermediate strings).

Array String Declaration

Declare the array size will solve your problem

 String[] title = {
            "Abundance",
            "Anxiety",
            "Bruxism",
            "Discipline",
            "Drug Addiction"
        };
    String urlbase = "http://www.somewhere.com/data/";
    String imgSel = "/logo.png";
    String[] mStrings = new String[title.length];

    for(int i=0;i<title.length;i++) {
        mStrings[i] = urlbase + title[i].toLowerCase() + imgSel;

        System.out.println(mStrings[i]);
    }

What data type to use for money in Java?

I like using Tiny Types which would wrap either a double, BigDecimal, or int as previous answers have suggested. (I would use a double unless precision problems crop up).

A Tiny Type gives you type safety so you don't confused a double money with other doubles.

How to find the users list in oracle 11g db?

You can think of a mysql database as a schema/user in Oracle. If you have the privileges, you can query the DBA_USERS view to see the list of schema.

MySQL Select Date Equal to Today

You can use the CONCAT with CURDATE() to the entire time of the day and then filter by using the BETWEEN in WHERE condition:

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE (users.signup_date BETWEEN CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59'))

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

Include php files when they are in different folders

If I understand you correctly, You have two folders, one houses your php script that you want to include into a file that is in another folder?

If this is the case, you just have to follow the trail the right way. Let's assume your folders are set up like this:

root
    includes
        php_scripts
            script.php
    blog
        content
            index.php

If this is the proposed folder structure, and you are trying to include the "Script.php" file into your "index.php" folder, you need to include it this way:

include("../../../includes/php_scripts/script.php");

The way I do it is visual. I put my mouse pointer on the index.php (looking at the file structure), then every time I go UP a folder, I type another "../" Then you have to make sure you go UP the folder structure ABOVE the folders that you want to start going DOWN into. After that, it's just normal folder hierarchy.

How do you UrlEncode without using System.Web?

Here's an example of sending a POST request that properly encodes parameters using application/x-www-form-urlencoded content type:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "param1", "value1" },
        { "param2", "value2" },
    };
    var result = client.UploadValues("http://foo.com", values);
}

How do I exit the results of 'git diff' in Git Bash on windows?

None of the above solutions worked for me on Windows 8

But the following command works fine

SHIFT + Q

Problems when trying to load a package in R due to rJava

An alternative package that you can use is readxl. This package don't require external dependencies.

Swift extract regex matches

The fastest way to return all matches and capture groups in Swift 5

extension String {
    func match(_ regex: String) -> [[String]] {
        let nsString = self as NSString
        return (try? NSRegularExpression(pattern: regex, options: []))?.matches(in: self, options: [], range: NSMakeRange(0, count)).map { match in
            (0..<match.numberOfRanges).map { match.range(at: $0).location == NSNotFound ? "" : nsString.substring(with: match.range(at: $0)) }
        } ?? []
    }
}

Returns a 2-dimentional array of strings:

"prefix12suffix fix1su".match("fix([0-9]+)su")

returns...

[["fix12su", "12"], ["fix1su", "1"]]

// First element of sub-array is the match
// All subsequent elements are the capture groups

What does status=canceled for a resource mean in Chrome Developer Tools?

I have embedded all types of font as well as woff, woff2, ttf when I embed a web font in style sheet. Recently I noticed that Chrome cancels request to ttf and woff when woff2 is present. I use Chrome version 66.0.3359.181 right now but I am not sure when Chrome started canceling of extra font types.

how to create a list of lists

Just came across the same issue today...

In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:

list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)

JFrame.dispose() vs System.exit()

In addition to the above you can use the System.exit() to return an exit code which may be very usuefull specially if your calling the process automatically using the System.exit(code); this can help you determine for example if an error has occured during the run.

Change bootstrap navbar collapse breakpoint without using LESS

I just did this successfully by using the following CSS code.

@media(max-width:1000px)  {

    .navbar-collapse.collapse {
        display: none !important;
    }

    .navbar-collapse {
        overflow-x: visible !important;
    }

    .navbar-collapse.in {
      overflow-y: auto !important;
    }

    .collapse.in {
      display: block !important;
    }

}

datetime datatype in java

Since Java 8, it seems like the java.time standard library is the way to go. From Joda time web page:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.


Back to your question. Were you to use Java 8, I think you want LocalDateTime. Because it contains the date and time-of-the-day, but is unaware of time zone or any reference point in time such as the unix epoch.

Difference between Encapsulation and Abstraction

Yes !!!! If I say Encapsulation is a kind of an advanced specific scope abstraction,

How many of you read/upvote my answer. Let's dig in why I am saying like this.

I need to clear two things before my claiming.

One is data hiding and, another one is the abstraction

Data hiding

Most of the time, we will not give direct access to our internal data. Our internal data should not go out directly that is an outside person can't access our internal data directly. It's all about security since we need to protect the internal states of a particular object.


Abstraction

For simplicity, hide the internal implementations is called abstraction. In abstraction, we only focus on the necessary things. Basically, We talk about "What to do" and not "How to do" in abstraction. Security also can be achieved by abstraction since we are not going to highlight "how we are implementing". Maintainability will be increased since we can alter the implementation but it will not affect our end user.


I said, "Encapsulation is a kind of an advanced specific scope abstraction". Why? because we can see encapsulation as data hiding + abstraction

encapsulation = data hiding + abstraction

In encapsulation, we need to hide the data so outside person can not see the data and we need to provide methods that can be used to access the data. These methods may have validations or other features inside those things also hidden to an outside person. So here, we are hiding the implementation of access methods and it is called abstraction.

This is why I said like above encapsulation is a kind of abstraction.

So Where is the difference?

The difference is the abstraction is a general one if we are hiding something from the user for simplicity, maintainability and security and,

encapsulation is a specific one for which is related to internal states security where we are hiding the internal state (data hiding) and we are providing methods to access the data and those methods implementation also hidden from the outside person(abstraction).

C++ - Decimal to binary converting

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

int main() {
    // Initialize Variables
    double x;
    int xOct;
    int xHex;

    //Initialize a variable that stores the order if the numbers in binary/sexagesimal base
    vector<int> rem;

    //Get Demical value
    cout << "Number (demical base): ";
    cin >> x;

    //Set the variables
    xOct = x;
    xHex = x;

    //Get the binary value
    for (int i = 0; x >= 1; i++) {
        rem.push_back(abs(remainder(x, 2)));
        x = floor(x / 2);
    }

    //Print binary value
    cout << "Binary: ";
    int n = rem.size();
    while (n > 0) {
        n--;
        cout << rem[n];
    } cout << endl;

    //Print octal base
    cout << oct << "Octal: " << xOct << endl;

    //Print hexademical base
    cout << hex << "Hexademical: " << xHex << endl;

    system("pause");
    return 0;
}

jquery datatables hide column

For anyone using server-side processing and passing database values into jQuery using a hidden column, I suggest "sClass" param. You'll be able to use css display: none to hide the column while still being able to retrieve its value.

css:

th.dpass, td.dpass {display: none;}

In datatables init:

"aoColumnDefs": [ { "sClass": "dpass", "aTargets": [ 0 ] } ] // first column in visible columns array gets class "dpass"

//EDIT: remember to add your hidden class to your thead cell also

What exactly does a jar file contain?

Just check if the aopalliance.jar file has .java files instead of .class files. if so, just extract the jar file, import it in eclipse & create a jar though eclipse. It worked for me.

SQL injection that gets around mysql_real_escape_string()

Well, there's nothing really that can pass through that, other than % wildcard. It could be dangerous if you were using LIKE statement as attacker could put just % as login if you don't filter that out, and would have to just bruteforce a password of any of your users. People often suggest using prepared statements to make it 100% safe, as data can't interfere with the query itself that way. But for such simple queries it probably would be more efficient to do something like $login = preg_replace('/[^a-zA-Z0-9_]/', '', $login);

C/C++ check if one bit is set in, i.e. int variable

The precedent answers show you how to handle bit checks, but more often then not, it is all about flags encoded in an integer, which is not well defined in any of the precedent cases.

In a typical scenario, flags are defined as integers themselves, with a bit to 1 for the specific bit it refers to. In the example hereafter, you can check if the integer has ANY flag from a list of flags (multiple error flags concatenated) or if EVERY flag is in the integer (multiple success flags concatenated).

Following an example of how to handle flags in an integer.

Live example available here: https://rextester.com/XIKE82408

//g++  7.4.0

#include <iostream>
#include <stdint.h>

inline bool any_flag_present(unsigned int value, unsigned int flags) {
    return bool(value & flags);
}

inline bool all_flags_present(unsigned int value, unsigned int flags) {
    return (value & flags) == flags;
}

enum: unsigned int {
    ERROR_1 = 1U,
    ERROR_2 = 2U, // or 0b10
    ERROR_3 = 4U, // or 0b100
    SUCCESS_1 = 8U,
    SUCCESS_2 = 16U,
    OTHER_FLAG = 32U,
};

int main(void)
{
    unsigned int value = 0b101011; // ERROR_1, ERROR_2, SUCCESS_1, OTHER_FLAG
    unsigned int all_error_flags = ERROR_1 | ERROR_2 | ERROR_3;
    unsigned int all_success_flags = SUCCESS_1 | SUCCESS_2;
    
    std::cout << "Was there at least one error: " << any_flag_present(value, all_error_flags) << std::endl;
    std::cout << "Are all success flags enabled: " << all_flags_present(value, all_success_flags) << std::endl;
    std::cout << "Is the other flag enabled with eror 1: " << all_flags_present(value, ERROR_1 | OTHER_FLAG) << std::endl;
    return 0;
}

Increase bootstrap dropdown menu width

Text will never wrap to the next line. The text continues on the same line until a
tag is encountered.

.dropdown-menu {
    white-space: nowrap;
}

WPF User Control Parent

Use VisualTreeHelper.GetParent or the recursive function below to find the parent window.

public static Window FindParentWindow(DependencyObject child)
{
    DependencyObject parent= VisualTreeHelper.GetParent(child);

    //CHeck if this is the end of the tree
    if (parent == null) return null;

    Window parentWindow = parent as Window;
    if (parentWindow != null)
    {
        return parentWindow;
    }
    else
    {
        //use recursion until it reaches a Window
        return FindParentWindow(parent);
    }
}

JVM option -Xss - What does it do exactly?

Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.

Refresh page after form submitting

If you want the form to be submitted on the same page then remove the action from the form attributes.

<form method="POST" name="myform">
 <!-- Your HTML code Here -->
</form>

However, If you want to reload the page or redirect the page after submitting the form from another file then you call this function in php and it will redirect the page in 0 seconds. Also, You can use the header if you want to, just make sure you don't have any content before using the header

 function page_redirect($location)
 {
   echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
   exit; 
 }

 // I want the page to go to google.
 // page_redirect("http://www.google.com")

Getting current directory in .NET web application

Use this code:

 HttpContext.Current.Server.MapPath("~")

Detailed Reference:

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward (/) or backward slash (), the MapPath method returns a path as if Path were a full, virtual path.

If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

Server.MapPath(null) and Server.MapPath("") will produce this effect too.

T-SQL CASE Clause: How to specify WHEN NULL

I tried casting to a string and testing for a zero-length string and it worked.

CASE 
   WHEN LEN(CAST(field_value AS VARCHAR(MAX))) = 0 THEN 
       DO THIS
END AS field 

Getting CheckBoxList Item values

You can try this:-

string values = "";
foreach(ListItem item in myCBL.Items){
if(item.Selected)
{
values += item.Value.ToString() + ",";  
}
}
values = values.TrimEnd(',');  //To eliminate comma in last.

Converting JSON String to Dictionary Not List

Here is a simple snippet that read's in a json text file from a dictionary. Note that your json file must follow the json standard, so it has to have " double quotes rather then ' single quotes.

Your JSON dump.txt File:

{"test":"1", "test2":123}

Python Script:

import json
with open('/your/path/to/a/dict/dump.txt') as handle:
    dictdump = json.loads(handle.read())

How to store Emoji Character in MySQL Database

I have a good solution to save your time. I also meet the same problem but I could not solve this problem by the first answer.

Your defualt character is utf-8. But emoji needs utf8mb4 to support it. If you have the permission to revise the configure file of mysql, you can follow this step.

Therefore, do this following step to upgrade your character set ( from utf-8 to utf8mb4).

step 1. open your my.cnf for mysql, add these following lines to your my.cnf.

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
init_connect='SET NAMES utf8mb4'

[mysql]
default-character-set = utf8mb4


[client]
default-character-set = utf8mb4

step2. stop your mysql service, and start mysql service

mysql.server stop
mysql.server start

Finished! Then you can check your character are changed into utf8mb4.

mysql> SHOW VARIABLES LIKE 'character_set%';
+--------------------------+----------------------------------------------------------+
| Variable_name            | Value                                                    |
+--------------------------+----------------------------------------------------------+
| character_set_client     | utf8mb4                                                  |
| character_set_connection | utf8mb4                                                  |
| character_set_database   | utf8mb4                                                  |
| character_set_filesystem | binary                                                   |
| character_set_results    | utf8mb4                                                  |
| character_set_server     | utf8mb4                                                  |
| character_set_system     | utf8                                                     |
| character_sets_dir       | /usr/local/Cellar/[email protected]/5.7.29/share/mysql/charsets/ |
+--------------------------+----------------------------------------------------------+
8 rows in set (0.00 sec)

How to initialize a list of strings (List<string>) with many string values

This is how you would do it.

_x000D_
_x000D_
List <string> list1 = new List <string>();
_x000D_
_x000D_
_x000D_

Do Not Forget to add

_x000D_
_x000D_
using System.Collections.Generic;
_x000D_
_x000D_
_x000D_

ssh: check if a tunnel is alive

stunnel is a good tool to make semi-permanent connections between hosts.

http://www.stunnel.org/

determine DB2 text string length

From similar question DB2 - find and compare the lentgh of the value in a table field - add RTRIM since LENGTH will return length of column definition. This should be correct:

select * from table where length(RTRIM(fieldName))=10

UPDATE 27.5.2019: maybe on older db2 versions the LENGTH function returned the length of column definition. On db2 10.5 I have tried the function and it returns data length, not column definition length:

select fieldname
, length(fieldName) len_only
, length(RTRIM(fieldName)) len_rtrim
from (values (cast('1234567890  ' as varchar(30)) )) 
as tab(fieldName)

FIELDNAME                      LEN_ONLY    LEN_RTRIM
------------------------------ ----------- -----------
1234567890                              12          10

One can test this by using this term:

where length(fieldName)!=length(rtrim(fieldName))

How to set default values for Angular 2 component properties?

That is interesting subject. You can play around with two lifecycle hooks to figure out how it works: ngOnChanges and ngOnInit.

Basically when you set default value to Input that's mean it will be used only in case there will be no value coming on that component. And the interesting part it will be changed before component will be initialized.

Let's say we have such components with two lifecycle hooks and one property coming from input.

@Component({
  selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
  @Input() property: string = 'default';

  ngOnChanges(changes) {
    console.log('Changed', changes.property.currentValue, changes.property.previousValue);
  }

  ngOnInit() {
    console.log('Init', this.property);
  }

}

Situation 1

Component included in html without defined property value

As result we will see in console: Init default

That's mean onChange was not triggered. Init was triggered and property value is default as expected.

Situation 2

Component included in html with setted property <cmp [property]="'new value'"></cmp>

As result we will see in console:

Changed new value Object {}

Init new value

And this one is interesting. Firstly was triggered onChange hook, which setted property to new value, and previous value was empty object! And only after that onInit hook was triggered with new value of property.

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

Joining pairs of elements of a list

Without building temporary lists:

>>> import itertools
>>> s = 'abcdefgh'
>>> si = iter(s)
>>> [''.join(each) for each in itertools.izip(si, si)]
['ab', 'cd', 'ef', 'gh']

or:

>>> import itertools
>>> s = 'abcdefgh'
>>> si = iter(s)
>>> map(''.join, itertools.izip(si, si))
['ab', 'cd', 'ef', 'gh']

Converting XDocument to XmlDocument and vice versa

You could try writing the XDocument to an XmlWriter piped to an XmlReader for an XmlDocument.

If I understand the concepts properly, a direct conversion is not possible (the internal structure is different / simplified with XDocument). But then, I might be wrong...

Setting the default active profile in Spring-boot

The neat way to do this without changing your source code each time is to use the OS environment variable SPRING_PROFILES_ACTIVE:

export SPRING_PROFILES_ACTIVE=production

how-to-set-active-spring-profiles

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

How to trigger ngClick programmatically

This following solution works for me :

angular.element(document.querySelector('#myselector')).click();

instead of :

angular.element('#myselector').triggerHandler('click');

git pull aborted with error filename too long

The msysgit FAQ on Git cannot create a filedirectory with a long path doesn't seem up to date, as it still links to old msysgit ticket #110. However, according to later ticket #122 the problem has been fixed in msysgit 1.9, thus:

  1. Update to msysgit 1.9 (or later)
  2. Launch Git Bash
  3. Go to your Git repository which 'suffers' of long paths issue
  4. Enable long paths support with git config core.longpaths true

So far, it's worked for me very well.

Be aware of important notice in comment on the ticket #122

don't come back here and complain that it breaks Windows Explorer, cmd.exe, bash or whatever tools you're using.

How to copy a collection from one database to another in MongoDB

In case some heroku users stumble here and like me want to copy some data from staging database to the production database or vice versa here's how you do it very conveniently (N.B. I hope there's no typos in there, can't check it atm., I'll try confirm the validity of the code asap):

to_app="The name of the app you want to migrate data to"
from_app="The name of the app you want to migrate data from"
collection="the collection you want to copy"
mongohq_url=`heroku config:get --app "$to_app" MONGOHQ_URL`
parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
to_token=${parts[0]}; to_url=${parts[1]}; to_db=${parts[2]}
mongohq_url=`heroku config:get --app "$from_app" MONGOHQ_URL`
parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
from_token=${parts[0]}; from_url=${parts[1]}; from_db=${parts[2]}
mongodump -h "$from_url" -u heroku -d "$from_db" -p"$from_token" -c "$collection" -o col_dump
mongorestore -h "$prod_url" -u heroku -d "$to_app" -p"$to_token" --dir col_dump/"$col_dump"/$collection".bson -c "$collection"

How can I style an Android Switch?

It's an awesome detailed reply by Janusz. But just for the sake of people who are coming to this page for answers, the easier way is at http://android-holo-colors.com/ (dead link) linked from Android Asset Studio

A good description of all the tools are at AndroidOnRocks.com (site offline now)

However, I highly recommend everybody to read the reply from Janusz as it will make understanding clearer. Use the tool to do stuffs real quick

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

You can use the overflow property

style="overflow: scroll ;max-height: 250px; width: 50%;"

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

mySQL :: insert into table, data from another table?

Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:

INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'

In the above query, there are 2 extra columns named email & current_time.

Replace whitespaces with tabs in linux

If you are talking about replacing all consecutive spaces on a line with a tab then tr -s '[:blank:]' '\t'.

[root@sysresccd /run/archiso/img_dev]# sfdisk -l -q -o Device,Start /dev/sda
Device         Start
/dev/sda1       2048
/dev/sda2     411648
/dev/sda3    2508800
/dev/sda4   10639360
/dev/sda5   75307008
/dev/sda6   96278528
/dev/sda7  115809778
[root@sysresccd /run/archiso/img_dev]# sfdisk -l -q -o Device,Start /dev/sda | tr -s '[:blank:]' '\t'
Device  Start
/dev/sda1       2048
/dev/sda2       411648
/dev/sda3       2508800
/dev/sda4       10639360
/dev/sda5       75307008
/dev/sda6       96278528
/dev/sda7       115809778

If you are talking about replacing all whitespace (e.g. space, tab, newline, etc.) then tr -s '[:space:]'.

[root@sysresccd /run/archiso/img_dev]# sfdisk -l -q -o Device,Start /dev/sda | tr -s '[:space:]' '\t'
Device  Start   /dev/sda1       2048    /dev/sda2       411648  /dev/sda3       2508800 /dev/sda4       10639360        /dev/sda5       75307008        /dev/sda6     96278528        /dev/sda7       115809778  

If you are talking about fixing a tab-damaged file then use expand and unexpand as mentioned in other answers.

Change the icon of the exe file generated from Visual Studio 2010

Check the project properties. It's configurable there if you are using another .net windows application for example

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

I think u want to change the default settings of android studio. Whenever a layout or Activity in created u want to create "RelativeLayout" by default. In that case, flow the step below

  1. click any folder u used to create layout or Activity
  2. then "New>> Edit File Templates
  3. then go to "Other" tab
  4. select "LayoutResourceFile.xml" and "LayoutResourceFile_vertical.xml"
  5. change "${ROOT_TAG}" to "RelativeLayout"
  6. click "Ok"

you are done

Div table-cell vertical align not working

Sometime floats brake the vertical align, is better to avoid them.

Spring Data JPA and Exists query

You can use Case expression for returning a boolean in your select query like below.

@Query("SELECT CASE WHEN count(e) > 0 THEN true ELSE false END FROM MyEntity e where e.my_column = ?1")

String to decimal conversion: dot separation instead of comma

All this is about cultures. If you have any other culture than "US English" (and also as good manners of development), you should use something like this:

var d = Convert.ToDecimal("1.2345", new CultureInfo("en-US"));
// (or 1,2345 with your local culture, for instance)

(obviously, you should replace the "en-US" with the culture of your number local culture)

the same way, if you want to do ToString()

d.ToString(new CultureInfo("en-US"));

Mysql - delete from multiple tables with one query

from two tables with foreign key you can try this Query:

DELETE T1, T2
FROM T1
INNER JOIN T2 ON T1.key = T2.key
WHERE condition

Why cannot cast Integer to String in java?

In your case don't need casting, you need call toString().

Integer i = 33;
String s = i.toString();
//or
s = String.valueOf(i);
//or
s = "" + i;

Casting. How does it work?

Given:

class A {}
class B extends A {}

(A)
  |
(B)

B b = new B(); //no cast
A a = b;  //upcast with no explicit cast
a = (A)b; //upcast with an explicit cast
b = (B)a; //downcast

A and B in the same inheritance tree and we can this:

a = new A();
b = (B)a;  // again downcast. Compiles but fails later, at runtime: java.lang.ClassCastException

The compiler must allow things that might possibly work at runtime. However, if the compiler knows with 100% that the cast couldn't possibly work, compilation will fail.
Given:

class A {}
class B1 extends A {}
class B2 extends A {}

        (A)
      /       \
(B1)       (B2)

B1 b1 = new B1();
B2 b2 = (B2)b1; // B1 can't ever be a B2

Error: Inconvertible types B1 and B2. The compiler knows with 100% that the cast couldn't possibly work. But you can cheat the compiler:

B2 b2 = (B2)(A)b1;

but anyway at runtime:

Exception in thread "main" java.lang.ClassCastException: B1 cannot be cast to B2

in your case:

          (Object)
            /       \
(Integer)       (String)

Integer i = 33;
//String s = (String)i; - compiler error
String s = (String)(Object)i;

at runtime: Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

TypeScript for ... of with index / key?

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

for (var [key, item] of someArray.entries()) { ... }

In TS this requires targeting ES2015 since it requires the runtime to support iterators, which ES5 runtimes don't. You can of course use something like Babel to make the output work on ES5 runtimes.

How do I include a JavaScript file in another JavaScript file?

Or rather than including at run time, use a script to concatenate prior to upload.

I use Sprockets (I don't know if there are others). You build your JavaScript code in separate files and include comments that are processed by the Sprockets engine as includes. For development you can include files sequentially, then for production to merge them...

See also:

Fatal error: Call to undefined function socket_create()

Open the php.ini file in your server environment and remove ; from ;extension=sockets. if it's doesn't work, you have to download the socket extension for PHP and put it into ext directory in the php installation path. Restart your http server and everything should work.

Notepad++ change text color?

You can Change it from:

Menu Settings -> Style Configurator

See on screenshot:

enter image description here

how to calculate percentage in python

I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"

Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...

I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.

#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

Here you can test the code and experiment with it.

Sorting a DropDownList? - C#, ASP.NET

I agree with sorting using ORDER BY when populating with a database query, if all you want is to sort the displayed results alphabetically. Let the database engine do the work of sorting.

However, sometimes you want some other sort order besides alphabetical. For example, you might want a logical sequence like: New, Open, In Progress, Completed, Approved, Closed. In that case, you could add a column to the database table to explicitly set the sort order. Name it something like SortOrder or DisplaySortOrder. Then, in your SQL, you'd ORDER BY the sort order field (without retrieving that field).

How to find NSDocumentDirectory in Swift?

Xcode 8.2.1 • Swift 3.0.2

let documentDirectoryURL =  try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

Xcode 7.1.1 • Swift 2.1

let documentDirectoryURL =  try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)

Changing the interval of SetInterval while it's running

You could use an anonymous function:

var counter = 10;
var myFunction = function(){
    clearInterval(interval);
    counter *= 10;
    interval = setInterval(myFunction, counter);
}
var interval = setInterval(myFunction, counter);

UPDATE: As suggested by A. Wolff, use setTimeout to avoid the need for clearInterval.

var counter = 10;
var myFunction = function() {
    counter *= 10;
    setTimeout(myFunction, counter);
}
setTimeout(myFunction, counter);

How to slice an array in Bash

There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.

version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}"    # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}"    # 7 1

"pip install unroll": "python setup.py egg_info" failed with error code 1

Had the same problem on my Win10 PC with different packages and tried everything mentioned so far.

Finally solved it by disabling Comodo Auto-Containment.

Since nobody has mentioned it yet, I hope it helps someone.

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

If the DLL and the .NET projects are in the same solution and you want to compile and run both every time, you can right click the properties of the .NET project, Build events, then add something like the following to Post-build event command line:

copy $(SolutionDir)Debug\MyOwn.dll .

It's basically a DOS line, and you can tweak based on where your DLL is being built to.

varbinary to string on SQL Server

"Converting a varbinary to a varchar" can mean different things.

If the varbinary is the binary representation of a string in SQL Server (for example returned by casting to varbinary directly or from the DecryptByPassPhrase or DECOMPRESS functions) you can just CAST it

declare @b varbinary(max)
set @b = 0x5468697320697320612074657374

select cast(@b as varchar(max)) /*Returns "This is a test"*/

This is the equivalent of using CONVERT with a style parameter of 0.

CONVERT(varchar(max), @b, 0)

Other style parameters are available with CONVERT for different requirements as noted in other answers.

C# Iterate through Class properties

I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo list was coming as empty. So, I tried the following and it worked for me.

    Type type = typeof(Record);
    FieldInfo[] properties = type.GetFields();
    foreach (FieldInfo property in properties) {
       Debug.LogError(property.Name);
    }

PHP Fatal error: Call to undefined function mssql_connect()

php.ini probably needs to read: extension=ext\php_sqlsrv_53_nts.dll

Or move the file to same directory as the php executable. This is what I did to my php5 install this week to get odbc_pdo working. :P

Additionally, that doesn't look like proper phpinfo() output. If you make a file with contents
<? phpinfo(); ?> and visit that page, the HTML output should show several sections, including one with loaded modules. (Edited to add: like shown in the screenshot of the above accepted answer)

Writing binary number system in C code

Use BOOST_BINARY (Yes, you can use it in C).

#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);

This macro is expanded to an octal literal during preprocessing.

Simple WPF RadioButton Binding?

Actually, using the converter like that breaks two-way binding, plus as I said above, you can't use that with enumerations either. The better way to do this is with a simple style against a ListBox, like this:

Note: Contrary to what DrWPF.com stated in their example, do not put the ContentPresenter inside the RadioButton or else if you add an item with content such as a button or something else, you will not be able to set focus or interact with it. This technique solves that. Also, you need to handle the graying of the text as well as removing of margins on labels or else it will not render correctly. This style handles both for you as well.

<Style x:Key="RadioButtonListItem" TargetType="{x:Type ListBoxItem}" >

    <Setter Property="Template">
        <Setter.Value>

            <ControlTemplate TargetType="ListBoxItem">

                <DockPanel LastChildFill="True" Background="{TemplateBinding Background}" HorizontalAlignment="Stretch" VerticalAlignment="Center" >

                    <RadioButton IsChecked="{TemplateBinding IsSelected}" Focusable="False" IsHitTestVisible="False" VerticalAlignment="Center" Margin="0,0,4,0" />

                    <ContentPresenter
                        Content             = "{TemplateBinding ContentControl.Content}"
                        ContentTemplate     = "{TemplateBinding ContentControl.ContentTemplate}"
                        ContentStringFormat = "{TemplateBinding ContentControl.ContentStringFormat}"
                        HorizontalAlignment = "{TemplateBinding Control.HorizontalContentAlignment}"
                        VerticalAlignment   = "{TemplateBinding Control.VerticalContentAlignment}"
                        SnapsToDevicePixels = "{TemplateBinding UIElement.SnapsToDevicePixels}" />

                </DockPanel>

            </ControlTemplate>

        </Setter.Value>

    </Setter>

</Style>

<Style x:Key="RadioButtonList" TargetType="ListBox">

    <Style.Resources>
        <Style TargetType="Label">
            <Setter Property="Padding" Value="0" />
        </Style>
    </Style.Resources>

    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Background"      Value="Transparent" />

    <Setter Property="ItemContainerStyle" Value="{StaticResource RadioButtonListItem}" />

    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBox}">
                <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="TextBlock.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
        </Trigger>
    </Style.Triggers>

</Style>

<Style x:Key="HorizontalRadioButtonList" BasedOn="{StaticResource RadioButtonList}" TargetType="ListBox">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Background="Transparent" Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>

You now have the look and feel of radio buttons, but you can do two-way binding, and you can use an enumeration. Here's how...

<ListBox Style="{StaticResource RadioButtonList}"
    SelectedValue="{Binding SomeVal}"
    SelectedValuePath="Tag">

    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOption}"     >Some option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOtherOption}">Some other option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.YetAnother}"     >Yet another option</ListBoxItem>

</ListBox>

Also, since we explicitly separated out the style that tragets the ListBoxItem rather than putting it inline, again as the other examples have shown, you can now create a new style off of it to customize things on a per-item basis such as spacing. (This will not work if you simply try to target ListBoxItem as the keyed style overrides generic control targets.)

Here's an example of putting a margin of 6 above and below each item. (Note how you have to explicitly apply the style via the ItemContainerStyle property and not simply targeting ListBoxItem in the ListBox's resource section for the reason stated above.)

<Window.Resources>
    <Style x:Key="SpacedRadioButtonListItem" TargetType="ListBoxItem" BasedOn="{StaticResource RadioButtonListItem}">
        <Setter Property="Margin" Value="0,6" />
    </Style>
</Window.Resources>

<ListBox Style="{StaticResource RadioButtonList}"
    ItemContainerStyle="{StaticResource SpacedRadioButtonListItem}"
    SelectedValue="{Binding SomeVal}"
    SelectedValuePath="Tag">

    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOption}"     >Some option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOtherOption}">Some other option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.YetAnother}"     >Ter another option</ListBoxItem>

</ListBox>

How to get value in the session in jQuery

Sessions are stored on the server and are set from server side code, not client side code such as JavaScript.

What you want is a cookie, someone's given a brilliant explanation in this Stack Overflow question here: How do I set/unset cookie with jQuery?

You could potentially use sessions and set/retrieve them with jQuery and AJAX, but it's complete overkill if Cookies will do the trick.

jQuery: How to get the event object in an event handler function without passing it as an argument?

in IE you can get the event object by window.event in other browsers with no 'use strict' directive, it is possible to get by arguments.callee.caller.arguments[0].

function myFunc(p1, p2, p3) {
    var evt = window.event || arguments.callee.caller.arguments[0];
}

How to extract the hostname portion of a URL in JavaScript

Try

document.location.host

or

document.location.hostname

How to disable horizontal scrolling of UIScrollView?

since iOS7 use

self.automaticallyAdjustsScrollViewInsets = NO;

//and create you page scroller with 3 pages

    self.pageView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.pageView setContentSize:CGSizeMake(self.view.frame.size.width*3, self.view.frame.size.height)];
    [self.pageView setShowsVerticalScrollIndicator:NO];
    [self.pageView setPagingEnabled:YES];
    [self.view addSubview:self.pageView];

How to remove padding around buttons in Android?

To remove the Top and Bottom padding

<com.google.android.material.button.MaterialButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="0dp"//to effect the following parameters, this must be added!
        android:insetTop="0dp"
        android:insetBottom="0dp"/>

To remove the Left and Right padding

<com.google.android.material.button.MaterialButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="0dp"//to effect the following parameters, this must be added!
        android:insetLeft="0dp"
        android:insetRight="0dp"/>

CSS3 scrollbar styling on a div

The problem with the css3 scroll bars is that, interaction can only be performed on the content. we can't interact with the scroll bar on touch devices.

Writing a dict to txt file and reading it back?

I created my own functions which work really nicely:

def writeDict(dict, filename, sep):
    with open(filename, "a") as f:
        for i in dict.keys():            
            f.write(i + " " + sep.join([str(x) for x in dict[i]]) + "\n")

It will store the keyname first, followed by all values. Note that in this case my dict contains integers so that's why it converts to int. This is most likely the part you need to change for your situation.

def readDict(filename, sep):
    with open(filename, "r") as f:
        dict = {}
        for line in f:
            values = line.split(sep)
            dict[values[0]] = {int(x) for x in values[1:len(values)]}
        return(dict)

How to position text over an image in css

A small and short way of doing the same

HTML

<div class="image">
     <p>
        <h3>Heading 3</h3>
        <h5>Heading 5</h5>
     </p>
</div>

CSS

.image {
        position: relative;
        margin-bottom: 20px;
        width: 100%;
        height: 300px;
        color: white;
        background: url('../../Images/myImg.jpg') no-repeat;
        background-size: 250px 250px;
    }

This page didn't load Google Maps correctly. See the JavaScript console for technical details

Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.

In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:

Google Maps API error: MissingKeyMapError [SOLVED]

Also, remember to replace YOUR_API_KEY with your actual API key!

Remove trailing comma from comma-separated string

I'm late on this thread but hope it will help to some one.......

String abc = "kushalhs , mayurvm , narendrabz ,";

if(abc.indexOf(",") != -1){
    abc = abc.substring(0,abc.length() - 1);
}

How get all values in a column using PHP?

How to put MySQL functions back into PHP 7
Step 1

First get the mysql extension source which was removed in March:

https://github.com/php/php-src/tree/PRE_PHP7_EREG_MYSQL_REMOVALS/ext/mysql

Step 2

Then edit your php.ini

Somewhere either in the “Extensions” section or “MySQL” section, simply add this line:

extension = /usr/local/lib/php/extensions/no-debug-non-zts-20141001/mysql.so

Step 3

Restart PHP and mysql_* functions should now be working again.

Step 4

Turn off all deprecated warnings including them from mysql_*:

error_reporting(E_ALL ^ E_DEPRECATED);

Now Below Code Help You :

$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
{
        $Data[] =  $row['names'];  
}

You can also get all values in column using mysql_fetch_assoc

$result = mysql_query("SELECT names FROM Customers");
    $Data= Array();
    while ($row = mysql_fetch_assoc($result)) 
    {
            $Data[] =  $row['names'];  
    }

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

Reference


YOU CAN USE MYSQLI ALTERNATIVE OF MYSQL EASY WAY


*

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);

// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);

// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);

// Free result set
mysqli_free_result($result);

mysqli_close($con);
?> 

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I had the same problem but from IIS in visual studio, I went to project properties -> Web -> and project url change http to https

Java Comparator class to sort arrays

The answer from @aioobe is excellent. I just want to add another way for Java 8.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };

Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);

System.out.println(Arrays.deepToString(twoDim));

For me it's intuitive and easy to remember with Java 8 syntax.

Import Android volley to Android Studio

Or you can simply do

ant jar

in your cloned volley git project. You should now see volley.jar in the volley projects bin folder. Copy this to you Android Studio's app\libs folder. Then add following under dependencies section of Module level build.gradle file -

compile files('libs/volley.jar')

And you should be good import and use the library classes in your project,

Suppress console output in PowerShell

It is a duplicate of this question, with an answer that contains a time measurement of the different methods.

Conclusion: Use [void] or > $null.

Setting new value for an attribute using jQuery

It is working you have to check attr after assigning value

LiveDemo

$('#amount').attr( 'datamin','1000');

alert($('#amount').attr( 'datamin'));?

Difference between System.DateTime.Now and System.DateTime.Today

DateTime.Today represents the current system date with the time part set to 00:00:00

and

DateTime.Now represents the current system date and time

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

I was able to get this to work thanks to this post utilizing VisualWGet. It worked great for me. The important part seems to be to check the -recursive flag (see image).

Also found that the -no-parent flag is important, othewise it will try to download everything.

enter image description here enter image description here

How should I call 3 functions in order to execute them one after the other?

It sounds like you're not fully appreciating the difference between synchronous and asynchronous function execution.

The code you provided in your update immediately executes each of your callback functions, which in turn immediately start an animation. The animations, however, execute asyncronously. It works like this:

  1. Perform a step in the animation
  2. Call setTimeout with a function containing the next animation step and a delay
  3. Some time passes
  4. The callback given to setTimeout executes
  5. Go back to step 1

This continues until the last step in the animation completes. In the meantime, your synchronous functions have long ago completed. In other words, your call to the animate function doesn't really take 3 seconds. The effect is simulated with delays and callbacks.

What you need is a queue. Internally, jQuery queues the animations, only executing your callback once its corresponding animation completes. If your callback then starts another animation, the effect is that they are executed in sequence.

In the simplest case this is equivalent to the following:

window.setTimeout(function() {
    alert("!");
    // set another timeout once the first completes
    window.setTimeout(function() {
        alert("!!");
    }, 1000);
}, 3000); // longer, but first

Here's a general asynchronous looping function. It will call the given functions in order, waiting for the specified number of seconds between each.

function loop() {
    var args = arguments;
    if (args.length <= 0)
        return;
    (function chain(i) {
        if (i >= args.length || typeof args[i] !== 'function')
            return;
        window.setTimeout(function() {
            args[i]();
            chain(i + 1);
        }, 2000);
    })(0);
}    

Usage:

loop(
  function() { alert("sam"); }, 
  function() { alert("sue"); });

You could obviously modify this to take configurable wait times or to immediately execute the first function or to stop executing when a function in the chain returns false or to apply the functions in a specified context or whatever else you might need.

How can I use an ES6 import in Node.js?

If you are using the modules system on the server side, you do not need to use Babel at all. To use modules in Node.js ensure that:

  1. Use a version of node that supports the --experimental-modules flag
  2. Your *.js files must then be renamed to *.mjs

That's it.

However and this is a big however, while your shinny pure ES6 code will run in an environment like Node.js (e.g., 9.5.0) you will still have the craziness of transpilling just to test. Also bear in mind that Ecma has stated that release cycles for JavaScript are going to be faster, with newer features delivered on a more regular basis. Whilst this will be no problems for single environments like Node.js, it's a slightly different proposition for browser environments. What is clear is that testing frameworks have a lot to do in catching up. You will still need to probably transpile for testing frameworks. I'd suggest using Jest.

Also be aware of bundling frameworks. You will be running into problems there.

How do I generate a stream from a string?

Modernized and slightly modified version of the extension methods for ToStream:

public static Stream ToStream(this string value) => ToStream(value, Encoding.UTF8);

public static Stream ToStream(this string value, Encoding encoding) 
                          => new MemoryStream(encoding.GetBytes(value ?? string.Empty));

Modification as suggested in @Palec's comment of @Shaun Bowe answer.

GCC -fPIC option

I'll try to explain what has already been said in a simpler way.

Whenever a shared lib is loaded, the loader (the code on the OS which load any program you run) changes some addresses in the code depending on where the object was loaded to.

In the above example, the "111" in the non-PIC code is written by the loader the first time it was loaded.

For not shared objects, you may want it to be like that because the compiler can make some optimizations on that code.

For shared object, if another process will want to "link" to that code he must read it to the same virtual addresses or the "111" will make no sense. but that virtual-space may already be in use in the second process.

How to know if other threads have finished?

You could also use the Executors object to create an ExecutorService thread pool. Then use the invokeAll method to run each of your threads and retrieve Futures. This will block until all have finished execution. Your other option would be to execute each one using the pool and then call awaitTermination to block until the pool is finished executing. Just be sure to call shutdown() when you're done adding tasks.

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

Convert string to nullable type (int, double, etc...)

public static class GenericExtension
{
    public static T? ConvertToNullable<T>(this String s) where T : struct 
    {
        try
        {
            return (T?)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(s);
        }
        catch (Exception)
        {
            return null;
        }
    }
}

Javascript - Append HTML to container element without innerHTML

This is what DocumentFragment was meant for.

var frag = document.createDocumentFragment();
var span = document.createElement("span");
span.innerHTML = htmldata;
for (var i = 0, ii = span.childNodes.length; i < ii; i++) {
    frag.appendChild(span.childNodes[i]);
}
element.appendChild(frag);

document.createDocumentFragment, .childNodes

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

How to configure socket connect timeout

it might be too late but there is neat solution based on Task.WaitAny (c# 5 +) :

 public static bool ConnectWithTimeout(this Socket socket, string host, int port, int timeout)
        {
            bool connected = false;
            Task result = socket.ConnectAsync(host, port);               
            int index = Task.WaitAny(new[] { result }, timeout);
            connected = socket.Connected;
            if (!connected) {
              socket.Close();
            }

            return connected;
        }

'any' vs 'Object'

Adding to Alex's answer and simplifying it:

Objects are more strict with their use and hence gives the programmer more compile time "evaluation" power and hence in a lot of cases provide more "checking capability" and coould prevent any leaks, whereas any is a more generic term and a lot of compile time checks might hence be ignored.

How to add browse file button to Windows Form using C#

var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string fileToOpen = FD.FileName;

    System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);

    //OR

    System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
    //etc
}

Computational complexity of Fibonacci Sequence

There's a very nice discussion of this specific problem over at MIT. On page 5, they make the point that, if you assume that an addition takes one computational unit, the time required to compute Fib(N) is very closely related to the result of Fib(N).

As a result, you can skip directly to the very close approximation of the Fibonacci series:

Fib(N) = (1/sqrt(5)) * 1.618^(N+1) (approximately)

and say, therefore, that the worst case performance of the naive algorithm is

O((1/sqrt(5)) * 1.618^(N+1)) = O(1.618^(N+1))

PS: There is a discussion of the closed form expression of the Nth Fibonacci number over at Wikipedia if you'd like more information.

Access key value from Web.config in Razor View-MVC3 ASP.NET

FOR MVC

-- WEB.CONFIG CODE IN APP SETTING -- <add key="PhaseLevel" value="1" />

-- ON VIEWS suppose you want to show or hide something based on web.config Value--

-- WRITE THIS ON TOP OF YOUR PAGE-- @{ var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString(); }

-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.

@if (phase != "1") { @Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml") }

Databound drop down list - initial value

To select a value from the dropdown use the index like this:

if we have the

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"></asp:DropDownList>

you would use :

DropDownList1.Items[DropDownList1.SelectedIndex].Value

this would return the value for the selected index.

How To limit the number of characters in JTextField?

Great question, and it's odd that the Swing toolkit doesn't include this functionality natively for JTextFields. But, here's a great answer from my Udemy.com course "Learn Java Like a Kid":

txtGuess = new JTextField();
txtGuess.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) { 
        if (txtGuess.getText().length() >= 3 ) // limit textfield to 3 characters
            e.consume(); 
    }  
});

This limits the number of characters in a guessing game text field to 3 characters, by overriding the keyTyped event and checking to see if the textfield already has 3 characters - if so, you're "consuming" the key event (e) so that it doesn't get processed like normal.

Using onBackPressed() in Android Fragments

Why don't you want to use the back stack? If there is an underlying problem or confusion maybe we can clear it up for you.

If you want to stick with your requirement just override your Activity's onBackPressed() method and call whatever method you're calling when the back arrow in your ActionBar gets clicked.

EDIT: How to solve the "black screen" fragment back stack problem:

You can get around that issue by adding a backstack listener to the fragment manager. That listener checks if the fragment back stack is empty and finishes the Activity accordingly:

You can set that listener in your Activity's onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FragmentManager fm = getFragmentManager();
    fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if(getFragmentManager().getBackStackEntryCount() == 0) finish();
        }
    });
}

Removing spaces from string

String  input = EditTextinput.getText().toString();
input = input.replace(" ", "");

Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim:

input = input.trim();

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

This is the most simple solution for me:

just the current date

$tStamp = Get-Date -format yyyy_MM_dd_HHmmss

current date with some months added

$tStamp = Get-Date (get-date).AddMonths(6).Date -Format yyyyMMdd