Programs & Examples On #Paas

paas is short for Platform-as-a-service, a category of cloud-centric services.

What is SaaS, PaaS and IaaS? With examples

IaaS, PaaS and SaaS are basically cloud computing segment.

IaaS (Infrastructure as a Service) - Infrastructure as a Service is a provision model of cloud computing in which an organization outsources the equipment used to support operations, including storage, hardware, servers and networking components. The service provider owns the equipment and is responsible for housing, running and maintaining it. The client typically pays on a per-use basis. Ex- Amazon Web Services, BlueLock, Cloudscaling and Datapipe

PaaS (Platform as a Service) - Platform as a Service is one of the GROWING sector of cloud computing. PaaS basically help developer to speed the development of app, saving money and most important innovating their applications and business instead of setting up configurations and managing things like servers and databases. In one line I can say Platform as a service (PaaS) automates the configuration, deployment and ongoing management of applications in the cloud. Ex: Heroku, EngineYard, App42 PaaS and OpenShift

SaaS (Software as a Service) - Software as a Service, SaaS is a software delivery method that provides access to software and its functions remotely as a Web-based service. Ex: Abiquo's and Akamai

Fastest way to check if a value exists in a list

You could put your items into a set. Set lookups are very efficient.

Try:

s = set(a)
if 7 in s:
  # do stuff

edit In a comment you say that you'd like to get the index of the element. Unfortunately, sets have no notion of element position. An alternative is to pre-sort your list and then use binary search every time you need to find an element.

Why is the jquery script not working?

This worked for me:

<script>
     jQuery.noConflict();
     // Use jQuery via jQuery() instead of via $()
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });  
</script>

Reason: "Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $".

Read full reason here: https://api.jquery.com/jquery.noconflict/

If this solves your issue, it's likely another library is also using $.

How to check for a valid URL in Java?

Here is way I tried and found useful,

URL u = new URL(name); // this would check for the protocol
u.toURI(); // does the extra checking required for validation of URI 

ArrayAdapter in android to create simple listview

The TextView resource id it needs is for a TextView layout file, so it won't be in the same activity.

You can create it by going to File > New > XML > XML Layout File, and enter the widget type, which is 'TextView' in the root tag field.

Source: https://www.kompulsa.com/the-simplest-way-to-implement-an-android-listview/

How do I use DateTime.TryParse with a Nullable<DateTime>?

Here is a slightly concised edition of what Jason suggested:

DateTime? d; DateTime dt;
d = DateTime.TryParse(DateTime.Now.ToString(), out dt)? dt : (DateTime?)null;

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

I think the textbox you are trying to access is not yet loaded onto the page at the time your javascript is being executed.

ie., For the Javascript to be able to read the textbox from the DOM of the page, the textbox must be available as an element. If the javascript is getting called before the textbox is written onto the page, the textbox will not be visible and so NULL is returned.

Android: how to refresh ListView contents?

In my understanding, if you want to refresh ListView immediately when data has changed, you should call notifyDataSetChanged() in RunOnUiThread().

private void updateData() {
    List<Data> newData = getYourNewData();
    mAdapter.setList(yourNewList);

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
                mAdapter.notifyDataSetChanged();
        }
    });
}

Using Selenium Web Driver to retrieve value of a HTML input

With selenium 2,

i usually write it like that :

WebElement element = driver.findElement(By.id("input_name"));
String elementval = element.getAttribute("value");

OR

String elementval = driver.findElement(By.id("input_name")).getAttribute("value");

what is reverse() in Django

The reverse() is used to adhere the django DRY principle i.e if you change the url in future then you can reference that url using reverse(urlname).

How can javascript upload a blob?

2019 Update

This updates the answers with the latest Fetch API and doesn't need jQuery.

Disclaimer: doesn't work on IE, Opera Mini and older browsers. See caniuse.

Basic Fetch

It could be as simple as:

  fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
                .then(response => console.log(response.text()))

Fetch with Error Handling

After adding error handling, it could look like:

fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
            .then(response => {
                if (response.ok) return response;
                else throw Error(`Server returned ${response.status}: ${response.statusText}`)
            })
            .then(response => console.log(response.text()))
            .catch(err => {
                alert(err);
            });

PHP Code

This is the server-side code in upload.php.

<?php    
    // gets entire POST body
    $data = file_get_contents('php://input');
    // write the data out to the file
    $fp = fopen("path/to/file", "wb");

    fwrite($fp, $data);
    fclose($fp);
?>

What is the behavior of integer division?

Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.

-5 / 2 = -2
 5 / 2 =  2

For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).

How do I vertically align something inside a span tag?

CSS vertical center image and text

I have Create one demo for vertical image center and text also i have test on firefox ,chrome,safari, internet explorer 9 and 8 too.

It is very short and easy css and html, Please check below code and you can find output on screenshort.

HTML

<div class="frame">
    <img src="capabilities_icon1.png" alt="" />
</div>

CSS

  .frame {
        height: 160px;      
        width: 160px;
        border: 1px solid red;
        white-space: nowrap;
        text-align: center; margin: 1em 0;
    }

    .frame::before {
        display: inline-block;
        height: 100%;
        vertical-align: middle;
        content:"";
    }

    img {
        background: #3A6F9A;
        vertical-align: middle;
    }

Output enter image description here

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

Update: React 16.0 introduced portals through ReactDOM.createPortal link

Update: next versions of React (Fiber: probably 16 or 17) will include a method to create portals: ReactDOM.unstable_createPortal() link


Use portals

Dan Abramov answer first part is fine, but involves a lot of boilerplate. As he said, you can also use portals. I'll expand a bit on that idea.

The advantage of a portal is that the popup and the button remain very close into the React tree, with very simple parent/child communication using props: you can easily handle async actions with portals, or let the parent customize the portal.

What is a portal?

A portal permits you to render directly inside document.body an element that is deeply nested in your React tree.

The idea is that for example you render into body the following React tree:

<div className="layout">
  <div className="outside-portal">
    <Portal>
      <div className="inside-portal">
        PortalContent
      </div>
    </Portal>
  </div>
</div>

And you get as output:

<body>
  <div class="layout">
    <div class="outside-portal">
    </div>
  </div>
  <div class="inside-portal">
    PortalContent
  </div>
</body>

The inside-portal node has been translated inside <body>, instead of its normal, deeply-nested place.

When to use a portal

A portal is particularly helpful for displaying elements that should go on top of your existing React components: popups, dropdowns, suggestions, hotspots

Why use a portal

No z-index problems anymore: a portal permits you to render to <body>. If you want to display a popup or dropdown, this is a really nice idea if you don't want to have to fight against z-index problems. The portal elements get added do document.body in mount order, which means that unless you play with z-index, the default behavior will be to stack portals on top of each others, in mounting order. In practice, it means that you can safely open a popup from inside another popup, and be sure that the 2nd popup will be displayed on top of the first, without having to even think about z-index.

In practice

Most simple: use local React state: if you think, for a simple delete confirmation popup, it's not worth to have the Redux boilerplate, then you can use a portal and it greatly simplifies your code. For such a use case, where the interaction is very local and is actually quite an implementation detail, do you really care about hot-reloading, time-traveling, action logging and all the benefits Redux brings you? Personally, I don't and use local state in this case. The code becomes as simple as:

class DeleteButton extends React.Component {
  static propTypes = {
    onDelete: PropTypes.func.isRequired,
  };

  state = { confirmationPopup: false };

  open = () => {
    this.setState({ confirmationPopup: true });
  };

  close = () => {
    this.setState({ confirmationPopup: false });
  };

  render() {
    return (
      <div className="delete-button">
        <div onClick={() => this.open()}>Delete</div>
        {this.state.confirmationPopup && (
          <Portal>
            <DeleteConfirmationPopup
              onCancel={() => this.close()}
              onConfirm={() => {
                this.close();
                this.props.onDelete();
              }}
            />
          </Portal>
        )}
      </div>
    );
  }
}

Simple: you can still use Redux state: if you really want to, you can still use connect to choose whether or not the DeleteConfirmationPopup is shown or not. As the portal remains deeply nested in your React tree, it is very simple to customize the behavior of this portal because your parent can pass props to the portal. If you don't use portals, you usually have to render your popups at the top of your React tree for z-index reasons, and usually have to think about things like "how do I customize the generic DeleteConfirmationPopup I built according to the use case". And usually you'll find quite hacky solutions to this problem, like dispatching an action that contains nested confirm/cancel actions, a translation bundle key, or even worse, a render function (or something else unserializable). You don't have to do that with portals, and can just pass regular props, since DeleteConfirmationPopup is just a child of the DeleteButton

Conclusion

Portals are very useful to simplify your code. I couldn't do without them anymore.

Note that portal implementations can also help you with other useful features like:

  • Accessibility
  • Espace shortcuts to close the portal
  • Handle outside click (close portal or not)
  • Handle link click (close portal or not)
  • React Context made available in portal tree

react-portal or react-modal are nice for popups, modals, and overlays that should be full-screen, generally centered in the middle of the screen.

react-tether is unknown to most React developers, yet it's one of the most useful tools you can find out there. Tether permits you to create portals, but will position automatically the portal, relative to a given target. This is perfect for tooltips, dropdowns, hotspots, helpboxes... If you have ever had any problem with position absolute/relative and z-index, or your dropdown going outside of your viewport, Tether will solve all that for you.

You can, for example, easily implement onboarding hotspots, that expands to a tooltip once clicked:

Onboarding hotspot

Real production code here. Can't be any simpler :)

<MenuHotspots.contacts>
  <ContactButton/>
</MenuHotspots.contacts>

Edit: just discovered react-gateway which permits to render portals into the node of your choice (not necessarily body)

Edit: it seems react-popper can be a decent alternative to react-tether. PopperJS is a library that only computes an appropriate position for an element, without touching the DOM directly, letting the user choose where and when he wants to put the DOM node, while Tether appends directly to the body.

Edit: there's also react-slot-fill which is interesting and can help solve similar problems by allowing to render an element to a reserved element slot that you put anywhere you want in your tree

jquery - Click event not working for dynamically created button

You could also create the input button in this way:

var button = '<input type="button" id="questionButton" value='+variable+'> <br />';


It might be the syntax of the Button creation that is off somehow.

How to change default JRE for all Eclipse workspaces?

My answer will overlap with amphibient's while adding on to it.

Your JAVA_HOME variable is fine, but you also need to append the following to your Path variable :

;%JAVA_HOME%\bin

This will allow your applications in your Windows environment to access your JDK. You should also restart your computer once you've added these environment variables before checking out if they work. In my case, even logging out and then back in didn't work : I had to completely restart.

If you want to check if the environment variables are set correctly, you can open up a command prompt and type >echo %JAVA_HOME and >echo %Path% to see if those variables are working correctly. While snooping around for solutions, I have also run into people claiming that they need to add quotations marks (") around the environment variables to make them work correctly ("%JAVA_HOME%"\bin) if your JAVA_HOME path includes spaces. I thought that this was my case at first, but after doing a full restart my variables seemed to work correctly without quotation marks despite the spaces.

How to repeat last command in python interpreter shell?

You didn't specify which environment. Assuming you are using IDLE.

From IDLE documentation: Command history:

Alt-p retrieves previous command matching what you have typed.
Alt-n retrieves next.
      (These are Control-p, Control-n on the Mac)
Return while cursor is on a previous command retrieves that command.
Expand word is also useful to reduce typing.

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

When would you use the different git merge strategies?

"Resolve" vs "Recursive" merge strategy

Recursive is the current default two-head strategy, but after some searching I finally found some info about the "resolve" merge strategy.

Taken from O'Reilly book Version Control with Git (Amazon) (paraphrased):

Originally, "resolve" was the default strategy for Git merges.

In criss-cross merge situations, where there is more than one possible merge basis, the resolve strategy works like this: pick one of the possible merge bases, and hope for the best. This is actually not as bad as it sounds. It often turns out that the users have been working on different parts of the code. In that case, Git detects that it's remerging some changes that are already in place and skips the duplicate changes, avoiding the conflict. Or, if these are slight changes that do cause conflict, at least the conflict should be easy for the developer to handle..

I have successfully merged trees using "resolve" that failed with the default recursive strategy. I was getting fatal: git write-tree failed to write a tree errors, and thanks to this blog post (mirror) I tried "-s resolve", which worked. I'm still not exactly sure why... but I think it was because I had duplicate changes in both trees, and resolve "skipped" them properly.

How to know if two arrays have the same values

Object equality check:JSON.stringify(array1.sort()) === JSON.stringify(array2.sort())

The above test also works with arrays of objects in which case use a sort function as documented in http://www.w3schools.com/jsref/jsref_sort.asp

Might suffice for small arrays with flat JSON schemas.

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

just reinstall your pgsql with direct version sudo apt-get install postgresql-9.5 (u must remove the package before install new one)

Have border wrap around text

The easiest way to do it is to make the display an inline block

<div id='page' style='width: 600px'>
  <h1 style='border:2px black solid; font-size:42px; display: inline-block;'>Title</h1>
</div>

if you do this it should work

How to call servlet through a JSP page

You could use <jsp:include> for this.

<jsp:include page="/servletURL" />

It's however usually the other way round. You call the servlet which in turn forwards to the JSP to display the results. Create a Servlet which does something like following in doGet() method.

request.setAttribute("result", "This is the result of the servlet call");
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);

