Programs & Examples On #Appdomain

An application domain is an isolated environment in which Microsoft .NET assemblies can be sandboxed, granted specific permissions or PermissionSets and executed.

How to Load an Assembly to AppDomain with all references recursively?

Once you pass the assembly instance back to the caller domain, the caller domain will try to load it! This is why you get the exception. This happens in your last line of code:

domain.Load(AssemblyName.GetAssemblyName(path));

Thus, whatever you want to do with the assembly, should be done in a proxy class - a class which inherit MarshalByRefObject.

Take in count that the caller domain and the new created domain should both have access to the proxy class assembly. If your issue is not too complicated, consider leaving the ApplicationBase folder unchanged, so it will be same as the caller domain folder (the new domain will only load Assemblies it needs).

In simple code:

public void DoStuffInOtherDomain()
{
    const string assemblyPath = @"[AsmPath]";
    var newDomain = AppDomain.CreateDomain("newDomain");
    var asmLoaderProxy = (ProxyDomain)newDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(ProxyDomain).FullName);

    asmLoaderProxy.GetAssembly(assemblyPath);
}

class ProxyDomain : MarshalByRefObject
{
    public void GetAssembly(string AssemblyPath)
    {
        try
        {
            Assembly.LoadFrom(AssemblyPath);
            //If you want to do anything further to that assembly, you need to do it here.
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException(ex.Message, ex);
        }
    }
}

If you do need to load the assemblies from a folder which is different than you current app domain folder, create the new app domain with specific dlls search path folder.

For example, the app domain creation line from the above code should be replaced with:

var dllsSearchPath = @"[dlls search path for new app domain]";
AppDomain newDomain = AppDomain.CreateDomain("newDomain", new Evidence(), dllsSearchPath, "", true);

This way, all the dlls will automaically be resolved from dllsSearchPath.

How can I know if Object is String type object?

Guard your cast with instanceof

String myString;
if (object instanceof String) {
  myString = (String) object;
}

Length of the String without using length() method

Hidden length() usage:

    String s = "foobar";

    int i = 0;
    for(char c: s.toCharArray())
    {
        i++;
    }

CSS Selector for <input type="?"

Yes. IE7+ supports attribute selectors:

input[type=radio]
input[type^=ra]
input[type*=d]
input[type$=io]

Element input with attribute type which contains a value that is equal to, begins with, contains or ends with a certain value.

Other safe (IE7+) selectors are:

  • Parent > child that has: p > span { font-weight: bold; }
  • Preceded by ~ element which is: span ~ span { color: blue; }

Which for <p><span/><span/></p> would effectively give you:

<p>
    <span style="font-weight: bold;">
    <span style="font-weight: bold; color: blue;">
</p>

Further reading: Browser CSS compatibility on quirksmode.com

I'm surprised that everyone else thinks it can't be done. CSS attribute selectors have been here for some time already. I guess it's time we clean up our .css files.

Extract time from moment js object

