Programs & Examples On #Bgga

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

One way that the Scala community can help ease the fear of programmers new to Scala is to focus on practice and to teach by example--a lot of examples that start small and grow gradually larger. Here are a few sites that take this approach:

After spending some time on these sites, one quickly realizes that Scala and its libraries, though perhaps difficult to design and implement, are not so difficult to use, especially in the common cases.

Why Doesn't C# Allow Static Methods to Implement an Interface?

Regarding static methods used in non-generic contexts I agree that it doesn't make much sense to allow them in interfaces, since you wouldn't be able to call them if you had a reference to the interface anyway. However there is a fundamental hole in the language design created by using interfaces NOT in a polymorphic context, but in a generic one. In this case the interface is not an interface at all but rather a constraint. Because C# has no concept of a constraint outside of an interface it is missing substantial functionality. Case in point:

T SumElements<T>(T initVal, T[] values)
{
    foreach (var v in values)
    {
        initVal += v;
    }
}

Here there is no polymorphism, the generic uses the actual type of the object and calls the += operator, but this fails since it can't say for sure that that operator exists. The simple solution is to specify it in the constraint; the simple solution is impossible because operators are static and static methods can't be in an interface and (here is the problem) constraints are represented as interfaces.

What C# needs is a real constraint type, all interfaces would also be constraints, but not all constraints would be interfaces then you could do this:

constraint CHasPlusEquals
{
    static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);
}

T SumElements<T>(T initVal, T[] values) where T : CHasPlusEquals
{
    foreach (var v in values)
    {
        initVal += v;
    }
}

There has been lots of talk already about making an IArithmetic for all numeric types to implement, but there is concern about efficiency, since a constraint is not a polymorphic construct, making a CArithmetic constraint would solve that problem.

Loading/Downloading image from URL on Swift

Swift 2.0 :

1)

if let url = NSURL(string: "http://etc...") {
    if let data = NSData(contentsOfURL: url) {
        imageURL.image = UIImage(data: data)
    }        
}

OR

imageURL.image =
    NSURL(string: "http:// image name...")
    .flatMap { NSData(contentsOfURL: $0) }
    .flatMap { UIImage(data: $0) }

2) Add this method to VC or Extension.

func load_image(urlString:String)
{   let imgURL: NSURL = NSURL(string: urlString)!
    let request: NSURLRequest = NSURLRequest(URL: imgURL)

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in

        if error == nil {
            self.image_element.image = UIImage(data: data)
        }
    }
}

Usage :

self.load_image(" url strig here")

How do I remove the last comma from a string using PHP?

Solutions to apply during a loop:

//1 - Using conditional:

$source = array (1,2,3);
$total = count($source);
    
$str = null;
    
for($i=0; $i <= $total; $i++){ 
        
    if($i < $total) {
        $str .= $i.',';
    }
    else {
        $str .= $i;
    }
}
    
echo $str; //0,1,2,3

//2 - Using rtrim:

$source = array (1,2,3);
$total = count($source);

$str = null;

for($i=0; $i <= $total; $i++){ 
    
        $str .= $i.',';
}

$str = substr($str,0,strlen($str)-1);
echo $str; //0,1,2,3

How to install easy_install in Python 2.7.1 on Windows 7

The recommended way to install setuptools on Windows is to download ez_setup.py and run it. The script will download the appropriate .egg file and install it for you.

For best results, uninstall previous versions FIRST (see Uninstalling).

Once installation is complete, you will find an easy_install.exe program in your Python Scripts subdirectory. For simple invocation and best results, add this directory to your PATH environment variable, if it is not already present.

more details : https://pypi.python.org/pypi/setuptools

ng: command not found while creating new project using angular-cli

This works to update your angular/cli //*Global package (cmd as administrator)

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest

Difference between Select Unique and Select Distinct

select unique is not valid syntax for what you are trying to do

you want to use either select distinct or select distinctrow

And actually, you don't even need distinct/distinctrow in what you are trying to do. You can eliminate duplicates by choosing the appropriate union statement parameters.

the below query by itself will only provide distinct values

select col from table1 
union 
select col from table2

if you did want duplicates you would have to do

select col from table1 
union all
select col from table2

How can I verify if an AD account is locked?

The LockedOut property is what you are looking for among all the properties you returned. You are only seeing incomplete output in TechNet. The information is still there. You can isolate that one property using Select-Object

Get-ADUser matt -Properties * | Select-Object LockedOut

LockedOut
---------
False

The link you referenced doesn't contain this information which is obviously misleading. Test the command with your own account and you will see much more information.

Note: Try to avoid -Properties *. While it is great for simple testing it can make queries, especially ones with multiple accounts, unnecessarily slow. So, in this case, since you only need lockedout:

Get-ADUser matt -Properties LockedOut | Select-Object LockedOut

How to list files in an android directory?

String[] listOfFiles = getActivity().getFilesDir().list();

or

String[] listOfFiles = Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS).list();

Correct way to initialize HashMap and can HashMap hold different value types?

In answer to your second question: Yes a HashMap can hold different types of objects. Whether that's a good idea or not depends on the problem you're trying to solve.

That said, your example won't work. The int value is not an Object. You have to use the Integer wrapper class to store an int value in a HashMap

Tracing XML request/responses with JAX-WS

Here is the solution in raw code (put together thanks to stjohnroe and Shamik):

Endpoint ep = Endpoint.create(new WebserviceImpl());
List<Handler> handlerChain = ep.getBinding().getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
ep.getBinding().setHandlerChain(handlerChain);
ep.publish(publishURL);

Where SOAPLoggingHandler is (ripped from linked examples):

package com.myfirm.util.logging.ws;

import java.io.PrintStream;
import java.util.Map;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/*
 * This simple SOAPHandler will output the contents of incoming
 * and outgoing messages.
 */
public class SOAPLoggingHandler implements SOAPHandler<SOAPMessageContext> {

    // change this to redirect output if desired
    private static PrintStream out = System.out;

    public Set<QName> getHeaders() {
        return null;
    }

    public boolean handleMessage(SOAPMessageContext smc) {
        logToSystemOut(smc);
        return true;
    }

    public boolean handleFault(SOAPMessageContext smc) {
        logToSystemOut(smc);
        return true;
    }

    // nothing to clean up
    public void close(MessageContext messageContext) {
    }

    /*
     * Check the MESSAGE_OUTBOUND_PROPERTY in the context
     * to see if this is an outgoing or incoming message.
     * Write a brief message to the print stream and
     * output the message. The writeTo() method can throw
     * SOAPException or IOException
     */
    private void logToSystemOut(SOAPMessageContext smc) {
        Boolean outboundProperty = (Boolean)
            smc.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (outboundProperty.booleanValue()) {
            out.println("\nOutbound message:");
        } else {
            out.println("\nInbound message:");
        }

        SOAPMessage message = smc.getMessage();
        try {
            message.writeTo(out);
            out.println("");   // just to add a newline
        } catch (Exception e) {
            out.println("Exception in handler: " + e);
        }
    }
}

else & elif statements not working in Python

 if guess == number:
     print ("Good")
 elif guess == 2:
     print ("Bad")
 else:
     print ("Also bad")

Make sure you have your identation right. The syntax is ok.

Add and Remove Views in Android Dynamically?

Hi You can try this way by adding relative layout and than add textview in that.

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

RelativeLayout relative = new RelativeLayout(getApplicationContext());
relative.setLayoutParams(lp);

TextView tv = new TextView(getApplicationContext());
tv.setLayoutParams(lp);

EditText edittv = new EditText(getApplicationContext());
edittv.setLayoutParams(lp);

relative.addView(tv);
relative.addView(edittv);

How can I display a modal dialog in Redux that performs asynchronous actions?

In my opinion the bare minimum implementation has two requirements. A state that keeps track of whether the modal is open or not, and a portal to render the modal outside of the standard react tree.

The ModalContainer component below implements those requirements along with corresponding render functions for the modal and the trigger, which is responsible for executing the callback to open the modal.

import React from 'react';
import PropTypes from 'prop-types';
import Portal from 'react-portal';

class ModalContainer extends React.Component {
  state = {
    isOpen: false,
  };

  openModal = () => {
    this.setState(() => ({ isOpen: true }));
  }

  closeModal = () => {
    this.setState(() => ({ isOpen: false }));
  }

  renderModal() {
    return (
      this.props.renderModal({
        isOpen: this.state.isOpen,
        closeModal: this.closeModal,
      })
    );
  }

  renderTrigger() {
     return (
       this.props.renderTrigger({
         openModal: this.openModal
       })
     )
  }

  render() {
    return (
      <React.Fragment>
        <Portal>
          {this.renderModal()}
        </Portal>
        {this.renderTrigger()}
      </React.Fragment>
    );
  }
}

ModalContainer.propTypes = {
  renderModal: PropTypes.func.isRequired,
  renderTrigger: PropTypes.func.isRequired,
};

export default ModalContainer;

And here's a simple use case...

import React from 'react';
import Modal from 'react-modal';
import Fade from 'components/Animations/Fade';
import ModalContainer from 'components/ModalContainer';

const SimpleModal = ({ isOpen, closeModal }) => (
  <Fade visible={isOpen}> // example use case with animation components
    <Modal>
      <Button onClick={closeModal}>
        close modal
      </Button>
    </Modal>
  </Fade>
);

const SimpleModalButton = ({ openModal }) => (
  <button onClick={openModal}>
    open modal
  </button>
);

const SimpleButtonWithModal = () => (
   <ModalContainer
     renderModal={props => <SimpleModal {...props} />}
     renderTrigger={props => <SimpleModalButton {...props} />}
   />
);

export default SimpleButtonWithModal;

I use render functions, because I want to isolate state management and boilerplate logic from the implementation of the rendered modal and trigger component. This allows the rendered components to be whatever you want them to be. In your case, I suppose the modal component could be a connected component that receives a callback function that dispatches an asynchronous action.

If you need to send dynamic props to the modal component from the trigger component, which hopefully doesn't happen too often, I recommend wrapping the ModalContainer with a container component that manages the dynamic props in its own state and enhance the original render methods like so.

import React from 'react'
import partialRight from 'lodash/partialRight';
import ModalContainer from 'components/ModalContainer';

class ErrorModalContainer extends React.Component {
  state = { message: '' }

  onError = (message, callback) => {
    this.setState(
      () => ({ message }),
      () => callback && callback()
    );
  }

  renderModal = (props) => (
    this.props.renderModal({
       ...props,
       message: this.state.message,
    })
  )

  renderTrigger = (props) => (
    this.props.renderTrigger({
      openModal: partialRight(this.onError, props.openModal)
    })
  )

  render() {
    return (
      <ModalContainer
        renderModal={this.renderModal}
        renderTrigger={this.renderTrigger}
      />
    )
  }
}

ErrorModalContainer.propTypes = (
  ModalContainer.propTypes
);

export default ErrorModalContainer;

Using "Object.create" instead of "new"

new and Object.create serve different purposes. new is intended to create a new instance of an object type. Object.create is intended to simply create a new object and set its prototype. Why is this useful? To implement inheritance without accessing the __proto__ property. An object instance's prototype referred to as [[Prototype]] is an internal property of the virtual machine and is not intended to be directly accessed. The only reason it is actually possible to directly access [[Prototype]] as the __proto__ property is because it has always been a de-facto standard of every major virtual machine's implementation of ECMAScript, and at this point removing it would break a lot of existing code.

In response to the answer above by 7ochem, objects should absolutely never have their prototype set to the result of a new statement, not only because there's no point calling the same prototype constructor multiple times but also because two instances of the same class can end up with different behavior if one's prototype is modified after being created. Both examples are simply bad code as a result of misunderstanding and breaking the intended behavior of the prototype inheritance chain.

Instead of accessing __proto__, an instance's prototype should be written to when an it is created with Object.create or afterward with Object.setPrototypeOf, and read with Object.getPrototypeOf or Object.isPrototypeOf.

Also, as the Mozilla documentation of Object.setPrototypeOf points out, it is a bad idea to modify the prototype of an object after it is created for performance reasons, in addition to the fact that modifying an object's prototype after it is created can cause undefined behavior if a given piece of code that accesses it can be executed before OR after the prototype is modified, unless that code is very careful to check the current prototype or not access any property that differs between the two.

Given

const X = function (v) { this.v = v }; X.prototype.whatAmI = 'X'; X.prototype.getWhatIAm = () => this.whatAmI; X.prototype.getV = () => this.v;

the following VM pseudo-code is equivalent to the statement const x0 = new X(1);:

const x0 = {}; x0.[[Prototype]] = X.prototype; X.prototype.constructor.call(x0, 1);

Note although the constructor can return any value, the new statement always ignores its return value and returns a reference to the newly created object.

And the following pseudo-code is equivalent to the statement const x1 = Object.create(X.prototype);:

const x0 = {}; x0.[[Prototype]] = X.prototype;

As you can see, the only difference between the two is that Object.create does not execute the constructor, which can actually return any value but simply returns the new object reference this if not otherwise specified.

Now, if we wanted to create a subclass Y with the following definition:

const Y = function(u) { this.u = u; } Y.prototype.whatAmI = 'Y'; Y.prototype.getU = () => this.u;

Then we can make it inherit from X like this by writing to __proto__:

Y.prototype.__proto__ = X.prototype;

While the same thing could be accomplished without ever writing to __proto__ with:

Y.prototype = Object.create(X.prototype); Y.prototype.constructor = Y;

In the latter case, it is necessary to set the constructor property of the prototype so that the correct constructor is called by the new Y statement, otherwise new Y will call the function X. If the programmer does want new Y to call X, it would be more properly done in Y's constructor with X.call(this, u)

Pie chart with jQuery

A few others that have not been mentioned:

For mini pies, lines and bars, Peity is brilliant, simple, tiny, fast, uses really elegant markup.

I'm not sure of it's relationship with Flot (given its name), but Flotr2 is pretty good, certainly does better pies than Flot.

Bluff produces nice-looking line graphs, but I had a bit of trouble with its pies.

Not what I was after, but another commercial product (much like Highcharts) is TeeChart.