and in /WEB-INF/result.jsp

<p>The result is ${result}</p>

Now call the Servlet by the URL which matches its <url-pattern> in web.xml, e.g. http://example.com/contextname/servletURL.

Do note that the JSP file is explicitly placed in /WEB-INF folder. This will prevent the user from opening the JSP file individually. The user can only call the servlet in order to open the JSP file.


If your actual question is "How to submit a form to a servlet?" then you just have to specify the servlet URL in the HTML form action.

<form action="servletURL" method="post">

Its doPost() method will then be called.


See also:

Pandas split DataFrame by column value

Using "groupby" and list comprehension:

Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.

DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]

accessing the separated DF like this:

ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF

accessing the column value of the separated DF like this:

ansI_chr=ans[i].chr 

How to remove the URL from the printing page?

You can remove the url dispalying on the printed document via your browser settings.You just click file->page setup->header and footer set all things as blank.if you hav ie,you just remove &U from footer textbox.hopefully this will help you

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@RequestMapping is a class level

@GetMapping is a method-level

With sprint Spring 4.3. and up things have changed. Now you can use @GetMapping on the method that will handle the http request. The class-level @RequestMapping specification is refined with the (method-level)@GetMapping annotation

Here is an example:

@Slf4j
@Controller
@RequestMapping("/orders")/* The @Request-Mapping annotation, when applied
                            at the class level, specifies the kind of requests 
                            that this controller handles*/  

public class OrderController {

@GetMapping("/current")/*@GetMapping paired with the classlevel
                        @RequestMapping, specifies that when an 
                        HTTP GET request is received for /order, 
                        orderForm() will be called to handle the request..*/

public String orderForm(Model model) {

model.addAttribute("order", new Order());

return "orderForm";
}
}

Prior to Spring 4.3, it was @RequestMapping(method=RequestMethod.GET)

Extra reading from a book authored by Craig Walls Extra reading from a book authored by Craig Walls

Draw in Canvas by finger, Android

tutorial to draw line use Bitmap, Canvas, and Paint class. draw-line-on-finger-touch and androiddraw

here one simple class to draw line using canvas as show below.

    public class TestLineView extends View {

    private Paint paint;
    private PointF startPoint, endPoint;
    private boolean isDrawing;

    public TestLineView(Context context)
    {
        super(context);
        init();
    }

    private void init()
    {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        if(isDrawing)
        {
            canvas.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, paint);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                startPoint = new PointF(event.getX(), event.getY());
                endPoint = new PointF();
                isDrawing = true;
                break;
            case MotionEvent.ACTION_MOVE:
                if(isDrawing)
                {
                    endPoint.x = event.getX();
                    endPoint.y = event.getY();
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                if(isDrawing)
                {
                    endPoint.x = event.getX();
                    endPoint.y = event.getY();
                    isDrawing = false;
                    invalidate();
                }
                break;
            default:
                break;
        }
        return true;
    }
}

How can I auto increment the C# assembly version via our CI platform (Hudson)?

I am assuming one might also do this with a text template where you create the assembly attributes in question on the fly from the environment like AssemblyVersion.tt does below.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#
var build = Environment.GetEnvironmentVariable("BUILD_NUMBER");
build = build == null ? "0" : int.Parse(build).ToString();
var revision = Environment.GetEnvironmentVariable("SVN_REVISION");
revision = revision == null ? "0" : int.Parse(revision).ToString();    
#>
using System.Reflection;
[assembly: AssemblyVersion("1.0.<#=build#>.<#=revision#>")]
[assembly: AssemblyFileVersion("1.0.<#=build#>.<#=revision#>")]

How to cast an Object to an int

Can't be done. An int is not an object, it's a primitive type. You can cast it to Integer, then get the int.

 Integer i = (Integer) o; // throws ClassCastException if o.getClass() != Integer.class

 int num = i; //Java 1.5 or higher

What's the difference between @Component, @Repository & @Service annotations in Spring?

We can answer this according to java standard

Referring to JSR-330, which is now supported by spring, you can only use @Named to define a bean (Somehow @Named=@Component). So according to this standard, there seems that there is no use to define stereotypes (like @Repository, @Service, @Controller) to categories beans.

But spring user these different annotations in different for the specific use, for example:

  1. Help developers define a better category for the competent. This categorizing may become helpful in some cases. (For example when you are using aspect-oriented, these can be a good candidate for pointcuts)
  2. @Repository annotation will add some functionality to your bean (some automatic exception translation to your bean persistence layer).
  3. If you are using spring MVC, the @RequestMapping can only be added to classes which are annotated by @Controller.

Get element inside element by class and ID - JavaScript

THe easiest way to do so is:

function findChild(idOfElement, idOfChild){
  let element = document.getElementById(idOfElement);
  return element.querySelector('[id=' + idOfChild + ']');
}

or better readable:

findChild = (idOfElement, idOfChild) => {
    let element = document.getElementById(idOfElement);
    return element.querySelector(`[id=${idOfChild}]`);
}

Configuration with name 'default' not found. Android Studio

Just a note on this question:

I had this exact error in my React Native app when trying to build to android. All you should have to do is $ npm i.

Java JDBC - How to connect to Oracle using Service Name instead of SID

When using dag instead of thin, the syntax below pointing to service name worked for me. The jdbc:thin solutions above did not work.

jdbc:dag:oracle://HOSTNAME:1521;ServiceName=SERVICE_NAME

How to change text color and console color in code::blocks?

Functions like textcolor worked in old compilers like turbo C and Dev C. In today's compilers these functions would not work. I am going to give two function SetColor and ChangeConsoleToColors. You copy paste these functions code in your program and do the following steps.The code I am giving will not work in some compilers.

The code of SetColor is -

 void SetColor(int ForgC)
 {
     WORD wColor;

      HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
      CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
                 //Mask out all but the background attribute, and add in the forgournd     color
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
 }

To use this function you need to call it from your program. For example I am taking your sample program -

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <dos.h>
#include <dir.h>

int main(void)
{
  SetColor(4);
  printf("\n \n \t This text is written in Red Color \n ");
  getch();
  return 0;
}

void SetColor(int ForgC)
 {
 WORD wColor;

  HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                 //Mask out all but the background attribute, and add in the forgournd color
      wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
      SetConsoleTextAttribute(hStdOut, wColor);
 }
 return;
}

When you run the program you will get the text color in RED. Now I am going to give you the code of each color -

Name         | Value
             |
Black        |   0
Blue         |   1
Green        |   2
Cyan         |   3
Red          |   4
Magenta      |   5
Brown        |   6
Light Gray   |   7
Dark Gray    |   8
Light Blue   |   9
Light Green  |   10
Light Cyan   |   11
Light Red    |   12
Light Magenta|   13
Yellow       |   14
White        |   15

Now I am going to give the code of ChangeConsoleToColors. The code is -

void ClearConsoleToColors(int ForgC, int BackC)
 {
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
  DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
}

In this function you pass two numbers. If you want normal colors just put the first number as zero and the second number as the color. My example is -

#include <windows.h>          //header file for windows
#include <stdio.h>

void ClearConsoleToColors(int ForgC, int BackC);

int main()
{
ClearConsoleToColors(0,15);
Sleep(1000);
return 0;
}
void ClearConsoleToColors(int ForgC, int BackC)
{
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
 DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
} 

In this case I have put the first number as zero and the second number as 15 so the console color will be white as the code for white is 15. This is working for me in code::blocks. Hope it works for you too.

(HTML) Download a PDF file instead of opening them in browser when clicked

Without html5 attribute one can achieve this by using php:

Create php file named download.php with this code:

<?php
ob_start();
$file = "yourPDF.pdf"

if (file_exists($file)) 
{
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit();
}

Now if you want to automatically start downloading pdf write this javascript:

<script>window.location = "download.php";</script>

If you want this to work on a link, use this...

<a href='javascript:window.location = "download.php"'>
    Download it!
</a>

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

The Key is the AssemblyResolve event raised by the AppDomain.