If you read the docs (http://momentjs.com/docs/#/displaying/) you can find this format:

moment("2015-01-16T12:00:00").format("hh:mm:ss a")

See JS Fiddle http://jsfiddle.net/Bjolja/6mn32xhu/

How to get the size of the current screen in WPF?

Take the time to scan through the SystemParameters members.

  • VirtualScreenWidth
  • VirtualScreenHeight

These even take into account the relative positions of the screens.

Only tested with two monitors.

What is the best way to insert source code examples into a Microsoft Word document?

I absolutely hate and despise working for free for Microsoft, given how after all those billions of dollars they STILL do not to have proper guides about stuff like this with screenshots on their damn website.

Anyways, here is a quick guide in Word 2010, using Notepad++ for syntax coloring, and a TextBox which can be captioned:

  1. Choose Insert / Text Box / Simple Text Box
    01word
  2. A default text box is inserted
    02word
  3. Switch to NPP, choose the language for syntax coloring of your code, go to Plugins / NPPExport / Copy RTF to clipboard
    03npp
  4. Switch back to word, and paste into the text box - it may be too small ...
    04word
  5. ... so you may have to change its size
    05word
  6. Having selected the text box, right-click on it, then choose Insert Caption ...
    06word
  7. In the Caption menu, if you don't have one already, click New Label, and set the new label to "Code", click OK ...
    07word
  8. ... then in the Caption dialog, switch the label to Code, and hit OK
    08word
  9. Finally, type your caption in the newly created caption box
    09word

Angular2 change detection: ngOnChanges not firing for nested object

I had to create a hack for it -

I created a Boolean Input variable and toggled it whenever array changed, which triggered change detection in the child component, hence achieving the purpose

How to print / echo environment variables?

The syntax

variable=value command

is often used to set an environment variables for a specific process. However, you must understand which process gets what variable and who interprets it. As an example, using two shells:

a=5
# variable expansion by the current shell:
a=3 bash -c "echo $a"
# variable expansion by the second shell:
a=3 bash -c 'echo $a'

The result will be 5 for the first echo and 3 for the second.

Read .mat files in Python

First save the .mat file as:

save('test.mat', '-v7')

After that, in Python, use the usual loadmat function:

import scipy.io as sio
test = sio.loadmat('test.mat')

C# DLL config file

you can use this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace GClass1
{
[Guid("D6F88E95-8A27-4ae6-B6DE-0542A0FC7039")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface _GesGasConnect
{
    [DispId(1)]
    int SetClass1Ver(string version);


}

[Guid("13FE32AD-4BF8-495f-AB4D-6C61BD463EA4")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("InterfacesSMS.Setting")]
public class Class1 : _Class1
{
    public Class1() { }


    public int SetClass1(string version)
    {
        return (DateTime.Today.Day);
    }
}
}

What is the best way to concatenate two vectors?

All the solutions are correct, but I found it easier just write a function to implement this. like this:

template <class T1, class T2>
void ContainerInsert(T1 t1, T2 t2)
{
    t1->insert(t1->end(), t2->begin(), t2->end());
}

That way you can avoid the temporary placement like this:

ContainerInsert(vec, GetSomeVector());

How to add a touch event to a UIView?

Swift 3 & Swift 4

import UIKit

extension UIView {
  func addTapGesture(tapNumber: Int, target: Any, action: Selector) {
    let tap = UITapGestureRecognizer(target: target, action: action)
    tap.numberOfTapsRequired = tapNumber
    addGestureRecognizer(tap)
    isUserInteractionEnabled = true
  }
}

Use

yourView.addTapGesture(tapNumber: 1, target: self, action: #selector(yourMethod))

Vue Js - Loop via v-for X times (in a range)

In 2.2.0+, when using v-for with a component, a key is now required.

<div v-for="item in items" :key="item.id">

Source

Android list view inside a scroll view

You should never use a ScrollView with a ListView, because ListView takes care of its own vertical scrolling. Most importantly, doing this defeats all of the important optimizations in ListView for dealing with large lists, since it effectively forces the ListView to display its entire list of items to fill up the infinite container supplied by ScrollView.

http://developer.android.com/reference/android/widget/ScrollView.html

Android EditText Hint

I don't know whether a direct way of doing this is available or not, but you surely there is a workaround via code: listen for onFocus event of EditText, and as soon it gains focus, set the hint to be nothing with something like editText.setHint(""):

This may not be exactly what you have to do, but it may be something like this-

myEditText.setOnFocusListener(new OnFocusListener(){
  public void onFocus(){
    myEditText.setHint("");
  }
});

How do you add swap to an EC2 instance?

We can add swap space in any server

create a file using dd command

 #dd if=/dev/zero of=/swapfile bs=1M count=2048
                    or
 #dd if=/dev/zero of=/swapfile bs=1024M count=2

bs is blocksize and count refers to the size in MB or GB

we can use vice versa

After creation change the permission of file :

 #chmod 600 /swapfile 

Then makeswap the file :

 #mkswap /swapfile 

Then enable the swap file with swapon command :

 #swapon  /swapfile 

Check with free command whether swap is enabled or not :

 #free -h
 #swapon -s

How to display a range input slider vertically

First, set height greater than width. In theory, this is all you should need. The HTML5 Spec suggests as much:

... the UA determined the orientation of the control from the ratio of the style-sheet-specified height and width properties.

Opera had it implemented this way, but Opera is now using WebKit Blink. As of today, no browser implements a vertical slider based solely on height being greater than width.

Regardless, setting height greater than width is needed to get the layout right between browsers. Applying left and right padding will also help with layout and positioning.

For Chrome, use -webkit-appearance: slider-vertical.

For IE, use writing-mode: bt-lr.

For Firefox, add an orient="vertical" attribute to the html. Pity that they did it this way. Visual styles should be controlled via CSS, not HTML.

_x000D_
_x000D_
input[type=range][orient=vertical]
{
    writing-mode: bt-lr; /* IE */
    -webkit-appearance: slider-vertical; /* WebKit */
    width: 8px;
    height: 175px;
    padding: 0 5px;
}
_x000D_
<input type="range" orient="vertical" />
_x000D_
_x000D_
_x000D_


Disclaimers:

This solution is based on current browser implementations of as yet undefined or unfinalized CSS properties. If you intend to use it in your code, be prepared to make code adjustments as newer browser versions are released and w3c recommendations are completed.

MDN contains an explicit warning against using -webkit-appearance on the web:

Do not use this property on Web sites: not only is it non-standard, but its behavior change from one browser to another. Even the keyword none has not the same behavior on each form element on different browsers, and some doesn't support it at all.

The caption for the vertical slider demo in the IE documentation erroneously indicates that setting height greater than width will display a range slider vertically, but this does not work. In the code section, it plainly does not set height or width, and instead uses writing-mode. The writing-mode property, as implemented by IE, is very robust. Sadly, the values defined in the current working draft of the spec as of this writing, are much more limited. Should future versions of IE drop support of bt-lr in favor of the currently proposed vertical-lr (which would be the equivalent of tb-lr), the slider would display upside down. Most likely, future versions would extend the writing-mode to accept new values rather than drop support for existing values. But, it's good to know what you are dealing with.

VIM Disable Automatic Newline At End Of File

I've implemented Blixtor's suggestions with Perl and Python post-processing, either running inside Vim (if it is compiled with such language support), or via an external Perl script. It's available as the PreserveNoEOL plugin on vim.org.

getResourceAsStream returns null

Don't use absolute paths, make them relative to the 'resources' directory in your project. Quick and dirty code that displays the contents of MyTest.txt from the directory 'resources'.

@Test
public void testDefaultResource() {
    // can we see default resources
    BufferedInputStream result = (BufferedInputStream) 
         Config.class.getClassLoader().getResourceAsStream("MyTest.txt");
    byte [] b = new byte[256];
    int val = 0;
    String txt = null;
    do {
        try {
            val = result.read(b);
            if (val > 0) {
                txt += new String(b, 0, val);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } 
    } while (val > -1);
    System.out.println(txt);
}

What does "publicPath" in Webpack do?

The webpack2 documentation explains this in a much cleaner way: https://webpack.js.org/guides/public-path/#use-cases

webpack has a highly useful configuration that let you specify the base path for all the assets on your application. It's called publicPath.

How do I check if a directory exists? "is_dir", "file_exists" or both?

A way to check if a path is directory can be following:

function isDirectory($path) {
    $all = @scandir($path);
    return $all !== false;
}

NOTE: It will return false for non-existant path too, but works perfectly for UNIX/Windows

How to center Font Awesome icons horizontally?

i solved my problem with this:

<div class="d-flex justify-content-center"></div>

im using bootstrap with font awesome icons.

if you want to know more acess the link below: https://getbootstrap.com/docs/4.0/utilities/flex/

Most efficient way to find smallest of 3 numbers Java?

Write a method minimum3 that returns the smallest of three floating-point numbers. Use the Math.min method to implement minimum3. Incorporate the method into an application that reads three values from the user, determines the smallest value and displays the result.

SQL using sp_HelpText to view a stored procedure on a linked server

Instead of invoking the sp_helptext locally with a remote argument, invoke it remotely with a local argument:

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText 'storedProcName'

How do I 'svn add' all unversioned files to SVN?

Use:

svn st | grep ? | cut -d? -f2 | xargs svn add

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

Inline comments for Bash?

How about storing it in a variable?

#extraargs=-F
ls -l $extraargs -a /etc

split string only on first instance of specified character

You can use the regular expression like:

var arr = element.split(/_(.*)/)
You can use the second parameter which specifies the limit of the split. i.e: var field = element.split('_', 1)[1];

Get width in pixels from element with style set with %?

This jQuery worked for me:

$("#banner-contenedor").css('width');

This will get you the computed width

http://api.jquery.com/css/

Send Post Request with params using Retrofit

The good way in my opinion is to send it in the POST Body this means you'll have a create a new POJO but some might like this implementation the most.

public interface APIInterface {
    @POST("/GetDetailWithMonthWithCode")
    List<LandingPageReport> getLandingPageReport(@Body Report report);
}

Then make your POJO with a constructor, getters and setters.

public static class Report {
    private String code;
    private String monthact;

    public Report(String code, String monthact) {
        this.code = code;
        this.monthact = monthact;  
    }

    // Getters and Setters...
}

And just call it the normal way.

Call<List<Report>> request = apiInterface
    .createRetrofitAPIInterface()
    .getLandingPageReport(new Report(code, monthact));

How to get the width of a react element

This is basically Marco Antônio's answer for a React custom hook, but modified to set the dimensions initially and not only after a resize.

export const useContainerDimensions = myRef => {
  const getDimensions = () => ({
    width: myRef.current.offsetWidth,
    height: myRef.current.offsetHeight
  })

  const [dimensions, setDimensions] = useState({ width: 0, height: 0 })

  useEffect(() => {
    const handleResize = () => {
      setDimensions(getDimensions())
    }

    if (myRef.current) {
      setDimensions(getDimensions())
    }

    window.addEventListener("resize", handleResize)

    return () => {
      window.removeEventListener("resize", handleResize)
    }
  }, [myRef])

  return dimensions;
};

Used in the same way:

const MyComponent = () => {
  const componentRef = useRef()
  const { width, height } = useContainerDimensions(componentRef)

  return (
    <div ref={componentRef}>
      <p>width: {width}px</p>
      <p>height: {height}px</p>
    <div/>
  )
}

Bootstrap 4 datapicker.js not included

You can use this and then you can add just a class form from bootstrap. (does not matter which version)

<div class="form-group">
 <label >Begin voorverkoop periode</label>
 <input type="date" name="bday" max="3000-12-31" 
        min="1000-01-01" class="form-control">
</div>
<div class="form-group">
 <label >Einde voorverkoop periode</label>
 <input type="date" name="bday" min="1000-01-01"
        max="3000-12-31" class="form-control">
</div>

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

The warning comes up because Tomcat scans all Jars for TLDs (Tagging Library Definitions).

Step1: To see which JARs are throwing up this warning, insert he following line to tomcat/conf/logging.properties

org.apache.jasper.servlet.TldScanner.level = FINE

Now you should be able to see warnings with a detail of which JARs are causing the intial warning

Step2 Since skipping unneeded JARs during scanning can improve startup time and JSP compilation time, we will skip un-needed JARS in the catalina.properties file. You have two options here -

  1. List all the JARs under the tomcat.util.scan.StandardJarScanFilter.jarsToSkip. But this can get cumbersome if you have a lot jars or if the jars keep changing.
  2. Alternatively, Insert tomcat.util.scan.StandardJarScanFilter.jarsToSkip=* to skip all the jars

You should now not see the above warnings and if you have a considerably large application, it should save you significant time in deploying an application.

Note: Tested in Tomcat8

Remove multiple items from a Python list in just one statement

But what if I don't know the indices of the items I want to remove?

I do not exactly understand why you do not like .remove but to get the first index corresponding to a value use .index(value):

ind=item_list.index('item')

then remove the corresponding value:

del item_list.pop[ind]

.index(value) gets the first occurrence of value, and .remove(value) removes the first occurrence of value

C# Validating input for textbox on winforms

Description

There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating event.

The Validating event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true the TextBox doesn't lose the focus.

MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order

Enter

GotFocus

Leave

Validating

Validated

LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Enter

GotFocus

LostFocus

Leave

Validating

Validated

Sample Validating Event

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    if (textBox1.Text != "something")
        e.Cancel = true;
}

Update

You can use the ErrorProvider to visualize that your TextBox is not valid. Check out Using Error Provider Control in Windows Forms and C#

More Information

Can I scale a div's height proportionally to its width using CSS?

Another great way to accomplish this is to use a transparent image with a set aspect ratio. Then set the width of the image to 100% and the height to auto. That unfortunately will push down the original content of the container. So you need to wrap the original content in another div and position it absolutely to the top of the parent div.

<div class="parent">
   <img class="aspect-ratio" src="images/aspect-ratio.png" />
   <div class="content">Content</div>
</div>

CSS

.parent {
  position: relative;
}
.aspect-ratio {
  width: 100%;
  height: auto;
}
.content {
  position: absolute;
  width: 100%;
  top: 0; left: 0;
}

Do a "git export" (like "svn export")?

I think @Aredridel's post was closest, but there's a bit more to that - so I will add this here; the thing is, in svn, if you're in a subfolder of a repo, and you do:

/media/disk/repo_svn/subdir$ svn export . /media/disk2/repo_svn_B/subdir

then svn will export all files that are under revision control (they could have also freshly Added; or Modified status) - and if you have other "junk" in that directory (and I'm not counting .svn subfolders here, but visible stuff like .o files), it will not be exported; only those files registered by the SVN repo will be exported. For me, one nice thing is that this export also includes files with local changes that have not been committed yet; and another nice thing is that the timestamps of the exported files are the same as the original ones. Or, as svn help export puts it:

  1. Exports a clean directory tree from the working copy specified by PATH1, at revision REV if it is given, otherwise at WORKING, into PATH2. ... If REV is not specified, all local changes will be preserved. Files not under version control will not be copied.

To realize that git will not preserve the timestamps, compare the output of these commands (in a subfolder of a git repo of your choice):

/media/disk/git_svn/subdir$ ls -la .

... and:

/media/disk/git_svn/subdir$ git archive --format=tar --prefix=junk/ HEAD | (tar -t -v --full-time -f -)

... and I, in any case, notice that git archive causes all the timestamps of the archived file to be the same! git help archive says:

git archive behaves differently when given a tree ID versus when given a commit ID or tag ID. In the first case the current time is used as the modification time of each file in the archive. In the latter case the commit time as recorded in the referenced commit object is used instead.

... but apparently both cases set the "modification time of each file"; thereby not preserving the actual timestamps of those files!

So, in order to also preserve the timestamps, here is a bash script, which is actually a "one-liner", albeit somewhat complicated - so below it is posted in multiple lines:

/media/disk/git_svn/subdir$ git archive --format=tar master | (tar tf -) | (\
  DEST="/media/diskC/tmp/subdirB"; \
  CWD="$PWD"; \
  while read line; do \
    DN=$(dirname "$line"); BN=$(basename "$line"); \
    SRD="$CWD"; TGD="$DEST"; \
    if [ "$DN" != "." ]; then \
      SRD="$SRD/$DN" ; TGD="$TGD/$DN" ; \
      if [ ! -d "$TGD" ] ; then \
        CMD="mkdir \"$TGD\"; touch -r \"$SRD\" \"$TGD\""; \
        echo "$CMD"; \
        eval "$CMD"; \
      fi; \
    fi; \
    CMD="cp -a \"$SRD/$BN\" \"$TGD/\""; \
    echo "$CMD"; \
    eval "$CMD"; \
    done \
)

Note that it is assumed that you're exporting the contents in "current" directory (above, /media/disk/git_svn/subdir) - and the destination you're exporting into is somewhat inconveniently placed, but it is in DEST environment variable. Note that with this script; you must create the DEST directory manually yourself, before running the above script.

After the script is ran, you should be able to compare:

ls -la /media/disk/git_svn/subdir
ls -la /media/diskC/tmp/subdirB   # DEST

... and hopefully see the same timestamps (for those files that were under version control).

Hope this helps someone,
Cheers!

React "after render" code?

In my experience window.requestAnimationFrame wasn't enough to ensure that the DOM had been fully rendered / reflow-complete from componentDidMount. I have code running that accesses the DOM immediately after a componentDidMount call and using solely window.requestAnimationFrame would result in the element being present in the DOM; however, updates to the element's dimensions aren't reflected yet since a reflow hasn't yet occurred.

The only truly reliable way for this to work was to wrap my method in a setTimeout and a window.requestAnimationFrame to ensure React's current call stack gets cleared before registering for the next frame's render.

function onNextFrame(callback) {
    setTimeout(function () {
        requestAnimationFrame(callback)
    })
}

If I had to speculate on why this is occurring / necessary I could see React batching DOM updates and not actually applying the changes to the DOM until after the current stack is complete.

Ultimately, if you're using DOM measurements in the code you're firing after the React callbacks you'll probably want to use this method.

Upgrading Node.js to latest version

If you are looking in linux..

npm update will not work mostly am not sure reason but following steps will help you to resolve issue...

Terminal process to upgrade node 4.x to 6.x.

 $ node -v
 v4.x

Check node path

$ which node
/usr/bin/node

Download latest(6.x) node files from [Download][1]

[1]: https://nodejs.org/dist/v6.9.2/node-v6.9.2-linux-x64.tar.xz and unzip files keep in /opt/node-v6.9.2-linux-x64/.

Now unlink current node and link with latest as following

$ unlink /usr/bin/node
$ ln -s /opt/node-v6.9.2-linux-x64/bin/node node
$ node -v
$ v6.9.2

Check to see if python script is running

I'm a big fan of Supervisor for managing daemons. It's written in Python, so there are plenty of examples of how to interact with or extend it from Python. For your purposes the XML-RPC process control API should work nicely.

How to set a session variable when clicking a <a> link

    session_start();
    if(isset($_SESSION['current'])){
         $_SESSION['oldlink']=$_SESSION['current'];
    }else{
         $_SESSION['oldlink']='no previous page';
    }
    $_SESSION['current']=$_SERVER['PHP_SELF'];

Maybe this is what you're looking for? It will remember the old link/page you're coming from (within your website).

Put that piece on top of each page.

If you want to make it 'refresh proof' you can add another check:

   if(isset($_SESSION['current']) && $_SESSION['current']!=$_SERVER['PHP_SELF'])

This will make the page not remember itself.

UPDATE: Almost the same as @Brandon though... Just use a php variable, I know this looks like a security risk, but when done correct it isn't.

 <a href="home.php?a=register">Register Now!</a>

PHP:

 if(isset($_GET['a']) /*you can validate the link here*/){
    $_SESSION['link']=$_GET['a'];
 }

Why even store the GET in a session? Just use it. Please tell me why you do not want to use GET. « Validate for more security. I maybe can help you with a better script.

How to make primary key as autoincrement for Room Persistence lib

This works for me:

@Entity(tableName = "note_table")
data class Note(
    @ColumnInfo(name="title") var title: String,
    @ColumnInfo(name="description") var description: String = "",
    @ColumnInfo(name="priority") var priority: Int,
    @PrimaryKey(autoGenerate = true) var id: Int = 0//last so that we don't have to pass an ID value or named arguments
)

Note that the id is last to avoid having to use named arguments when creating the entity, before inserting it into Room. Once it's been added to room, use the id when updating the entity.

Force the origin to start at 0

Simply add these to your ggplot:

+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

Example

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for


p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

enter image description here

Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge' could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.

Angular 4: How to include Bootstrap?

Watch Video or Follow the step

Install bootstrap 4 in angular 2 / angular 4 / angular 5 / angular 6

There is three way to include bootstrap in your project
1) Add CDN Link in index.html file
2) Install bootstrap using npm and set path in angular.json Recommended
3) Install bootstrap using npm and set path in index.html file

I recommended you following 2 methods that are installed bootstrap using npm because its installed in your project directory and you can easily access it

Method 1

Add Bootstrap, Jquery and popper.js CDN path to you angular project index.html file

Bootstrap.css
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
Bootstrap.js
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
Jquery.js
https://code.jquery.com/jquery-3.2.1.slim.min.js
Popper.js
https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js

Method 2

1) Install bootstrap using npm

npm install bootstrap --save

after the installation of Bootstrap 4, we Need two More javascript Package that is Jquery and Popper.js without these two package bootstrap is not complete because Bootstrap 4 is using Jquery and popper.js package so we have to install as well

2) Install JQUERY

npm install jquery --save

3) Install Popper.js

npm install popper.js --save

Now Bootstrap is Install on you Project Directory inside node_modules Folder

open angular.json this file are available on you angular directory open that file and add the path of bootstrap, jquery, and popper.js files inside styles[] and scripts[] path see the below example

"styles": [   
    "node_modules/bootstrap/dist/css/bootstrap.min.css",
    "styles.css"
  ],
  "scripts": [  
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/popper.js/dist/umd/popper.min.js",
    "node_modules/bootstrap/dist/js/bootstrap.min.js"
  ],

Note: Don't change a sequence of js file it should be like this

Method 3

Install bootstrap using npm follow Method 2 in method 3 we just set path inside index.html file instead of angular.json file

bootstrap.css

    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css">

Jquery.js