Android load from URL to Bitmap

Glide.with(context)
    .load("http://test.com/yourimage.jpg")  
    .asBitmap()  // ????????? ??? ? ?????? ??????
    .fitCenter()
    .into(new SimpleTarget<Bitmap>(100,100) {
          @Override
          public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {

           // do something with you bitmap 

                bitmap

          }
    }); 

Choose folders to be ignored during search in VS Code

If you have multiple folders in your workspace, set up the search.exclude on each folder. There's a drop-down next to WORKSPACE SETTINGS.

Folder Settings Tab

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.

Some keypoints will be:

  1. InnoDB does ACID-compliant transaction. http://en.wikipedia.org/wiki/ACID
  2. InnoDB does Referential Integrity (foreign key relations) http://www.w3resource.com/sql/joins/joining-tables-through-referential-integrity.php
  3. MyIsam does full text search, InnoDB doesn't
  4. I have been told InnoDB is faster on executing writes but slower than MyISAM doing reads (I cannot back this up and could not find any article that analyses this, I do however have the guy that told me this in high regard), feel free to ignore this point or do your own research.
  5. Default configuration does not work very well for InnoDB needs to be tweaked accordingly, run a tool like http://mysqltuner.pl/mysqltuner.pl to help you.

Notes:

  • In my opinion the second point is probably the one were InnoDB has a huge advantage over MyISAM.
  • Full text search not working with InnoDB is a bit of a pain, You can mix different storage engines but be careful when doing so.

Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.

Xcode - ld: library not found for -lPods

This problem-related to lPods can be fixed by following the steps below

  • Select your Project Target.
  • Go to "Build Phases" in "Link Binary With Libraries".
  • Now remove ".a" file of that library which is creating the problem.
  • Clean and Build.

This will work.

C# Macro definitions in Preprocessor

Turn the C Macro into a C# static method in a class.

Static image src in Vue.js template

This solution is for Vue-2 users:

  1. In vue-2 if you don't like to keep your files in static folder (relevant info), or
  2. In vue-2 & vue-cli-3 if you don't like to keep your files in public folder (static folder is renamed to public):

The simple solution is :)

<img src="@/assets/img/clear.gif" /> // just do this:
<img :src="require(`@/assets/img/clear.gif`)" // or do this:
<img :src="require(`@/assets/img/${imgURL}`)" // if pulling from: data() {return {imgURL: 'clear.gif'}}

If you like to keep your static images in static/assets/img or public/assets/img folder, then just do:

<img src="./assets/img/clear.gif" />
<img src="/assets/img/clear.gif" /> // in some case without dot ./

What is the difference between ELF files and bin files?

A bin file is just the bits and bytes that go into the rom or a particular address from which you will run the program. You can take this data and load it directly as is, you need to know what the base address is though as that is normally not in there.

An elf file contains the bin information but it is surrounded by lots of other information, possible debug info, symbols, can distinguish code from data within the binary. Allows for more than one chunk of binary data (when you dump one of these to a bin you get one big bin file with fill data to pad it to the next block). Tells you how much binary you have and how much bss data is there that wants to be initialised to zeros (gnu tools have problems creating bin files correctly).

The elf file format is a standard, arm publishes its enhancements/variations on the standard. I recommend everyone writes an elf parsing program to understand what is in there, dont bother with a library, it is quite simple to just use the information and structures in the spec. Helps to overcome gnu problems in general creating .bin files as well as debugging linker scripts and other things that can help to mess up your bin or elf output.

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

In my case, a colleague added Lombok to the project, and I had to install the Idea Lombok plug-in. In your case, it may be something else that requires a plug-in.

How to hide element using Twitter Bootstrap and show it using jQuery?

Based on the above answers, I have just added my own functions and this further doesn't conflict with the available jquery functions like .hide(), .show(), .toggle(). Hope it helps.

    /*
     * .hideElement()
     * Hide the matched elements. 
     */
    $.fn.hideElement = function(){
        $(this).addClass('hidden');
        return this;
    };

    /*
     * .showElement()
     * Show the matched elements.
     */
    $.fn.showElement = function(){
        $(this).removeClass('hidden');
        return this;
    };

    /*
     * .toggleElement()
     * Toggle the matched elements.
     */
    $.fn.toggleElement = function(){
        $(this).toggleClass('hidden');
        return this;
    };

How to get random value out of an array?

A simple way to getting Randdom value form Array.

$color_array =["red","green","blue","light_orange"];
$color_array[rand(0,3)

now every time you will get different colors from Array.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

There was an error in understanding of return Type Just add Header and it will solve your problem

@Headers("Content-Type: application/json")

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

The best way to understand is to simply think from top to bottom ( Large Desktops to Mobile Phones)

Firstly, as B3 is mobile first so if you use xs then the columns will be same from Large desktops to xs ( i recommend using xs or sm as this will keep everything the way you want on every screen size )

Secondly if you want to give different width to columns on different devices or resolutions, than you can add multiple classes e.g

the above will change the width according to the screen resolutions, REMEMBER i am keeping the total columns in each class = 12

I hope my answer would help!

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

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

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

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

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

In registry you can find environment variables under:

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

How do I specify the JDK for a GlassFish domain?

ERROR MESSAGE :

..... PWC6199: Generated servlet error: -Source 1.5 does not support the diamond operator (please use -source version 7 or higher to enable the diamond operator)

Solution

On MAC : go to

  • /Users/username/GlassFish_Server/glassfish/domains/domain2/config
  • open the default_web.xml file
  • find the jsp
  • add

    enter image description here

Create nice column output in python

Transposing the columns like that is a job for zip:

>>> a = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
>>> list(zip(*a))
[('a', 'aaaaaaaaaa', 'a'), ('b', 'b', 'bbbbbbbbbb'), ('c', 'c', 'c')]

To find the required length of each column, you can use max:

>>> trans_a = zip(*a)
>>> [max(len(c) for c in b) for b in trans_a]
[10, 10, 1]

Which you can use, with suitable padding, to construct strings to pass to print:

>>> col_lenghts = [max(len(c) for c in b) for b in trans_a]
>>> padding = ' ' # You might want more
>>> padding.join(s.ljust(l) for s,l in zip(a[0], col_lenghts))
'a          b          c'

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

update q
set q.QuestionID = a.QuestionID
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want

I recommend to check what the result set to update is before running the update (same query, just with a select):

select *
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want

Particularly whether each answer id has definitely only 1 associated question id.

Get changes from master into branch in Git

Check out the aq branch, and rebase from master.

git checkout aq
git rebase master

How to select data from 30 days?

You should be using DATEADD is Sql server so if try this simple select you will see the affect

Select DATEADD(Month, -1, getdate())

Result

2013-04-20 14:08:07.177

in your case try this query

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name

How to set the env variable for PHP?

Try display phpinfo() by file and check this var.

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

Angular2, what is the correct way to disable an anchor element?

Just came across this question, and wanted to suggest an alternate approach.

In the markup the OP provided, there is a click event binding. This makes me think that the elements are being used as "buttons". If that is the case, they could be marked up as <button> elements and styled like links, if that is the look you desire. (For example, Bootstrap has a built-in "link" button style, https://v4-alpha.getbootstrap.com/components/buttons/#examples)

This has several direct and indirect benefits. It allows you to bind to the disabled property, which when set will disable mouse and keyboard events automatically. It lets you style the disabled state based on the disabled attribute, so you don't have to also manipulate the element's class. It is also better for accessibility.

For a good write-up about when to use buttons and when to use links, see Links are not buttons. Neither are DIVs and SPANs

Invalidating JSON Web Tokens

An alternative would be to have a middleware script just for critical API endpoints.
This middleware script would check in the database if the token is invalidated by an admin.
This solution may be useful for cases where is not necessary to completely block the access of a user right away.

Creating a UICollectionView programmatically

  1. Building off @Warewolf's answer, the next step is to create your own custom cell.

    Go to File -> New -> File -> User Interface -> Empty -> Call this nib "customNib".

  2. In your customNib drag a UICollectionView Cell in. Give it reuse cell identifier @"Cell".

  3. File -> New -> File -> Cocoa Touch Class -> Class named "CustomCollectionViewCell" subclass if UICollectionViewCell.

  4. Go back to the custom nib, click cell and make this custom class "CustomCollectionViewCell".

  5. Go to your viewDidLoad viewcontroller and instead of

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];

    have

    UINib *nib = [UINib nibWithNibName:@"customNib" bundle:nil]; [_collectionView registerNib:nib forCellWithReuseIdentifier:@"Cell"];

  6. Also, change (to your new cell identifier)

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

pip3: command not found but python3-pip is already installed

Same issue on Fedora 23. I had to reinstall python3-pip to generate the proper pip3 folders in /usr/bin/.

sudo dnf reinstall python3-pip

What does "dereferencing" a pointer mean?

Code and explanation from Pointer Basics:

The dereference operation starts at the pointer and follows its arrow over to access its pointee. The goal may be to look at the pointee state or to change the pointee state. The dereference operation on a pointer only works if the pointer has a pointee -- the pointee must be allocated and the pointer must be set to point to it. The most common error in pointer code is forgetting to set up the pointee. The most common runtime crash because of that error in the code is a failed dereference operation. In Java the incorrect dereference will be flagged politely by the runtime system. In compiled languages such as C, C++, and Pascal, the incorrect dereference will sometimes crash, and other times corrupt memory in some subtle, random way. Pointer bugs in compiled languages can be difficult to track down for this reason.

void main() {   
    int*    x;  // Allocate the pointer x
    x = malloc(sizeof(int));    // Allocate an int pointee,
                            // and set x to point to it
    *x = 42;    // Dereference x to store 42 in its pointee   
}

Eclipse reports rendering library more recent than ADT plug-in

Change android version while rendering layout.

enter image description here

Change in API version 18 to 17 work for me.

Edit: Solution worked for Android Studio too.

Remove tracking branches no longer on remote

If you are using zsh shell with Oh My Zsh installed then the easiest way to do this safely is to use the built in autocomplete.

First determine which branches you want to delete with:

~ git branch --merged

  branch1
  branch2
  branch3
* master

this will show you a list of already merged branches

After you know a few you want to delete then type:

~ git branch -d 

All you have to do is hit [tab] and it will show you a list of local branches. Use tab-complete or just hit [tab] again and you can cycle through them to select a branch with [enter].

Tab Select the branches over and over again until you have a list of branches you wnat to delete:

~ git branch -d branch1 branch2 branch3

Now just press enter to delete your collection of branches.

If you aren't using zsh on your terminal... Get it here.

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

If you want to get source map file different version, you can use this link http://code.jquery.com/jquery-x.xx.x.min.map

Instead x.xx.x put your version number.

Note: Some links, which you get on this method, may be broken :)

Using new line(\n) in string and rendering the same in HTML

You could use a pre tag instead of a div. This would automatically display your \n's in the correct way.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
         var display_txt = "1st line text" +"\n" + "2nd line text";
         $('#somediv').html(display_txt).css("color", "green");
});
</script>
</head>
<body>

<pre>
<p id="somediv"></p>
</pre>

</body>
</html>

Round double in two decimal places in C#?

Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)

htaccess <Directory> deny from all

You can use from root directory:

RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html

Or:

RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');

PostgreSQL, checking date relative to "today"

I think this will do it:

SELECT * FROM MyTable WHERE mydate > now()::date - 365;

After installing with pip, "jupyter: command not found"

I had to run "rehash" and then it was able to find the jupyter command

Replace invalid values with None in Pandas DataFrame

Before proceeding with this post, it is important to understand the difference between NaN and None. One is a float type, the other is an object type. Pandas is better suited to working with scalar types as many methods on these types can be vectorised. Pandas does try to handle None and NaN consistently, but NumPy cannot.

My suggestion (and Andy's) is to stick with NaN.

But to answer your question...

pandas >= 0.18: Use na_values=['-'] argument with read_csv

If you loaded this data from CSV/Excel, I have good news for you. You can quash this at the root during data loading instead of having to write a fix with code as a subsequent step.

Most of the pd.read_* functions (such as read_csv and read_excel) accept a na_values attribute.

file.csv

A,B
-,1
3,-
2,-
5,3
1,-2
-5,4
-1,-1
-,0
9,0

Now, to convert the - characters into NaNs, do,

import pandas as pd
df = pd.read_csv('file.csv', na_values=['-'])
df

     A    B
0  NaN  1.0
1  3.0  NaN
2  2.0  NaN
3  5.0  3.0
4  1.0 -2.0
5 -5.0  4.0
6 -1.0 -1.0
7  NaN  0.0
8  9.0  0.0

And similar for other functions/file formats.

P.S.: On v0.24+, you can preserve integer type even if your column has NaNs (yes, talk about having the cake and eating it too). You can specify dtype='Int32'

df = pd.read_csv('file.csv', na_values=['-'], dtype='Int32')
df

     A    B
0  NaN    1
1    3  NaN
2    2  NaN
3    5    3
4    1   -2
5   -5    4
6   -1   -1
7  NaN    0
8    9    0

df.dtypes

A    Int32
B    Int32
dtype: object

The dtype is not a conventional int type... but rather, a Nullable Integer Type. There are other options.


Handling Numeric Data: pd.to_numeric with errors='coerce

If you're dealing with numeric data, a faster solution is to use pd.to_numeric with the errors='coerce' argument, which coerces invalid values (values that cannot be cast to numeric) to NaN.

pd.to_numeric(df['A'], errors='coerce')

0    NaN
1    3.0
2    2.0
3    5.0
4    1.0
5   -5.0
6   -1.0
7    NaN
8    9.0
Name: A, dtype: float64

To retain (nullable) integer dtype, use

pd.to_numeric(df['A'], errors='coerce').astype('Int32')

0    NaN
1      3
2      2
3      5
4      1
5     -5
6     -1
7    NaN
8      9
Name: A, dtype: Int32 

To coerce multiple columns, use apply:

df[['A', 'B']].apply(pd.to_numeric, errors='coerce').astype('Int32')

     A    B
0  NaN    1
1    3  NaN
2    2  NaN
3    5    3
4    1   -2
5   -5    4
6   -1   -1
7  NaN    0
8    9    0

...and assign the result back after.

More information can be found in this answer.

How do browser cookie domains work?

The previous answers are a little outdated.

RFC 6265 was published in 2011, based on the browser consensus at that time. Since then, there has been some complication with public suffix domains. I've written an article explaining the current situation - http://bayou.io/draft/cookie.domain.html

To summarize, rules to follow regarding cookie domain:

  • The origin domain of a cookie is the domain of the originating request.

  • If the origin domain is an IP, the cookie's domain attribute must not be set.

  • If a cookie's domain attribute is not set, the cookie is only applicable to its origin domain.

  • If a cookie's domain attribute is set,

    • the cookie is applicable to that domain and all its subdomains;
    • the cookie's domain must be the same as, or a parent of, the origin domain
    • the cookie's domain must not be a TLD, a public suffix, or a parent of a public suffix.

It can be derived that a cookie is always applicable to its origin domain.

The cookie domain should not have a leading dot, as in .foo.com - simply use foo.com

As an example,

  • x.y.z.com can set a cookie domain to itself or parents - x.y.z.com, y.z.com, z.com. But not com, which is a public suffix.
  • a cookie with domain=y.z.com is applicable to y.z.com, x.y.z.com, a.x.y.z.com etc.

Examples of public suffixes - com, edu, uk, co.uk, blogspot.com, compute.amazonaws.com

DateTime to javascript date

I know this is a little late, but here's the solution I had to come up with for handling dates when you want to be timezone independent. Essentially it involves converting everything to UTC.

From Javascript to Server:

Send out dates as epoch values with the timezone offset removed.

var d = new Date(2015,0,1) // Jan 1, 2015
// Ajax Request to server ...
$.ajax({
  url: '/target',
  params: { date: d.getTime() - (d.getTimezoneOffset() * 60 * 1000) }
});

The server then recieves 1420070400000 as the date epoch.

On the Server side, convert that epoch value to a datetime object:

DateTime d = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(epoch);

At this point the date is just the date/time provided by the user as they provided it. Effectively it is UTC.

Going the other way:

When the server pulls data from the database, presumably in UTC, get the difference as an epoch (making sure that both date objects are either local or UTC):

long ms = (long)utcDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;

or

long ms = (long)localDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)).TotalMilliseconds;