[STAThread]
static void Main(string[] args)
{
    fileDialog.ShowDialog();
    string fileName = fileDialog.FileName;
    if (string.IsNullOrEmpty(fileName) == false)
    {
        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        if (Directory.Exists(@"c:\Provisioning\") == false)
            Directory.CreateDirectory(@"c:\Provisioning\");

        assemblyDirectory = Path.GetDirectoryName(fileName);
        Assembly loadedAssembly = Assembly.LoadFile(fileName);

        List<Type> assemblyTypes = loadedAssembly.GetTypes().ToList<Type>();

        foreach (var type in assemblyTypes)
        {
            if (type.IsInterface == false)
            {
                StreamWriter jsonFile = File.CreateText(string.Format(@"c:\Provisioning\{0}.json", type.Name));
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                jsonFile.WriteLine(serializer.Serialize(Activator.CreateInstance(type)));
                jsonFile.Close();
            }
        }
    }
}

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string[] tokens = args.Name.Split(",".ToCharArray());
    System.Diagnostics.Debug.WriteLine("Resolving : " + args.Name);
    return Assembly.LoadFile(Path.Combine(new string[]{assemblyDirectory,tokens[0]+ ".dll"}));
}

iterate through a map in javascript

Functional Approach for ES6+

If you want to take a more functional approach to iterating over the Map object, you can do something like this

const myMap = new Map() 
myMap.forEach((value, key) => {
    console.log(value, key)
})

Running a simple shell script as a cronjob

Specify complete path and grant proper permission to scriptfile. I tried following script file to run through cron:

#!/bin/bash
/bin/mkdir /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/crondir

And crontab command is

* * * * * /bin/bash /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/test.sh

It worked for me.

Adding a newline into a string in C#

You can add a new line character after the @ symbol like so:

string newString = oldString.Replace("@", "@\n");  

You can also use the NewLine property in the Environment Class (I think it is Environment).

Read large files in Java

To save memory, do not unnecessarily store/duplicate the data in memory (i.e. do not assign them to variables outside the loop). Just process the output immediately as soon as the input comes in.

It really doesn't matter whether you're using BufferedReader or not. It will not cost significantly much more memory as some implicitly seem to suggest. It will at highest only hit a few % from performance. The same applies on using NIO. It will only improve scalability, not memory use. It will only become interesting when you've hundreds of threads running on the same file.

Just loop through the file, write every line immediately to other file as you read in, count the lines and if it reaches 100, then switch to next file, etcetera.

Kickoff example:

String encoding = "UTF-8";
int maxlines = 100;
BufferedReader reader = null;
BufferedWriter writer = null;

try {
    reader = new BufferedReader(new InputStreamReader(new FileInputStream("/bigfile.txt"), encoding));
    int count = 0;
    for (String line; (line = reader.readLine()) != null;) {
        if (count++ % maxlines == 0) {
            close(writer);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/smallfile" + (count / maxlines) + ".txt"), encoding));
        }
        writer.write(line);
        writer.newLine();
    }
} finally {
    close(writer);
    close(reader);
}

How do I get the position selected in a RecyclerView?

@Override
public void onClick(View v) {
     int pos = getAdapterPosition();
}

Simple as that, on ViewHolder

How to use OR condition in a JavaScript IF statement?

You can use Like

if(condition1 || condition2 || condition3 || ..........)
{       
     enter code here
}

Convert a Unicode string to an escaped ASCII string

string StringFold(string input, Func<char, string> proc)
{
  return string.Concat(input.Select(proc).ToArray());
}

string FoldProc(char input)
{
  if (input >= 128)
  {
    return string.Format(@"\u{0:x4}", (int)input);
  }
  return input.ToString();
}

string EscapeToAscii(string input)
{
  return StringFold(input, FoldProc);
}

TypeError: $.browser is undefined

I did solved using this jquery for Github

<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>

Please Refer this link for more info. https://github.com/Studio-42/elFinder/issues/469

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Changing default encoding of Python?

There is an insightful blog post about it.

See https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/.

I paraphrase its content below.

In python 2 which was not as strongly typed regarding the encoding of strings you could perform operations on differently encoded strings, and succeed. E.g. the following would return True.

u'Toshio' == 'Toshio'

That would hold for every (normal, unprefixed) string that was encoded in sys.getdefaultencoding(), which defaulted to ascii, but not others.

The default encoding was meant to be changed system-wide in site.py, but not somewhere else. The hacks (also presented here) to set it in user modules were just that: hacks, not the solution.

Python 3 did changed the system encoding to default to utf-8 (when LC_CTYPE is unicode-aware), but the fundamental problem was solved with the requirement to explicitly encode "byte"strings whenever they are used with unicode strings.

How can I start an Activity from a non-Activity class?

You can define a context for your application say ExampleContext which will hold the context of your application and then use it to instantiate an activity like this:

var intent = new Intent(Application.ApplicationContext, typeof(Activity2));
intent.AddFlags(ActivityFlags.NewTask);
Application.ApplicationContext.StartActivity(intent);

Please bear in mind that this code is written in C# as I use MonoDroid, but I believe it is very similar to Java. For how to create an ApplicationContext look at this thread

This is how I made my Application Class

    [Application]
    public class Application : Android.App.Application, IApplication
    {
        public Application(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
        {

        }
        public object MyObject { get; set; }
    }

Basic text editor in command prompt?

I want to add that it is very strange to introduce Core and Nano servers without native console full-featured editor. Like others I`ll recommend to use vim or nano. But my suggestion is to install it via OneGet (require WMF5)! They both are presented in Chocolatey repository so installation is simple and fast:


PS C:> Find-Package -Name vim | Format-Table -AutoSize
Name Version Status    ProviderName Source     Summary
---- ------- ------    ------------ ------     -------
vim  7.4.638 Available Chocolatey   chocolatey Vim is an advanced text editor...

PS C:> Install-Package vim

How to get a Docker container's IP address from the host

I use this simple way

docker exec -it <container id or name> hostname -i

e.g

ubuntu@myhost:~$ docker exec -it 3d618ac670fe hostname -i
10.0.1.5

How do I save a String to a text file using Java?

In Java 11 the java.nio.file.Files class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default:

Files.writeString(Path.of("my", "path"), "My String");

And the second method (see JavaDoc here) allows to specify an individual charset:

Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);

Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one:

Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);

Configuring user and password with Git Bash

If the git bash is not working properly due to recently changed password.

You could open the Git GUI, and clone from there. It will ask for password, once entered, you can close the GIT GUI window.

Now the git bash will work perfectly.

How do I include a file over 2 directories back?

following are ways to access your different directories:-

./ = Your current directory
../ = One directory lower
../../ = Two directories lower
../../../ = Three directories lower

Access: Move to next record until EOF

If you want cmd buttons that loop through the form's records, try adding this code to your cmdNext_Click and cmdPrevious_Click VBA. I have found it works well and copes with BOF / EOF issues:

On Error Resume Next

DoCmd.GoToRecord , , acNext

On Error Goto 0


On Error Resume Next

DoCmd.GoToRecord , , acPrevious

On Error Goto 0

Good luck! PT

Getting the base url of the website and globally passing it to twig in Symfony 2

Why do you need to get this root url ? Can't you generate directly absolute URL's ?

{{ url('_demo_hello', { 'name': 'Thomas' }) }}

This Twig code will generate the full http:// url to the _demo_hello route.

In fact, getting the base url of the website is only getting the full url of the homepage route :

{{ url('homepage') }}

(homepage, or whatever you call it in your routing file).

JSON formatter in C#?

Just use JsonDocument and Utf8JsonWriter. No third-party library required. No target object for deserialization for jsonString required.

using System.IO;
using System.Text;
using System.Text.Json;

// other code ...

public string Prettify(string jsonString)
{
    using var stream = new MemoryStream();
    var document = JsonDocument.Parse(jsonString);
    var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
    document.WriteTo(writer);
    writer.Flush();
    return Encoding.UTF8.GetString(stream.ToArray());
}

Is there a way to return a list of all the image file names from a folder using only Javascript?

Although you can run FTP commands using WebSockets, the simpler solution is listing your files using opendir in server side (PHP), and "spitting" it into the HTML source-code, so it will be available to client side.

The following code will do just that,

Optionally -

  • use <a> tag to present a link.
  • query for more information using server side (PHP),

    for example a file size,

PHP filesize TIP:   also you can easily overcome the 2GB limit of PHP's filesize using: AJAX + HEAD request + .htaccess rule to allow Content-Length access from client-side.

<?php
  /* taken from: https://github.com/eladkarako/download.eladkarako.com */

  $path = 'resources';
  $files = [];
  $handle = @opendir('./' . $path . '/');

  while ($file = @readdir($handle)) 
    ("." !== $file && ".." !== $file) && array_push($files, $file);
  @closedir($handle);
  sort($files); //uksort($files, "strnatcasecmp");

  $files = json_encode($files);

  unset($handle,$ext,$file,$path);
?>
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <div data-container></div>
  <script>
    /* you will see (for example): 'var files = ["1.bat","1.exe","1.txt"];' if your folder containes those 1.bat 1.exe 1.txt files, it will be sorted too! :) */

    var files = <?php echo $files; ?>;

    files = files.map(function(file){
      return '<a data-ext="##EXT##" download="##FILE##" href="http://download.eladkarako.com/resources/##FILE##">##FILE##</a>'
        .replace(/##FILE##/g,       file)
        .replace(/##EXT##/g,        file.split('.').slice(-1) )
        ;
    }).join("\n<br/>\n");

    document.querySelector('[data-container]').innerHTML = files;
  </script>

</body>
</html>

DOM result will look like that:

<html lang="en-US" dir="ltr"><head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <div data-container="">
    <a data-ext="bat" download="1.bat" href="http://download.eladkarako.com/resources/1.bat">1.bat</a>
    <br/>
    <a data-ext="exe" download="1.exe" href="http://download.eladkarako.com/resources/1.exe">1.exe</a>
    <br/>
    <a data-ext="txt" download="1.txt" href="http://download.eladkarako.com/resources/1.txt">1.txt</a>
    <br/>
  </div>
  <script>
    var files = ["1.bat","1.exe","1.txt"];

    files = files.map(function(file){
      return '<a data-ext="##EXT##" download="##FILE##" href="http://download.eladkarako.com/resources/##FILE##">##FILE##</a>'
        .replace(/##FILE##/g,       file)
        .replace(/##EXT##/g,        file.split('.').slice(-1) )
        ;
    }).join("\n<br/>\n");

    document.querySelector('[data-container').innerHTML = files;
  </script>


</body></html>

How to concatenate two strings in C++?

If you were programming in C, then assuming name really is a fixed-length array like you say, you have to do something like the following:

char filename[sizeof(name) + 4];
strcpy (filename, name) ;
strcat (filename, ".txt") ;
FILE* fp = fopen (filename,...

You see now why everybody recommends std::string?

Display an array in a readable/hierarchical format

Instead of

print_r($data);

try

print "<pre>";
print_r($data);
print "</pre>";

How do I correctly clean up a Python object?

I'd recommend using Python's with statement for managing resources that need to be cleaned up. The problem with using an explicit close() statement is that you have to worry about people forgetting to call it at all or forgetting to place it in a finally block to prevent a resource leak when an exception occurs.

To use the with statement, create a class with the following methods:

  def __enter__(self)
  def __exit__(self, exc_type, exc_value, traceback)

In your example above, you'd use

class Package:
    def __init__(self):
        self.files = []

    def __enter__(self):
        return self

    # ...

    def __exit__(self, exc_type, exc_value, traceback):
        for file in self.files:
            os.unlink(file)

Then, when someone wanted to use your class, they'd do the following:

with Package() as package_obj:
    # use package_obj

The variable package_obj will be an instance of type Package (it's the value returned by the __enter__ method). Its __exit__ method will automatically be called, regardless of whether or not an exception occurs.

You could even take this approach a step further. In the example above, someone could still instantiate Package using its constructor without using the with clause. You don't want that to happen. You can fix this by creating a PackageResource class that defines the __enter__ and __exit__ methods. Then, the Package class would be defined strictly inside the __enter__ method and returned. That way, the caller never could instantiate the Package class without using a with statement:

class PackageResource:
    def __enter__(self):
        class Package:
            ...
        self.package_obj = Package()
        return self.package_obj

    def __exit__(self, exc_type, exc_value, traceback):
        self.package_obj.cleanup()

You'd use this as follows:

with PackageResource() as package_obj:
    # use package_obj

jQuery equivalent to Prototype array.last()

Why not just use simple javascript?

var array=[1,2,3,4];
var lastEl = array[array.length-1];

You can write it as a method too, if you like (assuming prototype has not been included on your page):

Array.prototype.last = function() {return this[this.length-1];}

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

curl_init() function not working

In my case, in Xubuntu, I had to install libcurl3 libcurl3-dev libraries. With this command everything worked:

sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

Regex for string contains?

Assuming regular PCRE-style regex flavors:

If you want to check for it as a single, full word, it's \bTest\b, with appropriate flags for case insensitivity if desired and delimiters for your programming language. \b represents a "word boundary", that is, a point between characters where a word can be considered to start or end. For example, since spaces are used to separate words, there will be a word boundary on either side of a space.

If you want to check for it as part of the word, it's just Test, again with appropriate flags for case insensitivity. Note that usually, dedicated "substring" methods tend to be faster in this case, because it removes the overhead of parsing the regex.

jQuery - simple input validation - "empty" and "not empty"

    jQuery("#input").live('change', function() {
        // since we check more than once against the value, place it in a var.
        var inputvalue = $("#input").attr("value");

        // if it's value **IS NOT** ""
        if(inputvalue !== "") {
            jQuery(this).css('outline', 'solid 1px red'); 
        }   

        // else if it's value **IS** ""
        else if(inputvalue === "") {
            alert('empty'); 
        }

    });

How to get Django and ReactJS to work together?

Hoping to provide a more nuanced answer than any of the ones here, especially as some things have changed since this was originally asked ~4 years ago, and because many of the top-voted answers claiming that you have to set this up as two separate applications are not accurate.

You have two primary architecture options:

  1. A completely decoupled client/server approach using something like create-react-app and Django REST Framework
  2. A hybrid architecture where you set up a React build pipeline (likely using webpack) and then include the compiled files as static files in your Django templates.

These might look something like this:

Option 1 (Client/Server Architecture):

Client / Server Architecture

Option 2 (Hybrid Architecture):

Hybrid Architecture

The decision between these two will depend on your / your team's experience, as well as the complexity of your UI. The first option is good if you have a lot of JS experience, want to keep your front-end / back-end developers separate, or want to write your entire application as a React single-page-app. The second option is generally better if you are more familiar with Django and want to move quickly while also using React for some parts of your app. I find it's a particularly good fit for full-stack solo-developers.

There is a lot more information in the series "Modern JavaScript for Django Developers", including choosing your architecture, integrating your JS build into a Django project and building a single-page React app.

Full disclosure, I'm the author of that series.

How to copy a folder via cmd?

xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c

should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).

For reference about the arguments: http://ss64.com/nt/xcopy.html

How to install wget in macOS?

I update mac to Sierra , 10.12.3

My wget stop working.

When I tried to install by typing

brew install wget --with-libressl

I got the following warning

Warning: wget-1.19.1 already installed, it's just not linked.

Then tried to unsintall by typing

brew uninstall wget --with-libressl

Then I reinstalled by typing

brew install wget --with-libressl

Finally I got it worked.Thank God!

What is the correct way to declare a boolean variable in Java?

As stated by Levon, this is not mandatory as stated in the docs: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

This is probably either an habit from other languages that don't guarantee primitive data types default values.

How to force a hover state with jQuery?

You will have to use a class, but don't worry, it's pretty simple. First we'll assign your :hover rules to not only apply to physically-hovered links, but also to links that have the classname hovered.

a:hover, a.hovered { color: #ccff00; }

Next, when you click #btn, we'll toggle the .hovered class on the #link.

$("#btn").click(function() {
   $("#link").toggleClass("hovered");
});

If the link has the class already, it will be removed. If it doesn't have the class, it will be added.

How to escape JSON string?

Building on the answer by Dejan, what you can do is import System.Web.Helpers .NET Framework assembly, then use the following function:

static string EscapeForJson(string s) {
  string quoted = System.Web.Helpers.Json.Encode(s);
  return quoted.Substring(1, quoted.Length - 2);
}

The Substring call is required, since Encode automatically surrounds strings with double quotes.

How to create a .NET DateTime from ISO 8601 format

This solution makes use of the DateTimeStyles enumeration, and it also works with Z.

DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);

This prints the solution perfectly.

Check if an object belongs to a class in Java

Use the instanceof operator:

if(a instanceof MyClass)
{
    //do something
}

Passing parameter to controller action from a Html.ActionLink

You are using incorrect overload. You should use this overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
) 

And the correct code would be

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

Web scraping with Java

Look at an HTML parser such as TagSoup, HTMLCleaner or NekoHTML.

How may I align text to the left and text to the right in the same line?

Add span on each or group of words you want to align left or right. then add id or class on the span such as:

<h3>
<span id = "makeLeft"> Left Text</span>
<span id = "makeRight"> Right Text</span>
</h3>

CSS-

#makeLeft{
float: left;
}

#makeRight{
float: right;
}

ALTER TABLE on dependent column

If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:

ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]

For more info see the comments by the brilliant Aaron Bertrand on this answer.

Is module __file__ attribute absolute or relative?

Late simple example:

from os import path, getcwd, chdir

def print_my_path():
    print('cwd:     {}'.format(getcwd()))
    print('__file__:{}'.format(__file__))
    print('abspath: {}'.format(path.abspath(__file__)))

print_my_path()

chdir('..')

print_my_path()

Under Python-2.*, the second call incorrectly determines the path.abspath(__file__) based on the current directory:

cwd:     C:\codes\py
__file__:cwd_mayhem.py
abspath: C:\codes\py\cwd_mayhem.py
cwd:     C:\codes
__file__:cwd_mayhem.py
abspath: C:\codes\cwd_mayhem.py

As noted by @techtonik, in Python 3.4+, this will work fine since __file__ returns an absolute path.

Foreign keys in mongo?

How to design table like this in mongodb?

First, to clarify some naming conventions. MongoDB uses collections instead of tables.

I think there are no foreign keys!

Take the following model:

student
{ 
  _id: ObjectId(...),
  name: 'Jane',
  courses: [
    { course: 'bio101', mark: 85 },
    { course: 'chem101', mark: 89 }
  ]
}

course
{
  _id: 'bio101',
  name: 'Biology 101',
  description: 'Introduction to biology'
}

Clearly Jane's course list points to some specific courses. The database does not apply any constraints to the system (i.e.: foreign key constraints), so there are no "cascading deletes" or "cascading updates". However, the database does contain the correct information.

In addition, MongoDB has a DBRef standard that helps standardize the creation of these references. In fact, if you take a look at that link, it has a similar example.

How can I solve this task?

To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.

Lumen: get URL parameter in a Blade view

As per official documentation 8.x

We use the helper request

The request function returns the current request instance or obtains an input field's value from the current request:

$request = request();

$value = request('key', $default);

the value of request is an array you can simply retrieve your input using the input key as follow

$id = request()->id; //for http://locahost:8000/example?id=10

Case insensitive 'Contains(string)'

OrdinalIgnoreCase, CurrentCultureIgnoreCase or InvariantCultureIgnoreCase?

Since this is missing, here are some recommendations about when to use which one:

Dos

  • Use StringComparison.OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.
  • Use StringComparison.OrdinalIgnoreCase comparisons for increased speed.
  • Use StringComparison.CurrentCulture-based string operations when displaying the output to the user.
  • Switch current use of string operations based on the invariant culture to use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase when the comparison is
    linguistically irrelevant (symbolic, for example).
  • Use ToUpperInvariant rather than ToLowerInvariant when normalizing strings for comparison.

Don'ts

  • Use overloads for string operations that don't explicitly or implicitly specify the string comparison mechanism.
  • Use StringComparison.InvariantCulture -based string
    operations in most cases; one of the few exceptions would be
    persisting linguistically meaningful but culturally-agnostic data.

Based on these rules you should use:

string title = "STRING";
if (title.IndexOf("string", 0, StringComparison.[YourDecision]) != -1)
{
    // The string exists in the original
}

whereas [YourDecision] depends on the recommendations from above.

link of source: http://msdn.microsoft.com/en-us/library/ms973919.aspx

Get JSF managed bean by name in any Servlet related class

In a servlet based artifact, such as @WebServlet, @WebFilter and @WebListener, you can grab a "plain vanilla" JSF @ManagedBean @RequestScoped by:

Bean bean = (Bean) request.getAttribute("beanName");

and @ManagedBean @SessionScoped by:

Bean bean = (Bean) request.getSession().getAttribute("beanName");

and @ManagedBean @ApplicationScoped by:

Bean bean = (Bean) getServletContext().getAttribute("beanName");

Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return null. You'd then need to manually create the bean and use setAttribute("beanName", bean).


If you're able to use CDI @Named instead of the since JSF 2.3 deprecated @ManagedBean, then it's even more easy, particularly because you don't anymore need to manually create the beans:

@Inject
private Bean bean;

Note that this won't work when you're using @Named @ViewScoped because the bean can only be identified by JSF view state and that's only available when the FacesServlet has been invoked. So in a filter which runs before that, accessing an @Injected @ViewScoped will always throw ContextNotActiveException.


Only when you're inside @ManagedBean, then you can use @ManagedProperty:

@ManagedProperty("#{bean}")
private Bean bean;

Note that this doesn't work inside a @Named or @WebServlet or any other artifact. It really works inside @ManagedBean only.


If you're not inside a @ManagedBean, but the FacesContext is readily available (i.e. FacesContext#getCurrentInstance() doesn't return null), you can also use Application#evaluateExpressionGet():

FacesContext context = FacesContext.getCurrentInstance();
Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);

which can be convenienced as follows:

@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
    FacesContext context = FacesContext.getCurrentInstance();
    return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}

and can be used as follows:

Bean bean = findBean("bean");

See also:

How to navigate back to the last cursor position in Visual Studio Code?

I am on Mac OSX, so I can't answer for windows users:

I added a custom keymap entry and set it to Ctrl+? + Ctrl+?, while the original default is Ctrl+- and Ctrl+Shift+- (which translates to Ctrl+ß and Ctrl+Shift+ß on my german keyboard).

One can simply modify it in the user keymap settings:

{ "key": "ctrl+left",  "command": "workbench.action.navigateBack" },
{ "key": "ctrl+right", "command": "workbench.action.navigateForward" }

For the accepted answer I actually wonder :) Alt+? / Alt+? jumps wordwise for me (which is kinda standard in all editors). Did they really do this mapping for the windows version?

How to find the length of an array list?

System.out.println(myList.size());

Since no elements are in the list

output => 0

myList.add("newString");  // use myList.add() to insert elements to the arraylist
System.out.println(myList.size());

Since one element is added to the list

output => 1

HTML5 event handling(onfocus and onfocusout) using angular 2

If you want to catch the focus event dynamiclly on every input on your component :

import { AfterViewInit, Component, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {

  constructor(private el: ElementRef) {
  }

  ngAfterViewInit() {
       // document.getElementsByTagName('input') : to gell all Docuement imputs
       const inputList = [].slice.call((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
        inputList.forEach((input: HTMLElement) => {
            input.addEventListener('focus', () => {
                input.setAttribute('placeholder', 'focused');
            });
            input.addEventListener('blur', () => {
                input.removeAttribute('placeholder');
            });
        });
    }
}

Checkout the full code here : https://stackblitz.com/edit/angular-93jdir

Get root password for Google Cloud Engine VM

I had the same problem. Even after updating the password using sudo passwd it was not working. I had to give "multiple" roles for my user through IAM & Admin Refer Screen Shot on IAM & Admin screen of google cloud

After that i restarted the VM. Then again changed the password and then it worked.

user1@sap-hanaexpress-public-1-vm:~> sudo passwd
New password: 
Retype new password: 
passwd: password updated successfully
user1@sap-hanaexpress-public-1-vm:~> su
Password: 
sap-hanaexpress-public-1-vm:/home/user1 # whoami
root
sap-hanaexpress-public-1-vm:/home/user1 #

How do you unit test private methods?

I tend not to use compiler directives because they clutter things up quickly. One way to mitigate it if you really need them is to put them in a partial class and have your build ignore that .cs file when making the production version.

How to import a module in Python with importlib.import_module

And don't forget to create a __init__.py with each folder/subfolder (even if they are empty)

Kendo grid date column not formatting

I found this piece of information and got it to work correctly. The data given to me was in string format so I needed to parse the string using kendo.parseDate before formatting it with kendo.toString.

columns: [
    {
        field: "FirstName",
        title: "FIRST NAME"
    },
    {
        field: "LastName",
        title: "LAST NAME"
    },
    {
        field: "DateOfBirth",
        title: "DATE OF BIRTH",
        template: "#= kendo.toString(kendo.parseDate(DateOfBirth, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
    },
...


References:

  1. format-date-in-grid
  2. jsfiddle
  3. kendo ui date formatting

Elegant way to create empty pandas DataFrame with NaN of type float

You could specify the dtype directly when constructing the DataFrame:

>>> df = pd.DataFrame(index=range(0,4),columns=['A'], dtype='float')
>>> df.dtypes
A    float64
dtype: object

Specifying the dtype forces Pandas to try creating the DataFrame with that type, rather than trying to infer it.

How to print the number of characters in each line of a text file

I've tried the other answers listed above, but they are very far from decent solutions when dealing with large files -- especially once a single line's size occupies more than ~1/4 of available RAM.

Both bash and awk slurp the entire line, even though for this problem it's not needed. Bash will error out once a line is too long, even if you have enough memory.

I've implemented an extremely simple, fairly unoptimized python script that when tested with large files (~4 GB per line) doesn't slurp, and is by far a better solution than those given.

If this is time critical code for production, you can rewrite the ideas in C or perform better optimizations on the read call (instead of only reading a single byte at a time), after testing that this is indeed a bottleneck.

Code assumes newline is a linefeed character, which is a good assumption for Unix, but YMMV on Mac OS/Windows. Be sure the file ends with a linefeed to ensure the last line character count isn't overlooked.

from sys import stdin, exit

counter = 0
while True:
    byte = stdin.buffer.read(1)
    counter += 1
    if not byte:
        exit()
    if byte == b'\x0a':
        print(counter-1)
        counter = 0

Indentation Error in Python

In Notepad++

View --->Show Symbols --->Show White Spaces and Tabs(select)

replace all tabs with spaces.

How do you determine what technology a website is built on?

Most ASP.NET sites are easy to identify from the .aspx in the URLs. There are also telltale signs in the HTML source, like a hidden form field named __VIEWSTATE or the WebResource.axd JavaScript. HTML elements will often have id attributes starting with something like _ctl0.

Rails sites will usually include stylesheets from /stylesheets and JavaScript files from /javascripts and each URL will usually have a query string containing a timestamp to thwart caching. Form fields will often follow the naming convention of model_name[attribute_name].

Background images: how to fill whole div if image is small and vice versa

Rather than giving background-size:100%;
We can give background-size:contain;
Check out this for different options avaliable: http://www.css3.info/preview/background-size/

Twitter API returns error 215, Bad Authentication Data

This might help someone who use Zend_Oauth_Client to work with twitter api. This working config:

$accessToken = new Zend_Oauth_Token_Access();
$accessToken->setToken('accessToken');
$accessToken->setTokenSecret('accessTokenSecret');

$client = $accessToken->getHttpClient(array(
    'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
    'version' => '1.0', // it was 1.1 and I got 215 error.
    'signatureMethod' => 'HMAC-SHA1',
    'consumerKey' => 'foo',
    'consumerSecret' => 'bar',
    'requestTokenUrl' => 'https://api.twitter.com/oauth/request_token',
    'authorizeUrl' => 'https://api.twitter.com/oauth/authorize',
    'accessTokenUrl' => 'https://api.twitter.com/oauth/access_token',
    'timeout' => 30
));

It look like twitter api 1.0 allows oauth version to be 1.1 and 1.0, where twitter api 1.1 require only oauth version to be 1.0.

P.S We do not use Zend_Service_Twitter as it does not allow send custom params on status update.

Passing data between different controller action methods

Personally I don't like to use TempData, but I prefer to pass a strongly typed object as explained in Passing Information Between Controllers in ASP.Net-MVC.

You should always find a way to make it explicit and expected.

Run AVD Emulator without Android Studio

Assuming you've got Android Studio installed, and SDK in your PATH, it's:

emulator -avd avd_name

To get a list of AVD names, run:

emulator -list-avds

Source: https://developer.android.com/studio/run/emulator-commandline.html

How to add reference to a method parameter in javadoc?

As you can see in the Java Source of the java.lang.String class:

/**
 * Allocates a new <code>String</code> that contains characters from
 * a subarray of the character array argument. The <code>offset</code>
 * argument is the index of the first character of the subarray and
 * the <code>count</code> argument specifies the length of the
 * subarray. The contents of the subarray are copied; subsequent
 * modification of the character array does not affect the newly
 * created string.
 *
 * @param      value    array that is the source of characters.
 * @param      offset   the initial offset.
 * @param      count    the length.
 * @exception  IndexOutOfBoundsException  if the <code>offset</code>
 *               and <code>count</code> arguments index characters outside
 *               the bounds of the <code>value</code> array.
 */
public String(char value[], int offset, int count) {
    if (offset < 0) {
        throw new StringIndexOutOfBoundsException(offset);
    }
    if (count < 0) {
        throw new StringIndexOutOfBoundsException(count);
    }
    // Note: offset or count might be near -1>>>1.
    if (offset > value.length - count) {
        throw new StringIndexOutOfBoundsException(offset + count);
    }

    this.value = new char[count];
    this.count = count;
    System.arraycopy(value, offset, this.value, 0, count);
}

Parameter references are surrounded by <code></code> tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).

Select rows which are not present in other table

A.) The command is NOT EXISTS, you're missing the 'S'.

B.) Use NOT IN instead

SELECT ip 
  FROM login_log 
  WHERE ip NOT IN (
    SELECT ip
    FROM ip_location
  )
;

How do you stop MySQL on a Mac OS install?

mysql> show variables where variable_name like '%dir%';

| datadir | /opt/local/var/db/mysql5/ |

The application was unable to start correctly (0xc000007b)

I tried all the things specified here and found yet another answer. I had to compile my application with 32-bit DLLs. I had built the libraries both in 32-bit and 64-bit but had my PATH set to 64-bit libraries. After I recompiled my application (with a number of changes in my code as well) I got this dreaded error and struggled for two days. Finally, after trying a number of other things, I changed my PATH to have the 32-bit DLLs before the 64-bit DLLs (they have the same names). And it worked. I am just adding it here for completeness.

How to update/refresh specific item in RecyclerView

I got to solve this issue by catching the position of the item that needed to be modified and then in the adapter call

public void refreshBlockOverlay(int position) {
    notifyItemChanged(position);
}

, this will call onBindViewHolder(ViewHolder holder, int position) for this specific item at this specific position.

Formatting PowerShell Get-Date inside string

"This is my string with date in specified format $($theDate.ToString('u'))"

or

"This is my string with date in specified format $(Get-Date -format 'u')"

The sub-expression ($(...)) can include arbitrary expressions calls.

MSDN Documents both standard and custom DateTime format strings.

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

how to write value into cell with vba code without auto type conversion?

Cells(1,1).Value2 = "'123,456"

note the single apostrophe before the number - this will signal to excel that whatever follows has to be interpreted as text.

How to draw an overlay on a SurfaceView used by Camera on Android?

SurfaceView probably does not work like a regular View in this regard.

Instead, do the following:

  1. Put your SurfaceView inside of a FrameLayout or RelativeLayout in your layout XML file, since both of those allow stacking of widgets on the Z-axis
  2. Move your drawing logic into a separate custom View class
  3. Add an instance of the custom View class to the layout XML file as a child of the FrameLayout or RelativeLayout, but have it appear after the SurfaceView

This will cause your custom View class to appear to float above the SurfaceView.

See here for a sample project that layers popup panels above a SurfaceView used for video playback.

How to check for an empty object in an AngularJS view

please try this way with filter

angular.module('myApp')
    .filter('isEmpty', function () {
        var bar;
        return function (obj) {
            for (bar in obj) {
                if (obj.hasOwnProperty(bar)) {
                    return false;
                }
            }
            return true;
        };
    });

usage:

 <p ng-hide="items | isEmpty">Some Content</p>

Via from : Checking if object is empty, works with ng-show but not from controller?

How to change JAVA.HOME for Eclipse/ANT

Go to Environment variable and add

JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_37

till jdk path (exclude bin folder)
now set JAVA_HOME into path as PATH=%JAVA_HOME%\bin;
This will set java path to all the applications which are using java.

For ANT use,

ANT_HOME=C:\Program Files (x86)\apache-ant-1.8.2\bin;

and include ANT_HOME into PATH, so path will look like PATH=%JAVA_HOME%\bin;%ANT_HOME%;

How to extract img src, title and alt from html using php?

I have read the many comments on this page that complain that using a dom parser is unnecessary overhead. Well, it may be more expensive than a mere regex call, but the OP has stated that there is no control over the order of the attributes in the img tags. This fact leads to unnecessary regex pattern convolution. Beyond that, using a dom parser provides the additional benefits of readability, maintainability, and dom-awareness (regex is not dom-aware).

I love regex and I answer lots of regex questions, but when dealing with valid HTML there is seldom a good reason to regex over a parser.

In the demonstration below, see how easy and clean DOMDocument handles img tag attributes in any order with a mixture of quoting (and no quoting at all). Also notice that tags without a targeted attribute are not disruptive at all -- an empty string is provided as a value.

Code: (Demo)

$test = <<<HTML
<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny" />
<img src='/image/pricklycactus.jpg' title='Roger the cactus' alt='a big green prickly cactus' />
<p>This is irrelevant text.</p>
<img alt="an annoying white cockatoo" title="Polly the cockatoo" src="/image/noisycockatoo.jpg">
<img title=something src=somethingelse>
HTML;

libxml_use_internal_errors(true);  // silences/forgives complaints from the parser (remove to see what is generated)
$dom = new DOMDocument();
$dom->loadHTML($test);
foreach ($dom->getElementsByTagName('img') as $i => $img) {
    echo "IMG#{$i}:\n";
    echo "\tsrc = " , $img->getAttribute('src') , "\n";
    echo "\ttitle = " , $img->getAttribute('title') , "\n";
    echo "\talt = " , $img->getAttribute('alt') , "\n";
    echo "---\n";
}

Output:

IMG#0:
    src = /image/fluffybunny.jpg
    title = Harvey the bunny
    alt = a cute little fluffy bunny
---
IMG#1:
    src = /image/pricklycactus.jpg
    title = Roger the cactus
    alt = a big green prickly cactus
---
IMG#2:
    src = /image/noisycockatoo.jpg
    title = Polly the cockatoo
    alt = an annoying white cockatoo
---
IMG#3:
    src = somethingelse
    title = something
    alt = 
---

Using this technique in professional code will leave you with a clean script, fewer hiccups to contend with, and fewer colleagues that wish you worked somewhere else.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

I had the same problem with third parties scripts like CodeMirror for example and Krpano, and even using safeApply methods mentioned here haven't solved the error for me.

But what do has solved it is using $timeout service (don't forget to inject it first).

Thus, something like:

$timeout(function() {
  // run my code safely here
})

and if inside your code you are using

this

perhaps because it's inside a factory directive's controller or just need some kind of binding, then you would do something like:

.factory('myClass', [
  '$timeout',
  function($timeout) {

    var myClass = function() {};

    myClass.prototype.surprise = function() {
      // Do something suprising! :D
    };

    myClass.prototype.beAmazing = function() {
      // Here 'this' referes to the current instance of myClass

      $timeout(angular.bind(this, function() {
          // Run my code safely here and this is not undefined but
          // the same as outside of this anonymous function
          this.surprise();
       }));
    }

    return new myClass();

  }]
)

Attribute Error: 'list' object has no attribute 'split'

what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not

`def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = str(readfile.readlines())

    Type = readlines.split(",")
    x = Type[1]
    y = Type[2]
    for points in Type:
        print(x,y)
getQuakeData()`

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

SQLite table constraint - unique on multiple columns

Well, your syntax doesn't match the link you included, which specifies:

 CREATE TABLE name (column defs) 
    CONSTRAINT constraint_name    -- This is new
    UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE

Cannot create PoolableConnectionFactory

Go to my.ini file at the below path in windows C:\ProgramData\MySQL\MySQL Server 8.0\my.ini

and comment the below line

#bind-address=127.0.0.1

Then restart the MySQL server and connect.

Then you would be able to connect to MySQL from other IP address/machine.

encrypt and decrypt md5

There is no way to decrypt MD5. Well, there is, but no reasonable way to do it. That's kind of the point.

To check if someone is entering the correct password, you need to MD5 whatever the user entered, and see if it matches what you have in the database.

How to use Java property files?

Properties has become legacy. Preferences class is preferred to Properties.

A node in a hierarchical collection of preference data. This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. Typical implementations include flat files, OS-specific registries, directory servers and SQL databases. The user of this class needn't be concerned with details of the backing store.

Unlike properties which are String based key-value pairs, The Preferences class has several methods used to get and put primitive data in the Preferences data store. We can use only the following types of data:

  1. String
  2. boolean
  3. double
  4. float
  5. int
  6. long
  7. byte array

To load the the properties file, either you can provide absolute path Or use getResourceAsStream() if the properties file is present in your classpath.

package com.mypack.test;

import java.io.*;
import java.util.*;
import java.util.prefs.Preferences;

public class PreferencesExample {

    public static void main(String args[]) throws FileNotFoundException {
        Preferences ps = Preferences.userNodeForPackage(PreferencesExample.class);
        // Load file object
        File fileObj = new File("d:\\data.xml");
        try {
            FileInputStream fis = new FileInputStream(fileObj);
            ps.importPreferences(fis);
            System.out.println("Prefereces:"+ps);
            System.out.println("Get property1:"+ps.getInt("property1",10));

        } catch (Exception err) {
            err.printStackTrace();
        }
    }
}

xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE preferences SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>
<preferences EXTERNAL_XML_VERSION="1.0">
<root type="user">
<map />
<node name="com">
  <map />
  <node name="mypack">
    <map />
    <node name="test">
      <map>
        <entry key="property1" value="80" />
        <entry key="property2" value="Red" />
      </map>
    </node>
  </node>
</node>
</root>
</preferences>

Have a look at this article on internals of preferences store

How to copy std::string into std::vector<char>?

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

Specifying a custom DateTime format when serializing with Json.Net

Some times decorating the json convert attribute will not work ,it will through exception saying that "2010-10-01" is valid date. To avoid this types i removed json convert attribute on the property and mentioned in the deserilizedObject method like below.

var addresss = JsonConvert.DeserializeObject<AddressHistory>(address, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" });

Apply multiple functions to multiple groupby columns

The second half of the currently accepted answer is outdated and has two deprecations. First and most important, you can no longer pass a dictionary of dictionaries to the agg groupby method. Second, never use .ix.

If you desire to work with two separate columns at the same time I would suggest using the apply method which implicitly passes a DataFrame to the applied function. Let's use a similar dataframe as the one from above

df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
df

          a         b         c         d  group
0  0.418500  0.030955  0.874869  0.145641      0
1  0.446069  0.901153  0.095052  0.487040      0
2  0.843026  0.936169  0.926090  0.041722      1
3  0.635846  0.439175  0.828787  0.714123      1

A dictionary mapped from column names to aggregation functions is still a perfectly good way to perform an aggregation.

df.groupby('group').agg({'a':['sum', 'max'], 
                         'b':'mean', 
                         'c':'sum', 
                         'd': lambda x: x.max() - x.min()})

              a                   b         c         d
            sum       max      mean       sum  <lambda>
group                                                  
0      0.864569  0.446069  0.466054  0.969921  0.341399
1      1.478872  0.843026  0.687672  1.754877  0.672401

If you don't like that ugly lambda column name, you can use a normal function and supply a custom name to the special __name__ attribute like this:

def max_min(x):
    return x.max() - x.min()

max_min.__name__ = 'Max minus Min'

df.groupby('group').agg({'a':['sum', 'max'], 
                         'b':'mean', 
                         'c':'sum', 
                         'd': max_min})

              a                   b         c             d
            sum       max      mean       sum Max minus Min
group                                                      
0      0.864569  0.446069  0.466054  0.969921      0.341399
1      1.478872  0.843026  0.687672  1.754877      0.672401

Using apply and returning a Series

Now, if you had multiple columns that needed to interact together then you cannot use agg, which implicitly passes a Series to the aggregating function. When using apply the entire group as a DataFrame gets passed into the function.

I recommend making a single custom function that returns a Series of all the aggregations. Use the Series index as labels for the new columns:

def f(x):
    d = {}
    d['a_sum'] = x['a'].sum()
    d['a_max'] = x['a'].max()
    d['b_mean'] = x['b'].mean()
    d['c_d_prodsum'] = (x['c'] * x['d']).sum()
    return pd.Series(d, index=['a_sum', 'a_max', 'b_mean', 'c_d_prodsum'])

df.groupby('group').apply(f)

         a_sum     a_max    b_mean  c_d_prodsum
group                                           
0      0.864569  0.446069  0.466054     0.173711
1      1.478872  0.843026  0.687672     0.630494

If you are in love with MultiIndexes, you can still return a Series with one like this:

    def f_mi(x):
        d = []
        d.append(x['a'].sum())
        d.append(x['a'].max())
        d.append(x['b'].mean())
        d.append((x['c'] * x['d']).sum())
        return pd.Series(d, index=[['a', 'a', 'b', 'c_d'], 
                                   ['sum', 'max', 'mean', 'prodsum']])

df.groupby('group').apply(f_mi)

              a                   b       c_d
            sum       max      mean   prodsum
group                                        
0      0.864569  0.446069  0.466054  0.173711
1      1.478872  0.843026  0.687672  0.630494

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

Understanding dict.copy() - shallow or deep?

Adding to kennytm's answer. When you do a shallow copy parent.copy() a new dictionary is created with same keys,but the values are not copied they are referenced.If you add a new value to parent_copy it won't effect parent because parent_copy is a new dictionary not reference.

parent = {1: [1,2,3]}
parent_copy = parent.copy()
parent_reference = parent

print id(parent),id(parent_copy),id(parent_reference)
#140690938288400 140690938290536 140690938288400

print id(parent[1]),id(parent_copy[1]),id(parent_reference[1])
#140690938137128 140690938137128 140690938137128

parent_copy[1].append(4)
parent_copy[2] = ['new']

print parent, parent_copy, parent_reference
#{1: [1, 2, 3, 4]} {1: [1, 2, 3, 4], 2: ['new']} {1: [1, 2, 3, 4]}

The hash(id) value of parent[1], parent_copy[1] are identical which implies [1,2,3] of parent[1] and parent_copy[1] stored at id 140690938288400.

But hash of parent and parent_copy are different which implies They are different dictionaries and parent_copy is a new dictionary having values reference to values of parent

selectOneMenu ajax events

Be carefull that the page does not contain any empty component which has "required" attribute as "true" before your selectOneMenu component running.
If you use a component such as

<p:inputText label="Nm:" id="id_name" value="#{ myHelper.name}" required="true"/>

then,

<p:selectOneMenu .....></p:selectOneMenu>

and forget to fill the required component, ajax listener of selectoneMenu cannot be executed.

Clear the cache in JavaScript

Cause browser cache same link, you should add a random number end of the url. new Date().getTime() generate a different number.

Just add new Date().getTime() end of link as like call

'https://stackoverflow.com/questions.php?' + new Date().getTime()

Output: https://stackoverflow.com/questions.php?1571737901173

Gradle does not find tools.jar

Found it. System property 'java.home' is not JAVA_HOME environment variable. JAVA_HOME points to the JDK, while java.home points to the JRE. See that page for more info.

Soo... My problem was that my startpoint was the jre folder (C:\jdk1.6.0_26\jre) and not the jdk folder (C:\jdk1.6.0_26) as I thought(tools.jar is on the C:\jdk1.6.0_26\lib folder ). The compile line in dependencies.gradle should be:

compile files("${System.properties['java.home']}/../lib/tools.jar")

Check whether a path is valid

Just Simply Use

if (System.IO.Directory.Exists(path))
{
    ...
}

How can I present a file for download from an MVC controller?

mgnoonan,

You can do this to return a FileStream:

/// <summary>
/// Creates a new Excel spreadsheet based on a template using the NPOI library.
/// The template is changed in memory and a copy of it is sent to
/// the user computer through a file stream.
/// </summary>
/// <returns>Excel report</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult NPOICreate()
{
    try
    {
        // Opening the Excel template...
        FileStream fs =
            new FileStream(Server.MapPath(@"\Content\NPOITemplate.xls"), FileMode.Open, FileAccess.Read);

        // Getting the complete workbook...
        HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);

        // Getting the worksheet by its name...
        HSSFSheet sheet = templateWorkbook.GetSheet("Sheet1");

        // Getting the row... 0 is the first row.
        HSSFRow dataRow = sheet.GetRow(4);

        // Setting the value 77 at row 5 column 1
        dataRow.GetCell(0).SetCellValue(77);

        // Forcing formula recalculation...
        sheet.ForceFormulaRecalculation = true;

        MemoryStream ms = new MemoryStream();

        // Writing the workbook content to the FileStream...
        templateWorkbook.Write(ms);

        TempData["Message"] = "Excel report created successfully!";

        // Sending the server processed data back to the user computer...
        return File(ms.ToArray(), "application/vnd.ms-excel", "NPOINewFile.xls");
    }
    catch(Exception ex)
    {
        TempData["Message"] = "Oops! Something went wrong.";

        return RedirectToAction("NPOI");
    }
}

Aborting a shell script if any command returns a non-zero value

If you have cleanup you need to do on exit, you can also use 'trap' with the pseudo-signal ERR. This works the same way as trapping INT or any other signal; bash throws ERR if any command exits with a nonzero value:

# Create the trap with   
#    trap COMMAND SIGNAME [SIGNAME2 SIGNAME3...]
trap "rm -f /tmp/$MYTMPFILE; exit 1" ERR INT TERM
command1
command2
command3
# Partially turn off the trap.
trap - ERR
# Now a control-C will still cause cleanup, but
# a nonzero exit code won't:
ps aux | grep blahblahblah

Or, especially if you're using "set -e", you could trap EXIT; your trap will then be executed when the script exits for any reason, including a normal end, interrupts, an exit caused by the -e option, etc.

How can you export the Visual Studio Code extension list?

Windows (PowerShell) version of Benny's answer

Machine A:

In the Visual Studio Code PowerShell terminal:

code --list-extensions > extensions.list

Machine B:

  1. Copy extension.list to the machine B

  2. In the Visual Studio Code PowerShell terminal:

     cat extensions.list |% { code --install-extension $_}
    

How to execute a file within the python interpreter?

For python3 use either with xxxx = name of yourfile.

exec(open('./xxxx.py').read())

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

this works. thanks. I am injecting custom html and compile it using angular in the controller.

        var tableContent= '<div>Search: <input ng-model="searchText"></div>' 
                            +'<div class="table-heading">'
                            +    '<div class="table-col">Customer ID</div>'
                           + ' <div class="table-col" ng-click="vm.openDialog(c.CustomerId)">{{c.CustomerId}}</div>';

            $timeout(function () {
            var linkingFunction = $compile(tableContent);
            var elem = linkingFunction($scope);

            // You can then use the DOM element like normal.
            jQuery(tablePanel).append(elem);

            console.log("timeout");
        },100);

Marker in leaflet, click event

I found the solution:

function onClick(e) {alert(this.getLatLng());}

used the method getLatLng() of the marker

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

Remove #N/A in vlookup result

If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.

=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))

or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.

=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")

in earlier versions you need to repeat the VLOOKUP, e.g.

=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))

Operator overloading on class templates

// In MyClass.h
MyClass<T>& operator+=(const MyClass<T>& classObj);


// In MyClass.cpp
template <class T>
MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) {
  // ...
  return *this;
}

This is invalid for templates. The full source code of the operator must be in all translation units that it is used in. This typically means that the code is inline in the header.

Edit: Technically, according to the Standard, it is possible to export templates, however very few compilers support it. In addition, you CAN also do the above if the template is explicitly instantiated in MyClass.cpp for all types that are T- but in reality, that normally defies the point of a template.

More edit: I read through your code, and it needs some work, for example overloading operator[]. In addition, typically, I would make the dimensions part of the template parameters, allowing for the failure of + or += to be caught at compile-time, and allowing the type to be meaningfully stack allocated. Your exception class also needs to derive from std::exception. However, none of those involve compile-time errors, they're just not great code.

Python: How to get stdout after running os.system?

commands also works.

import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result

It works on linux, python 2.7.

ConnectionTimeout versus SocketTimeout

A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.

A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.

Android SDK location should not contain whitespace, as this cause problems with NDK tools

I just wanted to add a solution for Mac users since this is the top article that comes up for searches related to this issue. If you have macOS 10.13 or later you can make use of APFS Space Sharing.

  • Open Disk Utility
  • Click Partition
  • Click Add Volume -- no need to Partition as we are adding an APFS volume which shares space within the current partition/container)
  • Give the volume a name (without spaces)
  • Click Add
  • You can now mount this drive like any other via Terminal: cd /Volumes/<your_volume_name>
  • Create an empty folder in the new volume -- I called mine sdk
  • You can now select the volume and directory while installing Android Studio

How do I check if a given string is a legal/valid file name under Windows?

Also CON, PRN, AUX, NUL, COM# and a few others are never legal filenames in any directory with any extension.

In laymans terms, what does 'static' mean in Java?

In addition to what @inkedmn has pointed out, a static member is at the class level. Therefore, the said member is loaded into memory by the JVM once for that class (when the class is loaded). That is, there aren't n instances of a static member loaded for n instances of the class to which it belongs.

Most recent previous business day in Python

Solution irrespective of different jurisdictions having different holidays:

If you need to find the right id within a table, you can use this snippet. The Table model is a sqlalchemy model and the dates to search from are in the field day.

def last_relevant_date(db: Session, given_date: date) -> int:
    available_days = (db.query(Table.id, Table.day)
                      .order_by(desc(Table.day))
                      .limit(100).all())
    close_dates = pd.DataFrame(available_days)
    close_dates['delta'] = close_dates['day'] - given_date
    past_dates = (close_dates
                  .loc[close_dates['delta'] < pd.Timedelta(0, unit='d')])
    table_id = int(past_dates.loc[past_dates['delta'].idxmax()]['id'])
    return table_id

This is not a solution that I would recommend when you have to convert in bulk. It is rather generic and expensive as you are not using joins. Moreover, it assumes that you have a relevant day that is one of the 100 most recent days in the model Table. So it tackles data input that may have different dates.

Android Webview - Completely Clear the Cache

use case: list of item are displaying in recycler view, whenever any item click it hides recycler view and shows web view with item url.

problem: i have similar problem in which once i open a url_one in webview , then try to open another url_two in webview, it shows url_one in background till url_two is loaded.

solution: so to solve what i did is load blank string "" as url just before hiding url_one and loading url_two.

output: whenever i load any new url in webview it does not show any other web page in background.

code

public void showWebView(String url){
        webView.loadUrl(url);
        recyclerView.setVisibility(View.GONE);
        webView.setVisibility(View.VISIBLE);
    }

public void onListItemClick(String url){
   showWebView(url);
}

public void hideWebView(){
        // loading blank url so it overrides last open url
        webView.loadUrl("");
        webView.setVisibility(View.GONE);
        recyclerView.setVisibility(View.GONE);
   }


 @Override
public void onBackPressed() {
    if(webView.getVisibility() == View.VISIBLE){
        hideWebView();
    }else{
        super.onBackPressed();
    }
}

How do I hide an element on a click event anywhere outside of the element?

Try this

 $('.myDiv').click(function(e) { //button click class name is myDiv
  e.stopPropagation();
 })

 $(function(){
  $(document).click(function(){  
  $('.myDiv').hide(); //hide the button

  });
});

I use class name instead of ID, because in asp.net you have to worry about the extra stuff .net attaches to the id

EDIT- Since you added a another piece, it would work like this:

 $('.myDiv').click(function() { //button click class name is myDiv
  e.stopPropagation();
 })

 $(function(){
  $('.openDiv').click(function() {
  $('.myDiv').show(); 

  });
  $(document).click(function(){  
  $('.myDiv').hide(); //hide the button

  });
});

Split a string into array in Perl

Just use /\s+/ against '' as a splitter. In this case all "extra" blanks were removed. Usually this particular behaviour is required. So, in you case it will be:

my $line = "file1.gz file1.gz file3.gz";
my @abc = split(/\s+/, $line);

How to have image and text side by side

Use following code : jsfiddle.net/KqHEC/

HTML

<div class='container2'>
        <div class="left">
            <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails'>
        </div>  
    <div   class="right" >
    <h4>Facebook</h4>
    <div style="font-size:.7em;width:160px;float:left;">fine location, GPS, coarse location</div>
    <div style="float:right;font-size:.7em">0 mins ago</div>
    </div>
</div>

CSS

.iconDetails {
 margin-left:2%;
float:left; 
height:40px;
width:40px; 
} 

.container2 {
    width:270px;
    height:auto;
    padding:1%;
    float:left;
}
h4{margin:0}
.left {float:left;width:45px;}
.right {float:left;margin:0 0 0 5px;width:215px;}

http://jsfiddle.net/KqHEC/1/

.NET - How do I retrieve specific items out of a Dataset?

int intVar = (int)ds.Tables[0].Rows[0][n];   // n = column index

Implementing two interfaces in a class with same method. Which interface method is overridden?

Well if they are both the same it doesn't matter. It implements both of them with a single concrete method per interface method.

bash export command

Are you certain that the software (and not yourself, since your test actually only shows the shell used as default for your user) uses /bin/bash ?

How do I rename the extension for a bunch of files?

Nice & simple!

find . -iname *.html  -exec mv {} "$(basename {} .html).text"  \;

What is the unix command to see how much disk space there is and how much is remaining?

I love doing du -sh * | sort -nr | less to sort by the largest files first

.attr("disabled", "disabled") issue

To add disabled attribute

$('#id').attr("disabled", "true");

To remove Disabled Attribute

$('#id').removeAttr('disabled');

Sort a two dimensional array based on one column

  1. install java8 jdk+jre

  2. use lamda expression to sort 2D array.

code:

import java.util.Arrays;
import java.util.Comparator;

class SortString {

    public static void main(final String[] args) {
        final String[][] data = new String[][] {
                new String[] { "2009.07.25 20:24", "Message A" },
                new String[] { "2009.07.25 20:17", "Message G" },
                new String[] { "2009.07.25 20:25", "Message B" },
                new String[] { "2009.07.25 20:30", "Message D" },
                new String[] { "2009.07.25 20:01", "Message F" },
                new String[] { "2009.07.25 21:08", "Message E" },
                new String[] { "2009.07.25 19:54", "Message R" } 
        };
        // this is applicable only in java 8 version.
        Arrays.sort(data, (String[] s1, String[] s2) -> s1[0].compareTo(s2[0]));

        // we can also use Comparator.comparing and point to Comparable value we want to use        
        // Arrays.sort(data, Comparator.comparing(row->row[0]));

        for (final String[] s : data) {
            System.out.println(s[0] + " " + s[1]);
        }
    }
}

output

2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E

Do C# Timers elapse on a separate thread?

For System.Timers.Timer:

See Brian Gideon's answer below

For System.Threading.Timer:

MSDN Documentation on Timers states:

The System.Threading.Timer class makes callbacks on a ThreadPool thread and does not use the event model at all.

So indeed the timer elapses on a different thread.

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

Simple way to set it in visual studio IDE.

Project > Properties> Debug > Environment variables

enter image description here

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

Use the zzz format specifier to get the timezone offset as hours and minutes. You also want to use the HH format specifier to get the hours in 24 hour format.

DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")

Result:

2011-08-09T23:49:58+02:00

Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:

DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")

Custom Date and Time Format Strings

How to configure WAMP (localhost) to send email using Gmail?

As an alternative to PHPMailer, Pear's Mail and others you could use the Zend's library

  $config = array('auth' => 'login',
                   'ssl' => 'ssl',
                   'port'=> 465,
                   'username' => '[email protected]',
                   'password' => 'XXXXXXX');

 $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
 $mail = new Zend_Mail();
 $mail->setBodyText('This is the text of the mail.');
 $mail->setFrom('[email protected]', 'Some Sender');
 $mail->addTo('[email protected]', 'Some Recipient');
 $mail->setSubject('TestSubj');
 $mail->send($transport); 

That is my set up in localhost server and I can able to see incoming mail to my mail box.

How to decode a QR-code image in (preferably pure) Python?

I'm answering only the part of the question about zbar installation.

I spent nearly half an hour a few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:

PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.

PS2: I just tested pyzbar with pip install pyzbar and it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.

Bootstrap 3 Glyphicons CDN

An alternative would be to use Font-Awesome for icons:

Including Font-Awesome

Open Font-Awesome on CDNJS and copy the CSS url of the latest version:

<link rel="stylesheet" href="<url>">

Or in CSS

@import url("<url>");

For example (note, the version will change):

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

Usage:

<i class="fa fa-bed"></i>

It contains a lot of icons!

How to import existing *.sql files in PostgreSQL 8.4?

Well, the shortest way I know of, is following:

psql -U {user_name} -d {database_name} -f {file_path} -h {host_name}

database_name: Which database should you insert your file data in.

file_path: Absolute path to the file through which you want to perform the importing.

host_name: The name of the host. For development purposes, it is mostly localhost.

Upon entering this command in console, you will be prompted to enter your password.

How to make multiple divs display in one line but still retain width?

You can use float:left in DIV or use SPAN tag, like

<div style="width:100px;float:left"> First </div> 
<div> Second </div> 
<br/>

or

<span style="width:100px;"> First </span> 
<span> Second </span> 
<br/>

When to use setAttribute vs .attribute= in JavaScript?

None of the previous answers are complete and most contain misinformation.

There are three ways of accessing the attributes of a DOM Element in JavaScript. All three work reliably in modern browsers as long as you understand how to utilize them.

1. element.attributes

Elements have a property attributes that returns a live NamedNodeMap of Attr objects. The indexes of this collection may be different among browsers. So, the order is not guaranteed. NamedNodeMap has methods for adding and removing attributes (getNamedItem and setNamedItem, respectively).

Notice that though XML is explicitly case sensitive, the DOM spec calls for string names to be normalized, so names passed to getNamedItem are effectively case insensitive.

Example Usage:

_x000D_
_x000D_
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//you can look up specific attributes_x000D_
var classAttr = div.attributes.getNamedItem('CLASS');_x000D_
document.write('attributes.getNamedItem() Name: ' + classAttr.name + ' Value: ' + classAttr.value + '<br>');_x000D_
_x000D_
//you can enumerate all defined attributes_x000D_
for(var i = 0; i < div.attributes.length; i++) {_x000D_
  var attr = div.attributes[i];_x000D_
  document.write('attributes[] Name: ' + attr.name + ' Value: ' + attr.value + '<br>');_x000D_
}_x000D_
_x000D_
//create custom attribute_x000D_
var customAttr = document.createAttribute('customTest');_x000D_
customAttr.value = '567';_x000D_
div.attributes.setNamedItem(customAttr);_x000D_
_x000D_
//retreive custom attribute_x000D_
customAttr = div.attributes.getNamedItem('customTest');_x000D_
document.write('attributes.getNamedItem() Name: ' + customAttr.name + ' Value: ' + customAttr.value + '<br>');
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
_x000D_
_x000D_

2. element.getAttribute & element.setAttribute

These methods exist directly on the Element without needing to access attributes and its methods but perform the same functions.

Again, notice that string name are case insensitive.

Example Usage:

_x000D_
_x000D_
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//get specific attributes_x000D_
document.write('Name: class Value: ' + div.getAttribute('class') + '<br>');_x000D_
document.write('Name: ID Value: ' + div.getAttribute('ID') + '<br>');_x000D_
document.write('Name: DATA-TEST Value: ' + div.getAttribute('DATA-TEST') + '<br>');_x000D_
document.write('Name: nonStandard Value: ' + div.getAttribute('nonStandard') + '<br>');_x000D_
_x000D_
_x000D_
//create custom attribute_x000D_
div.setAttribute('customTest', '567');_x000D_
_x000D_
//retreive custom attribute_x000D_
document.write('Name: customTest Value: ' + div.getAttribute('customTest') + '<br>');
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
_x000D_
_x000D_

3. Properties on the DOM object, such as element.id

Many attributes can be accessed using convenient properties on the DOM object. Which attributes exist depends on the DOM node's type, not which attributes are defined in the HTML. The properties are defined somewhere in the prototype chain of DOM object in question. The specific properties defined will depend on the type of Element you are accessing. For example, className and id are defined on Element and exist on all DOM nodes that are elements (ie. not text or comment nodes). But value is more narrow. It's defined on HTMLInputElement and may not exist on other elements.

Notice that JavaScript properties are case sensitive. Although most properties will use lowercase, some are camelCase. So always check the spec to be sure.

This "chart" captures a portion of the prototype chain for these DOM objects. It's not even close to complete, but it captures the overall structure.

                      ____________Node___________
                      |               |         |
                   Element           Text   Comment
                   |     |
           HTMLElement   SVGElement
           |         |
HTMLInputElement   HTMLSpanElement

Example Usage:

_x000D_
_x000D_
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//get specific attributes_x000D_
document.write('Name: class Value: ' + div.className + '<br>');_x000D_
document.write('Name: id Value: ' + div.id + '<br>');_x000D_
document.write('Name: ID Value: ' + div.ID + '<br>'); //undefined_x000D_
document.write('Name: data-test Value: ' + div.dataset.test + '<br>'); //.dataset is a special case_x000D_
document.write('Name: nonStandard Value: ' + div.nonStandard + '<br>'); //undefined
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
_x000D_
_x000D_

Caveat: This is an explanation of how the HTML spec defines and modern browsers handle attributes. I did not attempt to deal with limitations of ancient, broken browsers. If you need to support old browsers, in addition to this information, you will need to know what is broken in the those browsers.

Copy files without overwrite

Belisarius' solution is good.

To elaborate on that slightly terse answer:

  • /E makes Robocopy recursively copy subdirectories, including empty ones.
  • /XC excludes existing files with the same timestamp, but different file sizes. Robocopy normally overwrites those.
  • /XN excludes existing files newer than the copy in the source directory. Robocopy normally overwrites those.
  • /XO excludes existing files older than the copy in the source directory. Robocopy normally overwrites those.

With the Changed, Older, and Newer classes excluded, Robocopy does exactly what the original poster wants - without needing to load a scripting environment.

REST API - Bulk Create or Update in single request

I think that you could use a POST or PATCH method to handle this since they typically design for this.

  • Using a POST method is typically used to add an element when used on list resource but you can also support several actions for this method. See this answer: How to Update a REST Resource Collection. You can also support different representation formats for the input (if they correspond to an array or a single elements).

    In the case, it's not necessary to define your format to describe the update.

  • Using a PATCH method is also suitable since corresponding requests correspond to a partial update. According to RFC5789 (http://tools.ietf.org/html/rfc5789):

    Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

    In the case, you have to define your format to describe the partial update.

I think that in this case, POST and PATCH are quite similar since you don't really need to describe the operation to do for each element. I would say that it depends on the format of the representation to send.

The case of PUT is a bit less clear. In fact, when using a method PUT, you should provide the whole list. As a matter of fact, the provided representation in the request will be in replacement of the list resource one.

You can have two options regarding the resource paths.

  • Using the resource path for doc list

In this case, you need to explicitely provide the link of docs with a binder in the representation you provide in the request.

Here is a sample route for this /docs.

The content of such approach could be for method POST:

[
    { "doc_number": 1, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 2, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 3, "binder": 5, (other fields in the case of creation) },
    (...)
]
  • Using sub resource path of binder element

In addition you could also consider to leverage sub routes to describe the link between docs and binders. The hints regarding the association between a doc and a binder doesn't have now to be specified within the request content.

Here is a sample route for this /binder/{binderId}/docs. In this case, sending a list of docs with a method POST or PATCH will attach docs to the binder with identifier binderId after having created the doc if it doesn't exist.

The content of such approach could be for method POST:

[
    { "doc_number": 1, (other fields in the case of creation) },
    { "doc_number": 2, (other fields in the case of creation) },
    { "doc_number": 3, (other fields in the case of creation) },
    (...)
]

Regarding the response, it's up to you to define the level of response and the errors to return. I see two levels: the status level (global level) and the payload level (thinner level). It's also up to you to define if all the inserts / updates corresponding to your request must be atomic or not.

  • Atomic

In this case, you can leverage the HTTP status. If everything goes well, you get a status 200. If not, another status like 400 if the provided data aren't correct (for example binder id not valid) or something else.

  • Non atomic

In this case, a status 200 will be returned and it's up to the response representation to describe what was done and where errors eventually occur. ElasticSearch has an endpoint in its REST API for bulk update. This could give you some ideas at this level: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/bulk.html.

  • Asynchronous

You can also implement an asynchronous processing to handle the provided data. In this case, the HTTP status returns will be 202. The client needs to pull an additional resource to see what happens.

Before finishing, I also would want to notice that the OData specification addresses the issue regarding relations between entities with the feature named navigation links. Perhaps could you have a look at this ;-)

The following link can also help you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.

Hope it helps you, Thierry

Installing MySQL Python on Mac OS X

Install mysql via homebrew, then you can install mysql python via pip.

pip install MySQL-python

It works for me.

How to perform an SQLite query within an Android application?

This will also work if the pattern you want to match is a variable.

dbh = new DbHelper(this);
SQLiteDatabase db = dbh.getWritableDatabase();

Cursor c = db.query(
    "TableName", 
    new String[]{"ColumnName"}, 
    "ColumnName LIKE ?", 
    new String[]{_data+"%"}, 
    null, 
    null, 
    null
);

while(c.moveToNext()){
    // your calculation goes here
}

XML Document to String

Assuming doc is your instance of org.w3c.dom.Document:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

Mocking Logger and LoggerFactory with PowerMock and Mockito

The following is a test class that mocks private static final Logger named log in class LogUtil.

In addition to mocking the getLogger factory call, it is necessary to explicitly set the field using reflection, in @BeforeClass

public class LogUtilTest {

    private static Logger logger;

    private static MockedStatic<LoggerFactory> loggerFactoryMockedStatic;

    /**
     * Since {@link LogUtil#log} being a static final variable it is only initialized once at the class load time
     * So assertions are also performed against the same mock {@link LogUtilTest#logger}
     */
    @BeforeClass
    public static void beforeClass() {
        logger = mock(Logger.class);
        loggerFactoryMockedStatic = mockStatic(LoggerFactory.class);
        loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(logger);
        Whitebox.setInternalState(LogUtil.class, "log", logger);
    }

    @AfterClass
    public static void after() {
        loggerFactoryMockedStatic.close();
    }
} 

An object reference is required to access a non-static member

I'm guessing you get the error on accessing audioSounds and minTime, right?

The problem is you can't access instance members from static methods. What this means is that, a static method is a method that exists only once and can be used by all other objects (if its access modifier permits it).

Instance members, on the other hand, are created for every instance of the object. So if you create ten instances, how would the runtime know out of all these instances, which audioSounds list it should access?

Like others said, make your audioSounds and minTime static, or you could make your method an instance method, if your design permits it.

How to use the "required" attribute with a "radio" input field

TL;DR: Set the required attribute for at least one input of the radio group.


Setting required for all inputs is more clear, but not necessary (unless dynamically generating radio-buttons).

To group radio buttons they must all have the same name value. This allows only one to be selected at a time and applies required to the whole group.

_x000D_
_x000D_
<form>_x000D_
  Select Gender:<br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="male" required>_x000D_
    Male_x000D_
  </label><br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="female">_x000D_
    Female_x000D_
  </label><br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="other">_x000D_
    Other_x000D_
  </label><br>_x000D_
_x000D_
  <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Also take note of:

To avoid confusion as to whether a radio button group is required or not, authors are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general, authors are encouraged to avoid having radio button groups that do not have any initially checked controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.

Source

PYTHONPATH vs. sys.path

In general I would consider setting up of an environment variable (like PYTHONPATH) to be a bad practice. While this might be fine for a one off debugging but using this as
a regular practice might not be a good idea.

Usage of environment variable leads to situations like "it works for me" when some one
else reports problems in the code base. Also one might carry the same practice with the test environment as well, leading to situations like the tests running fine for a particular developer but probably failing when some one launches the tests.

403 Forbidden vs 401 Unauthorized HTTP responses

they are not logged in or do not belong to the proper user group

You have stated two different cases; each case should have a different response:

  1. If they are not logged in at all you should return 401 Unauthorized
  2. If they are logged in but don't belong to the proper user group, you should return 403 Forbidden

Note on the RFC based on comments received to this answer:

If the user is not logged in they are un-authenticated, the HTTP equivalent of which is 401 and is misleadingly called Unauthorized in the RFC. As section 10.4.2 states for 401 Unauthorized:

"The request requires user authentication."

If you're unauthenticated, 401 is the correct response. However if you're unauthorized, in the semantically correct sense, 403 is the correct response.

File count from a folder

System.IO.Directory myDir = GetMyDirectoryForTheExample();
int count = myDir.GetFiles().Length;

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

I had to add parseInt() to tell v-for it was looking at a number.

<li v-for="n in parseInt(count)" :key="n">{{n}}</li>

Convert dd-mm-yyyy string to date

Use this format: myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00

Ansible - read inventory hosts and variables to group_vars/all file

Yes the example by nixlike works very well.

Inventory:

[docker-host]
myhost1 user=barbara
myhost2 user=heather

playbook:

---

- hosts: localhost
  connection: local         

     tasks:    
        - name: loop debug inventory hostnames
          debug: 
            msg: "the docker host is {{ item }}"
          with_inventory_hostnames: docker-host
        - name: loop debug items
          debug: 
            msg: "the docker host is {{ hostvars[item]['user'] }}"
          with_items: "{{ groups['docker-host'] }}"

output:

ansible-playbook ansible/tests/vars-test-local.yml

PLAY [localhost]


TASK [setup] ******************************************************************* ok: [localhost]

TASK [loop debug inventory hostnames] ****************************************** ok: [localhost] => (item=myhost2) => { "item": "myhost2", "msg": "the docker host is myhost2" } ok: [localhost] => (item=myhost1) => { "item": "myhost1", "msg": "the docker host is myhost1" }

TASK [loop debug items] ******************************************************** ok: [localhost] => (item=myhost1) => { "item": "myhost1", "msg": "the docker host is barbara" } ok: [localhost] => (item=myhost2) => { "item": "myhost2", "msg": "the docker host is heather" }

PLAY RECAP ********************************************************************* localhost : ok=3 changed=0 unreachable=0
failed=0

thanks!

CentOS: Enabling GD Support in PHP Installation

The thing that did the trick for me eventually was:

yum install gd gd-devel php-gd

and then restart apache:

service httpd restart

Python - add PYTHONPATH during command line module run

This is for windows:

For example, I have a folder named "mygrapher" on my desktop. Inside, there's folders called "calculation" and "graphing" that contain Python files that my main file "grapherMain.py" needs. Also, "grapherMain.py" is stored in "graphing". To run everything without moving files, I can make a batch script. Let's call this batch file "rungraph.bat".

@ECHO OFF
setlocal
set PYTHONPATH=%cd%\grapher;%cd%\calculation
python %cd%\grapher\grapherMain.py
endlocal

This script is located in "mygrapher". To run things, I would get into my command prompt, then do:

>cd Desktop\mygrapher (this navigates into the "mygrapher" folder)
>rungraph.bat (this executes the batch file)

Make the console wait for a user input to close

The problem with Java console input is that it's buffered input, and requires an enter key to continue.

There are these two discussions: Detecting and acting on keyboard direction keys in Java and Java keyboard input parsing in a console app

The latter of which used JLine to get his problem solved.

I personally haven't used it.

Send data from a textbox into Flask?

This worked for me.

def parse_data():
    if request.method == "POST":
        data = request.get_json()
        print(data['answers'])
        return render_template('output.html', data=data)
$.ajax({
      type: 'POST',
      url: "/parse_data",
      data: JSON.stringify({values}),
      contentType: "application/json;charset=utf-8",
      dataType: "json",
      success: function(data){
        // do something with the received data
      }
    });

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml from a file deployed at http://run.jsbin.com due to the same-origin policy.


As the source (aka origin) page and the target URL are at different domains (run.jsbin.com and www.ecb.europa.eu), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET.

In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.


Example:

A page at http://www.example.com/myPage.html can only directly request services that are at http://www.example.com, like http://www.example.com/api/myService. If the service is hosted at another domain (say http://www.ok.com/api/myService), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a (CORS) request* across different domains, your browser:

  • Will include an Origin header in the original request (with the page's domain as value) and perform it as usual; and then
  • Only if the server response to that request contains the adequate headers (Access-Control-Allow-Origin is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).


* The above depicts the steps in a simple request, such as a regular GET with no fancy headers. If the request is not simple (like a POST with application/json as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS request to the target URL. Like above, it only will continue if the response to this OPTIONS request contains the CORS headers. This OPTIONS call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers header.


How to fix it?

Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com it will only make regular calls to www.example.com! Other URLs, such as api.example.com or even example.com or www.example.com:8080 are considered different domains by the browser! Yes, if the port is different, then it is a different domain!

Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin) to the server's responses. (Each server/language has a way to do that - check some solutions here.)

Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.

How do I change the default location for Git Bash on Windows?

Open this file:

C:\Program Files\Git\etc\bash.bashrc

And append the following line:

cd /c/Users/<User>/Documents/path/to/your/repos

Restart Git bash

Angularjs simple file download causes router to redirect

in template

<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
    system_update_alt
</md-icon></md-button>

in controller

     $scope.export = function(){ $window.location.href = $scope.export; };

How do I get a file name from a full path with PHP?

The basename function should give you what you want:

Given a string containing a path to a file, this function will return the base name of the file.

For instance, quoting the manual's page:

<?php
    $path = "/home/httpd/html/index.php";
    $file = basename($path);         // $file is set to "index.php"
    $file = basename($path, ".php"); // $file is set to "index"
?>

Or, in your case:

$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map';
var_dump(basename($full));

You'll get:

string(10) "Output.map"

How to move the cursor word by word in the OS X Terminal

Out of the box you can use the quite bizarre Esc+F to move to the beginning of the next word and Esc+B to move to the beginning of the current word.

Interpreting "condition has length > 1" warning from `if` function

Just adding a point to the whole discussion as to why this warning comes up (It wasn't clear to me before). The reason one gets this is as mentioned before is because 'a' in this case is a vector and the inequality 'a>0' produces another vector of TRUE and FALSE (where 'a' is >0 or not).

If you would like to instead test if any value of 'a>0', you can use functions - 'any' or 'all'

Best

Removing elements from array Ruby

Not very simple but:

a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,3].count(k)}.values.flatten
=> [1, 1, 2, 2]

Also handles the case for multiples in the 'subtrahend':

a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,1,3].count(k)}.values.flatten
=> [1, 2, 2]

EDIT: this is more an enhancement combining Norm212 and my answer to make a "functional" solution.

b = [1,1,3].each.with_object( a ) { |del| a.delete_at( a.index( del ) ) }

Put it in a lambda if needed:

subtract = lambda do |minuend, subtrahend|
  subtrahend.each.with_object( minuend ) { |del| minuend.delete_at( minuend.index( del ) ) }
end

then:

subtract.call a, [1,1,3]

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

R object identification

str(x)

It's all you need to remember for 99% of cases.

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

JpaRepository extends PagingAndSortingRepository which in turn extends CrudRepository.

Their main functions are:

Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository. So if you don't need the repository to have the functions provided by JpaRepository and PagingAndSortingRepository , use CrudRepository.

Flutter: how to make a TextField with HintText but no Underline?

I was using the TextField flutter control.I got the user typed input using below methods.

onChanged:(value){
}

Running Google Maps v2 on the Android emulator

I am able to have my emulator to run my app with Google Map V.2 (with Google Play Service V.4). I followed steps that others suggested with some failures, however I learned from it and somehow make it work. This is how:

  1. First of all: You must have coded your map app. correctly with all the appropriate permissions setup in your metafile XML, and have Google Play Services APK part of your app. To verify this is true, you must run your app on REAL device and know it works with its map there. Then you can proceed to process your emulator as shown below.

  2. Create a new emulator, or use your existing emulator with specs:

    • Target Name = Android 4.1.2
    • API Level = 16
    • CPU = Any. However, I found ARM is much faster/responsive than x86
    • Have enough RAM memory and space MB
  3. Run you emulator (your target emulator must be running!)

  4. Download the following APKs (available via dropbox per 4/2/2013) to your local directory (scan for virus!):

  5. Install these two APK into your running (target) emulator with ADB command:

    DOS/Console Prompt> adb -e install [path-to-APK-file]

    NOTE: Possibly, you have had these APKs installed in your emulator during this trial-error, and need to re-install for some reason. You must uninstall them first by: adb -e uninstall (com.google.android.gms or com.android.vending)

  6. Here, it is where things could get tricky. You think you were done, but when you open your app with Map again, but all you get is an error saying something in the form of: "Google Play services out of date. Requires 2012100 but found 2010110", and may see a button to "Update" Google Play. If this is the case, do NOT attempt to click the update button since it won't do anything. I got this error too, and I resolved it by both of these additional steps:

    • Clean-rebuild-reinstall my app into the emulator
    • Shutdown my emulator and re-start it.
  7. That's it, it works now nicely.

How to round up a number in Javascript?

Normal rounding will work with a small tweak:

Math.round(price * 10)/10

and if you want to keep a currency format, you can use the Number method .toFixed()

(Math.round(price * 10)/10).toFixed(2)

Though this will make it a String =)

On linux SUSE or RedHat, how do I load Python 2.7

To install Python 2.7.2 use this script - https://github.com/bngsudheer/bangadmin/blob/master/linux/centos/6/x86_64/build-python-27.sh

It also makes sure you get sqlite and readline support.

error::make_unique is not a member of ‘std’

make_unique is an upcoming C++14 feature and thus might not be available on your compiler, even if it is C++11 compliant.

You can however easily roll your own implementation:

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

(FYI, here is the final version of make_unique that was voted into C++14. This includes additional functions to cover arrays, but the general idea is still the same.)

Printing tuple with string formatting in Python

Talk is cheap, show you the code:

>>> tup = (10, 20, 30)
>>> i = 50
>>> print '%d      %s'%(i,tup)
50  (10, 20, 30)
>>> print '%s'%(tup,)
(10, 20, 30)
>>> 

How to convert hashmap to JSON object in Java

Example using json

Map<String, Object> data = new HashMap<String, Object>();
    data.put( "name", "Mars" );
    data.put( "age", 32 );
    data.put( "city", "NY" );
    JSONObject json = new JSONObject();
    json.putAll( data );
    System.out.printf( "JSON: %s", json.toString(2) );

output::

JSON: {
  "age": 32,
  "name": "Mars",
  "city": "NY"
}

You can also try to use Google's GSON.Google's GSON is the best library available to convert Java Objects into their JSON representation.

http://code.google.com/p/google-gson/