<script src="node_modules/jquery/dist/jquery.min.js"><br>

Bootstrap.js

<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"><br>

Popper.js

<script src="node_modules/popper.js/dist/umd/popper.min.js"><br>

Now Bootstrap Working fine Now

"Active Directory Users and Computers" MMC snap-in for Windows 7?

As @CraigHyatt mentioned in one of the comments:

"Control Panel -> Programs and Features -> Turn Windows features on or off -> Remote Server Administration Tools -> AD DS and AD LDS Tools"

This worked like a charm in Windows Server 2008. A reboot was necessary, but the Active Directory Users and Computers snap in was available after that.

What exactly is \r in C language?

It's Carriage Return. Source: http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx

The following repeats the loop until the user has pressed the Return key.

while(ch!='\r')
{
  ch=getche();
}

Calculating the angle between the line defined by two points

A few answers here have tried to explain the "screen" issue where top left is 0,0 and bottom right is (positive) screen width, screen height. Most grids have the Y axis as positive above X not below.

The following method will work with screen values instead of "grid" values. The only difference to the excepted answer is the Y values are inverted.

/**
 * Work out the angle from the x horizontal winding anti-clockwise 
 * in screen space. 
 * 
 * The value returned from the following should be 315. 
 * <pre>
 * x,y -------------
 *     |  1,1
 *     |    \
 *     |     \
 *     |     2,2
 * </pre>
 * @param p1
 * @param p2
 * @return - a double from 0 to 360
 */
public static double angleOf(PointF p1, PointF p2) {
    // NOTE: Remember that most math has the Y axis as positive above the X.
    // However, for screens we have Y as positive below. For this reason, 
    // the Y values are inverted to get the expected results.
    final double deltaY = (p1.y - p2.y);
    final double deltaX = (p2.x - p1.x);
    final double result = Math.toDegrees(Math.atan2(deltaY, deltaX)); 
    return (result < 0) ? (360d + result) : result;
}

How to tell which disk Windows Used to Boot

Unless C: is not the drive that windows booted from.
Parse the %SystemRoot% variable, it contains the location of the windows folder (i.e. c:\windows).

How to POST form data with Spring RestTemplate?

Your url String needs variable markers for the map you pass to work, like:

String url = "https://app.example.com/hr/email?{email}";

Or you could explicitly code the query params into the String to begin with and not have to pass the map at all, like:

String url = "https://app.example.com/hr/[email protected]";

See also https://stackoverflow.com/a/47045624/1357094

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

How to enable DataGridView sorting when user clicks on the column header?

I suggest using a DataTable.DefaultView as a DataSource. Then the line below.

foreach (DataGridViewColumn column in gridview.Columns)
    {
       column.SortMode = DataGridViewColumnSortMode.Automatic;
    }

After that the gridview itself will manage sorting(Ascending or Descending is supported.)

method in class cannot be applied to given types

call generateNumbers(numbers);, your generateNumbers(); expects int[] as an argument ans you were passing none, thus the error

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

How to set an environment variable in a running docker container

To:

  1. set up many env. vars in one step,
  2. prevent exposing them in 'sh' history, like with '-e' option (passing credentials/api tokens!),

you can use

--env-file key_value_file.txt

option:

docker run --env-file key_value_file.txt $INSTANCE_ID

Powershell: Get FQDN Hostname

Local Computer FQDN via dotNet class

[System.Net.Dns]::GetHostEntry([string]$env:computername).HostName

or

[System.Net.Dns]::GetHostEntry([string]"localhost").HostName

Reference:

Dns Methods (System.Net)

note: GetHostByName method is obsolete


Local computer FQDN via WMI query

$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
Write-Host $myFQDN

Reference:

Win32_ComputerSystem class

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Simplest way to fetch duplicates/repeated values from array/string :

_x000D_
_x000D_
function getDuplicates(param) {_x000D_
  var duplicates = {}_x000D_
_x000D_
  for (var i = 0; i < param.length; i++) {_x000D_
    var char = param[i]_x000D_
    if (duplicates[char]) {_x000D_
      duplicates[char]++_x000D_
    } else {_x000D_
      duplicates[char] = 1_x000D_
    }_x000D_
  }_x000D_
  return duplicates_x000D_
}_x000D_
_x000D_
console.log(getDuplicates("aeiouaeiou"));_x000D_
console.log(getDuplicates(["a", "e", "i", "o", "u", "a", "e"]));_x000D_
console.log(getDuplicates([1, 2, 3, 4, 5, 1, 1, 2, 3]));
_x000D_
_x000D_
_x000D_

PHP get domain name

Similar question has been asked in stackoverflow before.

See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

error: command 'gcc' failed with exit status 1 on CentOS

Is gcc installed?

sudo yum install gcc

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

How to convert MySQL time to UNIX timestamp using PHP?

Instead of strtotime you should use DateTime with PHP. You can also regard the timezone this way:

$dt = DateTime::createFromFormat('Y-m-d H:i:s', $mysqltime, new DateTimeZone('Europe/Berlin'));
$unix_timestamp = $dt->getTimestamp();

$mysqltime is of type MySQL Datetime, e. g. 2018-02-26 07:53:00.

What is the difference between RTP or RTSP in a streaming server?

I think thats correct. RTSP may use RTP internally.

System.Timers.Timer vs System.Threading.Timer

This article offers a fairly comprehensive explanation:

"Comparing the Timer Classes in the .NET Framework Class Library" - also available as a .chm file

The specific difference appears to be that System.Timers.Timer is geared towards multithreaded applications and is therefore thread-safe via its SynchronizationObject property, whereas System.Threading.Timer is ironically not thread-safe out-of-the-box.

I don't believe that there is a difference between the two as it pertains to how small your intervals can be.

Convert an NSURL to an NSString

In Objective-C:

NSString *myString = myURL.absoluteString;

In Swift:

var myString = myURL.absoluteString

More info in the docs:

Why does flexbox stretch my image rather than retaining aspect ratio?

The key attribute is align-self: center:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
img {_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
img.align-self {_x000D_
  align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
    <p>Without align-self:</p>_x000D_
    <img src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
    <p>With align-self:</p>_x000D_
    <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSONException: Value of type java.lang.String cannot be converted to JSONObject

In my case the problem occured from php file. It gave unwanted characters.That is why a json parsing problem occured.

Then I paste my php code in Notepad++ and select Encode in utf-8 without BOM from Encoding tab and running this code-

My problem gone away.

Get full path of a file with FileUpload Control

On Internet Explorer Options, on security tab click on custom security button, there have an option to send the local path when loading some file to server.

Disabled as default. Just enable it.

When to use React setState callback

Consider setState call

this.setState({ counter: this.state.counter + 1 })

IDEA

setState may be called in async function

So you cannot rely on this. If the above call was made inside a async function this will refer to state of component at that point of time but we expected this to refer to property inside state at time setState calling or beginning of async task. And as task was async call thus that property may have changed in time being. Thus it is unreliable to use this keyword to refer to some property of state thus we use callback function whose arguments are previousState and props which means when async task was done and it was time to update state using setState call prevState will refer to state now when setState has not started yet. Ensuring reliability that nextState would not be corrupted.

Wrong Code: would lead to corruption of data

this.setState(
   {counter:this.state.counter+1}
 );

Correct Code with setState having call back function:

 this.setState(
       (prevState,props)=>{
           return {counter:prevState.counter+1};
        }
    );

Thus whenever we need to update our current state to next state based on value possed by property just now and all this is happening in async fashion it is good idea to use setState as callback function.

I have tried to explain it in codepen here CODE PEN

Open multiple Eclipse workspaces on the Mac

Based on a previous answer that helped me, but different directory:

cd /Applications/Eclipse.app/Contents/MacOS
./eclipse &

Thanks

How to check compiler log in sql developer?

I can also use

show errors;

In sql worksheet.

Show MySQL host via SQL Command

To get current host name :-

select @@hostname;
show variables where Variable_name like '%host%';

To get hosts for all incoming requests :-

select host from information_schema.processlist;

Based on your last comment,
I don't think you can resolve IP for the hostname using pure mysql function,
as it require a network lookup, which could be taking long time.

However, mysql document mention this :-

resolveip google.com.sg

docs :- http://dev.mysql.com/doc/refman/5.0/en/resolveip.html

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

This might be somewhat of a hack, but it got the job done in our case:

(0 || myfield)::integer

Explanation (Tested on Postgres 8.4):

The above mentioned expression yields NULL for NULL-values in myfield and 0 for empty strings (This exact behaviour may or may not fit your use case).

SELECT id, (0 || values)::integer from test_table ORDER BY id

Test data:

CREATE TABLE test_table
(
  id integer NOT NULL,
  description character varying,
  "values" character varying,
  CONSTRAINT id PRIMARY KEY (id)
)

-- Insert Test Data
INSERT INTO test_table VALUES (1, 'null', NULL);
INSERT INTO test_table VALUES (2, 'empty string', '');
INSERT INTO test_table VALUES (3, 'one', '1');

The query will yield the following result:

 ---------------------
 |1|null        |NULL|
 |2|empty string|0   |
 |3|one         |1   |
 ---------------------

Whereas select only values::integer will result in an error message.

Hope this helps.

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

It registers the driver; something of the form:

public class SomeDriver implements Driver {
  static {
    try {
      DriverManager.registerDriver(new SomeDriver());
    } catch (SQLException e) {
      // TODO Auto-generated catch block
    }
  }

  //etc: implemented methods
}

How to iterate through a DataTable

You can also use linq extensions for DataSets:

var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
{
    TextBox1.Text = imgPath;
}

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

Delete the .xap file if your breakpoint aren't being hit. Inside YourProject.Web/ClientBin Delete YourProject.xap. I've have tried all above and stumble across this fix, works everytime. Wise to clean the project after deleting as well.

Intellij IDEA Java classes not auto compiling on save

WARNING

Eclipse Mode plug-in is obsolete and is not compatible with the recent IDEA 12+ builds. If you install it, IDE will hang on every file change and will respond extremely slow.


IntelliJ IDEA doesn't use automatic build, it detects errors on the fly, not via compiler. Similar to Eclipse mode will be available in IDEA 12:

Make project automatically

Use Build | Make, it invokes the incremental make process that will compile only changed and dependent files (it's very fast).

There is also a FAQ entry that may help.

Update on the automatic make feature: When run/debug configuration is running, Make project automatically has no effect. Classes on disk will change only on Build | Make. It's the core design decision as in our opinion class changes on disk should be always under user's control. Automatic make is not the copycat of Eclipse feature, it works differently and it's main purpose is to save time waiting for the classes to be ready when they are really needed (before running the app or tests). Automatic make doesn't replace the explicit compilation that you still need to trigger like in the case described in this question. If you are looking for different behavior, EclipseMode plug-in linked in the FAQ above would be a better choice.

How to use border with Bootstrap

If you are using Bootstrap 4 and higher try this to put borders around your empty divs use border border-primary here is an example of my code:

<div class="row border border-primary">
        <div class="col border border-primary">logo</div>
        <div class="col border border-primary">navbar</div>
    </div>

Here is the link to the border utility in Bootstrap 4: https://getbootstrap.com/docs/4.2/utilities/borders/

how to add lines to existing file using python

Open the file for 'append' rather than 'write'.

with open('file.txt', 'a') as file:
    file.write('input')

How to implement a ViewPager with different Fragments / Layouts

Code for adding fragment

public Fragment getItem(int position) {

    switch (position){
        case 0:
            return new Fragment1();

        case 1:
            return new Fragment2();

        case 2:
            return new Fragment3();

        case 3:
            return new Fragment4();

        default:
            break;
    }

    return null;
}

Create an xml file for each fragment say for Fragment1, use fragment_one.xml as layout file, use the below code in Fragment1 java file.

public class Fragment1 extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_one, container, false);

        return view;

    }
}

Later you can make necessary corrections.. It worked for me.

How to secure phpMyAdmin

The simplest approach would be to edit the webserver, most likely an Apache2 installation, configuration and give phpmyadmin a different name.

A second approach would be to limit the IP addresses from where phpmyadmin may be accessed (e.g. only local lan or localhost).

I just assigned a variable, but echo $variable shows something else

echo $var output highly depends on the value of IFS variable. By default it contains space, tab, and newline characters:

[ks@localhost ~]$ echo -n "$IFS" | cat -vte
 ^I$

This means that when shell is doing field splitting (or word splitting) it uses all these characters as word separators. This is what happens when referencing a variable without double quotes to echo it ($var) and thus expected output is altered.

One way to prevent word splitting (besides using double quotes) is to set IFS to null. See http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_05 :

If the value of IFS is null, no field splitting shall be performed.