When javascript receives this value, create a new date object. However, this date object is going to be assumed local time, so you need to offset it by the current timezone:

var epochValue = 1420070400000 // value pulled from server.
var utcDateVal = new Date(epochValue);
var actualDate = new Date(utcDateVal.getTime() + (utcDateVal.getTimezoneOffset() * 60 * 1000))

console.log(utcDateVal); // Wed Dec 31 2014 19:00:00 GMT-0500 (Eastern Standard Time)
console.log(actualDate); // Thu Jan 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)

As far as I know, this should work for any time zone where you need to display dates that are timezone independent.

Youtube API Limitations

Apart from other answer There are calculator provided by Youtube to check your usage. It is good to identify your usage. https://developers.google.com/youtube/v3/determine_quota_cost

enter image description here

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

Before you start merging MVC and Web API projects I would suggest to read about cons and pros to separate these as different projects. One very important thing (my own) is authentication systems, which is totally different.

IF you need to use authenticated requests on both MVC and Web API, you need to remember that Web API is RESTful (don't need to keep session, simple HTTP requests, etc.), but MVC is not.

To look on the differences of implementations simply create 2 different projects in Visual Studio 2013 from Templates: one for MVC and one for Web API (don't forget to turn On "Individual Authentication" during creation). You will see a lot of difference in AuthencationControllers.

So, be aware.

Set a button group's width to 100% and make buttons equal width?

I don't like the solution of settings widths on .btn because it assumes there'll always be the same number of items in the .btn-group. This is a faulty assumption and leads to bloated, presentation-specific CSS.

A better solution is to change how .btn-group with .btn-block and child .btn(s) are display. I believe this is what you're looking for:

.btn-group.btn-block {
    display: table;
}
.btn-group.btn-block > .btn {
    display: table-cell;
}

Here's a fiddle: http://jsfiddle.net/DEwX8/123/

If you'd prefer to have equal-width buttons (within reason) and can support only browsers that support flexbox, try this instead:

.btn-group.btn-block {
    display: flex;
}
.btn-group.btn-block > .btn {
    flex: 1;
}

Here's a fiddle: http://jsfiddle.net/DEwX8/124/

How to stop/terminate a python script from running?

  • To stop a python script just press Ctrl + C.
  • Inside a script with exit(), you can do it.
  • You can do it in an interactive script with just exit.
  • You can use pkill -f name-of-the-python-script.

How to get POSTed JSON in Flask?

First of all, the .json attribute is a property that delegates to the request.get_json() method, which documents why you see None here.

You need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None otherwise. See the Flask Request documentation:

This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see is_json()), otherwise it will be None.

You can tell request.get_json() to skip the content type requirement by passing it the force=True keyword argument.

Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.

Multi-line string with extra space (preserved indentation)

it will work if you put it as below:

AA='first line
\nsecond line 
\nthird line'
echo $AA
output:
first line
second line
third line

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

How do I import modules or install extensions in PostgreSQL 9.1+?

Into psql terminal put:

\i <path to contrib files>

in ubuntu it usually is /usr/share/postgreslq/<your pg version>/contrib/<contrib file>.sql

How to perform grep operation on all files in a directory?

If you want to do multiple commands, you could use:

for I in `ls *.sql`
do
    grep "foo" $I >> foo.log
    grep "bar" $I >> bar.log
done

How to get all the AD groups for a particular user?

The following example is from the Code Project article, (Almost) Everything In Active Directory via C#:

// userDn is a Distinguished Name such as:
// "LDAP://CN=Joe Smith,OU=Sales,OU=domain,OU=com"
public ArrayList Groups(string userDn, bool recursive)
{
    ArrayList groupMemberships = new ArrayList();
    return AttributeValuesMultiString("memberOf", userDn,
        groupMemberships, recursive);
}

public ArrayList AttributeValuesMultiString(string attributeName,
     string objectDn, ArrayList valuesCollection, bool recursive)
{
    DirectoryEntry ent = new DirectoryEntry(objectDn);
    PropertyValueCollection ValueCollection = ent.Properties[attributeName];
    IEnumerator en = ValueCollection.GetEnumerator();

    while (en.MoveNext())
    {
        if (en.Current != null)
        {
            if (!valuesCollection.Contains(en.Current.ToString()))
            {
                valuesCollection.Add(en.Current.ToString());
                if (recursive)
                {
                    AttributeValuesMultiString(attributeName, "LDAP://" +
                    en.Current.ToString(), valuesCollection, true);
                }
            }
        }
    }
    ent.Close();
    ent.Dispose();
    return valuesCollection;
}

Just call the Groups method with the Distinguished Name for the user, and pass in the bool flag to indicate if you want to include nested / child groups memberships in your resulting ArrayList:

ArrayList groups = Groups("LDAP://CN=Joe Smith,OU=Sales,OU=domain,OU=com", true);
foreach (string groupName in groups)
{
    Console.WriteLine(groupName);
}

If you need to do any serious level of Active Directory programming in .NET I highly recommend bookmarking & reviewing the Code Project article I mentioned above.

Android Intent Cannot resolve constructor

this work for me

    ncharacters.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent openncharacter = new Intent(getApplicationContext(),ncharacters.class);
            startActivity(openncharacter);
        }
    });

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

Java Multiple Inheritance

Interfaces don't simulate multiple inheritance. Java creators considered multiple inheritance wrong, so there is no such thing in Java.

If you want to combine the functionality of two classes into one - use object composition. I.e.

public class Main {
    private Component1 component1 = new Component1();    
    private Component2 component2 = new Component2();
}

And if you want to expose certain methods, define them and let them delegate the call to the corresponding controller.

Here interfaces may come handy - if Component1 implements interface Interface1 and Component2 implements Interface2, you can define

class Main implements Interface1, Interface2

So that you can use objects interchangeably where the context allows it.

So in my point of view, you can't get into diamond problem.

Regex: Specify "space or start of string" and "space or end of string"

You can use any of the following:

\b      #A word break and will work for both spaces and end of lines.
(^|\s)  #the | means or. () is a capturing group. 


/\b(stackoverflow)\b/

Also, if you don't want to include the space in your match, you can use lookbehind/aheads.

(?<=\s|^)         #to look behind the match
(stackoverflow)   #the string you want. () optional
(?=\s|$)          #to look ahead.

How to install PyQt5 on Windows?

easiest way, I think download Eric, unzip go to sources, open python directory, drag the install script into the python icon, not folder, follow prompts

Groovy executing shell commands

command = "ls *"

def execute_state=sh(returnStdout: true, script: command)

but if the command failure the process will terminate

how to make a div to wrap two float divs inside?

Float everything.

If you have a floated div inside a non-floated div, everything gets all screwy. That's why most CSS frameworks like Blueprint and 960.gs all use floated containers and divs.

To answer your particular question,

<div class="container">
<!--
.container {
  float: left;
  width: 100%;
}
-->
  <div class="sidebar">
  <!--
  .sidebar {
    float: left;
    width: 20%;
    height: auto;
  }
  -->
  </div>
  <div class="content">
  <!--
  .sidebar {
    float: left;
    width: 20%;
    height: auto;
  }
  -->
  </div>
</div>

should work just fine, as long as you float:left; all of your <div>s.

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

The best way to do this is by a simple check and assess. I usually do something like this:

#ifndef _DEPRECATION_DISABLE   /* One time only */
#define _DEPRECATION_DISABLE   /* Disable deprecation true */
#if (_MSC_VER >= 1400)         /* Check version */
#pragma warning(disable: 4996) /* Disable deprecation */
#endif /* #if defined(NMEA_WIN) && (_MSC_VER >= 1400) */
#endif /* #ifndef _DEPRECATION_DISABLE */

All that is really required is the following:

#pragma warning(disable: 4996)

Hasn't failed me yet; Hope this helps

Using iFrames In ASP.NET

How about:

<asp:HtmlIframe ID="yourIframe" runat="server" />

Is supported since .Net Framework 4.5

If you have Problems using this control, you might take a look here.

Add another class to a div

I am facing the same issue. If parent element is hidden then after showing the element chosen drop down are not showing. This is not a perfect solution but it solved my issue. After showing the element you can use following code.

function onshowelement() { $('.chosen').chosen('destroy'); $(".chosen").chosen({ width: '100%' }); }

PHPExcel how to set cell value dynamically

I don't have much experience working with php but from a logic standpoint this is what I would do.

  1. Loop through your result set from MySQL
  2. In Excel you should already know what A,B,C should be because those are the columns and you know how many columns you are returning.
  3. The row number can just be incremented with each time through the loop.

Below is some pseudocode illustrating this technique:

    for (int i = 0; i < MySQLResults.count; i++){
         $objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name); 
        // Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
         $objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
         $objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
    }

Passing HTML to template using Flask/Jinja2

the ideal way is to

{{ something|safe }}

than completely turning off auto escaping.

JSLint says "missing radix parameter"

You can turn off this rule if you wish to skip that test.

Insert:

radix: false

Under the "rules" property in the tslint.json file.

It's not recommended to do that if you don't understand this exception.

Rename Excel Sheet with VBA Macro

The "no frills" options are as follows:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

Date object to Calendar [Java]

Calendar tCalendar = Calendar.getInstance();
tCalendar.setTime(date);

date is a java.util.Date object. You may use Calendar.getInstance() as well to obtain the Calendar instance(much more efficient).

Find out whether radio button is checked with JQuery?

... Thanks guys... all I needed was the 'value' of the checked radio button where each radio button in the set had a different id...

 var user_cat = $("input[name='user_cat']:checked").val();

works for me...

Change bootstrap navbar collapse breakpoint without using LESS

2018 UPDATE

Bootstrap 4

Changing the navbar breakpoint is easier in Bootstrap 4 using the navbar-expand-* classes:

<nav class="navbar fixed-top navbar-expand-sm">..</nav>

  • navbar-expand-sm = mobile menu on xs screens <576px
  • navbar-expand-md = mobile menu on sm screens <768px
  • navbar-expand-lg = mobile menu on md screens <992px
  • navbar-expand-xl = mobile menu on lg screens <1200px
  • navbar-expand = never use mobile menu
  • (no expand class) = always use mobile menu

If you exclude navbar-expand-* the mobile menu will be used at all widths. Here's a demo of all 6 navbar states: Bootstrap 4 Navbar Example

You can also use a custom breakpoint (???px) by adding a little CSS. For example, here's 1300px..

@media (min-width: 1300px){
    .navbar-expand-custom {
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: flex-start;
    }
    .navbar-expand-custom .navbar-nav {
        flex-direction: row;
    }
    .navbar-expand-custom .navbar-nav .nav-link {
        padding-right: .5rem;
        padding-left: .5rem;
    }
    .navbar-expand-custom .navbar-collapse {
        display: flex!important;
    }
    .navbar-expand-custom .navbar-toggler {
        display: none;
    }
}

Bootstrap 4 Custom Navbar Breakpoint
Bootstrap 4 Navbar Breakpoint Examples


Bootstrap 3

For Bootstrap 3.3.x, here is the working CSS to override the navbar breakpoint. Change 991px to the pixel dimension of the point at which you want the navbar to collapse...

@media (max-width: 991px) {
  .navbar-header {
      float: none;
  }
  .navbar-left,.navbar-right {
      float: none !important;
  }
  .navbar-toggle {
      display: block;
  }
  .navbar-collapse {
      border-top: 1px solid transparent;
      box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
  }
  .navbar-fixed-top {
      top: 0;
      border-width: 0 0 1px;
  }
  .navbar-collapse.collapse {
      display: none!important;
  }
  .navbar-nav {
      float: none!important;
      margin-top: 7.5px;
  }
  .navbar-nav>li {
      float: none;
  }
  .navbar-nav>li>a {
      padding-top: 10px;
      padding-bottom: 10px;
  }
  .collapse.in{
      display:block !important;
  }
}

Working example for 991px: http://www.bootply.com/j7XJuaE5v6
Working example for 1200px: https://www.codeply.com/go/VsYaOLzfb4 (with search form)

Note: The above works for anything over 768px. If you need to change it to less than 768px the example of less than 768px is here.


How can I use Ruby to colorize the text output to a terminal?

As String class methods (unix only):

class String
def black;          "\e[30m#{self}\e[0m" end
def red;            "\e[31m#{self}\e[0m" end
def green;          "\e[32m#{self}\e[0m" end
def brown;          "\e[33m#{self}\e[0m" end
def blue;           "\e[34m#{self}\e[0m" end
def magenta;        "\e[35m#{self}\e[0m" end
def cyan;           "\e[36m#{self}\e[0m" end
def gray;           "\e[37m#{self}\e[0m" end

def bg_black;       "\e[40m#{self}\e[0m" end
def bg_red;         "\e[41m#{self}\e[0m" end
def bg_green;       "\e[42m#{self}\e[0m" end
def bg_brown;       "\e[43m#{self}\e[0m" end
def bg_blue;        "\e[44m#{self}\e[0m" end
def bg_magenta;     "\e[45m#{self}\e[0m" end
def bg_cyan;        "\e[46m#{self}\e[0m" end
def bg_gray;        "\e[47m#{self}\e[0m" end

def bold;           "\e[1m#{self}\e[22m" end
def italic;         "\e[3m#{self}\e[23m" end
def underline;      "\e[4m#{self}\e[24m" end
def blink;          "\e[5m#{self}\e[25m" end
def reverse_color;  "\e[7m#{self}\e[27m" end
end

and usage:

puts "I'm back green".bg_green
puts "I'm red and back cyan".red.bg_cyan
puts "I'm bold and green and backround red".bold.green.bg_red

on my console:

enter image description here

additional:

def no_colors
  self.gsub /\e\[\d+m/, ""
end

removes formatting characters

Note

puts "\e[31m" # set format (red foreground)
puts "\e[0m"   # clear format
puts "green-#{"red".red}-green".green # will be green-red-normal, because of \e[0

SQL Client for Mac OS X that works with MS SQL Server

Since there currently isn't a MS SQL client for Mac OS X, I would, as Modesty has suggested, use Remote Desktop for the Mac.

How to set adaptive learning rate for GradientDescentOptimizer?

From tensorflow official docs

global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.1
learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,
                                       100000, 0.96, staircase=True)

# Passing global_step to minimize() will increment it at each step.
learning_step = (
tf.train.GradientDescentOptimizer(learning_rate)
.minimize(...my loss..., global_step=global_step))

How to clear the logs properly for a Docker container?

I needed something I could run as one command, instead of having to write docker ps and copying over each Container ID and running the command multiple times. I've adapted BMitch's answer and thought I'd share in case someone else may find this useful.

Mixing xargs seems to pull off what I need here:

docker ps --format='{{.ID}}' | \
  xargs -I {} sh -c 'echo > $(docker inspect --format="{{.LogPath}}" {})'

This grabs each Container ID listed by docker ps (will erase your logs for any container on that list!), pipes it into xargs and then echoes a blank string to replace the log path of the container.

selected value get from db into dropdown select box option using php mysql error

BEST code and simple

<select id="example-getting-started" multiple="multiple" name="category">

    <?php
    $query = "select * from mine";
    $results = mysql_query($query);

    while ($rows = mysql_fetch_assoc(@$results)){ 
    ?>
    <option value="<?php echo $rows['category'];?>"><?php echo $rows['category'];?></option>

    <?php
    } 
    ?>
</select>

How do I create a unique ID in Java?

If you want short, human-readable IDs and only need them to be unique per JVM run:

private static long idCounter = 0;

public static synchronized String createID()
{
    return String.valueOf(idCounter++);
}    

Edit: Alternative suggested in the comments - this relies on under-the-hood "magic" for thread safety, but is more scalable and just as safe:

private static AtomicLong idCounter = new AtomicLong();

public static String createID()
{
    return String.valueOf(idCounter.getAndIncrement());
}

What does $ mean before a string?

It signifies string interpolation.

It will protect you because it is adding compilation time protection on the string evaluation.

You will no longer get an exception with string.Format("{0}{1}",secondParamIsMissing)

Scroll Element into View with Selenium

def scrollToElement(element: WebElement) = {
  val location = element.getLocation
  driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
}

What does .class mean in Java?

This <?> is a beast. It often leads to confusion and errors, because, when you see it first, then you start believing, <?> is a wildcard for any java type. Which is .. not true. <?> is the unknown type, a slight and nasty difference.

It's not a problem when you use it with Class. Both lines work and compile:

Class anyType = String.class;
Class <?> theUnknownType = String.class;

But - if we start using it with collections, then we see strange compiletime errors:

List<?> list = new ArrayList<Object>();  // ArrayList<?> is not allowed
list.add("a String");                    // doesn't compile ...

Our List<?> is not a collection, that is suitable for just any type of object. It can only store one type: the mystic "unkown type". Which is not a real type, for sure.

Adding content to a linear layout dynamically?

I found more accurate way to adding views like linear layouts in kotlin (Pass parent layout in inflate() and false)

val parentLayout = view.findViewById<LinearLayout>(R.id.llRecipientParent)
val childView = layoutInflater.inflate(R.layout.layout_recipient, parentLayout, false)
parentLayout.addView(childView)

How to load external webpage in WebView

Add below method in your activity class.Here browser is nothing but your webview object.

Now you can view web contain page wise easily.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && browser.canGoBack()) {
        browser.goBack();
        return true;
    }
    return false;
}

When to use 'npm start' and when to use 'ng serve'?

There are more than that. The executed executables are different.

npm run start

will run your projects local executable which is located in your node_modules/.bin.

ng serve

will run another executable which is global.

It means if you clone and install an Angular project which is created with angular-cli version 5 and your global cli version is 7, then you may have problems with ng build.

Looking to understand the iOS UIViewController lifecycle

The methods viewWillLayoutSubviews and viewDidLayoutSubviews aren't mentioned in the diagrams, but these are called between viewWillAppear and viewDidAppear. They can be called multiple times.

Placing border inside of div and not on its edge

Although this question has already been adequately answered with solutions using the box-shadow and outline properties, I would like to slightly expand on this for all those who have landed here (like myself) searching for a solution for an inner border with an offset

So let's say you have a black 100px x 100px div and you need to inset it with a white border - which has an inner offset of 5px (say) - this can still be done with the above properties.

box-shadow

The trick here is to know that multiple box-shadows are allowed, where the first shadow is on top and subsequent shadows have lower z-ordering.

With that knowledge, the box-shadow declaration will be:

box-shadow: inset 0 0 0 5px black, inset 0 0 0 10px white;

_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: black;_x000D_
  box-shadow: inset 0 0 0 5px black, inset 0 0 0 10px white; _x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Basically, what that declaration is saying is: render the last (10px white) shadow first, then render the previous 5px black shadow above it.

outline with outline-offset

For the same effect as above the outline declarations would be:

outline: 5px solid white;
outline-offset: -10px;

_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: black;_x000D_
  outline: 5px solid white;_x000D_
  outline-offset: -10px;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

NB: outline-offset isn't supported by IE if that's important to you.


Codepen demo

Get the current date in java.sql.Date format

tl;dr

myPreparedStatement.setObject(   // Directly exchange java.time objects with database without the troublesome old java.sql.* classes.
    … ,                                   
    LocalDate.parse(             // Parse string as a `LocalDate` date-only value.
        "2018-01-23"             // Input string that complies with standard ISO 8601 formatting.
    ) 
)

java.time

The modern approach uses the java.time classes that supplant the troublesome old legacy classes such as java.util.Date and java.sql.Date.

For a date-only value, use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

The java.time classes use standard formats when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate ld = LocalDate.parse( input ) ;

You can directly exchange java.time objects with your database using a JDBC driver compliant with JDBC 4.2 or later. You can forget about transforming in and out of java.sql.* classes.

myPreparedStatement.setObject( … , ld ) ;

Retrieval:

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

About java.time

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

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

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

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Android: Color To Int conversion

All the methods and variables in Color are static. You can not instantiate a Color object.

Official Color Docs

The Color class defines methods for creating and converting color ints.

Colors are represented as packed ints, made up of 4 bytes: alpha, red, green, blue.

The values are unpremultiplied, meaning any transparency is stored solely in the alpha component, and not in the color components.

The components are stored as follows (alpha << 24) | (red << 16) | (green << 8) | blue.

Each component ranges between 0..255 with 0 meaning no contribution for that component, and 255 meaning 100% contribution.

Thus opaque-black would be 0xFF000000 (100% opaque but no contributions from red, green, or blue), and opaque-white would be 0xFFFFFFFF

How to use a jQuery plugin inside Vue

run npm install jquery --save

then on your root component, place this

global.jQuery = require('../node_modules/jquery/dist/jquery.js');
var $ = global.jQuery;

Do not forget to export it to enable you to use it with other components

export default {
  name: 'App',
  components: {$}
}

Psql could not connect to server: No such file or directory, 5432 error?

This works for me:

pg_ctl -D /usr/local/var/[email protected] stop;
brew services stop [email protected];
brew services start [email protected];

cURL equivalent in Node.js?

EDIT:

For new projects please refrain from using request, since now the project is in maitainance mode, and will eventually be deprecated

https://github.com/request/request/issues/3142

Instead i would recommend Axios, the library is in line with Node latest standards, and there are some available plugins to enhance it, enabling mock server responses, automatic retries and other features.

https://github.com/axios/axios

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

Or using async / await:

try{
    const response = await axios.get('/user?ID=12345');
    console.log(response)
} catch(axiosErr){
    console.log(axiosErr)
}

I usually use REQUEST, its a simplified but powerful HTTP client for Node.js

https://github.com/request/request

Its on NPM npm install request

Here is a usage sample:

var request = require('request');

request('http://www.google.com', function (error, response, body) {
   if (!error && response.statusCode == 200) {
       console.log(body) // Show the HTML for the Google homepage.
   }
})

Apache VirtualHost 403 Forbidden

It could be you haven't setup PHP~!

sum two columns in R

The sum function will add all numbers together to produce a single number, not a vector (well, at least not a vector of length greater than 1).

It looks as though at least one of your columns is a factor. You could convert them into numeric vectors by checking this

head(as.numeric(data$col1))  # make sure this gives you the right output

And if that looks right, do

data$col1 <- as.numeric(data$col1)
data$col2 <- as.numeric(data$col2)

You might have to convert them into characters first. In which case do

data$col1 <- as.numeric(as.character(data$col1))
data$col2 <- as.numeric(as.character(data$col2))

It's hard to tell which you should do without being able to see your data.

Once the columns are numeric, you just have to do

data$col3 <- data$col1 + data$col2

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

postgresql - add boolean column to table set default

If you are using postgresql then you have to use column type BOOLEAN in lower case as boolean.

ALTER TABLE users ADD "priv_user" boolean DEFAULT false;

How can I pass a file argument to my bash script using a Terminal command in Linux?

It'll be easier (and more "proper", see below) if you just run your script as

myprogram /path/to/file