Setting to null means setting to empty value:

IFS=

Test:

[ks@localhost ~]$ echo -n "$IFS" | cat -vte
 ^I$
[ks@localhost ~]$ var=$'key\nvalue'
[ks@localhost ~]$ echo $var
key value
[ks@localhost ~]$ IFS=
[ks@localhost ~]$ echo $var
key
value
[ks@localhost ~]$ 

How to change legend size with matplotlib.pyplot

using import matplotlib.pyplot as plt

Method 1: specify the fontsize when calling legend (repetitive)

plt.legend(fontsize=20) # using a size in points
plt.legend(fontsize="x-large") # using a named size

With this method you can set the fontsize for each legend at creation (allowing you to have multiple legends with different fontsizes). However, you will have to type everything manually each time you create a legend.

(Note: @Mathias711 listed the available named fontsizes in his answer)

Method 2: specify the fontsize in rcParams (convenient)

plt.rc('legend',fontsize=20) # using a size in points
plt.rc('legend',fontsize='medium') # using a named size

With this method you set the default legend fontsize, and all legends will automatically use that unless you specify otherwise using method 1. This means you can set your legend fontsize at the beginning of your code, and not worry about setting it for each individual legend.

If you use a named size e.g. 'medium', then the legend text will scale with the global font.size in rcParams. To change font.size use plt.rc(font.size='medium')

How can I reference a dll in the GAC from Visual Studio?

Registering assmblies into the GAC does not then place a reference to the assembly in the add references dialog. You still need to reference the assembly by path for your project, the main difference being you do not need to use the copy local option, your app will find it at runtime.

In this particular case, you just need to reference your assembly by path (browse) or if you really want to have it in the add reference dialog there is a registry setting where you can add additional paths.

Note, if you ship your app to someone who does not have this assembly installed you will need to ship it, and in this case you really need to use the SharedManagementObjects.msi redistributable.

Code line wrapping - how to handle long lines

IMHO this is the best way to write your line :

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
        new HashMap<Class<? extends Persistent>, PersistentHelper>();

This way the increased indentation without any braces can help you to see that the code was just splited because the line was too long. And instead of 4 spaces, 8 will make it clearer.

How to escape single quotes in MySQL

Use this code:

<?php
    $var = "This is Ashok's Pen.";

    mysql_real_escape_string($var);
?>

This will solve your problem, because the database can't detect the special characters of a string.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

I had this issue and what I did and solved the problem was that I used AsEnumerable() just before my Join clause. here is my query:

List<AccountViewModel> selectedAccounts;

 using (ctx = SmallContext.GetInstance()) {
                var data = ctx.Transactions.
                    Include(x => x.Source).
                    Include(x => x.Relation).
                    AsEnumerable().
                    Join(selectedAccounts, x => x.Source.Id, y => y.Id, (x, y) => x).
                    GroupBy(x => new { Id = x.Relation.Id, Name = x.Relation.Name }).
                    ToList();
            }

I was wondering why this issue happens, and now I think It is because after you make a query via LINQ, the result will be in memory and not loaded into objects, I don't know what that state is but they are in in some transitional state I think. Then when you use AsEnumerable() or ToList(), etc, you are placing them into physical memory objects and the issue is resolving.

What is difference between Axios and Fetch?

In addition... I was playing around with various libs in my test and noticed their different handling of 4xx requests. In this case my test returns a json object with a 400 response. This is how 3 popular libs handle the response:

// request-promise-native
const body = request({ url: url, json: true })
const res = await t.throws(body);
console.log(res.error)


// node-fetch
const body = await fetch(url)
console.log(await body.json())


// Axios
const body = axios.get(url)
const res = await t.throws(body);
console.log(res.response.data)

Of interest is that request-promise-native and axios throw on 4xx response while node-fetch doesn't. Also fetch uses a promise for json parsing.

Playing m3u8 Files with HTML Video Tag

Adding to ben.bourdin answer, you can at least in any HTML based application, check if the browser supports HLS in its video element:

Let´s assume that your video element ID is "myVideo", then through javascript you can use the "canPlayType" function (http://www.w3schools.com/tags/av_met_canplaytype.asp)

var videoElement = document.getElementById("myVideo");
if(videoElement.canPlayType('application/vnd.apple.mpegurl') === "probably" || videoElement.canPlayType('application/vnd.apple.mpegurl') === "maybe"){
    //Actions like playing the .m3u8 content
}
else{
    //Actions like playing another video type
}

The canPlayType function, returns:

"" when there is no support for the specified audio/video type

"maybe" when the browser might support the specified audio/video type

"probably" when it most likely supports the specified audio/video type (you can use just this value in the validation to be more sure that your browser supports the specified type)

Hope this help :)

Best regards!

Asynchronous file upload (AJAX file upload) using jsp and javascript

I don't believe AJAX can handle file uploads but this can be achieved with libraries that leverage flash. Another advantage of the flash implementation is the ability to do multiple files at once (like gmail).

SWFUpload is a good start : http://www.swfupload.org/documentation

jQuery and some of the other libraries have plugins that leverage SWFUpload. On my last project we used SWFUpload and Java without a problem.

Also helpful and worth looking into is Apache's FileUpload : http://commons.apache.org/fileupload/index.html

Free Online Team Foundation Server

One of recent the TFS Rocks pocasts mentioned such an organisation, may have been number 16.

C# static class constructor

We can create static constructor

static class StaticParent 
{
  StaticParent() 
  {
    //write your initialization code here

  }

}

and it is always parameter less.

static class StaticParent
{
    static int i =5;
    static StaticParent(int i)  //Gives error
    {
      //write your initialization code here
    }
}

and it doesn't have the access modifier

Removing Conda environment

First deactivate the environment and come back to the base environment. From the base, you should be able to run the command conda env remove -n <envname>. This will give you the message

Remove all packages in environment C:\Users\<username>\AppData\Local\Continuum\anaconda3\envs\{envname}:

Convert JS object to JSON string

Use this,

var j={"name":"binchen"};
 var myJSON = JSON.stringify(j);

AngularJS - How to use $routeParams in generating the templateUrl?

templateUrl can be use as function with returning generated URL. We can manipulate url with passing argument which takes routeParams.

See the example.

.when('/:screenName/list',{
    templateUrl: function(params){
         return params.screenName +'/listUI'
    }
})

Hope this help.

ImportError: No module named PyQt4.QtCore

I had the "No module named PyQt4.QtCore" error and installing the python-qt4 package fixed it only partially: I could run

from PyQt4.QtCore import SIGNAL

from a python interpreter but only without activating my virtualenv.

The only solution I've found till now to use a virtualenv is to copy the PyQt4 folder and the sip.so file into my virtualenv as explained here: Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

Does HTTP use UDP?

UDP is the best protocol for streaming, because it doesn't make demands for missing packages like TCP. And if it doesn't make demands, the flow is far more faster and without any buffering.

Even the stream delay is lesser than TCP. That is because TCP (as a far more secure protocol) makes demands for missing packages, overwriting the existing ones.

So TCP is a protocol too advanced to be used for streaming.

yii2 redirect in controller action does not work?

In Yii2 we need to return() the result from the action.I think you need to add a return in front of your redirect.

  return $this->redirect(['user/index']);

Delete directory with files in it?

I want to expand on the answer by @alcuadrado with the comment by @Vijit for handling symlinks. Firstly, use getRealPath(). But then, if you have any symlinks that are folders it will fail as it will try and call rmdir on a link - so you need an extra check.

$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
    if ($file->isLink()) {
        unlink($file->getPathname());
    } else if ($file->isDir()){
        rmdir($file->getPathname());
    } else {
        unlink($file->getPathname());
    }
}
rmdir($dir);

How to debug a Flask app

To activate debug mode in flask you simply type set FLASK_DEBUG=1 on your CMD for windows and export FLASK_DEBUG=1 on Linux termial then restart your app and you are good to go!!

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

onKeyDown event not working on divs in React

You should use tabIndex attribute to be able to listen onKeyDown event on a div in React. Setting tabIndex="0" should fire your handler.

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

Display an array in a readable/hierarchical format

foreach($array as $v) echo $v, PHP_EOL;

UPDATE: A more sophisticated solution would be:

 $test = [
    'key1' => 'val1',
    'key2' => 'val2',
    'key3' => [
        'subkey1' => 'subval1',
        'subkey2' => 'subval2',
        'subkey3' => [
            'subsubkey1' => 'subsubval1',
            'subsubkey2' => 'subsubval2',
        ],
    ],
];
function printArray($arr, $pad = 0, $padStr = "\t") {
    $outerPad = $pad;
    $innerPad = $pad + 1;
    $out = '[' . PHP_EOL;
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $out .= str_repeat($padStr, $innerPad) . $k . ' => ' . printArray($v, $innerPad) . PHP_EOL;
        } else {
            $out .= str_repeat($padStr, $innerPad) . $k . ' => ' . $v;
            $out .= PHP_EOL;
        }
    }
    $out .= str_repeat($padStr, $outerPad) . ']';
    return $out;
}

echo printArray($test);

This prints out:

    [
        key1 => val1
        key2 => val2
        key3 => [
            subkey1 => subval1
            subkey2 => subval2
            subkey3 => [
                subsubkey1 => subsubval1
                subsubkey2 => subsubval2
            ]
        ]
    ]

text-align: right on <select> or <option>

The best solution for me was to make

select {
    direction: rtl;
}

and then

option {
    direction: ltr;
}

again. So there is no change in how the text is read in a screen reader or and no formatting-problem.

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

How do I open a new fragment from another fragment?

 Fragment fr = new Fragment_class();
             FragmentManager fm = getFragmentManager();
            FragmentTransaction fragmentTransaction = fm.beginTransaction();
            fragmentTransaction.add(R.id.viewpagerId, fr);
            fragmentTransaction.commit();

Just to be precise, R.id.viewpagerId is cretaed in your current class layout, upon calling, the new fragment automatically gets infiltrated.

Get city name using geolocation

Here is updated working version for me which will get City/Town, It looks like some fields are modified in the json response. Referring previous answers for this questions. ( Thanks to Michal & one more reference : Link

var geocoder;

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
// Get the latitude and the longitude;
function successFunction(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  codeLatLng(lat, lng);
}

function errorFunction() {
  alert("Geocoder failed");
}

function initialize() {
  geocoder = new google.maps.Geocoder();

}

function codeLatLng(lat, lng) {
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({latLng: latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        var arrAddress = results;
        console.log(results);
        $.each(arrAddress, function(i, address_component) {
          if (address_component.types[0] == "locality") {
            console.log("City: " + address_component.address_components[0].long_name);
            itemLocality = address_component.address_components[0].long_name;
          }
        });
      } else {
        alert("No results found");
      }
    } else {
      alert("Geocoder failed due to: " + status);
    }
  });
}

CURL alternative in Python

If you are using a command to just call curl like that, you can do the same thing in Python with subprocess. Example:

subprocess.call(['curl', '-i', '-H', '"Accept: application/xml"', '-u', 'login:key', '"https://app.streamsend.com/emails"'])

Or you could try PycURL if you want to have it as a more structured api like what PHP has.

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The solution I opted for was to format the date with the mysql query :

String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

I had the exact same issue. Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50

String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

was returning a date formatted as such : 2017-01-01 21:02:50.0

How to select unique records by SQL

It depends on which rown you want to return for each unique item. Your data seems to indicate the minimum data value so in this instance for SQL Server.

SELECT item, min(data)
FROM  table
GROUP BY item

How do I detect whether a Python variable is a function?

A function is just a class with a __call__ method, so you can do

hasattr(obj, '__call__')

For example:

>>> hasattr(x, '__call__')
True

>>> x = 2
>>> hasattr(x, '__call__')
False

That is the "best" way of doing it, but depending on why you need to know if it's callable or note, you could just put it in a try/execpt block:

try:
    x()
except TypeError:
    print "was not callable"

It's arguable if try/except is more Python'y than doing if hasattr(x, '__call__'): x().. I would say hasattr is more accurate, since you wont accidently catch the wrong TypeError, for example:

>>> def x():
...     raise TypeError
... 
>>> hasattr(x, '__call__')
True # Correct
>>> try:
...     x()
... except TypeError:
...     print "x was not callable"
... 
x was not callable # Wrong!

Model Binding to a List MVC 4

This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though.

ViewModel looks like this:

public class MyViewModel
{
   public List<Person> Persons{get;set;}
}

View(with BeginForm of course):

@model MyViewModel


@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    @Html.HiddenFor(m => m.Persons[i].PersonId)
    @Html.EditorFor(m => m.Persons[i].FirstName) 
    @Html.EditorFor(m => m.Persons[i].LastName)         
}

Action:

[HttpPost]public ViewResult(MyViewModel vm)
{
...

Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form.

Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback:

@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    if(i != 4)//conditionally hide 5th item, 
    { //but BUG occurs on postback, all items after 5th will not be bound to the the list
      @Html.HiddenFor(m => m.Persons[i].PersonId)
      @Html.EditorFor(m => m.Persons[i].FirstName) 
      @Html.EditorFor(m => m.Persons[i].LastName)           
    }
}

Where does Internet Explorer store saved passwords?

I found the answer. IE stores passwords in two different locations based on the password type:

  • Http-Auth: %APPDATA%\Microsoft\Credentials, in encrypted files
  • Form-based: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2, encrypted with the url

From a very good page on NirSoft.com:

Starting from version 7.0 of Internet Explorer, Microsoft completely changed the way that passwords are saved. In previous versions (4.0 - 6.0), all passwords were saved in a special location in the Registry known as the "Protected Storage". In version 7.0 of Internet Explorer, passwords are saved in different locations, depending on the type of password. Each type of passwords has some limitations in password recovery:

  • AutoComplete Passwords: These passwords are saved in the following location in the Registry: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2 The passwords are encrypted with the URL of the Web sites that asked for the passwords, and thus they can only be recovered if the URLs are stored in the history file. If you clear the history file, IE PassView won't be able to recover the passwords until you visit again the Web sites that asked for the passwords. Alternatively, you can add a list of URLs of Web sites that requires user name/password into the Web sites file (see below).

  • HTTP Authentication Passwords: These passwords are stored in the Credentials file under Documents and Settings\Application Data\Microsoft\Credentials, together with login passwords of LAN computers and other passwords. Due to security limitations, IE PassView can recover these passwords only if you have administrator rights.

In my particular case it answers the question of where; and I decided that I don't want to duplicate that. I'll continue to use CredRead/CredWrite, where the user can manage their passwords from within an established UI system in Windows.

How do I check particular attributes exist or not in XML?

EDIT

Disregard - you can't use ItemOf (that's what I get for typing before I test). I'd strikethrough the text if I could figure out how...or maybe I'll simply delete the answer, since it was ultimately wrong and useless.

END EDIT

You can use the ItemOf(string) property in the XmlAttributesCollection to see if the attribute exists. It returns null if it's not found.

foreach (XmlNode xNode in nodeListName)
{
    if (xNode.ParentNode.Attributes.ItemOf["split"] != null)
    {
         parentSplit = xNode.ParentNode.Attributes["split"].Value;
    }
}

XmlAttributeCollection.ItemOf Property (String)

PHP new line break in emails

I know this is an old question but anyway it might help someone.

I tend to use PHP_EOL for this purposes (due to cross-platform compatibility).

echo "line 1".PHP_EOL."line 2".PHP_EOL;

If you're planning to show the result in a browser then you have to use "<br>".

EDIT: since your exact question is about emails, things are a bit different. For pure text emails see Brendan Bullen's accepted answer. For HTML emails you simply use HTML formatting.

Using $_POST to get select option value from HTML

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

Python Pandas replicate rows in dataframe

Other way is using concat() function:

import pandas as pd

In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

In [604]: df
Out[604]: 
  col1  col2
0    a     0
1    b     1
2    c     2

In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]: 
  col1  col2
0    a     0
1    b     1
2    c     2
3    a     0
4    b     1
5    c     2
6    a     0
7    b     1
8    c     2

In [606]: pd.concat([df]*3)
Out[606]: 
  col1  col2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2

Executing multi-line statements in the one-line command-line?

you could do

echo -e "import sys\nfor r in range(10): print 'rob'" | python

or w/out pipes:

python -c "exec(\"import sys\nfor r in range(10): print 'rob'\")"

or

(echo "import sys" ; echo "for r in range(10): print 'rob'") | python

or @SilentGhost's answer / @Crast's answer

Any way to replace characters on Swift String?

Swift 3, Swift 4, Swift 5 Solution

let exampleString = "Example string"

//Solution suggested above in Swift 3.0
let stringToArray = exampleString.components(separatedBy: " ")
let stringFromArray = stringToArray.joined(separator: "+")

//Swiftiest solution
let swiftyString = exampleString.replacingOccurrences(of: " ", with: "+")

javascript, is there an isObject function like isArray?

use the following

It will return a true or false

theObject instanceof Object

Removing numbers from string

Would this work for your situation?

>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'

This makes use of a list comprehension, and what is happening here is similar to this structure:

no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
    if not i.isdigit():
        no_digits.append(i)

# Now join all elements of the list with '', 
# which puts all of the characters together.
result = ''.join(no_digits)

As @AshwiniChaudhary and @KirkStrauser point out, you actually do not need to use the brackets in the one-liner, making the piece inside the parentheses a generator expression (more efficient than a list comprehension). Even if this doesn't fit the requirements for your assignment, it is something you should read about eventually :) :

>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'

xls to csv converter

I'd use csvkit, which uses xlrd (for xls) and openpyxl (for xlsx) to convert just about any tabular data to csv.

Once installed, with its dependencies, it's a matter of:

python in2csv myfile > myoutput.csv

It takes care of all the format detection issues, so you can pass it just about any tabular data source. It's cross-platform too (no win32 dependency).

map vs. hash_map in C++

Some of the key differences are in the complexity requirements.

  • A map requires O(log(N)) time for inserts and finds operations, as it's implemented as a Red-Black Tree data structure.

  • An unordered_map requires an 'average' time of O(1) for inserts and finds, but is allowed to have a worst-case time of O(N). This is because it's implemented using Hash Table data structure.

So, usually, unordered_map will be faster, but depending on the keys and the hash function you store, can become much worse.

Warning comparison between pointer and integer

In this line ...

if (*message == "\0") {

... as you can see in the warning ...

warning: comparison between pointer and integer
      ('int' and 'char *')

... you are actually comparing an int with a char *, or more specifically, an int with an address to a char.

To fix this, use one of the following:

if(*message == '\0') ...
if(message[0] == '\0') ...
if(!*message) ...

On a side note, if you'd like to compare strings you should use strcmp or strncmp, found in string.h.

Javascript equivalent of php's strtotime()?

Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

Try Moment.js - it provides cross-browser functionality for parsing dates:

var timestamp = moment("2013-02-08 09:30:26.123");
console.log(timestamp.milliseconds()); // return timestamp in milliseconds
console.log(timestamp.second()); // return timestamp in seconds

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

I've face this problem, i fixed it by deleting the emulator then created a new one with higher API level.

In my case I've created API-30

How to implement OnFragmentInteractionListener

For those of you who visit this page looking for further clarification on this error, in my case the activity making the call to the fragment needed to have 2 implements in this case, like this:

public class MyActivity extends Activity implements 
    MyFragment.OnFragmentInteractionListener, 
    NavigationDrawerFragment.NaviationDrawerCallbacks {
    ...// rest of the code
}

Validate form field only on submit or user input

Erik Aigner,

Please use $dirty(The field has been modified) and $invalid (The field content is not valid).

Please check below examples for angular form validation

1)

Validation example HTML for user enter inputs:

<form  ng-app="myApp"  ng-controller="validateCtrl" name="myForm" novalidate>
  <p>Email:<br>
    <input type="email" name="email" ng-model="email" required>
    <span ng-show="myForm.email.$dirty && myForm.email.$invalid">
      <span ng-show="myForm.email.$error.required">Email is required.</span>
      <span ng-show="myForm.email.$error.email">Invalid email address.</span>
      </span>
  </p>
    </form>

2)

Validation example HTML/Js for user submits :

      <form  ng-app="myApp"  ng-controller="validateCtrl" name="myForm" novalidate form-submit-validation="">
      <p>Email:<br>
        <input type="email" name="email" ng-model="email" required>
        <span ng-show="submitted || myForm.email.$dirty && myForm.email.$invalid">
          <span ng-show="myForm.email.$error.required">Email is required.</span>
          <span ng-show="myForm.email.$error.email">Invalid email address.</span>
          </span>
      </p>
<p>
  <input type="submit">
</p>
</form>

Custom Directive :

app.directive('formSubmitValidation', function () {

        return {
            require: 'form',
            compile: function (tElem, tAttr) {

                tElem.data('augmented', true);

                return function (scope, elem, attr, form) {
                    elem.on('submit', function ($event) {
                        scope.$broadcast('form:submit', form);

                        if (!form.$valid) {
                            $event.preventDefault();
                        }
                        scope.$apply(function () {
                            scope.submitted = true;
                        });


                    });
                }
            }
        };


  })

3)

you don't want use directive use ng-change function like below

  <form  ng-app="myApp"  ng-controller="validateCtrl" name="myForm" novalidate ng-change="submitFun()">
      <p>Email:<br>
        <input type="email" name="email" ng-model="email" required>
        <span ng-show="submitted || myForm.email.$dirty && myForm.email.$invalid">
          <span ng-show="myForm.email.$error.required">Email is required.</span>
          <span ng-show="myForm.email.$error.email">Invalid email address.</span>
          </span>
      </p>
<p>
  <input type="submit">
</p>
</form>

Controller SubmitFun() JS:

 var app = angular.module('example', []);
 app.controller('exampleCntl', function($scope) {
 $scope.submitFun = function($event) {
 $scope.submitted = true;
  if (!$scope.myForm.$valid) 
  {
        $event.preventDefault();
   }
  }

});

How to cast List<Object> to List<MyClass>

Another approach would be using a java 8 stream.

    List<Customer> customer = myObjects.stream()
                                  .filter(Customer.class::isInstance)
                                  .map(Customer.class::cast)
                                  .collect(toList());

How to clear memory to prevent "out of memory error" in excel vba?

I was able to fix this error by simply initializing a variable that was being used later in my program. At the time, I wasn't using Option Explicit in my class/module.

Why does the C preprocessor interpret the word "linux" as the constant "1"?

Use this command

gcc -dM -E - < /dev/null

to get this

    #define _LP64 1