Then you can access the path within the script as $1 (for argument #1, similarly $2 is argument #2, etc.)

file="$1"
externalprogram "$file" [other parameters]

Or just

externalprogram "$1" [otherparameters]

If you want to extract the path from something like --file=/path/to/file, that's usually done with the getopts shell function. But that's more complicated than just referencing $1, and besides, switches like --file= are intended to be optional. I'm guessing your script requires a file name to be provided, so it doesn't make sense to pass it in an option.

Most efficient method to groupby on an array of objects

Using ES6 Map object:

_x000D_
_x000D_
/**
 * @description
 * Takes an Array<V>, and a grouping function,
 * and returns a Map of the array grouped by the grouping function.
 *
 * @param list An array of type V.
 * @param keyGetter A Function that takes the the Array type V as an input, and returns a value of type K.
 *                  K is generally intended to be a property key of V.
 *
 * @returns Map of the array grouped by the grouping function.
 */
//export function groupBy<K, V>(list: Array<V>, keyGetter: (input: V) => K): Map<K, Array<V>> {
//    const map = new Map<K, Array<V>>();
function groupBy(list, keyGetter) {
    const map = new Map();
    list.forEach((item) => {
         const key = keyGetter(item);
         const collection = map.get(key);
         if (!collection) {
             map.set(key, [item]);
         } else {
             collection.push(item);
         }
    });
    return map;
}


// example usage

const pets = [
    {type:"Dog", name:"Spot"},
    {type:"Cat", name:"Tiger"},
    {type:"Dog", name:"Rover"}, 
    {type:"Cat", name:"Leo"}
];
    
const grouped = groupBy(pets, pet => pet.type);
    
console.log(grouped.get("Dog")); // -> [{type:"Dog", name:"Spot"}, {type:"Dog", name:"Rover"}]
console.log(grouped.get("Cat")); // -> [{type:"Cat", name:"Tiger"}, {type:"Cat", name:"Leo"}]

const odd = Symbol();
const even = Symbol();
const numbers = [1,2,3,4,5,6,7];

const oddEven = groupBy(numbers, x => (x % 2 === 1 ? odd : even));
    
console.log(oddEven.get(odd)); // -> [1,3,5,7]
console.log(oddEven.get(even)); // -> [2,4,6]
_x000D_
_x000D_
_x000D_

About Map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Error while trying to retrieve text for error ORA-01019

Well,

Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

When are static variables initialized?

Starting with the code from the other question:

class MyClass {
  private static MyClass myClass = new MyClass();
  private static final Object obj = new Object();
  public MyClass() {
    System.out.println(obj); // will print null once
  }
}

A reference to this class will start initialization. First, the class will be marked as initialized. Then the first static field will be initialized with a new instance of MyClass(). Note that myClass is immediately given a reference to a blank MyClass instance. The space is there, but all values are null. The constructor is now executed and prints obj, which is null.

Now back to initializing the class: obj is made a reference to a new real object, and we're done.

If this was set off by a statement like: MyClass mc = new MyClass(); space for a new MyClass instance is again allocated (and the reference placed in mc). The constructor is again executed and again prints obj, which now is not null.

The real trick here is that when you use new, as in WhatEverItIs weii = new WhatEverItIs( p1, p2 ); weii is immediately given a reference to a bit of nulled memory. The JVM will then go on to initialize values and run the constructor. But if you somehow reference weii before it does so--by referencing it from another thread or or by referencing from the class initialization, for instance--you are looking at a class instance filled with null values.

Replace multiple characters in one replace call

Specify the /g (global) flag on the regular expression to replace all matches instead of just the first:

string.replace(/_/g, ' ').replace(/#/g, '')

To replace one character with one thing and a different character with something else, you can't really get around needing two separate calls to replace. You can abstract it into a function as Doorknob did, though I would probably have it take an object with old/new as key/value pairs instead of a flat array.

How to "wait" a Thread in Android

Don't use wait(), use either android.os.SystemClock.sleep(1000); or Thread.sleep(1000);.

The main difference between them is that Thread.sleep() can be interrupted early -- you'll be told, but it's still not the full second. The android.os call will not wake early.

How can I tell AngularJS to "refresh"

Why $apply should be called?

TL;DR: $apply should be called whenever you want to apply changes made outside of Angular world.


Just to update @Dustin's answer, here is an explanation of what $apply exactly does and why it works.

$apply() is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.

Angular allows any value to be used as a binding target. Then at the end of any JavaScript code turn, it checks to see if the value has changed. That step that checks to see if any binding values have changed actually has a method, $scope.$digest()1. We almost never call it directly, as we use $scope.$apply() instead (which will call $scope.$digest).

Angular only monitors variables used in expressions and anything inside of a $watch living inside the scope. So if you are changing the model outside of the Angular context, you will need to call $scope.$apply() for those changes to be propagated, otherwise Angular will not know that they have been changed thus the binding will not be updated2.

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

If you use Guava (v11 minimum) in your project you can use Maps::transformValues.

Map<String, Column> newColumnMap = Maps.transformValues(
  originalColumnMap,
  Column::new // equivalent to: x -> new Column(x) 
)

Note: The values of this map are evaluated lazily. If the transformation is expensive you can copy the result to a new map like suggested in the Guava docs.

To avoid lazy evaluation when the returned map doesn't need to be a view, copy the returned map into a new map of your choosing.

How to use a SQL SELECT statement with Access VBA

Access 2007 can lose the CurrentDb: see http://support.microsoft.com/kb/167173, so in the event of getting "Object Invalid or no longer set" with the examples, use:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")

How do I compile with -Xlint:unchecked?

other way to compile using -Xlint:unchecked through command line

javac abc.java -Xlint:unchecked

it will show the unchecked and unsafe warnings.

to call onChange event after pressing Enter key

You can use event.key

_x000D_
_x000D_
function Input({onKeyPress}) {_x000D_
  return (_x000D_
    <div>_x000D_
      <h2>Input</h2>_x000D_
      <input type="text" onKeyPress={onKeyPress}/>_x000D_
    </div>_x000D_
  )_x000D_
}_x000D_
_x000D_
class Form extends React.Component {_x000D_
  state = {value:""}_x000D_
_x000D_
  handleKeyPress = (e) => {_x000D_
    if (e.key === 'Enter') {_x000D_
      this.setState({value:e.target.value})_x000D_
    }_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <section>_x000D_
        <Input onKeyPress={this.handleKeyPress}/>_x000D_
        <br/>_x000D_
        <output>{this.state.value}</output>_x000D_
      </section>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Form />,_x000D_
  document.getElementById("react")_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id="react"></div>
_x000D_
_x000D_
_x000D_

Multiprocessing vs Threading Python

Other answers have focused more on the multithreading vs multiprocessing aspect, but in python Global Interpreter Lock (GIL) has to be taken into account. When more number (say k) of threads are created, generally they will not increase the performance by k times, as it will still be running as a single threaded application. GIL is a global lock which locks everything out and allows only single thread execution utilizing only a single core. The performance does increase in places where C extensions like numpy, Network, I/O are being used, where a lot of background work is done and GIL is released.
So when threading is used, there is only a single operating system level thread while python creates pseudo-threads which are completely managed by threading itself but are essentially running as a single process. Preemption takes place between these pseudo threads. If the CPU runs at maximum capacity, you may want to switch to multiprocessing.
Now in case of self-contained instances of execution, you can instead opt for pool. But in case of overlapping data, where you may want processes communicating you should use multiprocessing.Process.

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

I had the same issue and tried all the options (delete schema, delete specific row, update checksum) but nothing works.

In my case flyway-core dependency got corrupted somehow.

Solution:

  1. Delete flyway-core folder from ~.m2\local repository path...\org\flywaydb\flyway-core.

  2. Execute "maven clean install" so that it will download new one and add it into a project.

I hope this will help.

How to retrieve images from MySQL database and display in an html tag

add $row = mysql_fetch_object($result); after your mysql_query();

your html <img src="<?php echo $row->dvdimage; ?>" width="175" height="200" />

How to keep the console window open in Visual C++?

cin.get(), or system("PAUSE"). I haven't heard you can use return(0);

Android: converting String to int

It's already a string? Remove the getText() call.

int myNum = 0;

try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
  // Handle parse error.
}

Loop through Map in Groovy?

Another option:

def map = ['a':1, 'b':2, 'c':3]
map.each{
  println it.key +" "+ it.value
}

How to return a boolean method in java?

Best way would be to declare Boolean variable within the code block and return it at end of code, like this:

public boolean Test(){
    boolean booleanFlag= true; 
    if (A>B)
    {booleanFlag= true;}
    else 
    {booleanFlag = false;}
    return booleanFlag;

}

I find this the best way.

How to hide the border for specified rows of a table?

I use this with good results:

border-style:hidden;

It also works for:

border-right-style:hidden; /*if you want to hide just a border on a cell*/

Example:

_x000D_
_x000D_
<style type="text/css">_x000D_
      table, th, td {_x000D_
       border: 2px solid green;_x000D_
      }_x000D_
      tr.hide_right > td, td.hide_right{_x000D_
        border-right-style:hidden;_x000D_
      }_x000D_
      tr.hide_all > td, td.hide_all{_x000D_
        border-style:hidden;_x000D_
      }_x000D_
  }_x000D_
</style>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="hide_right">11</td>_x000D_
    <td>12</td>_x000D_
    <td class="hide_all">13</td>_x000D_
  </tr>_x000D_
  <tr class="hide_right">_x000D_
    <td>21</td>_x000D_
    <td>22</td>_x000D_
    <td>23</td>_x000D_
  </tr>_x000D_
  <tr class="hide_all">_x000D_
    <td>31</td>_x000D_
    <td>32</td>_x000D_
    <td>33</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here is the result: enter image description here

cin and getline skipping input

The structure of your menu code is the issue:

cin >> choice;   // new line character is left in the stream

 switch ( ... ) {
     // We enter the handlers, '\n' still in the stream
 }

cin.ignore();   // Put this right after cin >> choice, before you go on
                // getting input with getline.

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

in my case it was an error in the storyboard source code, follow these steps:

  1. first open your story board as source code
  2. search for <connections>
  3. remove unwanted connections

For example:

<connections>
    <outlet property="mapPostsView" destination="4EV-NK-Bhn" id="ubM-Z6-mwl"/>
    <outlet property="mapView" destination="kx6-TV-oQg" id="4wY-jv-Ih6"/>
    <outlet property="sidebarButton" destination="6UH-BZ-60q" id="8Yz-5G-HpY"/>
</connections>

As you see, these are connections between your code variables' names and the storyboard layout xml tags ;)

Why does adb return offline after the device string?

Check that the ADB version that you are running is newer than the version of the OS on the connected devices. For me, updating the ADB helped to get the device online.

Laravel Eloquent update just if changes have been made

You can use getChanges() on Eloquent model even after persisting.

iPhone: How to get current milliseconds?

This is what I used for Swift

var date = NSDate()
let currentTime = Int64(date.timeIntervalSince1970 * 1000)

print("Time in milliseconds is \(currentTime)")

used this site to verify accuracy http://currentmillis.com/

reading HttpwebResponse json response, C#

First you need an object

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}

Then in here

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
        }

    }

I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

JavaScriptSerializer System.Web.Script.Serialization

Why catch and rethrow an exception in C#?

You don't want to throw ex - as this will lose the call stack. See Exception Handling (MSDN).

And yes, the try...catch is doing nothing useful (apart from lose the call stack - so it's actually worse - unless for some reason you didn't want to expose this information).

How do I alter the position of a column in a PostgreSQL database table?

Open the table in PGAdmin and in the SQL pane at the bottom copy the SQL Create Table statement. Then open the Query Tool and paste. If the table has data, change the table name to 'new_name', if not, delete the comment "--" in the Drop Table line. Edit the column sequence as required. Mind the missing/superfluous comma in the last column in case you have moved it. Execute the new SQL Create Table command. Refresh and ... voilà.

For empty tables in the design stage this method is quite practical.

In case the table has data, we need to rearrange the column sequence of the data as well. This is easy: use INSERT to import the old table into its new version with:

INSERT INTO new ( c2, c3, c1 ) SELECT * from old;

... where c2, c3, c1 are the columns c1, c2, c3 of the old table in their new positions. Please note that in this case you must use a 'new' name for the edited 'old' table, or you will lose your data. In case the column names are many, long and/or complex use the same method as above to copy the new table structure into a text editor, and create the new column list there before copying it into the INSERT statement.

After checking that all is well, DROP the old table and change the the 'new' name to 'old' using ALTER TABLE new RENAME TO old; and you are done.

What is the difference between vmalloc and kmalloc?

You only need to worry about using physically contiguous memory if the buffer will be accessed by a DMA device on a physically addressed bus (like PCI). The trouble is that many system calls have no way to know whether their buffer will eventually be passed to a DMA device: once you pass the buffer to another kernel subsystem, you really cannot know where it is going to go. Even if the kernel does not use the buffer for DMA today, a future development might do so.

vmalloc is often slower than kmalloc, because it may have to remap the buffer space into a virtually contiguous range. kmalloc never remaps, though if not called with GFP_ATOMIC kmalloc can block.

kmalloc is limited in the size of buffer it can provide: 128 KBytes*). If you need a really big buffer, you have to use vmalloc or some other mechanism like reserving high memory at boot.

*) This was true of earlier kernels. On recent kernels (I tested this on 2.6.33.2), max size of a single kmalloc is up to 4 MB! (I wrote a fairly detailed post on this.) — kaiwan

For a system call you don't need to pass GFP_ATOMIC to kmalloc(), you can use GFP_KERNEL. You're not an interrupt handler: the application code enters the kernel context by means of a trap, it is not an interrupt.

Find an object in SQL Server (cross-database)

You can achieve this by using the following query:

EXEC sp_msforeachdb 
    'IF EXISTS
    (
        SELECT  1 
        FROM    [?].sys.objects 
        WHERE   name LIKE ''OBJECT_TO_SEARCH''
    )
    SELECT 
        ''?''       AS DB, 
        name        AS Name, 
        type_desc   AS Type 
    FROM [?].sys.objects 
    WHERE name LIKE ''OBJECT_TO_SEARCH'''

Just replace OBJECT_TO_SEARCH with the actual object name you are interested in (or part of it, surrounded with %).

More details here: https://peevsvilen.blog/2019/07/30/search-for-an-object-in-sql-server/

Accessing localhost (xampp) from another computer over LAN network - how to?

I am Fully agree With BugFinder.

In simple Words, just put ip address 192.168.1.56 in your browser running on 192.168.1.2!

if it does not work then there are following possible reasons for that :

  1. Network Connectivity Issue :

    • First of all Check your network Connectivity using ping 192.168.1.56 command in command prompt/terminal on 192.168.1.2 computer.
  2. Firewall Problem : Your windows firewall setting do not have allowing rule for XAMPP(apache). (Most probable problem)

    • (solution) go to advanced firewall settings and add inbound and outbound rules for Apache executable file.
  3. Apache Configuration problem. : Your apache is configured to listen only local requests.

    • (Solution) you can it by opening httpd.conf file and replace Listen 127.0.0.1:80 to Listen 80 or *Listen :80
  4. Port Conflict with other Servers(IIS etc.)

    • (Solution) Turn off apache server and then open local host in browser. if any response is obtained then turnoff that server then start Apache.

if all above does not work then probably there is some configuration problem on your apache server.try to find it out otherwise just reinstall it and transfer all php files(htdocs) to new installation of XAMPP/WAMP.

Pull new updates from original GitHub repository into forked GitHub repository

If there is nothing to lose you could also just delete your fork just go to settings... go to danger zone section below and click delete repository. It will ask you to input the repository name and your password after. After that you just fork the original again.

Center content in responsive bootstrap navbar

Update 2020...

Bootstrap 5 Beta

The Navbar is still flexbox based in Bootstrap 5 and centering content works the same as it did with Bootstrap 4. Examples

Bootstrap 4

Centering Navbar content is easier is Bootstrap 4, and you can see many centering scenarios explained here: https://stackoverflow.com/a/20362024/171456

Bootstrap 3

Another scenario that doesn't seem to have been answered yet is centering both the brand and navbar links. Here's a solution..

.navbar .navbar-header,
.navbar-collapse {
    float:none;
    display:inline-block;
    vertical-align: top;
}

@media (max-width: 768px) {
    .navbar-collapse  {
        display: block;
    }
}

http://codeply.com/go/1lrdvNH9GI

Also see: Bootstrap NavBar with left, center or right aligned items

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

The default configuration of most SMTP servers is not to relay from an untrusted source to outside domains. For example, imagine that you contact the SMTP server for foo.com and ask it to send a message to [email protected]. Because the SMTP server doesn't really know who you are, it will refuse to relay the message. If the server did do that for you, it would be considered an open relay, which is how spammers often do their thing.

If you contact the foo.com mail server and ask it to send mail to [email protected], it might let you do it. It depends on if they trust that you're who you say you are. Often, the server will try to do a reverse DNS lookup, and refuse to send mail if the IP you're sending from doesn't match the IP address of the MX record in DNS. So if you say that you're the bar.com mail server but your IP address doesn't match the MX record for bar.com, then it will refuse to deliver the message.

You'll need to talk to the administrator of that SMTP server to get the authentication information so that it will allow relay for you. You'll need to present those credentials when you contact the SMTP server. Usually it's either a user name/password, or it can use Windows permissions. Depends on the server and how it's configured.

See Unable to send emails to external domain using SMTP for an example of how to send the credentials.

What are the differences between a HashMap and a Hashtable in Java?

My small contribution :

  1. First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.

  2. Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.

  3. Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.

How to disable button in React.js

Using refs is not best practice because it reads the DOM directly, it's better to use React's state instead. Also, your button doesn't change because the component is not re-rendered and stays in its initial state.

You can use setState together with an onChange event listener to render the component again every time the input field changes:

// Input field listens to change, updates React's state and re-renders the component.
<input onChange={e => this.setState({ value: e.target.value })} value={this.state.value} />

// Button is disabled when input state is empty.
<button disabled={!this.state.value} />

Here's a working example:

_x000D_
_x000D_
class AddItem extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { value: '' };_x000D_
    this.onChange = this.onChange.bind(this);_x000D_
    this.add = this.add.bind(this);_x000D_
  }_x000D_
_x000D_
  add() {_x000D_
    this.props.onButtonClick(this.state.value);_x000D_
    this.setState({ value: '' });_x000D_
  }_x000D_
_x000D_
  onChange(e) {_x000D_
    this.setState({ value: e.target.value });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div className="add-item">_x000D_
        <input_x000D_
          type="text"_x000D_
          className="add-item__input"_x000D_
          value={this.state.value}_x000D_
          onChange={this.onChange}_x000D_
          placeholder={this.props.placeholder}_x000D_
        />_x000D_
        <button_x000D_
          disabled={!this.state.value}_x000D_
          className="add-item__button"_x000D_
          onClick={this.add}_x000D_
        >_x000D_
          Add_x000D_
        </button>_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <AddItem placeholder="Value" onButtonClick={v => console.log(v)} />,_x000D_
  document.getElementById('View')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id='View'></div>
_x000D_
_x000D_
_x000D_

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Use a virtual machine. Start fresh as often as you want, and stop doing these hacks that may or may not simulate a clean machine.

Seriously, use VMWare or VirtualPC.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

For similar assembly binding errors , following steps may help:

  1. Right click on your Solution and click Manage Nuget Packages for Solution ...
  2. go to Consolidate Tab (last tab) and check if any any differences between packages installed in different projects inside your solution. specially pay attention to your referenced projects which may have lower versions because they usually are less noticed)
  3. consolidate specially packages related to your assembly error and note that many packages are dependent on some other packages like *.code & *.api & ...
  4. after resolving all suspected consolidations , rebuild and rerun the app and see if the assembly bindings are resolved.

Alter Table Add Column Syntax

Just remove COLUMN from ADD COLUMN

ALTER TABLE Employees
  ADD EmployeeID numeric NOT NULL IDENTITY (1, 1)

ALTER TABLE Employees ADD CONSTRAINT
        PK_Employees PRIMARY KEY CLUSTERED 
        (
          EmployeeID
        ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

You could try this registry hack:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
"DeadGWDetectDefault"=dword:00000001
"KeepAliveTime"=dword:00120000

If it works, just keep increasing the KeepAliveTime. It is currently set for 2 minutes.

How do I use brew installed Python as the default Python?

As you are using Homebrew the following command gives a better picture:

brew doctor

Output:

==> /usr/bin occurs before /usr/local/bin This means that system-provided programs will be used instead of those provided by Homebrew. This is an issue if you eg. brew installed Python.

Consider editing your .bash_profile to put: /usr/local/bin ahead of /usr/bin in your $PATH.

is there a css hack for safari only NOT chrome?

This works:

@media not all and (min-resolution:.001dpcm) { 
  @media {
    /* your code for Safari Desktop & Mobile */
    body {
      background-color: red;
      color: blue;
    }
    /* end */
  }
}

Converting HTML element to string in JavaScript / JQuery

you can just wrap it into another element and call html after that:

$('<div><iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe></div>').html();

note that outerHTML doesn't exist on older browsers but innerHTML still does (it doesn't exist for example in ff < 11 while it's still used on many older computers)

Latex - Change margins of only a few pages

I've used this in beamer, but not for general documents, but it looks like that's what the original hint suggests

\newenvironment{changemargin}[2]{%
\begin{list}{}{%
\setlength{\topsep}{0pt}%
\setlength{\leftmargin}{#1}%
\setlength{\rightmargin}{#2}%
\setlength{\listparindent}{\parindent}%
\setlength{\itemindent}{\parindent}%
\setlength{\parsep}{\parskip}%
}%
\item[]}{\end{list}}

Then to use it

\begin{changemargin}{-1cm}{-1cm}

don't forget to

\end{changemargin}

at the end of the page

I got this from Changing margins “on the fly” in the TeX FAQ.

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

Is there a job scheduler library for node.js?

node-crontab allows you to edit system cron jobs from node.js. Using this library will allow you to run programs even after your main process termintates. Disclaimer: I'm the developer.

Evaluate expression given as a string

Sorry but I don't understand why too many people even think a string was something that could be evaluated. You must change your mindset, really. Forget all connections between strings on one side and expressions, calls, evaluation on the other side.

The (possibly) only connection is via parse(text = ....) and all good R programmers should know that this is rarely an efficient or safe means to construct expressions (or calls). Rather learn more about substitute(), quote(), and possibly the power of using do.call(substitute, ......).

fortunes::fortune("answer is parse")
# If the answer is parse() you should usually rethink the question.
#    -- Thomas Lumley
#       R-help (February 2005)

Dec.2017: Ok, here is an example (in comments, there's no nice formatting):

q5 <- quote(5+5)
str(q5)
# language 5 + 5

e5 <- expression(5+5)
str(e5)
# expression(5 + 5)

and if you get more experienced you'll learn that q5 is a "call" whereas e5 is an "expression", and even that e5[[1]] is identical to q5:

identical(q5, e5[[1]])
# [1] TRUE

How to send json data in POST request using C#

You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient:

using (var client = new HttpClient())
{
    // This would be the like http://www.uber.com
    client.BaseAddress = new Uri("Base Address/URL Address");

    // serialize your json using newtonsoft json serializer then add it to the StringContent
    var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 

    // method address would be like api/callUber:SomePort for example
    var result = await client.PostAsync("Method Address", content);
    string resultContent = await result.Content.ReadAsStringAsync();   
}

How do you create a Marker with a custom icon for google maps API v3?

LatLng hello = new LatLng(X, Y);          // whereX & Y are coordinates

Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
                R.drawable.university);   // where university is the icon name that is used as a marker.

mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(icon)).position(hello).title("Hello World!"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(hello));

Declaring and initializing a string array in VB.NET

I believe you need to specify "Option Infer On" for this to work.

Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.

Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.

Opinion incoming:

Also, you mention that you've got "Option Explicit Off". Please don't do this.

Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":

Dim X as Integer
Y = 3

This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.

SQL Server - Convert varchar to another collation (code page) to fix character encoding

I think SELECT CAST( CAST([field] AS VARBINARY(120)) AS varchar(120)) for your update

What Vim command(s) can be used to quote/unquote words?

Visual mode map example to add single quotes around a selected block of text:

:vnoremap qq <Esc>`>a'<Esc>`<i'<Esc>

Quickly reading very large tables as dataframes

A minor additional points worth mentioning. If you have a very large file you can on the fly calculate the number of rows (if no header) using (where bedGraph is the name of your file in your working directory):

>numRow=as.integer(system(paste("wc -l", bedGraph, "| sed 's/[^0-9.]*\\([0-9.]*\\).*/\\1/'"), intern=T))

You can then use that either in read.csv , read.table ...

>system.time((BG=read.table(bedGraph, nrows=numRow, col.names=c('chr', 'start', 'end', 'score'),colClasses=c('character', rep('integer',3)))))
   user  system elapsed 
 25.877   0.887  26.752 
>object.size(BG)
203949432 bytes

How do I download and save a file locally on iOS using objective C?

I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:

NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
  NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString  *documentsDirectory = [paths objectAtIndex:0];  

  NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
  [urlData writeToFile:filePath atomically:YES];
}

Bootstrap with jQuery Validation Plugin

I used this for radio's:

    if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
        error.appendTo(element.parent().parent());
    }
    else if (element.parent(".input-group").length) {
        error.insertAfter(element.parent());
    }
    else {
        error.insertAfter(element);
    }

this way the error is displayed under last radio option.

How to get video duration, dimension and size in PHP?

https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...

<?php
        require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);

        $width=$fileinfo['video']['resolution_x'];
        $height=$fileinfo['video']['resolution_y'];

        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '<pre>';print_r($fileinfo);echo '</pre>';
?>

"Cross origin requests are only supported for HTTP." error when loading a local file

I was getting this exact error when loading an HTML file on the browser that was using a json file from the local directory. In my case, I was able to solve this by creating a simple node server that allowed to server static content. I left the code for this at this other answer.

When to use CouchDB over MongoDB and vice versa

Be aware of an issue with sparse unique indexes in MongoDB. I've hit it and it is extremely cumbersome to workaround.

The problem is this - you have a field, which is unique if present and you wish to find all the objects where the field is absent. The way sparse unique indexes are implemented in Mongo is that objects where that field is missing are not in the index at all - they cannot be retrieved by a query on that field - {$exists: false} just does not work.

The only workaround I have come up with is having a special null family of values, where an empty value is translated to a special prefix (like null:) concatenated to a uuid. This is a real headache, because one has to take care of transforming to/from the empty values when writing/quering/reading. A major nuisance.

I have never used server side javascript execution in MongoDB (it is not advised anyway) and their map/reduce has awful performance when there is just one Mongo node. Because of all these reasons I am now considering to check out CouchDB, maybe it fits more to my particular scenario.

BTW, if anyone knows the link to the respective Mongo issue describing the sparse unique index problem - please share.

Javascript - remove an array item by value

As a variant

delete array[array.indexOf(item)];

If you know nothing about delete operator, DON'T use this.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

EDIT - related to 2.3.0 (2016-12-07)

NOTE: to get solution for previous version, check the history of this post

Similar topic is discussed here Equivalent of $compile in Angular 2. We need to use JitCompiler and NgModule. Read more about NgModule in Angular2 here:

In a Nutshell

There is a working plunker/example (dynamic template, dynamic component type, dynamic module,JitCompiler, ... in action)

The principal is:
1) create Template
2) find ComponentFactory in cache - go to 7)
3) - create Component
4) - create Module
5) - compile Module
6) - return (and cache for later use) ComponentFactory
7) use Target and ComponentFactory to create an Instance of dynamic Component

Here is a code snippet (more of it here) - Our custom Builder is returning just built/cached ComponentFactory and the view Target placeholder consume to create an instance of the DynamicComponent

  // here we get a TEMPLATE with dynamic content === TODO
  var template = this.templateBuilder.prepareTemplate(this.entity, useTextarea);

  // here we get Factory (just compiled or from cache)
  this.typeBuilder
      .createComponentFactory(template)
      .then((factory: ComponentFactory<IHaveDynamicData>) =>
    {
        // Target will instantiate and inject component (we'll keep reference to it)
        this.componentRef = this
            .dynamicComponentTarget
            .createComponent(factory);

        // let's inject @Inputs to component instance
        let component = this.componentRef.instance;

        component.entity = this.entity;
        //...
    });

This is it - in nutshell it. To get more details.. read below

.

TL&DR

Observe a plunker and come back to read details in case some snippet requires more explanation

.

Detailed explanation - Angular2 RC6++ & runtime components

Below description of this scenario, we will

  1. create a module PartsModule:NgModule (holder of small pieces)
  2. create another module DynamicModule:NgModule, which will contain our dynamic component (and reference PartsModule dynamically)
  3. create dynamic Template (simple approach)
  4. create new Component type (only if template has changed)
  5. create new RuntimeModule:NgModule. This module will contain the previously created Component type
  6. call JitCompiler.compileModuleAndAllComponentsAsync(runtimeModule) to get ComponentFactory
  7. create an Instance of the DynamicComponent - job of the View Target placeholder and ComponentFactory
  8. assign @Inputs to new instance (switch from INPUT to TEXTAREA editing), consume @Outputs

NgModule

We need an NgModules.

While I would like to show a very simple example, in this case, I would need three modules (in fact 4 - but I do not count the AppModule). Please, take this rather than a simple snippet as a basis for a really solid dynamic component generator.

There will be one module for all small components, e.g. string-editor, text-editor (date-editor, number-editor...)

@NgModule({
  imports:      [ 
      CommonModule,
      FormsModule
  ],
  declarations: [
      DYNAMIC_DIRECTIVES
  ],
  exports: [
      DYNAMIC_DIRECTIVES,
      CommonModule,
      FormsModule
  ]
})
export class PartsModule { }

Where DYNAMIC_DIRECTIVES are extensible and are intended to hold all small parts used for our dynamic Component template/type. Check app/parts/parts.module.ts

The second will be module for our Dynamic stuff handling. It will contain hosting components and some providers.. which will be singletons. Therefor we will publish them standard way - with forRoot()

import { DynamicDetail }          from './detail.view';
import { DynamicTypeBuilder }     from './type.builder';
import { DynamicTemplateBuilder } from './template.builder';

@NgModule({
  imports:      [ PartsModule ],
  declarations: [ DynamicDetail ],
  exports:      [ DynamicDetail],
})

export class DynamicModule {

    static forRoot()
    {
        return {
            ngModule: DynamicModule,
            providers: [ // singletons accross the whole app
              DynamicTemplateBuilder,
              DynamicTypeBuilder
            ], 
        };
    }
}

Check the usage of the forRoot() in the AppModule

Finally, we will need an adhoc, runtime module.. but that will be created later, as a part of DynamicTypeBuilder job.

The forth module, application module, is the one who keeps declares compiler providers:

...
import { COMPILER_PROVIDERS } from '@angular/compiler';    
import { AppComponent }   from './app.component';
import { DynamicModule }    from './dynamic/dynamic.module';

@NgModule({
  imports:      [ 
    BrowserModule,
    DynamicModule.forRoot() // singletons
  ],
  declarations: [ AppComponent],
  providers: [
    COMPILER_PROVIDERS // this is an app singleton declaration
  ],

Read (do read) much more about NgModule there:

A template builder

In our example we will process detail of this kind of entity

entity = { 
    code: "ABC123",
    description: "A description of this Entity" 
};

To create a template, in this plunker we use this simple/naive builder.

The real solution, a real template builder, is the place where your application can do a lot

// plunker - app/dynamic/template.builder.ts
import {Injectable} from "@angular/core";

@Injectable()
export class DynamicTemplateBuilder {

    public prepareTemplate(entity: any, useTextarea: boolean){
      
      let properties = Object.keys(entity);
      let template = "<form >";
      let editorName = useTextarea 
        ? "text-editor"
        : "string-editor";
        
      properties.forEach((propertyName) =>{
        template += `
          <${editorName}
              [propertyName]="'${propertyName}'"
              [entity]="entity"
          ></${editorName}>`;
      });
  
      return template + "</form>";
    }
}

A trick here is - it builds a template which uses some set of known properties, e.g. entity. Such property(-ies) must be part of dynamic component, which we will create next.

To make it a bit more easier, we can use an interface to define properties, which our Template builder can use. This will be implemented by our dynamic Component type.

export interface IHaveDynamicData { 
    public entity: any;
    ...
}

A ComponentFactory builder

Very important thing here is to keep in mind:

our component type, build with our DynamicTypeBuilder, could differ - but only by its template (created above). Components' properties (inputs, outputs or some protected) are still same. If we need different properties, we should define different combination of Template and Type Builder

So, we are touching the core of our solution. The Builder, will 1) create ComponentType 2) create its NgModule 3) compile ComponentFactory 4) cache it for later reuse.

An dependency we need to receive:

// plunker - app/dynamic/type.builder.ts
import { JitCompiler } from '@angular/compiler';
    
@Injectable()
export class DynamicTypeBuilder {

  // wee need Dynamic component builder
  constructor(
    protected compiler: JitCompiler
  ) {}

And here is a snippet how to get a ComponentFactory:

// plunker - app/dynamic/type.builder.ts
// this object is singleton - so we can use this as a cache
private _cacheOfFactories:
     {[templateKey: string]: ComponentFactory<IHaveDynamicData>} = {};
  
public createComponentFactory(template: string)
    : Promise<ComponentFactory<IHaveDynamicData>> {    
    let factory = this._cacheOfFactories[template];

    if (factory) {
        console.log("Module and Type are returned from cache")
       
        return new Promise((resolve) => {
            resolve(factory);
        });
    }
    
    // unknown template ... let's create a Type for it
    let type   = this.createNewComponent(template);
    let module = this.createComponentModule(type);
    
    return new Promise((resolve) => {
        this.compiler
            .compileModuleAndAllComponentsAsync(module)
            .then((moduleWithFactories) =>
            {
                factory = _.find(moduleWithFactories.componentFactories
                                , { componentType: type });

                this._cacheOfFactories[template] = factory;

                resolve(factory);
            });
    });
}

Above we create and cache both Component and Module. Because if the template (in fact the real dynamic part of that all) is the same.. we can reuse

And here are two methods, which represent the really cool way how to create a decorated classes/types in runtime. Not only @Component but also the @NgModule

protected createNewComponent (tmpl:string) {
  @Component({
      selector: 'dynamic-component',
      template: tmpl,
  })
  class CustomDynamicComponent  implements IHaveDynamicData {
      @Input()  public entity: any;
  };
  // a component for this particular template
  return CustomDynamicComponent;
}
protected createComponentModule (componentType: any) {
  @NgModule({
    imports: [
      PartsModule, // there are 'text-editor', 'string-editor'...
    ],
    declarations: [
      componentType
    ],
  })
  class RuntimeComponentModule
  {
  }
  // a module for just this Type
  return RuntimeComponentModule;
}

Important:

our component dynamic types differ, but just by template. So we use that fact to cache them. This is really very important. Angular2 will also cache these.. by the type. And if we would recreate for the same template strings new types... we will start to generate memory leaks.

ComponentFactory used by hosting component

Final piece is a component, which hosts the target for our dynamic component, e.g. <div #dynamicContentPlaceHolder></div>. We get a reference to it and use ComponentFactory to create a component. That is in a nutshell, and here are all the pieces of that component (if needed, open plunker here)

Let's firstly summarize import statements:

import {Component, ComponentRef,ViewChild,ViewContainerRef}   from '@angular/core';
import {AfterViewInit,OnInit,OnDestroy,OnChanges,SimpleChange} from '@angular/core';

import { IHaveDynamicData, DynamicTypeBuilder } from './type.builder';
import { DynamicTemplateBuilder }               from './template.builder';

@Component({
  selector: 'dynamic-detail',
  template: `
<div>
  check/uncheck to use INPUT vs TEXTAREA:
  <input type="checkbox" #val (click)="refreshContent(val.checked)" /><hr />
  <div #dynamicContentPlaceHolder></div>  <hr />
  entity: <pre>{{entity | json}}</pre>
</div>
`,
})
export class DynamicDetail implements AfterViewInit, OnChanges, OnDestroy, OnInit
{ 
    // wee need Dynamic component builder
    constructor(
        protected typeBuilder: DynamicTypeBuilder,
        protected templateBuilder: DynamicTemplateBuilder
    ) {}
    ...

We just receive, template and component builders. Next are properties which are needed for our example (more in comments)

// reference for a <div> with #dynamicContentPlaceHolder
@ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef}) 
protected dynamicComponentTarget: ViewContainerRef;
// this will be reference to dynamic content - to be able to destroy it
protected componentRef: ComponentRef<IHaveDynamicData>;

// until ngAfterViewInit, we cannot start (firstly) to process dynamic stuff
protected wasViewInitialized = false;

// example entity ... to be recieved from other app parts
// this is kind of candiate for @Input
protected entity = { 
    code: "ABC123",
    description: "A description of this Entity" 
  };

In this simple scenario, our hosting component does not have any @Input. So it does not have to react to changes. But despite of that fact (and to be ready for coming changes) - we need to introduce some flag if the component was already (firstly) initiated. And only then we can start the magic.

Finally we will use our component builder, and its just compiled/cached ComponentFacotry. Our Target placeholder will be asked to instantiate the Component with that factory.

protected refreshContent(useTextarea: boolean = false){
  
  if (this.componentRef) {
      this.componentRef.destroy();
  }
  
  // here we get a TEMPLATE with dynamic content === TODO
  var template = this.templateBuilder.prepareTemplate(this.entity, useTextarea);

  // here we get Factory (just compiled or from cache)
  this.typeBuilder
      .createComponentFactory(template)
      .then((factory: ComponentFactory<IHaveDynamicData>) =>
    {
        // Target will instantiate and inject component (we'll keep reference to it)
        this.componentRef = this
            .dynamicComponentTarget
            .createComponent(factory);

        // let's inject @Inputs to component instance
        let component = this.componentRef.instance;

        component.entity = this.entity;
        //...
    });
}

small extension

Also, we need to keep a reference to compiled template.. to be able properly destroy() it, whenever we will change it.

// this is the best moment where to start to process dynamic stuff
public ngAfterViewInit(): void
{
    this.wasViewInitialized = true;
    this.refreshContent();
}
// wasViewInitialized is an IMPORTANT switch 
// when this component would have its own changing @Input()
// - then we have to wait till view is intialized - first OnChange is too soon
public ngOnChanges(changes: {[key: string]: SimpleChange}): void
{
    if (this.wasViewInitialized) {
        return;
    }
    this.refreshContent();
}

public ngOnDestroy(){
  if (this.componentRef) {
      this.componentRef.destroy();
      this.componentRef = null;
  }
}

done

That is pretty much it. Do not forget to Destroy anything what was built dynamically (ngOnDestroy). Also, be sure to cache dynamic types and modules if the only difference is their template.

Check it all in action here

to see previous versions (e.g. RC5 related) of this post, check the history

How to export and import environment variables in windows?

A PowerShell script based on @Mithrl's answer

# export_env.ps1
$Date = Get-Date
$DateStr = '{0:dd-MM-yyyy}' -f $Date

mkdir -Force $PWD\env_exports | Out-Null

regedit /e "$PWD\env_exports\user_env_variables[$DateStr].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "$PWD\env_exports\global_env_variables[$DateStr].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

Proper use of errors

Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.

EvalError --- Creates an instance representing an error that occurs regarding the global function eval().

InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".

RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.

ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference.

SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval().

TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.

URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.

JQuery Validate Dropdown list

Easiest way to get it done is by adding required into your select

Select the best option
<br/>

<select name="dd1" id="dd1" required>
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select> 

<br/><br/>?

How to join (merge) data frames (inner, outer, left, right)

I would recommend checking out Gabor Grothendieck's sqldf package, which allows you to express these operations in SQL.

library(sqldf)

## inner join
df3 <- sqldf("SELECT CustomerId, Product, State 
              FROM df1
              JOIN df2 USING(CustomerID)")

## left join (substitute 'right' for right join)
df4 <- sqldf("SELECT CustomerId, Product, State 
              FROM df1
              LEFT JOIN df2 USING(CustomerID)")

I find the SQL syntax to be simpler and more natural than its R equivalent (but this may just reflect my RDBMS bias).

See Gabor's sqldf GitHub for more information on joins.

How to get only numeric column values?

SELECT column1 FROM table WHERE column1 not like '%[0-9]%'

Removing the '^' did it for me. I'm looking at a varchar field and when I included the ^ it excluded all of my non-numerics which is exactly what I didn't want. So, by removing ^ I only got non-numeric values back.

Round float to x decimals?

I coded a function (used in Django project for DecimalField) but it can be used in Python project :

This code :

  • Manage integers digits to avoid too high number
  • Manage decimals digits to avoid too low number
  • Manage signed and unsigned numbers

Code with tests :

def convert_decimal_to_right(value, max_digits, decimal_places, signed=True):

    integer_digits = max_digits - decimal_places
    max_value = float((10**integer_digits)-float(float(1)/float((10**decimal_places))))

    if signed:
        min_value = max_value*-1
    else:
        min_value = 0

    if value > max_value:
        value = max_value

    if value < min_value:
        value = min_value

    return round(value, decimal_places)


value = 12.12345
nb = convert_decimal_to_right(value, 4, 2)
# nb : 12.12

value = 12.126
nb = convert_decimal_to_right(value, 4, 2)
# nb : 12.13

value = 1234.123
nb = convert_decimal_to_right(value, 4, 2)
# nb : 99.99

value = -1234.123
nb = convert_decimal_to_right(value, 4, 2)
# nb : -99.99

value = -1234.123
nb = convert_decimal_to_right(value, 4, 2, signed = False)
# nb : 0

value = 12.123
nb = convert_decimal_to_right(value, 8, 4)
# nb : 12.123

Combine GET and POST request methods in Spring

@RequestMapping(value = "/books", method = { RequestMethod.GET, 
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
     HttpServletRequest request) 
    throws ParseException {

//your code 
}

This will works for both GET and POST.

For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter

like below

public class BooksFilter{

private String parameter1;
private String parameter2;

   //getters and setters

URl should be like below

/books?parameter1=blah

Like this way u can use it for both GET and POST

How to add hamburger menu in bootstrap

To create icon you can use Glyphicon in Bootstrap:

<a href="#" class="btn btn-info btn-sm">
    <span class="glyphicon glyphicon-menu-hamburger"></span>
</a>

And then control size of icon in css:

.glyphicon-menu-hamburger {
  font-size: npx;
}

CXF: No message body writer found for class - automatically mapping non-simple resources

You can also configure CXFNonSpringJAXRSServlet (assuming JSONProvider is used):

<init-param>
  <param-name>jaxrs.providers</param-name>
  <param-value>
      org.apache.cxf.jaxrs.provider.JSONProvider
      (writeXsiType=false)
  </param-value> 
</init-param>

Getting GET "?" variable in laravel

We have similar situation right now and as of this answer, I am using laravel 5.6 release.

I will not use your example in the question but mine, because it's related though.

I have route like this:

Route::name('your.name.here')->get('/your/uri', 'YourController@someMethod');

Then in your controller method, make sure you include

use Illuminate\Http\Request;

and this should be above your controller, most likely a default, if generated using php artisan, now to get variable from the url it should look like this:

  public function someMethod(Request $request)
  {
    $foo = $request->input("start");
    $bar = $request->input("limit");

    // some codes here
  }

Regardless of the HTTP verb, the input() method may be used to retrieve user input.

https://laravel.com/docs/5.6/requests#retrieving-input

Hope this help.

how to find array size in angularjs

You can find the number of members in a Javascript array by using its length property:

var number = $scope.names.length;

Docs - Array.prototype.length

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

In Python, how to check if a string only contains certain characters?

EDIT: Changed the regular expression to exclude A-Z

Regular expression solution is the fastest pure python solution so far

reg=re.compile('^[a-z0-9\.]+$')
>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')
True
>>> timeit.Timer("reg.match('jsdlfjdsf12324..3432jsdflsdf')", "import re; reg=re.compile('^[a-z0-9\.]+$')").timeit()
0.70509696006774902

Compared to other solutions:

>>> timeit.Timer("set('jsdlfjdsf12324..3432jsdflsdf') <= allowed", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
3.2119350433349609
>>> timeit.Timer("all(c in allowed for c in 'jsdlfjdsf12324..3432jsdflsdf')", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
6.7066690921783447

If you want to allow empty strings then change it to:

reg=re.compile('^[a-z0-9\.]*$')
>>>reg.match('')
False

Under request I'm going to return the other part of the answer. But please note that the following accept A-Z range.

You can use isalnum

test_str.replace('.', '').isalnum()

>>> 'test123.3'.replace('.', '').isalnum()
True
>>> 'test123-3'.replace('.', '').isalnum()
False

EDIT Using isalnum is much more efficient than the set solution

>>> timeit.Timer("'jsdlfjdsf12324..3432jsdflsdf'.replace('.', '').isalnum()").timeit()
0.63245487213134766

EDIT2 John gave an example where the above doesn't work. I changed the solution to overcome this special case by using encode

test_str.replace('.', '').encode('ascii', 'replace').isalnum()

And it is still almost 3 times faster than the set solution

timeit.Timer("u'ABC\u0131\u0661'.encode('ascii', 'replace').replace('.','').isalnum()", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
1.5719811916351318

In my opinion using regular expressions is the best to solve this problem

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

How to enable curl in xampp?

You can add any extension (in Wamp and Xampp servers) by removing the semi-colon (;)

PHP exec() vs system() vs passthru()

They have slightly different purposes.

  • exec() is for calling a system command, and perhaps dealing with the output yourself.
  • system() is for executing a system command and immediately displaying the output - presumably text.
  • passthru() is for executing a system command which you wish the raw return from - presumably something binary.

Regardless, I suggest you not use any of them. They all produce highly unportable code.

Java math function to convert positive int to negative and negative to positive?

original *= -1;

Simple line of code, original is any int you want it to be.

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

How to set HTML5 required attribute in Javascript?

Short version

element.setAttribute("required", "");    //turns required on
element.required = true;                 //turns required on through reflected attribute
jQuery(element).attr('required', '');    //turns required on
$("#elementId").attr('required', '');    //turns required on

element.removeAttribute("required");     //turns required off
element.required = false;                //turns required off through reflected attribute
jQuery(element).removeAttr('required');  //turns required off
$("#elementId").removeAttr('required');  //turns required off

if (edName.hasAttribute("required")) { }  //check if required
if (edName.required) { }                 //check if required using reflected attribute

Long Version

Once T.J. Crowder managed to point out reflected properties, i learned that following syntax is wrong:

element.attributes["name"] = value; //bad! Overwrites the HtmlAttribute object
element.attributes.name = value;    //bad! Overwrites the HtmlAttribute object
value = element.attributes.name;    //bad! Returns the HtmlAttribute object, not its value
value = element.attributes["name"]; //bad! Returns the HtmlAttribute object, not its value

You must go through element.getAttribute and element.setAttribute:

element.getAttribute("foo");         //correct
element.setAttribute("foo", "test"); //correct

This is because the attribute actually contains a special HtmlAttribute object:

element.attributes["foo"];           //returns HtmlAttribute object, not the value of the attribute
element.attributes.foo;              //returns HtmlAttribute object, not the value of the attribute

By setting an attribute value to "true", you are mistakenly setting it to a String object, rather than the HtmlAttribute object it requires:

element.attributes["foo"] = "true";  //error because "true" is not a HtmlAttribute object
element.setAttribute("foo", "true"); //error because "true" is not an HtmlAttribute object

Conceptually the correct idea (expressed in a typed language), is:

HtmlAttribute attribute = new HtmlAttribute();
attribute.value = "";
element.attributes["required"] = attribute;

This is why:

  • getAttribute(name)
  • setAttribute(name, value)

exist. They do the work on assigning the value to the HtmlAttribute object inside.

On top of this, some attribute are reflected. This means that you can access them more nicely from Javascript:

//Set the required attribute
//element.setAttribute("required", ""); 
element.required = true;

//Check the attribute
//if (element.getAttribute("required")) {...}
if (element.required) {...}

//Remove the required attribute
//element.removeAttribute("required");
element.required = false;

What you don't want to do is mistakenly use the .attributes collection:

element.attributes.required = true;     //WRONG!
if (element.attributes.required) {...}  //WRONG!
element.attributes.required = false;    //WRONG!

Testing Cases

This led to testing around the use of a required attribute, comparing the values returned through the attribute, and the reflected property

document.getElementById("name").required;
document.getElementById("name").getAttribute("required");

with results:

HTML                         .required        .getAttribute("required")
==========================   ===============  =========================
<input>                      false (Boolean)  null (Object)
<input required>             true  (Boolean)  "" (String)
<input required="">          true  (Boolean)  "" (String)
<input required="required">  true  (Boolean)  "required" (String)
<input required="true">      true  (Boolean)  "true" (String)
<input required="false">     true  (Boolean)  "false" (String)
<input required="0">         true  (Boolean)  "0" (String)

Trying to access the .attributes collection directly is wrong. It returns the object that represents the DOM attribute:

edName.attributes["required"] => [object Attr]
edName.attributes.required    => [object Attr]

This explains why you should never talk to the .attributes collect directly. You're not manipulating the values of the attributes, but the objects that represent the attributes themselves.

How to set required?

What's the correct way to set required on an attribute? You have two choices, either the reflected property, or through correctly setting the attribute:

element.setAttribute("required", "");         //Correct
edName.required = true;                       //Correct

Strictly speaking, any other value will "set" the attribute. But the definition of Boolean attributes dictate that it should only be set to the empty string "" to indicate true. The following methods all work to set the required Boolean attribute,

but do not use them:

element.setAttribute("required", "required"); //valid, but not preferred
element.setAttribute("required", "foo");      //works, but silly
element.setAttribute("required", "true");     //Works, but don't do it, because:
element.setAttribute("required", "false");    //also sets required boolean to true
element.setAttribute("required", false);      //also sets required boolean to true
element.setAttribute("required", 0);          //also sets required boolean to true

We already learned that trying to set the attribute directly is wrong:

edName.attributes["required"] = true;       //wrong
edName.attributes["required"] = "";         //wrong
edName.attributes["required"] = "required"; //wrong
edName.attributes.required = true;          //wrong
edName.attributes.required = "";            //wrong
edName.attributes.required = "required";    //wrong

How to clear required?

The trick when trying to remove the required attribute is that it's easy to accidentally turn it on:

edName.removeAttribute("required");     //Correct
edName.required = false;                //Correct

With the invalid ways:

edName.setAttribute("required", null);    //WRONG! Actually turns required on!
edName.setAttribute("required", "");      //WRONG! Actually turns required on!
edName.setAttribute("required", "false"); //WRONG! Actually turns required on!
edName.setAttribute("required", false);   //WRONG! Actually turns required on!
edName.setAttribute("required", 0);       //WRONG! Actually turns required on!

When using the reflected .required property, you can also use any "falsey" values to turn it off, and truthy values to turn it on. But just stick to true and false for clarity.

How to check for required?

Check for the presence of the attribute through the .hasAttribute("required") method:

if (edName.hasAttribute("required"))
{
}

You can also check it through the Boolean reflected .required property:

if (edName.required)
{
}

How can I validate a string to only allow alphanumeric characters in it?

I needed to check for A-Z, a-z, 0-9; without a regex (even though the OP asks for regex).

Blending various answers and comments here, and discussion from https://stackoverflow.com/a/9975693/292060, this tests for letter or digit, avoiding other language letters, and avoiding other numbers such as fraction characters.

if (!String.IsNullOrEmpty(testString)
    && testString.All(c => Char.IsLetterOrDigit(c) && (c < 128)))
{
    // Alphanumeric.
}

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

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

Q: What is happening here?

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

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

If input field is empty, disable submit button

For those that use coffeescript, I've put the code we use globally to disable the submit buttons on our most widely used form. An adaption of Adil's answer above.

$('#new_post button').prop 'disabled', true
$('#new_post #post_message').keyup ->
    $('#new_post button').prop 'disabled', if @value == '' then true else false
    return

What is the best IDE for C Development / Why use Emacs over an IDE?

Netbeans has great C and C++ support. Some people complain that it's bloated and slow, but I've been using it almost exclusively for personal projects and love it. The code assistance feature is one of the best I've seen.

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
{
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
    {
        this.Name = name;
        this.Artist = artist;
        this.Year = year;
    }
}

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994
};

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 
}

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"
};

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

how to call a onclick function in <a> tag?

Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.

Example:

function newwin() {              
 myWindow=window.open('lead_data.php?leadid=1','myWin','width=400,height=650')
}

See how to call it from your anchor tag

<a onclick='newwin()'>Anchor</a>

Update

Visit this jsbin

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

May be this will help you a lot to understand your problem.

Howto? Parameters and LIKE statement SQL

Sometimes the symbol used as a placeholder % is not the same if you execute a query from VB as when you execute it from MS SQL / Access. Try changing your placeholder symbol from % to *. That might work.
However, if you debug and want to copy your SQL string directly in MS SQL or Access to test it, you may have to change the symbol back to % in MS SQL or Access in order to actually return values.

Hope this helps

String comparison in bash. [[: not found

How you are running your script? If you did with

$ sh myscript

you should try:

$ bash myscript

or, if the script is executable:

$ ./myscript

sh and bash are two different shells. While in the first case you are passing your script as an argument to the sh interpreter, in the second case you decide on the very first line which interpreter will be used.

Importing CommonCrypto in a Swift framework

This answer discusses how to make it work inside a framework, and with Cocoapods and Carthage

modulemap approach

I use modulemap in my wrapper around CommonCrypto https://github.com/onmyway133/arcane, https://github.com/onmyway133/Reindeer

For those getting header not found, please take a look https://github.com/onmyway133/Arcane/issues/4 or run xcode-select --install

  • Make a folder CCommonCrypto containing module.modulemap

      module CCommonCrypto {
        header "/usr/include/CommonCrypto/CommonCrypto.h"
        export *
      }
    
  • Go to Built Settings -> Import Paths

      ${SRCROOT}/Sources/CCommonCrypto
    

Cocoapods with modulemap approach

public header approach

Cocoapods with public header approach

Interesting related posts

What is the difference between Builder Design pattern and Factory Design pattern?

First some general things to follow my argumentation:

The main challenge in designing big software systems is that they have to be flexible and uncomplicated to change. For this reason, there are some metrics like coupling and cohesion. To achieve systems that can be easily altered or extended in its functionality without the need to redesign the whole system from scratch, you can follow the design principles (like SOLID, etc.). After a while some developer recognized that if they follow those principles there are some similar solutions that worked well to similar problems. Those standard solutions turned out to be the design patterns.

So the design patterns are to support you to follow the general design principles in order to achieve loosely coupled systems with high cohesion.

Answering the question:

By asking the difference between two patterns you have to ask yourself what pattern makes your system in which way more flexible. Each pattern has its own purpose to organize dependencies between classes in your system.

The Abstract Factory Pattern: GoF: “Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”

What does this mean: By providing an interface like this the call to the constructor of each of the family’s product is encapsulated in the factory class. And because this is the only place in your whole system where those constructors are called you can alter your system by implementing a new factory class. If you exchange the representation of the factory through another, you can exchange a whole set of products without touching the majority of your code.

The Builder Pattern: GoF: “Separate the construction of a complex object from its representation so that the same construction process can create different representations.”

What does this mean: You encapsulate the process of construction in another class, called the director (GoF). This director contains the algorithm of creating new instances of the product (e.g. compose a complex product out of other parts). To create the integral parts of the whole product the director uses a builder. By exchanging the builder in the director you can use the same algorithm to create the product, but change the representations of single parts (and so the representation of the product). To extend or modify your system in the representation of the product, all you need to do is to implement a new builder class.

So in short: The Abstract Factory Pattern’s purpose is to exchange a set of products which are made to be used together. The Builder Pattern’s purpose is to encapsulate the abstract algorithm of creating a product to reuse it for different representations of the product.

In my opinion you can’t say that the Abstract Factory Pattern is the big brother of the Builder Pattern. YES, they are both creational patterns, but the main intent of the patterns is entirely different.

How can I delete all cookies with JavaScript?

This is a function we are using in our application and it is working fine.

delete cookie: No argument method

function clearListCookies()
{   
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++)
    {   
        var spcook =  cookies[i].split("=");
        deleteCookie(spcook[0]);
    }
    function deleteCookie(cookiename)
    {
        var d = new Date();
        d.setDate(d.getDate() - 1);
        var expires = ";expires="+d;
        var name=cookiename;
        //alert(name);
        var value="";
        document.cookie = name + "=" + value + expires + "; path=/acc/html";                    
    }
    window.location = ""; // TO REFRESH THE PAGE
}

Edit: This will delete the cookie by setting it to yesterday's date.

Hibernate: Automatically creating/updating the db tables based on entity classes

In support to @thorinkor's answer I would extend my answer to use not only @Table (name = "table_name") annotation for entity, but also every child variable of entity class should be annotated with @Column(name = "col_name"). This results into seamless updation to the table on the go.

For those who are looking for a Java class based hibernate config, the rule applies in java based configurations also(NewHibernateUtil). Hope it helps someone else.

How do I filter query objects by date range in Django?

You can get around the "impedance mismatch" caused by the lack of precision in the DateTimeField/date object comparison -- that can occur if using range -- by using a datetime.timedelta to add a day to last date in the range. This works like:

start = date(2012, 12, 11)
end = date(2012, 12, 18)
new_end = end + datetime.timedelta(days=1)

ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])

As discussed previously, without doing something like this, records are ignored on the last day.

Edited to avoid the use of datetime.combine -- seems more logical to stick with date instances when comparing against a DateTimeField, instead of messing about with throwaway (and confusing) datetime objects. See further explanation in comments below.

Parsing JSON in Java without knowing JSON format

Would you be satisfied with a Map from Jackson?

ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.readValue(jsonString, new TypeReference<HashMap<String,Object>>(){});

Or maybe a JsonNode?

JsonNode jsonNode = objectMapper.readTree(String jsonString) 

Static way to get 'Context' in Android?

Kotlin

open class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        mInstance = this
    }

    companion object {
        lateinit var mInstance: MyApp
        fun getContext(): Context? {
            return mInstance.applicationContext
        }
    }
}

and get Context like

MyApp.mInstance

or

MyApp.getContext()

How to read lines of a file in Ruby

Your first file has Mac Classic line endings (that’s "\r" instead of the usual "\n"). Open it with

File.open('foo').each(sep="\r") do |line|

to specify the line endings.