#define _STDC_PREDEF_H 1
#define __ATOMIC_ACQUIRE 2
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_CONSUME 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __ATOMIC_HLE_RELEASE 131072
#define __ATOMIC_RELAXED 0
#define __ATOMIC_RELEASE 3
#define __ATOMIC_SEQ_CST 5
#define __BIGGEST_ALIGNMENT__ 16
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __CHAR16_TYPE__ short unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __CHAR_BIT__ 8
#define __DBL_DECIMAL_DIG__ 17
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __DBL_DIG__ 15
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define __DBL_HAS_DENORM__ 1
#define __DBL_HAS_INFINITY__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __DBL_MANT_DIG__ 53
#define __DBL_MAX_10_EXP__ 308
#define __DBL_MAX_EXP__ 1024
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __DBL_MIN_10_EXP__ (-307)
#define __DBL_MIN_EXP__ (-1021)
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __DEC128_EPSILON__ 1E-33DL
#define __DEC128_MANT_DIG__ 34
#define __DEC128_MAX_EXP__ 6145
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __DEC128_MIN_EXP__ (-6142)
#define __DEC128_MIN__ 1E-6143DL
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __DEC32_EPSILON__ 1E-6DF
#define __DEC32_MANT_DIG__ 7
#define __DEC32_MAX_EXP__ 97
#define __DEC32_MAX__ 9.999999E96DF
#define __DEC32_MIN_EXP__ (-94)
#define __DEC32_MIN__ 1E-95DF
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __DEC64_EPSILON__ 1E-15DD
#define __DEC64_MANT_DIG__ 16
#define __DEC64_MAX_EXP__ 385
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __DEC64_MIN_EXP__ (-382)
#define __DEC64_MIN__ 1E-383DD
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DECIMAL_BID_FORMAT__ 1
#define __DECIMAL_DIG__ 21
#define __DEC_EVAL_METHOD__ 2
#define __ELF__ 1
#define __FINITE_MATH_ONLY__ 0
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __FLT_DECIMAL_DIG__ 9
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __FLT_DIG__ 6
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __FLT_EVAL_METHOD__ 0
#define __FLT_HAS_DENORM__ 1
#define __FLT_HAS_INFINITY__ 1
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MANT_DIG__ 24
#define __FLT_MAX_10_EXP__ 38
#define __FLT_MAX_EXP__ 128
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __FLT_MIN_10_EXP__ (-37)
#define __FLT_MIN_EXP__ (-125)
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __FLT_RADIX__ 2
#define __FXSR__ 1
#define __GCC_ASM_FLAG_OUTPUTS__ 1
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __GCC_HAVE_DWARF2_CFI_ASM 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_IEC_559 2
#define __GCC_IEC_559_COMPLEX 2
#define __GNUC_MINOR__ 3
#define __GNUC_PATCHLEVEL__ 0
#define __GNUC_STDC_INLINE__ 1
#define __GNUC__ 6
#define __GXX_ABI_VERSION 1010
#define __INT16_C(c) c
#define __INT16_MAX__ 0x7fff
#define __INT16_TYPE__ short int
#define __INT32_C(c) c
#define __INT32_MAX__ 0x7fffffff
#define __INT32_TYPE__ int
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int
#define __INT8_C(c) c
#define __INT8_MAX__ 0x7f
#define __INT8_TYPE__ signed char
#define __INTMAX_C(c) c ## L
#define __INTMAX_MAX__ 0x7fffffffffffffffL
#define __INTMAX_TYPE__ long int
#define __INTPTR_MAX__ 0x7fffffffffffffffL
#define __INTPTR_TYPE__ long int
#define __INT_FAST16_MAX__ 0x7fffffffffffffffL
#define __INT_FAST16_TYPE__ long int
#define __INT_FAST32_MAX__ 0x7fffffffffffffffL
#define __INT_FAST32_TYPE__ long int
#define __INT_FAST64_MAX__ 0x7fffffffffffffffL
#define __INT_FAST64_TYPE__ long int
#define __INT_FAST8_MAX__ 0x7f
#define __INT_FAST8_TYPE__ signed char
#define __INT_LEAST16_MAX__ 0x7fff
#define __INT_LEAST16_TYPE__ short int
#define __INT_LEAST32_MAX__ 0x7fffffff
#define __INT_LEAST32_TYPE__ int
#define __INT_LEAST64_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST64_TYPE__ long int
#define __INT_LEAST8_MAX__ 0x7f
#define __INT_LEAST8_TYPE__ signed char
#define __INT_MAX__ 0x7fffffff
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __LDBL_DIG__ 18
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __LDBL_HAS_DENORM__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __LDBL_HAS_QUIET_NAN__ 1
#define __LDBL_MANT_DIG__ 64
#define __LDBL_MAX_10_EXP__ 4932
#define __LDBL_MAX_EXP__ 16384
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __LDBL_MIN_10_EXP__ (-4931)
#define __LDBL_MIN_EXP__ (-16381)
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __LONG_LONG_MAX__ 0x7fffffffffffffffLL
#define __LONG_MAX__ 0x7fffffffffffffffL
#define __LP64__ 1
#define __MMX__ 1
#define __NO_INLINE__ 1
#define __ORDER_BIG_ENDIAN__ 4321
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __ORDER_PDP_ENDIAN__ 3412
#define __PIC__ 2
#define __PIE__ 2
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __PTRDIFF_MAX__ 0x7fffffffffffffffL
#define __PTRDIFF_TYPE__ long int
#define __REGISTER_PREFIX__ 
#define __SCHAR_MAX__ 0x7f
#define __SEG_FS 1
#define __SEG_GS 1
#define __SHRT_MAX__ 0x7fff
#define __SIG_ATOMIC_MAX__ 0x7fffffff
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __SIG_ATOMIC_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __SIZEOF_FLOAT128__ 16
#define __SIZEOF_FLOAT80__ 16
#define __SIZEOF_FLOAT__ 4
#define __SIZEOF_INT128__ 16
#define __SIZEOF_INT__ 4
#define __SIZEOF_LONG_DOUBLE__ 16
#define __SIZEOF_LONG_LONG__ 8
#define __SIZEOF_LONG__ 8
#define __SIZEOF_POINTER__ 8
#define __SIZEOF_PTRDIFF_T__ 8
#define __SIZEOF_SHORT__ 2
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WCHAR_T__ 4
#define __SIZEOF_WINT_T__ 4
#define __SIZE_MAX__ 0xffffffffffffffffUL
#define __SIZE_TYPE__ long unsigned int
#define __SSE2_MATH__ 1
#define __SSE2__ 1
#define __SSE_MATH__ 1
#define __SSE__ 1
#define __SSP_STRONG__ 3
#define __STDC_HOSTED__ 1
#define __STDC_IEC_559_COMPLEX__ 1
#define __STDC_IEC_559__ 1
#define __STDC_ISO_10646__ 201605L
#define __STDC_NO_THREADS__ 1
#define __STDC_UTF_16__ 1
#define __STDC_UTF_32__ 1
#define __STDC_VERSION__ 201112L
#define __STDC__ 1
#define __UINT16_C(c) c
#define __UINT16_MAX__ 0xffff
#define __UINT16_TYPE__ short unsigned int
#define __UINT32_C(c) c ## U
#define __UINT32_MAX__ 0xffffffffU
#define __UINT32_TYPE__ unsigned int
#define __UINT64_C(c) c ## UL
#define __UINT64_MAX__ 0xffffffffffffffffUL
#define __UINT64_TYPE__ long unsigned int
#define __UINT8_C(c) c
#define __UINT8_MAX__ 0xff
#define __UINT8_TYPE__ unsigned char
#define __UINTMAX_C(c) c ## UL
#define __UINTMAX_MAX__ 0xffffffffffffffffUL
#define __UINTMAX_TYPE__ long unsigned int
#define __UINTPTR_MAX__ 0xffffffffffffffffUL
#define __UINTPTR_TYPE__ long unsigned int
#define __UINT_FAST16_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST16_TYPE__ long unsigned int
#define __UINT_FAST32_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST32_TYPE__ long unsigned int
#define __UINT_FAST64_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST64_TYPE__ long unsigned int
#define __UINT_FAST8_MAX__ 0xff
#define __UINT_FAST8_TYPE__ unsigned char
#define __UINT_LEAST16_MAX__ 0xffff
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __UINT_LEAST32_MAX__ 0xffffffffU
#define __UINT_LEAST32_TYPE__ unsigned int
#define __UINT_LEAST64_MAX__ 0xffffffffffffffffUL
#define __UINT_LEAST64_TYPE__ long unsigned int
#define __UINT_LEAST8_MAX__ 0xff
#define __UINT_LEAST8_TYPE__ unsigned char
#define __USER_LABEL_PREFIX__ 
#define __VERSION__ "6.3.0 20170406"
#define __WCHAR_MAX__ 0x7fffffff
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __WCHAR_TYPE__ int
#define __WINT_MAX__ 0xffffffffU
#define __WINT_MIN__ 0U
#define __WINT_TYPE__ unsigned int
#define __amd64 1
#define __amd64__ 1
#define __code_model_small__ 1
#define __gnu_linux__ 1
#define __has_include(STR) __has_include__(STR)
#define __has_include_next(STR) __has_include_next__(STR)
#define __k8 1
#define __k8__ 1
#define __linux 1
#define __linux__ 1
#define __pic__ 2
#define __pie__ 2
#define __unix 1
#define __unix__ 1
#define __x86_64 1
#define __x86_64__ 1
#define linux 1
#define unix 1

Maven: add a folder or jar file into current classpath

From docs and example it is not clear that classpath manipulation is not allowed.

<configuration>
 <compilerArgs>
  <arg>classpath=${basedir}/lib/bad.jar</arg>
 </compilerArgs>
</configuration>

But see Java docs (also https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/solaris/javac.html)

-classpath path Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set.

Maybe it is possible to get current classpath and extend it,
see in maven, how output the classpath being used?

    <properties>
      <cpfile>cp.txt</cpfile>
    </properties>

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.9</version>
    <executions>
      <execution>
        <id>build-classpath</id>
        <phase>generate-sources</phase>
        <goals>
          <goal>build-classpath</goal>
        </goals>
        <configuration>
          <outputFile>${cpfile}</outputFile>
        </configuration>
      </execution>
    </executions>
  </plugin>

Read file (Read a file into a Maven property)

<plugin>
  <groupId>org.codehaus.gmaven</groupId>
  <artifactId>gmaven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <phase>generate-resources</phase>
      <goals>
        <goal>execute</goal>
      </goals>
      <configuration>
        <source>
          def file = new File(project.properties.cpfile)
          project.properties.cp = file.getText()
        </source>
      </configuration>
    </execution>
  </executions>
</plugin>

and finally

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
      <compilerArgs>
         <arg>classpath=${cp}:${basedir}/lib/bad.jar</arg>
      </compilerArgs>
    </configuration>
   </plugin>

Outline effect to text

This mixin for SASS will give smooth results, using 8-axis:

@mixin stroke($size: 1px, $color: #000) {
  text-shadow:
    -#{$size} -#{$size} 0 $color,
     0        -#{$size} 0 $color,
     #{$size} -#{$size} 0 $color,
     #{$size}  0        0 $color,
     #{$size}  #{$size} 0 $color,
     0         #{$size} 0 $color,
    -#{$size}  #{$size} 0 $color,
    -#{$size}  0        0 $color;
}

And normal CSS:

text-shadow:
  -1px -1px 0 #000,
   0   -1px 0 #000,
   1px -1px 0 #000,
   1px  0   0 #000,
   1px  1px 0 #000,
   0    1px 0 #000,
  -1px  1px 0 #000,
  -1px  0   0 #000;

How to write log to file

This works for me

  1. created a package called logger.go

    package logger
    
    import (
      "flag"
      "os"
      "log"
      "go/build"
    )
    
    var (
      Log      *log.Logger
    )
    
    
    func init() {
        // set location of log file
        var logpath = build.Default.GOPATH + "/src/chat/logger/info.log"
    
       flag.Parse()
       var file, err1 = os.Create(logpath)
    
       if err1 != nil {
          panic(err1)
       }
          Log = log.New(file, "", log.LstdFlags|log.Lshortfile)
          Log.Println("LogFile : " + logpath)
    }
    
    1. import the package wherever you want to log e.g main.go

      package main
      
      import (
         "logger"
      )
      
      const (
         VERSION = "0.13"
       )
      
      func main() {
      
          // time to use our logger, print version, processID and number of running process
          logger.Log.Printf("Server v%s pid=%d started with processes: %d", VERSION, os.Getpid(),runtime.GOMAXPROCS(runtime.NumCPU()))
      
      }
      

How to use passive FTP mode in Windows command prompt?

This is a common problem . when we start the ftp connection only the external ip opens the port for pasv connection. but the ip behind the NAT doesn't open the connection so passive connection fails with PASV command

we need to specify that while opening the connection so open connection with

ftp -p {host}

How can I add an image file into json object?

public class UploadToServer extends Activity {

TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;

String upLoadServerUri = null;

/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_to_server);

    uploadButton = (Button) findViewById(R.id.uploadButton);
    messageText = (TextView) findViewById(R.id.messageText);

    messageText.setText("Uploading file path :- '/mnt/sdcard/"
            + uploadFileName + "'");

    /************* Php script path ****************/
    upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";

    uploadButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(UploadToServer.this, "",
                    "Uploading file...", true);

            new Thread(new Runnable() {
                public void run() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText.setText("uploading started.....");
                        }
                    });

                    uploadFile(uploadFilePath + "" + uploadFileName);

                }
            }).start();
        }
    });
}

public int uploadFile(String sourceFileUri) {

    String fileName = sourceFileUri;

    HttpURLConnection connection = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
                + uploadFileName);

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :"
                        + uploadFilePath + "" + uploadFileName);
            }
        });

        return 0;

    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP connection to the URL
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true); // Allow Inputs
            connection.setDoOutput(true); // Allow Outputs
            connection.setUseCaches(false); // Don't use a Cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(connection.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            // dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
            // + fileName + "\"" + lineEnd);
            dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                    + URLEncoder.encode(fileName, "UTF-8") + lineEnd);

            dos.writeBytes(lineEnd);

            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {

                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                + " http://www.androidexample.com/media/uploads/"
                                + uploadFileName;

                        messageText.setText(msg);
                        Toast.makeText(UploadToServer.this,
                                "File Upload Complete.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText
                            .setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(UploadToServer.this,
                            "MalformedURLException", Toast.LENGTH_SHORT)
                            .show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Got Exception : see logcat ");
                    Toast.makeText(UploadToServer.this,
                            "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

PHP FILE

<?php
$target_path  = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
 echo "There was an error uploading the file, please try again!";
}
?>

Suppress Scientific Notation in Numpy When Creating Array From Nested List

I guess what you need is np.set_printoptions(suppress=True), for details see here: http://pythonquirks.blogspot.fr/2009/10/controlling-printing-in-numpy.html

For SciPy.org numpy documentation, which includes all function parameters (suppress isn't detailed in the above link), see here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How to embed a Facebook page's feed into my website

If you are looking for a custom code instead of plugin, then this might help you. Facebook graph has under gone some changes since it has evolved. These steps are for the latest Graph API which I tried recently and worked well.

There are two main steps involved - 1. Getting Facebook Access Token, 2. Calling the Graph API passing the access token.

1. Getting the access token - Here is the step by step process to get the access token for your Facebook page. - Embed Facebook page feed on my website. As per this you need to create an app in Facebook developers page which would give you an App Id and an App Secret. Use these two and get the Access Token.

2. Calling the Graph API - This would be pretty simple once you get the access token. You just need to form a URL to Graph API with all the fields/properties you want to retrieve and make a GET request to this URL. Here is one example on how to do it in asp.net MVC. Embedding facebook feeds using asp.net mvc. This should be pretty similar in any other technology as it would be just a HTTP GET request.

Sample FQL Query: https://graph.facebook.com/FBPageName/posts?fields=full_picture,picture,link,message,created_time&limit=5&access_token=YOUR_ACCESS_TOKEN_HERE

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

In this case no conditionals are needed to set the variable.

This one-liner XPath expression:

boolean(joined-subclass)

is true() only when the child of the current node, named joined-subclass exists and it is false() otherwise.

The complete stylesheet is:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

 <xsl:template match="class">
   <xsl:variable name="subexists"
        select="boolean(joined-subclass)"
   />

   subexists:  <xsl:text/>
   <xsl:value-of select="$subexists" />
 </xsl:template>
</xsl:stylesheet>

Do note, that the use of the XPath function boolean() in this expression is to convert a node (or its absense) to one of the boolean values true() or false().

Get source jar files attached to Eclipse for Maven-managed dependencies

There is also a similiar question that answers this and includes example pom settings.

Firebase FCM force onTokenRefresh() to be called

FirebaseInstanceIdService

This class is deprecated. In favour of overriding onNewToken in FirebaseMessagingService. Once that has been implemented, this service can be safely removed.

The new way to do this would be to override the onNewToken method from FirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("NEW_TOKEN",s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }
} 

Also dont forget to add the service in the Manifest.xml

<service
    android:name=".MyFirebaseMessagingService"
    android:stopWithTask="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

How to delete columns that contain ONLY NAs?

One way of doing it:

df[, colSums(is.na(df)) != nrow(df)]

If the count of NAs in a column is equal to the number of rows, it must be entirely NA.

Or similarly

df[colSums(!is.na(df)) > 0]

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

1. Final • Final is used to apply restrictions on class, method and variable. • Final class can't be inherited, final method can't be overridden and final variable value can't be changed. • Final variables are initialized at the time of creation except in case of blank final variable which is initialized in Constructor. • Final is a keyword.

2. Finally • Finally is used for exception handling along with try and catch. • It will be executed whether exception is handled or not. • This block is used to close the resources like database connection, I/O resources. • Finally is a block.

3. Finalize • Finalize is called by Garbage collection thread just before collecting eligible objects to perform clean up processing. • This is the last chance for object to perform any clean-up but since it’s not guaranteed that whether finalize () will be called, its bad practice to keep resource till finalize call. • Finalize is a method.

Error: Specified cast is not valid. (SqlManagerUI)

This would also happen when you are trying to restore a newer version backup in a older SQL database. For example when you try to restore a DB backup that is created in 2012 with 110 compatibility and you are trying to restore it in 2008 R2.

How to generate UL Li list from string array using jquery?

Other variation of Abhishek Bhalani: You can use Array.map() instead of $.each()

var items = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist');
items.map( (item,i ) => {
      var li = $('<li/>')
        .addClass('ui-menu-item')
        .attr('role', 'menuitem')
        .appendTo(cList);
      $('<a class="ui-all">'+ i + ': ' + item.name + '<a/>')
        .appendTo(li);
    });

How to import an Oracle database from dmp file and log file?

If you are using impdp command example from @sathyajith-bhat response:

impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;

you will need to use mandatory parameter directory and create and grant it as:

CREATE OR REPLACE DIRECTORY DMP_DIR AS 'c:\Users\USER\Downloads';
GRANT READ, WRITE ON DIRECTORY DMP_DIR TO {USER};

or use one of defined:

select * from DBA_DIRECTORIES;

My ORACLE Express 11g R2 has default named DATA_PUMP_DIR (located at {inst_dir}\app\oracle/admin/xe/dpdump/) you sill need to grant it for your user.

How can I change NULL to 0 when getting a single value from a SQL function?

ORACLE/PLSQL:

NVL FUNCTION

SELECT NVL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

This SQL statement would return 0 if the SUM(Price) returned a null value. Otherwise, it would return the SUM(Price) value.

Why do we use volatile keyword?

Consider this code,

int some_int = 100;

while(some_int == 100)
{
   //your code
}

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

volatile int some_int = 100; //note the 'volatile' qualifier now!

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.


Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

I get the same question as you you can click here :

About the question in xcode5 "no matching provisioning profiles found"

(About xcode5 ?no matching provisioning profiles found )

When I was fitting with iOS7,I get the warning like this:no matching provisioning profiles found. the reason may be that your project is in other group.

Do like this:find the file named *.xcodeproj in your protect,show the content of it.

You will see three files:

  1. project.pbxproj
  2. project.xcworkspace
  3. xcuserdata

open the first, search the uuid and delete the row.

Pass by Reference / Value in C++

My understanding of the words "If the function modifies that value, the modifications appear also within the scope of the calling function for both passing by value and by reference" is that they are an error.

Modifications made in a called function are not in scope of the calling function when passing by value.

Either you have mistyped the quoted words or they have been extracted out of whatever context made what appears to be wrong, right.

Could you please ensure you have correctly quoted your source and if there are no errors there give more of the text surrounding that statement in the source material.

Spark read file from S3 using sc.textFile ("s3n://...)

  1. Download the hadoop-aws jar from maven repository matching your hadoop version.
  2. Copy the jar to $SPARK_HOME/jars location.

Now in your Pyspark script, setup AWS Access Key & Secret Access Key.

spark.sparkContext._jsc.hadoopConfiguration().set("fs.s3.awsAccessKeyId", "ACCESS_KEY")
spark.sparkContext._jsc.hadoopConfiguration().set("fs.s3.awsSecretAccessKey", "YOUR_SECRET_ACCESSS_KEY")

// where spark is SparkSession instance

For Spark scala:

spark.sparkContext.hadoopConfiguration.set("fs.s3.awsAccessKeyId", "ACCESS_KEY")
spark.sparkContext.hadoopConfiguration.set("fs.s3.awsSecretAccessKey", "YOUR_SECRET_ACCESSS_KEY")

String split on new line, tab and some number of spaces

Just use .strip(), it removes all whitespace for you, including tabs and newlines, while splitting. The splitting itself can then be done with data_string.splitlines():

[s.strip() for s in data_string.splitlines()]

Output:

>>> [s.strip() for s in data_string.splitlines()]
['Name: John Smith', 'Home: Anytown USA', 'Phone: 555-555-555', 'Other Home: Somewhere Else', 'Notes: Other data', 'Name: Jane Smith', 'Misc: Data with spaces']

You can even inline the splitting on : as well now:

>>> [s.strip().split(': ') for s in data_string.splitlines()]
[['Name', 'John Smith'], ['Home', 'Anytown USA'], ['Phone', '555-555-555'], ['Other Home', 'Somewhere Else'], ['Notes', 'Other data'], ['Name', 'Jane Smith'], ['Misc', 'Data with spaces']]

How to read an http input stream

a complete code for reading from a webservice in two ways

public void buttonclick(View view) {
    // the name of your webservice where reactance is your method
    new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance");
}

public class GetMethodDemo extends AsyncTask<String, Void, String> {
    //see also: 
    // https://developer.android.com/reference/java/net/HttpURLConnection.html
    //writing to see:    https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
    String server_response;
    @Override
    protected String doInBackground(String... strings) {
        URL url;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
            in.close();
            Log.v("bufferv ", server_response);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.e("Response", "" + server_response);
   //assume there is a field with id editText
        EditText editText = (EditText) findViewById(R.id.editText);
        editText.setText(server_response);
    }
}

Twitter Bootstrap: Print content of modal window

I just use a bit of jQuery/javascript:

html:

<h1>Don't Print</h1>

<a data-target="#myModal" role="button" class="btn" data-toggle="modal">Launch modal</a>

<div class="modal fade hide" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"      aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
     <h3 id="myModalLabel">Modal to print</h3>
  </div>
  <div class="modal-body">
    <p>Print Me</p>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary" id="printButton">Print</button>
  </div>
</div>

js:

$('#printButton').on('click', function () {
    if ($('.modal').is(':visible')) {
        var modalId = $(event.target).closest('.modal').attr('id');
        $('body').css('visibility', 'hidden');
        $("#" + modalId).css('visibility', 'visible');
        $('#' + modalId).removeClass('modal');
        window.print();
        $('body').css('visibility', 'visible');
        $('#' + modalId).addClass('modal');
    } else {
        window.print();
    }
});

here is the fiddle

Cross-Origin Request Headers(CORS) with PHP headers

Handling CORS requests properly is a tad more involved. Here is a function that will respond more fully (and properly).

/**
 *  An example CORS-compliant method.  It will allow any GET, POST, or OPTIONS requests from any
 *  origin.
 *
 *  In a production environment, you probably want to be more restrictive, but this gives you
 *  the general idea of what is involved.  For the nitty-gritty low-down, read:
 *
 *  - https://developer.mozilla.org/en/HTTP_access_control
 *  - https://fetch.spec.whatwg.org/#http-cors-protocol
 *
 */
function cors() {
    
    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
        // you want to allow, and if so:
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
        
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        exit(0);
    }
    
    echo "You have CORS!";
}

Security Notes

When a browser wants to execute a cross-site request it first confirms that this is okay with a "pre-flight" request to the URL. By allowing CORS you are telling the browser that responses from this URL can be shared with other domains.

CORS does not protect your server. CORS attempts to protect your users by telling browsers what the restrictions should be on sharing responses with other domains. Normally this kind of sharing is utterly forbidden, so CORS is a way to poke a hole in the browser's normal security policy. These holes should be as small as possible, so always check the HTTP_ORIGIN against some kind of internal list.

There are some dangers here, especially if the data the URL serves up is normally protected. You are effectively allowing browser content that originated on some other server to read (and possibly manipulate) data on your server.

If you are going to use CORS, please read the protocol carefully (it is quite small) and try to understand what you're doing. A reference URL is given in the code sample for that purpose.

Header security

It has been observed that the HTTP_ORIGIN header is insecure, and that is true. In fact, all HTTP headers are insecure to varying meanings of the term. Unless a header includes a verifiable signature/hmac, or the whole conversation is authenticated via TLS, headers are just "something the browser has told me".

In this case, the browser is saying "an object from domain X wants to get a response from this URL. Is that okay?" The point of CORS is to be able to answer, "yes I'll allow that".

Disable browser's back button

Globally, disabling the back button is indeed bad practice. But, in certain situations, the back button functionality doesn't make sense.

Here's one way to prevent unwanted navigation between pages:

Top page (file top.php):

<?php
    session_start();
    $_SESSION[pid]++;
    echo "top page $_SESSION[pid]";
    echo "<BR><a href='secondary.php?pid=$_SESSION[pid]'>secondary page</a>";
?>

Secondary page (file secondary.php):

<?php
    session_start();
    if ($_SESSION[pid] != $_GET[pid]) 
        header("location: top.php");
    else {
        echo "secondary page $_SESSION[pid]";
        echo "<BR><a href='top.php'>top</a>";
    }
?>

The effect is to allow navigating from the top page forward to the secondary page and back (e.g. Cancel) using your own links. But, after returning to the top page the browser back button is prevented from navigating to the secondary page.

Multiple inputs on one line

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

"Integer number too large" error message for 600851475143

At compile time the number "600851475143" is represented in 32-bit integer, try long literal instead at the end of your number to get over from this problem.

Compare DATETIME and DATE ignoring time portion

You may use DateDiff and compare by day.

DateDiff(dd,@date1,@date2) > 0

It means @date2 > @date1

For example :

select DateDiff(dd, '01/01/2021 10:20:00', '02/01/2021 10:20:00') 

has the result : 1

SQL Server: IF EXISTS ; ELSE

EDIT

I want to add the reason that your IF statement seems to not work. When you do an EXISTS on an aggregate, it's always going to be true. It returns a value even if the ID doesn't exist. Sure, it's NULL, but its returning it. Instead, do this:

if exists(select 1 from table where id = 4)

and you'll get to the ELSE portion of your IF statement.


Now, here's a better, set-based solution:

update b
  set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
  on b.id = a.id
where
  b.id = yourid

This has the benefit of being able to run on the entire table rather than individual ids.

Space between two divs

DIVs inherently lack any useful meaning, other than to divide, of course.

Best course of action would be to add a meaningful class name to them, and style their individual margins in CSS.

<h1>Important Title</h1>
<div class="testimonials">...</div>
<div class="footer">...</div>

h1 {margin-bottom: 0.1em;}
div.testimonials {margin-bottom: 0.2em;}
div.footer {margin-bottom: 0;}

Can I embed a custom font in an iPhone application?

One important notice: You should use the "PostScript name" associated with the font, not its Full name or Family name. This name can often be different from the normal name of the font.

How to lazy load images in ListView in Android

I use droidQuery. There are two mechanisms for loading an image from a URL. The first (shorthand) is simply:

$.with(myView).image(url);

This can be added into an ArrayAdapter's getView(...) method very easily.


The longhand method will give a lot more control, and has options not even discussed here (such as cacheing and callbacks), but a basic implementation that specifies the output size as 200px x 200px can be found here:

$.ajax(new AjaxOptions().url(url)
    .type("GET")
    .dataType("image")
    .imageWidth(200).imageHeight(200)
    .success(new Function() {
        @Override
        public void invoke($ droidQuery, Object... params) {
            myImageView.setImageBitmap((Bitmap) params[0]);
        }
    })
    .error(new Function() {
        @Override
        public void invoke($ droidQuery, Object... params) {
            AjaxError e = (AjaxError) params[0];
            Log.e("$", "Error " + e.status + ": " + e.error);
        }
    })
);

Loop through a comma-separated shell variable

#/bin/bash   
TESTSTR="abc,def,ghij"

for i in $(echo $TESTSTR | tr ',' '\n')
do
echo $i
done

I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.

other solution is to set IFS to certain separator

Change width of select tag in Twitter Bootstrap

In bootstrap 3, it is recommended that you size inputs by wrapping them in col-**-# div tags. It seems that most things have 100% width, especially .form-control elements.

https://getbootstrap.com/docs/3.3/css/#forms-control-sizes

Run a task every x-minutes with Windows Task Scheduler

To schedule the update to be automatic you should:

  • Go to Control Panel » Administrative Tools » Scheduled Tasks
  • Create the (basic) task
  • Go to Schedule » Advanced
  • Check the box for "Repeat Task" every 10 minutes with a duration of, e.g. 24 hours or Indefinitely
  • Leave End Date unchecked

If you cannot find the Schedule settings, look under: Properties, Edit, Triggers.

How to force a view refresh without having it trigger automatically from an observable?

You can't call something on the entire viewModel, but on an individual observable you can call myObservable.valueHasMutated() to notify subscribers that they should re-evaluate. This is generally not necessary in KO, as you mentioned.

How to access random item in list?

I needed to more item instead of just one. So, I wrote this:

public static TList GetSelectedRandom<TList>(this TList list, int count)
       where TList : IList, new()
{
    var r = new Random();
    var rList = new TList();
    while (count > 0 && list.Count > 0)
    {
        var n = r.Next(0, list.Count);
        var e = list[n];
        rList.Add(e);
        list.RemoveAt(n);
        count--;
    }

    return rList;
}

With this, you can get elements how many you want as randomly like this:

var _allItems = new List<TModel>()
{
    // ...
    // ...
    // ...
}

var randomItemList = _allItems.GetSelectedRandom(10); 

How do I clear a C++ array?

If only to 0 then you can use memset:

int* a = new int[6];

memset(a, 0, 6*sizeof(int));

Function for 'does matrix contain value X?'

Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus

X = primes(20);
ismember([15 17],X)
ans =
      0    1

Since 15 is not prime, but 17 is, ismember has done its job well here.

Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.

~isempty(find(X == 15))
~isempty(find(X == 17))

or,

any(X == 15)
any(X == 17)

Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.

tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

Combine hover and click functions (jQuery)?

var hoverAndClick = function() {
    // Your actions here
} ;

$("#target").hover( hoverAndClick ).click( hoverAndClick ) ;

IF-THEN-ELSE statements in postgresql

case when field1>0 then field2/field1 else 0 end as field3

Print all but the first three columns

Cut has a --complement flag that makes it easy (and fast) to delete columns. The resulting syntax is analogous with what you want to do -- making the solution easier to read/understand. Complement also works for the case where you would like to delete non-contiguous columns.

$ foo='1 2 3 %s 5 6 7'
$ echo "$foo" | cut --complement -d' ' -f1-3
%s 5 6 7
$

SQLite Reset Primary Key Field

If you want to reset every RowId via content provider try this

rowCounter=1;
do {            
            rowId = cursor.getInt(0);
            ContentValues values;
            values = new ContentValues();
            values.put(Table_Health.COLUMN_ID,
                       rowCounter);
            updateData2DB(context, values, rowId);
            rowCounter++;

        while (cursor.moveToNext());

public static void updateData2DB(Context context, ContentValues values, int rowId) {
    Uri uri;
    uri = Uri.parseContentProvider.CONTENT_URI_HEALTH + "/" + rowId);
    context.getContentResolver().update(uri, values, null, null);
}

validation of input text field in html using javascript

function hasValue( val ) { // Return true if text input is valid/ not-empty
    return val.replace(/\s+/, '').length; // boolean
}

For multiple elements you can pass inside your input elements loop their value into that function argument.

If a user inserted one or more spaces, thanks to the regex s+ the function will return false.

Ternary operators in JavaScript without an "else"

More often, people use logical operators to shorten the statement syntax:

!defaults.slideshowWidth &&
  (defaults.slideshowWidth = obj.find('img').width() + 'px');

But in your particular case the syntax can be even simpler:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width() + 'px';

This code will return the defaults.slideshowWidth value if the defaults.slideshowWidth is evaluated to true and obj.find('img').width() + 'px' value otherwise.

See Short-Circuit Evaluation of logical operators for details.

Bootstrap button - remove outline on Chrome OS X

Here's the solution:

_x000D_
_x000D_
#sec-one{padding: 15px 0;}_x000D_
p{text-align: center;}_x000D_
/*_x000D_
* Change the color to any color you want;_x000D_
* or set to none if you don't any outline at all._x000D_
*/_x000D_
*:focus:not(a){_x000D_
    outline: 2px solid #f90d0e !important;_x000D_
    box-shadow: none !important;_x000D_
}
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
</head>_x000D_
<body>_x000D_
<section id="sec-one">_x000D_
<div class="container">_x000D_
    <div class="row">_x000D_
      <div class="col">_x000D_
        <form>_x000D_
          <fieldset class="form-group">_x000D_
            <input type="text" class="form-control" placeholder="Full Name" required>_x000D_
          </fieldset>_x000D_
           <fieldset class="form-group">_x000D_
            <input type="email" class="form-control" placeholder="Email Address" required>_x000D_
          </fieldset>_x000D_
          <fieldset class="form-group">_x000D_
            <input type="submit" class="btn btn-default" value="Sign Up">_x000D_
          </fieldset>_x000D_
          </form>_x000D_
      </div>_x000D_
    </div>_x000D_
</div>_x000D_
</section>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This works 100% hope it helps you.

IIS Request Timeout on long ASP.NET operation

Great and exhaustive answerby @Kev!

Since I did long processing only in one admin page in a WebForms application I used the code option. But to allow a temporary quick fix on production I used the config version in a <location> tag in web.config. This way my admin/processing page got enough time, while pages for end users and such kept their old time out behaviour.

Below I gave the config for you Googlers needing the same quick fix. You should ofcourse use other values than my '4 hour' example, but DO note that the session timeOut is in minutes, while the request executionTimeout is in seconds!

And - since it's 2015 already - for a NON- quickfix you should use .Net 4.5's async/await now if at all possible, instead of the .NET 2.0's ASYNC page that was state of the art when KEV answered in 2010 :).

<configuration>
    ... 
    <compilation debug="false" ...>
    ... other stuff ..

    <location path="~/Admin/SomePage.aspx">
        <system.web>
            <sessionState timeout="240" />
            <httpRuntime executionTimeout="14400" />
        </system.web>
    </location>
    ...
</configuration>

SQL: parse the first, middle and last name from a fullname field

Check this query in Athena for only one-space separated string (e.g. first name and middle name combination):

SELECT name, REVERSE( SUBSTR( REVERSE(name), 1, STRPOS(REVERSE(name), ' ') ) ) AS middle_name FROM name_table

If you expect to have two or more spaces, you can easily extend the above query.

What does "@" mean in Windows batch scripts

It means "don't echo the command to standard output".

Rather strangely,

echo off

will send echo off to the output! So,

@echo off

sets this automatic echo behaviour off - and stops it for all future commands, too.

Source: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/batch.mspx?mfr=true

Java Currency Number format

I was crazy enough to write my own function:

This will convert integer to currency format (can be modified for decimals as well):

 String getCurrencyFormat(int v){
        String toReturn = "";
        String s =  String.valueOf(v);
        int length = s.length();
        for(int i = length; i >0 ; --i){
            toReturn += s.charAt(i - 1);
            if((i - length - 1) % 3 == 0 && i != 1) toReturn += ',';
        }
        return "$" + new StringBuilder(toReturn).reverse().toString();
    }

What is the difference between "SMS Push" and "WAP Push"?

An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.

WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.

The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.

Excel formula to reference 'CELL TO THE LEFT'

Even simpler:

=indirect(address(row(), column() - 1))

OFFSET returns a reference relative to the current reference, so if indirect returns the correct reference, you don't need it.

Differences between TCP sockets and web sockets, one more time

When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.

But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.

Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.

Incomplete type is not allowed: stringstream

#include <sstream> and use the fully qualified name i.e. std::stringstream ss;

How to change default language for SQL Server?

Please try below:

DECLARE @Today DATETIME;  
SET @Today = '12/5/2007';  

SET LANGUAGE Italian;  
SELECT DATENAME(month, @Today) AS 'Month Name';  

SET LANGUAGE us_english;  
SELECT DATENAME(month, @Today) AS 'Month Name' ;  
GO  

Reference:

https://docs.microsoft.com/en-us/sql/t-sql/statements/set-language-transact-sql

Getting a "This application is modifying the autolayout engine from a background thread" error?

You get similar error message while debugging with print statements without using 'dispatch_async' So when you get that error message, its time to use

Swift 4

DispatchQueue.main.async { //code }

Swift 3

DispatchQueue.main.async(){ //code }

Earlier Swift versions

dispatch_async(dispatch_get_main_queue()){ //code }

How do I get the serial key for Visual Studio Express?

The question is about VS 2008 Express.

Microsoft's web page for registering Visual Studio 2008 Express has been dead (404) for some time, so registering it is not possible.

Instead, as a workaround, you can temporarily remove the requirement to register VS2008Exp by deleting (or renaming) the registry key:

HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration

To ensure that this is working beforehand, click Help -> register product within VS2008.

You should see text like

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 10 more days before you will be required to register it."

Close the application, delete that key, reopen, click help->register product.

The text should now say

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 30 more days before you will be required to register it."

So you have two options - delete that key manually every 30 days, or run it from a batch file that also contains a line like:

reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f

[Edit: User @i486 confirms on testing that this workaround works even after the expiration period has expired]

[Edit2: User @Wyatt8740 has a much more elegant way to prevent the value from reappearing.]

HTML text input field with currency symbol

_x000D_
_x000D_
.currencyinput {_x000D_
    border: 1px inset #ccc;_x000D_
    padding-bottom: 1px;//FOR IE & Chrome_x000D_
}_x000D_
.currencyinput input {_x000D_
    border: 0;_x000D_
}
_x000D_
<span class="currencyinput">$<input type="text" name="currency"></span>
_x000D_
_x000D_
_x000D_

How to split one string into multiple strings separated by at least one space in bash shell?

Did you try just passing the string variable to a for loop? Bash, for one, will split on whitespace automatically.

sentence="This is   a sentence."
for word in $sentence
do
    echo $word
done

 

This
is
a
sentence.

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

Working for me only after installing Python 2.7.x (not 3.x) and then npm uninstall node-sass && npm install node-sass like @Quinn Comendant said.

How to enable Google Play App Signing

I had to do following:

  1. Create an app in google play console enter image description here

2.Go to App releases -> Manage production -> Create release

3.Click continue on Google Play App Signing enter image description here

4.Create upload certificate by running "keytool -genkey -v -keystore c:\path\to\cert.keystore -alias uploadKey -keyalg RSA -keysize 2048 -validity 10000"

5.Sign your apk with generated certificate (c:\path\to\cert.keystore)

6.Upload signed apk in App releases -> Manage production -> Edit release

7.By uploading apk, certificate generated in step 4 has been added to App Signing certificates and became your signing cert for all future builds.

How to upload a file and JSON data in Postman?

Postman multipart form-data content-type

Select [Content Type] from [SHOW COLUMNS] then set content-type of "application/json" to the parameter of json text.