Programs & Examples On #Boost spirit qi

a practical, scalable parsing library for C++

groovy: safely find a key in a map and return its value

def mymap = [name:"Gromit", id:1234]
def x = mymap.find{ it.key == "likes" }?.value
if(x)
    println "x value: ${x}"

println x.getClass().name

?. checks for null and does not create an exception in Groovy. If the key does not exist, the result will be a org.codehaus.groovy.runtime.NullObject.

How to send PUT, DELETE HTTP request in HttpURLConnection?

UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this stackoverflow question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients. Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

With Angular CLI 6 you need to use builders as ng eject is deprecated and will soon be removed in 8.0. That's what it says when I try to do an ng eject

enter image description here

You can use angular-builders package (https://github.com/meltedspark/angular-builders) to provide your custom webpack config.

I have tried to summarize all in a single blog post on my blog - How to customize build configuration with custom webpack config in Angular CLI 6

but essentially you add following dependencies -

  "devDependencies": {
    "@angular-builders/custom-webpack": "^7.0.0",
    "@angular-builders/dev-server": "^7.0.0",
    "@angular-devkit/build-angular": "~0.11.0",

In angular.json make following changes -

  "architect": {
    "build": {
      "builder": "@angular-builders/custom-webpack:browser",
      "options": {
        "customWebpackConfig": {"path": "./custom-webpack.config.js"},

Notice change in builder and new option customWebpackConfig. Also change

    "serve": {
      "builder": "@angular-builders/dev-server:generic",

Notice the change in builder again for serve target. Post these changes you can create a file called custom-webpack.config.js in your same root directory and add your webpack config there.

However, unlike ng eject configuration provided here will be merged with default config so just add stuff you want to edit/add.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

I had the same issue trying to do something the same as you and I fixed it with something similar to Richie Fredicson's answer.

When you run createComponent() it is created with undefined input variables. Then after that when you assign data to those input variables it changes things and causes that error in your child template (in my case it was because I was using the input in an ngIf, which changed once I assigned the input data).

The only way I could find to avoid it in this specific case is to force change detection after you assign the data, however I didn't do it in ngAfterContentChecked().

Your example code is a bit hard to follow but if my solution works for you it would be something like this (in the parent component):

export class ParentComponent implements AfterViewInit {
  // I'm assuming you have a WidgetDirective.
  @ViewChild(WidgetDirective) widgetHost: WidgetDirective;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private changeDetector: ChangeDetectorRef
  ) {}

  ngAfterViewInit() {
    renderWidgetInsideWidgetContainer();
  }

  renderWidgetInsideWidgetContainer() {
    let component = this.storeFactory.getWidgetComponent(this.dataSource.ComponentName);
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
    let viewContainerRef = this.widgetHost.viewContainerRef;
    viewContainerRef.clear();
    let componentRef = viewContainerRef.createComponent(componentFactory);
    debugger;
    // This <IDataBind> type you are using here needs to be changed to be the component
    // type you used for the call to resolveComponentFactory() above (if it isn't already).
    // It tells it that this component instance if of that type and then it knows
    // that WidgetDataContext and WidgetPosition are @Inputs for it.
    (<IDataBind>componentRef.instance).WidgetDataContext = this.dataSource.DataContext;
    (<IDataBind>componentRef.instance).WidgetPosition = this.dataSource.Position;
    this.changeDetector.detectChanges();
  }
}

Mine is almost the same as that except I'm using @ViewChildren instead of @ViewChild as I have multiple host elements.

Run a vbscript from another vbscript

Try this.

Option Explicit

On error resume next
Dim Shellobj
Set Shellobj = CreateObject("WScript.Shell")

Shellobj.Run "Test.vbs" 

Set Shellobj = Nothing

What is the python "with" statement designed for?

points 1, 2, and 3 being reasonably well covered:

4: it is relatively new, only available in python2.6+ (or python2.5 using from __future__ import with_statement)

ASP.Net MVC: Calling a method from a view

You can implement a static formatting method or an HTML helper, then use this syntaxe :

@using class_of_method_namespace
...
// HTML page here
@className.MethodName()

or in case of HTML Helper

@Html.MehtodName()

Switch between two frames in tkinter

One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.

Note: for this to work, all of the widgets for a page must have that page (ie: self) or a descendant as a parent (or master, depending on the terminology you prefer).

Here's a bit of a contrived example to show you the general concept:

try:
    import tkinter as tk                # python 3
    from tkinter import font as tkfont  # python 3
except ImportError:
    import Tkinter as tk     # python 2
    import tkFont as tkfont  # python 2

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

start page page 1 page 2

If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.

For example, to create the classes individually you can remove the loop (for F in (StartPage, ...) with this:

self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)

self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")

Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:

How to set JAVA_HOME in Mac permanently?

Try this link http://www.mkyong.com/java/how-to-set-java_home-environment-variable-on-mac-os-x/

This explains correctly, I did the following to make it work

  1. Open Terminal
  2. Type vim .bash_profile
  3. Type your java instalation dir in my case export JAVA_HOME="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
  4. Click ESC then type :wq (save and quit in vim)
  5. Then type source .bash_profile
  6. echo $JAVA_HOME if you see the path you are all set.

Hope it helps.

Invariant Violation: _registerComponent(...): Target container is not a DOM element

the ready function can be used like this:

$(document).ready(function () {
  React.render(<App />, document.body);
});

If you don't want to use jQuery, you can use the onload function:

<body onload="initReact()">...</body>

How to generate entire DDL of an Oracle schema (scriptable)?

To generate the DDL script for an entire SCHEMA i.e. a USER, you could use dbms_metadata.get_ddl.

Execute the following script in SQL*Plus created by Tim Hall:

Provide the username when prompted.

set long 20000 longchunksize 20000 pagesize 0 linesize 1000 feedback off verify off trimspool on
column ddl format a1000

begin
   dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'SQLTERMINATOR', true);
   dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'PRETTY', true);
end;
/

variable v_username VARCHAR2(30);

exec:v_username := upper('&1');

select dbms_metadata.get_ddl('USER', u.username) AS ddl
from   dba_users u
where  u.username = :v_username
union all
select dbms_metadata.get_granted_ddl('TABLESPACE_QUOTA', tq.username) AS ddl
from   dba_ts_quotas tq
where  tq.username = :v_username
and    rownum = 1
union all
select dbms_metadata.get_granted_ddl('ROLE_GRANT', rp.grantee) AS ddl
from   dba_role_privs rp
where  rp.grantee = :v_username
and    rownum = 1
union all
select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', sp.grantee) AS ddl
from   dba_sys_privs sp
where  sp.grantee = :v_username
and    rownum = 1
union all
select dbms_metadata.get_granted_ddl('OBJECT_GRANT', tp.grantee) AS ddl
from   dba_tab_privs tp
where  tp.grantee = :v_username
and    rownum = 1
union all
select dbms_metadata.get_granted_ddl('DEFAULT_ROLE', rp.grantee) AS ddl
from   dba_role_privs rp
where  rp.grantee = :v_username
and    rp.default_role = 'YES'
and    rownum = 1
union all
select to_clob('/* Start profile creation script in case they are missing') AS ddl
from   dba_users u
where  u.username = :v_username
and    u.profile <> 'DEFAULT'
and    rownum = 1
union all
select dbms_metadata.get_ddl('PROFILE', u.profile) AS ddl
from   dba_users u
where  u.username = :v_username
and    u.profile <> 'DEFAULT'
union all
select to_clob('End profile creation script */') AS ddl
from   dba_users u
where  u.username = :v_username
and    u.profile <> 'DEFAULT'
and    rownum = 1
/

set linesize 80 pagesize 14 feedback on trimspool on verify on

How can I find the first and last date in a month using PHP?

The easiest way is to use date, which lets you mix hard-coded values with ones extracted from a timestamp. If you don't give a timestamp, it assumes the current date and time.

// Current timestamp is assumed, so these find first and last day of THIS month
$first_day_this_month = date('m-01-Y'); // hard-coded '01' for first day
$last_day_this_month  = date('m-t-Y');

// With timestamp, this gets last day of April 2010
$last_day_april_2010 = date('m-t-Y', strtotime('April 21, 2010'));

date() searches the string it's given, like 'm-t-Y', for specific symbols, and it replaces them with values from its timestamp. So we can use those symbols to extract the values and formatting that we want from the timestamp. In the examples above:

  • Y gives you the 4-digit year from the timestamp ('2010')
  • m gives you the numeric month from the timestamp, with a leading zero ('04')
  • t gives you the number of days in the timestamp's month ('30')

You can be creative with this. For example, to get the first and last second of a month:

$timestamp    = strtotime('February 2012');
$first_second = date('m-01-Y 00:00:00', $timestamp);
$last_second  = date('m-t-Y 12:59:59', $timestamp); // A leap year!

See http://php.net/manual/en/function.date.php for other symbols and more details.

Class JavaLaunchHelper is implemented in two places

I have found the other workaround: to exclude libinstrument.dylib from project path. To do so, go to the Preferences -> Build, Execution and Deployment -> Compiler -> Excludes -> + and here add file by the path in error message.

What is the use of "assert"?

Assertions are statements that state a fact confidently in our program.

Syntax : assert <condition> or assert <condition>,<error message>

It has a condition/expression which is supposed to be always true. If the condition is false, the assert statement will halt the program and throw an error message saying AssertionError. So your assertion expression will be something that you don't want in your program.

e.g.

  1. assert <condition> -- using assert without <error message>

    var = int(input("Enter value 1-9 inclusive:"))                                 
    assert var!=0 
    print(var)
    

    Output :

    If input is 0 :

    AssertionError
    

    If input is 1 :

    1
    
  2. assert <condition>,<error message> -- using assert with an <error message>

    var = int(input("Enter value 1-9 inclusive:"))                                 
    assert var!=0,"Input cannot be zero"
    print(var)
    

    Output :

    If input is 0 :

    AssertionError: Input cannot be zero
    

    If input is 1 :

    1
    

Key Points :

  1. It is used as a debugging tool.
  2. It takes an expression and an optional message.
  3. It exists in almost every programming language

Can you nest html forms?

Although the question is pretty old and I agree with the @everyone that nesting of form is not allowed in HTML

But this something all might want to see this

where you can hack(I'm calling it a hack since I'm sure this ain't legitimate) html to allow browser to have nested form

<form id="form_one" action="http://apple.com">
  <div>
    <div>
        <form id="form_two" action="/">
            <!-- DUMMY FORM TO ALLOW BROWSER TO ACCEPT NESTED FORM -->
      </form>
    </div>
      <br/>
    <div>
      <form id="form_three" action="http://www.linuxtopia.org/">
          <input type='submit' value='LINUX TOPIA'/>
      </form>
    </div>
      <br/>

    <div>
      <form id="form_four" action="http://bing.com">
          <input type='submit' value='BING'/>
      </form>
    </div>
      <br/>  
    <input type='submit' value='Apple'/>
  </div>  
</form>

JS FIDDLE LINK

http://jsfiddle.net/nzkEw/10/

element with the max height from a set of elements

The html that you posted should use some <br> to actually have divs with different heights. Like this:

<div>
    <div class="panel">
      Line 1<br>
      Line 2
    </div>
    <div class="panel">
      Line 1<br>
      Line 2<br>
      Line 3<br>
      Line 4
    </div>
    <div class="panel">
      Line 1
    </div>
    <div class="panel">
      Line 1<br>
      Line 2
    </div>
</div>

Apart from that, if you want a reference to the div with the max height you can do this:

var highest = null;
var hi = 0;
$(".panel").each(function(){
  var h = $(this).height();
  if(h > hi){
     hi = h;
     highest = $(this);  
  }    
});
//highest now contains the div with the highest so lets highlight it
highest.css("background-color", "red");

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

SOAP request to WebService with java

A SOAP request is an XML file consisting of the parameters you are sending to the server.

The SOAP response is equally an XML file, but now with everything the service wants to give you.

Basically the WSDL is a XML file that explains the structure of those two XML.


To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             http://www.webservicex.net/uszip.asmx?op=GetInfoByCity


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:GetInfoByCity>
                        <myNamespace:USCity>New York</myNamespace:USCity>
                    </myNamespace:GetInfoByCity>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}

css3 transition animation on load?

Even simplier solution (still with [one line inline] javascript):

Use this as the body tag: Note that body. or this. did not work for me. Only the long ; querySelector allow the use of classList.remove (Linux Chromium)

<body class="onload" onload="document.querySelector('body').classList.remove('onload')">

and add this line on top of your other css rules.

body.onload *{ transform: none !important; }

Take note that this can apply to opacity (as requested by OP [other posters] ) simply by using opacity as a transition trigger instead. (might even work on any other css ruling in the same fashion and you can use multiple class for explicity delay between triggering)

The logic is the same. Enforce no transform (with :none !importanton all child element of body.onloadand once the document is loaded remove the class to trigger all transition on all elements as specified in your css.

FIRST ANSWER BELOW (SEE EDIT ABOVE FOR SHORTER ANSWER)

Here is a reverse solution:

  1. Make your html layout and set the css accordingly to your final result (with all the transformation you want).
  2. Set the transition property to your liking
  3. add a class (eg: waitload) to the elements you want to transform AFTER load. The CSS keyword !important is the key word here.
  4. Once the document is loaded, use JS to remove the class from the elements to to start transformation (and remove the transition: none override).

Works with multiple transition on multiple elements. Did not try cross-browser compatibility.

#rotated{
    transform : rotate(90deg) /* any other transformation */;
    transition  3s;
}
#translated{
    transform : translate(90px) /* any other transformation */;
    transition  3s;
}
.waitload{
    transform: none !important;
}
<div id='rotated' class='waitload'>
    rotate after load
</div>
<div id='translated' class='waitload'>
    trasnlate after load
</div>
<script type="text/javascript">
     // or body onload ?
    [...document.querySelectorAll('.waitload')]
        .map(e => e.classList.remove('waitload'));

</script>

Simple java program of pyramid

enter image description here

 import java.util.Scanner;
    public class Print {
        public static void main(String[] args) {
            int row,temp,c,n;
            Scanner s=new Scanner(System.in);
            n=s.nextInt();
            temp = n;
            for ( row = 1 ; row <= n ; row++ )
               {
                  for ( c = 1 ; c < temp ; c++ )
                    System.out.print(" ");

                  temp--;

                  for ( c = 1 ; c <= 2*row - 1 ; c++ )
                      System.out.print("*");

                  System.out.println("");
               }
        }

    }

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

TLDR:

  1. Rebooting both application and DB servers is the quickest fix where data volume, network settings and code haven't changed. We always do so as a rule
  2. May be indicator of failing hard-drive that needs replacement - check system notifications

I have often encountered this error for various reasons and have had various solutions, including:

  1. refactoring my code to use SqlBulkCopy
  2. increasing Timeout values, as stated in various answers or checking for underlying causes (may not be data related)
  3. Connection Timeout (Default 15s) - How long it takes to wait for a connection to be established with the SQL server before terminating - TCP/PORT related - can go through a troubleshooting checklist (very handy MSDN article)
  4. Command Timeout (Default 30s) - How long it takes to wait for the execution of a query - Query execution/network traffic related - also has a troubleshooting process (another very handy MSDN article)
  5. Rebooting of the server(s) - both application & DB Server (if separate) - where code and data haven't changed, environment must have changed - First thing you must do. Typically caused by patches (operating system, .Net Framework or SQL Server patches or updates). Particularly if timeout exception appears as below (even if we do not use Azure):
    • System.Data.Entity.Core.EntityException: An exception has been raised that is likely due to a transient failure. If you are connecting to a SQL Azure database consider using SqlAzureExecutionStrategy. ---> System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.) ---> System.ComponentModel.Win32Exception: The semaphore timeout period has expired

CSS Image size, how to fill, but not stretch?

To fit image in fullscreen try this:

background-repeat: round;

Are email addresses case sensitive?

I know this is an old question but I just want to comment here: To any extent email addresses ARE case sensitive, most users would be "very unwise" to actively use an email address that requires capitals. They would soon stop using the address because they'd be missing a lot of their mail. (Unless they have a specific reason to make things difficult, and they expect mail only from specific senders they know.)

That's because imperfect humans as well as imperfect software exist, (Surprise!) which will assume all email is lowercase, and for this reason these humans and software will send messages using a "lower cased version" of the address regardless of how it was provided to them. If the recipient is unable to receive such messages, it won't be long before they notice they're missing a lot, and switch to a lowercase-only email address, or get their server set up to be case-insensitive.

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

How can I get input radio elements to horizontally align?

To get your radio button to list horizontally , just add

RepeatDirection="Horizontal"

to your .aspx file where the asp:radiobuttonlist is being declared.

How to echo in PHP, HTML tags

You can replace '<' with &lt; and '>' with &gt;. For example:

echo "&lt;div&gt;";

The output will be visible <div>.

For longer strings, make a function, for example

function example($input) {
    $output = str_replace('>', '&gt;', str_replace('<', '&lt;', $html));
    return $output;
}

echo example($your_html);

Don't forget to put backslashes href=\"#\" or do it with single quotes href='#' or change it in a function too with str_replace.

Select first 4 rows of a data.frame in R

Using the index:

df[1:4,]

Where the values in the parentheses can be interpreted as either logical, numeric, or character (matching the respective names):

df[row.index, column.index]

Read help(`[`) for more detail on this subject, and also read about index matrices in the Introduction to R.

Detect when a window is resized using JavaScript ?

If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:

Super Super compact

var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }

All 3 possible combinations together (ES6)

var t
window.onresize = () => {
    resizing(this, this.innerWidth, this.innerHeight) //1
    if (typeof t == 'undefined') resStarted() //2
    clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}

function resizing(target, w, h) {
    console.log(`Youre resizing: width ${w} height ${h}`)
}    
function resStarted() { 
    console.log('Resize Started') 
}
function resEnded() { 
    console.log('Resize Ended') 
}

How do I log errors and warnings into a file?

That's my personal short function

# logging
/*
[2017-03-20 3:35:43] [INFO] [file.php] Here we are
[2017-03-20 3:35:43] [ERROR] [file.php] Not good
[2017-03-20 3:35:43] [DEBUG] [file.php] Regex empty

mylog ('hallo') -> INFO
mylog ('fail', 'e') -> ERROR
mylog ('next', 'd') -> DEBUG
mylog ('next', 'd', 'debug.log') -> DEBUG file debug.log
*/
function mylog($text, $level='i', $file='logs') {
    switch (strtolower($level)) {
        case 'e':
        case 'error':
            $level='ERROR';
            break;
        case 'i':
        case 'info':
            $level='INFO';
            break;
        case 'd':
        case 'debug':
            $level='DEBUG';
            break;
        default:
            $level='INFO';
    }
    error_log(date("[Y-m-d H:i:s]")."\t[".$level."]\t[".basename(__FILE__)."]\t".$text."\n", 3, $file);
}

Convert .class to .java

Invoking javap to read the bytecode

The javap command takes class-names without the .class extension. Try

javap -c ClassName

Converting .class files back to .java files

javap will however not give you the implementations of the methods in java-syntax. It will at most give it to you in JVM bytecode format.

To actually decompile (i.e., do the reverse of javac) you will have to use proper decompiler. See for instance the following related question:

Question mark and colon in statement. What does it mean?

In the particular case you've provided, it's a conditional assignment. The part before the question mark (?) is a boolean condition, and the parts either side of the colon (:) are the values to assign based on the result of the condition (left side of the colon is the value for true, right side is the value for false).

Sorting a list using Lambda/Linq to objects

Sort uses the IComparable interface, if the type implements it. And you can avoid the ifs by implementing a custom IComparer:

class EmpComp : IComparer<Employee>
{
    string fieldName;
    public EmpComp(string fieldName)
    {
        this.fieldName = fieldName;
    }

    public int Compare(Employee x, Employee y)
    {
        // compare x.fieldName and y.fieldName
    }
}

and then

list.Sort(new EmpComp(sortBy));

Pretty print in MongoDB shell as default

(note: this is answer to original version of the question, which did not have requirements for "default")

You can ask it to be pretty.

db.collection.find().pretty()

Android and Facebook share intent

Here is something I did which open Facebook App with Link

shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setComponent(new ComponentName("com.facebook.katana",
                    "com.facebook.katana.activity.composer.ImplicitShareIntentHandler"));

shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,  videoUrl);

The server committed a protocol violation. Section=ResponseStatusLine ERROR

Skype was the main cause of my problem:

This error usually occurs when you have set up Visual Studio to debug an existing web application running in IIS rather than the built in ASP.NET debug web server. IIS by default listens for web requests on port 80. In this case, another application is already listening for requests on port 80. Typically, the offending application is Skype, which by default takes over listening on ports 80 and 443 when installed. Skype is already occupy the port 80. So IIS is unable to start.

To resolve the issue follow the steps:

Skype -> Tools -> Options -> Advanced -> Connection:

Uncheck "Use port 80 and 443 as alternatives for incoming connections".

And as pointed out below perform an IIS reset once done.

Compare a string using sh shell

-eq is a mathematical comparison operator. I've never used it for string comparison, relying on == and != for compares.

if [ 'XYZ' == 'ABC' ]; then   # Double equal to will work in Linux but not on HPUX boxes it should be if [ 'XYZ' = 'ABC' ] which will work on both
  echo "Match"
else
  echo "No Match"
fi

What is the difference between XML and XSD?

XML versus XSD

XML defines the syntax of elements and attributes for structuring data in a well-formed document.

XSD (aka XML Schema), like DTD before, powers the eXtensibility in XML by enabling the user to define the vocabulary and grammar of the elements and attributes in a valid XML document.

Foreign Key naming scheme

This is probably over-kill, but it works for me. It helps me a great deal when I am dealing with VLDBs especially. I use the following:

CONSTRAINT [FK_ChildTableName_ChildColName_ParentTableName_PrimaryKeyColName]

Of course if for some reason you are not referencing a primary key you must be referencing a column contained in a unique constraint, in this case:

CONSTRAINT [FK_ChildTableName_ChildColumnName_ParentTableName_ColumnInUniqueConstaintName]

Can it be long, yes. Has it helped keep info clear for reports, or gotten me a quick jump on that the potential issue is during a prod-alert 100% would love to know peoples thoughts on this naming convention.

How to get all groups that a user is a member of?

Studying all comments presented gave me a starting point (thanks for such) but left me with several unresolved issues. As result here is my answer. The code snippet provided does a little more than what is asked for but it provides helpful debugging info.

[array] $script:groupsdns = @()
function Get-ADPrincipalGroupMembershipRecursive() 
{
  Param( [string] $dn, [int] $level = 0, [array] $groups = @() )

  #if(($groupsdns | where { $_.DistinguishedName -eq $dn }).Count -ne 0 ) { return $groups } # dependency on next statement
  #$groupsdns += (Get-ADObject $dn -Properties MemberOf) # Get-ADObject cannot find an object with identity
  if ($script:groupsdns.Contains($dn)) { return $groups }
  $script:groupsdns += $dn
  $mo = $Null
  $mo = Get-ADObject $dn -Properties MemberOf # Get-ADObject cannot find an object with identity
  $group = ($dn + " (" + $level.ToString())
  if ($mo -eq $Null) { $group += "!" }
  $group += ")"
  $groups += $group
  foreach( $groupdn in $mo.MemberOf )
  {
    $groups = Get-ADPrincipalGroupMembershipRecursive -dn $groupdn -level ($level+1) -groups $groups
  }
  if ($level -le 0) 
  { 
    $primarygroupdn = (Get-ADUser -Identity $dn -Properties PrimaryGroup).PrimaryGroup 
    $groups = Get-ADPrincipalGroupMembershipRecursive -dn $primarygroupdn -level ($level+1) -groups $groups
  }
  return $groups
}
$adusergroups = Get-ADPrincipalGroupMembershipRecursive -dn $aduser.DistinguishedName
$adusergroups | ft -AutoSize | `
              Out-File -Width 512 Get-ADPrincipalGroupMembershipRecursive.txt #-Append #-Wrap # | Sort-Object -Property Name

Is "delete this" allowed in C++?

The C++ FAQ Lite has a entry specifically for this

I think this quote sums it up nicely

As long as you're careful, it's OK for an object to commit suicide (delete this).

Forcing Internet Explorer 9 to use standards document mode

Make sure you take into account that adding this tag,

<meta http-equiv="X-UA-Compatible" content="IE=Edge">

may only allow compatibility with the latest versions. It all depends on your libraries

CSS Float: Floating an image to the left of the text

I almost always just use overflow:hidden on my text-elements in those situations, it often works like a charm ;)

.post-container {
 margin: 20px 20px 0 0;
 border:5px solid #333;
}
.post-thumb img {
 float: left;
}
.post-content {
 overflow:hidden;
}

Possible to view PHP code of a website?

A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.

For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.

Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.

However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.

Read the Security section of the PHP manual as a starting point to keeping your code safe.

Meaning of "[: too many arguments" error from if [] (square brackets)

I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-

export k=$(date "+%k");
if [ $k -ge 16 ] 
    then exit 0; 
else 
    echo "good job for nothing"; 
fi;

that way I resolved my problem. Hope that will help for you too.

Better way to find control in ASP.NET

Late as usual. If anyone is still interested in this there are a number of related SO questions and answers. My version of recursive extension method for resolving this:

public static IEnumerable<T> FindControlsOfType<T>(this Control parent)
                                                        where T : Control
{
    foreach (Control child in parent.Controls)
    {
        if (child is T)
        {
            yield return (T)child;
        }
        else if (child.Controls.Count > 0)
        {
            foreach (T grandChild in child.FindControlsOfType<T>())
            {
                yield return grandChild;
            }
        }
    }
}

Adding elements to object

This is an old question, anyway today the best practice is by using Object.defineProperty

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});

object1.property1 = 77;
// throws an error in strict mode

console.log(object1.property1);
// expected output: 42

Git:nothing added to commit but untracked files present

Please Follow this process

First of all install git bash and create a repository on git

1) Go to working directory where the file exist which you want to push on remote and create .git folder by

$ git init

2) Add the files in your new local repository.

$ git add .

Note: while you are in same folder make sure you have placed dot after command if you putting path or not putting dot that will create ambiguity

3) Commit the files that you've staged in your local repository.

$ git commit -m "First commit"**

4) after this go to git repository and copy remote URL

$ git remote add origin *remote repository URL

5)

$ git remote -v

Note: this will ask for user.email and user.name just put it as per config

6)

$ git push origin master

this will push whole committed code to FILE.git on repository

And I think we done

OwinStartup not firing

I think what some people were trying to get to above is that if you want to programatically make your OWIN server "come to life", you'd be calling something like this:

using Microsoft.Owin.Hosting;

    IDisposable _server = WebApp.Start<StartupMethod>("http://+:5000"); 
              // Start Accepting HTTP via all interfaces on port 5000

Once you make this call, you will see the call to StartupMethod() fire in the debugger

String Comparison in Java

The String.compareTo(..) method performs lexicographical comparison. Lexicographically == alphebetically.

HttpContext.Current.Request.Url.Host what it returns?

The Host property will return the domain name you used when accessing the site. So, in your development environment, since you're requesting

http://localhost:950/m/pages/Searchresults.aspx?search=knife&filter=kitchen

It's returning localhost. You can break apart your URL like so:

Protocol: http
Host: localhost
Port: 950
PathAndQuery: /m/pages/SearchResults.aspx?search=knight&filter=kitchen

Creating an empty list in Python

I use [].

  1. It's faster because the list notation is a short circuit.
  2. Creating a list with items should look about the same as creating a list without, why should there be a difference?

How to change content on hover

_x000D_
_x000D_
.label:after{_x000D_
    content:'ADD';_x000D_
}_x000D_
.label:hover:after{_x000D_
    content:'NEW';_x000D_
}
_x000D_
<span class="label"></span>
_x000D_
_x000D_
_x000D_

Add marker to Google Map on Click

This is actually a documented feature, and can be found here

// This event listener calls addMarker() when the map is clicked.
  google.maps.event.addListener(map, 'click', function(e) {
    placeMarker(e.latLng, map);
  });

  function placeMarker(position, map) {
    var marker = new google.maps.Marker({
      position: position,
      map: map
    });  
    map.panTo(position);
  }

How to find whether MySQL is installed in Red Hat?

to ckeck the status use the below command, which worked on debian....

/etc/init.d/mysql status

to start my sql server use the below command

/etc/init.d/mysql start

to stop the server use the below command

/etc/init.d/mysql stop

Get Return Value from Stored procedure in asp.net

Do it this way (make necessary changes in code)..

            SqlConnection con = new SqlConnection(GetConnectionString());
            con.Open();
            SqlCommand cmd = new SqlCommand("CheckUser", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter p1 = new SqlParameter("username", username.Text);
            SqlParameter p2 = new SqlParameter("password", password.Text);
            cmd.Parameters.Add(p1);
            cmd.Parameters.Add(p2);
            SqlDataReader rd = cmd.ExecuteReader();
            if(rd.HasRows)
            {
                //do the things
            }
            else
            {
                lblinfo.Text = "abc";
            }

Split comma-separated input box values into array in jquery, and loop through it

var array = searchTerms.split(",");

for (var i in array){
     alert(array[i]);
}

How to create a new component in Angular 4 using CLI

ng generate component component_name was not working in my case because instead of using 'app' as project folder name, I renamed it to something else. I again changed it to app. Now, it is working fine

How do I change the value of a global variable inside of a function

<script>
var x = 2; //X is global and value is 2.

function myFunction()
{
 x = 7; //x is local variable and value is 7.

}

myFunction();

alert(x); //x is gobal variable and the value is 7
</script>

How do you connect to a MySQL database using Oracle SQL Developer?

My experience with windows client and linux/mysql server:

When sqldev is used in a windows client and mysql is installed in a linux server meaning, sqldev network access to mysql.

Assuming mysql is already up and running and the databases to be accessed are up and functional:

• Ensure the version of sqldev (32 or 64). If 64 and to avoid dealing with path access copy a valid 64 version of msvcr100.dll into directory ~\sqldeveloper\jdev\bin.

a. Open the file msvcr100.dll in notepad and search for first occurrence of “PE “

 i. “PE  d” it is 64.

ii. “PE  L” it is 32.

b. Note: if sqldev is 64 and msvcr100.dll is 32, the application gets stuck at startup.

• For sqldev to work with mysql there is need of the JDBC jar driver. Download it from mysql site.

a. Driver name = mysql-connector-java-x.x.xx

b. Copy it into someplace related to your sqldeveloper directory.

c. Set it up in menu sqldev Tools/Preferences/Database/Third Party JDBC Driver (add entry)

• In Linux/mysql server change file /etc/mysql/mysql.conf.d/mysqld.cnf look for

bind-address = 127.0.0.1 (this linux localhost)

and change to

bind-address = xxx.xxx.xxx.xxx (this linux server real IP or machine name if DNS is up)

• Enter to linux mysql and grant needed access for example

# mysql –u root -p

GRANT ALL ON . to root@'yourWindowsClientComputerName' IDENTIFIED BY 'mysqlPasswd';

flush privileges;

restart mysql - sudo /etc/init.d/mysql restart

• Start sqldev and create a new connection

a. user = root

b. pass = (your mysql pass)

c. Choose MySql tab

 i.   Hostname = the linux IP hostname

 ii.  Port     = 3306 (default for mysql)

 iii. Choose Database = (from pull down the mysql database you want to use)

 iv.  save and connect

That is all I had to do in my case.

Thank you,

Ale

node and Error: EMFILE, too many open files

I am not sure whether this will help anyone, I started working on a big project with lot of dependencies which threw me the same error. My colleague suggested me to install watchman using brew and that fixed this problem for me.

brew update
brew install watchman

Edit on 26 June 2019: Github link to watchman

Is there a better way to compare dictionary values

You can use sets for this too

>>> a = {'x': 1, 'y': 2}
>>> b = {'y': 2, 'x': 1}
>>> set(a.iteritems())-set(b.iteritems())
set([])
>>> a['y']=3
>>> set(a.iteritems())-set(b.iteritems())
set([('y', 3)])
>>> set(b.iteritems())-set(a.iteritems())
set([('y', 2)])
>>> set(b.iteritems())^set(a.iteritems())
set([('y', 3), ('y', 2)])

CSS checkbox input styling

Although CSS does provide a way for you to do the style specific to the checkbox type or another type, there are going to be problems with browsers that do not support this.

I think your only option in this case is going to be to apply classes to your checkboxes.

just add the class="checkbox" to your checkboxes.

Then create that style in your css code.

One thing you could do is this:

main.css

input[type="checkbox"] { /* css code here */ }

ie.css

.checkbox{ /* css code here for ie */ }

Then use the IE specific css include:

<!--[if lt IE 7]>
   <link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->

You will still need to add the class for it to work in IE, and it will not work in other non-IE browsers that do not support IE. But it will make your website forward-thinking with css code and as IE gets support, you will be able to remove the ie specific css code and also the css classes from the checkboxes.

How to clean old dependencies from maven repositories?

If you are on Unix, you could use the access time of the files in there. Just enable access time for your filesystem, then run a clean build of all your projects you would like to keep dependencies for and then do something like this (UNTESTED!):

find ~/.m2 -amin +5 -iname '*.pom' | while read pom; do parent=`dirname "$pom"`; rm -Rf "$parent"; done

This will find all *.pom files which have last been accessed more than 5 minutes ago (assuming you started your builds max 5 minutes ago) and delete their directories.

Add "echo " before the rm to do a 'dry-run'.

OraOLEDB.Oracle provider is not registered on the local machine

  1. Right Click on My Computer
  2. Click on properties
  3. Click on Advanced System Settings
  4. Click on "Environment Variables" button.
  5. In the system Variable section find the "PATH" variable
  6. Edit the "PATH" variable and add Oracle installation path to it (from your local machine) like ;C:\oracle\product\10.2.0\client_1\bin

How to close Android application?

Just write this code on your button EXIT click.

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("LOGOUT", true);
startActivity(intent);

And in the onCreate() method of your MainActivity.class write below code as a first line,

if (getIntent().getBooleanExtra("LOGOUT", false))
{
    finish();
}

git rebase fatal: Needed a single revision

The error occurs when your repository does not have the default branch set for the remote. You can use the git remote set-head command to modify the default branch, and thus be able to use the remote name instead of a specified branch in that remote.

To query the remote (in this case origin) for its HEAD (typically master), and set that as the default branch:

$ git remote set-head origin --auto

If you want to use a different default remote branch locally, you can specify that branch:

$ git remote set-head origin new-default

Once the default branch is set, you can use just the remote name in git rebase <remote> and any other commands instead of explicit <remote>/<branch>.

Behind the scenes, this command updates the reference in .git/refs/remotes/origin/HEAD.

$ cat .git/refs/remotes/origin/HEAD 
ref: refs/remotes/origin/master

See the git-remote man page for further details.

Change the mouse cursor on mouse over to anchor-like style

You actually don't need jQuery, just CSS. For example, here's some HTML:

<div class="special"></div>

And here's the CSS:

.special
{
    cursor: pointer;
}

Render HTML to an image

You can add reference HtmlRenderer to your project and do the following,

string htmlCode ="<p>This is a sample html.</p>";
Image image = HtmlRender.RenderToImage(htmlCode ,new Size(500,300));

get the value of DisplayName attribute

Late to the party I know.

I use this:

public static string GetPropertyDisplayName(PropertyInfo pi)
{
  var dp = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().SingleOrDefault();
  return dp != null ? dp.DisplayName : pi.Name;
}

Hope this helps.

Set scroll position

... Or just replace body by documentElement:

document.documentElement.scrollTop = 0;

How to fix Cannot find module 'typescript' in Angular 4?

If you don't have particular needs, I suggest to install Typescript locally.

NPM Installation Method

npm install --global typescript # Global installation
npm install --save-dev typescript # Local installation

Yarn Installation Method

yarn global add typescript # Global installation
yarn add --dev typescript # Local installation

Setting Inheritance and Propagation flags with set-acl and powershell

Just because you're in PowerShell don't forgot about good ol' exes. Sometimes they can provide the easiest solution e.g.:

icacls.exe $folder /grant 'domain\user:(OI)(CI)(M)'

How to get the separate digits of an int number?

// could be any num this is a randomly generated one
int num = (int) (Math.random() * 1000);

// this will return each number to a int variable
int num1 = num % 10;
int num2 = num / 10 % 10;
int num3 = num /100 % 10;

// you could continue this pattern for 4,5,6 digit numbers
// dont need to print you could then use the new int values man other ways
System.out.print(num1);
System.out.print("\n" + num2);
System.out.print("\n" + num3);

What are the dark corners of Vim your mom never told you about?

gg=G

Corrects indentation for entire file. I was missing my trusty <C-a><C-i> in Eclipse but just found out vim handles it nicely.

Datanode process not running in Hadoop

You need to do something like this:

  • bin/stop-all.sh (or stop-dfs.sh and stop-yarn.sh in the 2.x serie)
  • rm -Rf /app/tmp/hadoop-your-username/*
  • bin/hadoop namenode -format (or hdfs in the 2.x serie)

the solution was taken from: http://pages.cs.brandeis.edu/~cs147a/lab/hadoop-troubleshooting/. Basically it consists in restarting from scratch, so make sure you won't loose data by formating the hdfs.

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

How do I search for an object by its ObjectId in the mongo console?

Simply do:

db.getCollection('test').find('4ecbe7f9e8c1c9092c000027');

How can I generate Unix timestamps?

With NodeJS, just open a terminal and type:
node -e "console.log(new Date().getTime())" or node -e "console.log(Date.now())"

ContractFilter mismatch at the EndpointDispatcher exception

A "ContractFilter mismatch at the EndpointDispatcher" means the receiver could not process the message because it did not match any of the contracts the receiver has configured for the endpoint which received the message.

This can be because:

  • You have different contracts between client and sender.
  • You're using a different binding between client and sender.
  • The message security settings are not consistent between client and sender.

Have at look at the EndpointDispatcher class for more information on the subject.

So:

Make certain that your client and server contracts match.

  • If you've generated your client from a WSDL, is the WSDL up-to-date?
  • If you've made a recent change to the contract, have you deployed the right version of both client and server?
  • If you've hand-crafted your client contract classes, make sure the namespaces, elements names and action names match the ones expected by the server.

Check the bindings are the same between client and server.

  • If you're using a .config file to manage your endpoints, make sure the binding elements match.

Check the security settings are the same between client and server.

  • If you're using a .config file to manage your endpoints, make sure the security elements match.

Gets byte array from a ByteBuffer in java

Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.

I.e.

byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"

Which might not be what you intend to do.

If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.

Using sessions & session variables in a PHP Login Script

$session_start();

extract($_POST);         
//extract data from submit post 

if(isset($submit))  
{

if($user=="user" && $pass=="pass")

{

$_SESSION['user']= $user;   

//if correct password and name store in session 

}
else {

echo "Invalid user and password";

header("Locatin:form.php");

}

if(isset($_SESSION['user'])) 

{

//your home page code here

exit;
}

change PATH permanently on Ubuntu

Add the following line in your .profile file in your home directory (using vi ~/.profile):

PATH=$PATH:/home/me/play
export PATH

Then, for the change to take effect, simply type in your terminal:

$ . ~/.profile

Making the main scrollbar always visible

An alternative approach is to set the width of the html element to 100vw. On many if not most browsers, this negates the effect of scrollbars on the width.

html { width: 100vw; }

Is there any way to do HTTP PUT in python

I also recommend httplib2 by Joe Gregario. I use this regularly instead of httplib in the standard lib.

How does MySQL process ORDER BY and LIMIT in a query?

It will order first, then get the first 20. A database will also process anything in the WHERE clause before ORDER BY.

With CSS, use "..." for overflowed block of multi-lines

I've found this css (scss) solution that works quite well. On webkit browsers it shows the ellipsis and on other browsers it just truncates the text. Which is fine for my intended use.

$font-size: 26px;
$line-height: 1.4;
$lines-to-show: 3;

h2 {
  display: block; /* Fallback for non-webkit */
  display: -webkit-box;
  max-width: 400px;
  height: $font-size*$line-height*$lines-to-show; /* Fallback for non-webkit */
  margin: 0 auto;
  font-size: $font-size;
  line-height: $line-height;
  -webkit-line-clamp: $lines-to-show;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

An example by the creator: http://codepen.io/martinwolf/pen/qlFdp

jQuery Loop through each div

Like this:

$(".target").each(function(){
    var images = $(this).find(".scrolling img");
    var width = images.width();
    var imgLength = images.length;
    $(this).find(".scrolling").width( width * imgLength * 1.2 );
});

The $(this) refers to the current .target which will be looped through. Within this .target I'm looking for the .scrolling img and get the width. And then keep on going...

Images with different widths

If you want to calculate the width of all images (when they have different widths) you can do it like this:

// Get the total width of a collection.
$.fn.getTotalWidth = function(){
    var width = 0;
    this.each(function(){
        width += $(this).width();
    });
    return width;
}

$(".target").each(function(){
    var images = $(this).find(".scrolling img");
    var width = images.getTotalWidth();
    $(this).find(".scrolling").width( width * 1.2 );
});

Java - Convert image to Base64

The line

base64String = Base64.encode(byteArray);

converts the full array (102400 bytes) to Base64, not just the number of bytes you have read. You need to pass it the numbers of bytes.

CORS: credentials mode is 'include'

If you're using .NET Core, you will have to .AllowCredentials() when configuring CORS in Startup.CS.

Inside of ConfigureServices

services.AddCors(o => {
    o.AddPolicy("AllowSetOrigins", options =>
    {
        options.WithOrigins("https://localhost:xxxx");
        options.AllowAnyHeader();
        options.AllowAnyMethod();
        options.AllowCredentials();
    });
});

services.AddMvc();

Then inside of Configure:

app.UseCors("AllowSetOrigins");
app.UseMvc(routes =>
    {
        // Routing code here
    });

For me, it was specifically just missing options.AllowCredentials() that caused the error you mentioned. As a side note in general for others having CORS issues as well, the order matters and AddCors() must be registered before AddMVC() inside of your Startup class.

Understanding the order() function

they are similar but not same

set.seed(0)
x<-matrix(rnorm(10),1)

# one can compute from the other
rank(x)  == col(x)%*%diag(length(x))[order(x),]
order(x) == col(x)%*%diag(length(x))[rank(x),]
# rank can be used to sort
sort(x) == x%*%diag(length(x))[rank(x),]

Strtotime() doesn't work with dd/mm/YYYY format

Are you getting this value from a database? If so, consider formatting it in the database (use date_format in mysql, for example). If not, exploding the value may be the best bet, since strtotime just doesn't seem to appreciate dd/mm/yyyy values.

How can I create database tables from XSD files?

Might take a look at the XSD tool in visual studio 2k8... I have created a relational dataset from an xsd and it might help your out somehow.

How do I use cx_freeze?

find the cxfreeze script and run it. It will be in the same path as your other python helper scripts, such as pip.

cxfreeze Main.py --target-dir dist

read more at: http://cx-freeze.readthedocs.org/en/latest/script.html#script

JavaScript - Hide a Div at startup (load)

I've had the same problem.

Use CSS to hide is not the best solution, because sometimes you want users without JS can see the div.. The cleanest solution is to hide the div with JQuery. But the div is visible about 0.5 seconde, which is problematic if the div is on the top of the page.

In these cases, I use an intermediate solution, without JQuery. This one works and is immediate :

<script>document.write('<style>.js_hidden { display: none; }</style>');</script>

<div class="js_hidden">This div will be hidden for JS users, and visible for non JS users.</div>

Of course, you can still add all the effects you want on the div, JQuery toggle() for example. And you will get the best behaviour possible (imho) :

  • for non JS users, the div is visible directly
  • for JS users, the div is hidden and has toggle effect.

What is thread Safe in java?

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.

How do I make a text input non-editable?

You can use readonly attribute, if you want your input only to be read. And you can use disabled attribute, if you want input to be shown, but totally disabled (even processing languages like PHP wont be able to read those).

How to change already compiled .class file without decompile?

I added some codes and save .class file.

What you see in JD EClipse Decompiler is decompiled representation of byte code in the .class file. Even though you change the text it won't affect the byte code.

Clear listview content?

Remove your items from your custom adapter and call notifyDataSetChanged().

Set a default font for whole iOS app?

We have achieved the same in Swift -Xcode 7.2 using Parent View Controller and Child view controller (Inheritance).

File - New - Cocoa Touch class - ParentViewController.

    import UIKit
    import Foundation

    class ParentViewController: UIViewController {

        var appUIColor:UIColor = UIColor.redColor()
        var appFont:UIFont = UIFont(name: "Copperplate", size: 20)!

        override func viewDidLoad() {
            super.viewDidLoad()
        }
        func addStatusBar()
        {
            let view = UIView(frame:
                CGRect(x: 0.0, y: 0.0, width: UIScreen.mainScreen().bounds.size.width, height: 20.0)
            )
            view.backgroundColor = appUIColor
            self.view.addSubview(view)
        }
    }    

Make child view controllers and associate with a StoryBoard VC, add a textLabel.

    import UIKit

    class FontTestController: ParentViewController {
        @IBOutlet var testLabel: UILabel!

        override func viewDidLoad() {
            super.viewDidLoad()
            testLabel.font =  appFont
            testLabel.textColor = appUIColor
        }

OR Make a custom UILabel Class(Sub classing method) and associate required labels to it.

import Foundation
import UIKit

class CustomFontLabel: UILabel {
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        backgroundColor = ParentViewController().appUIColor
        font = ParentViewController().appFont
        textColor = UIColor.blackColor()
    }
}

Note: The Font and colour declared in Parent VC are implemented in CustomFontLabel . The advantage is we can alter the properties of uilabel/any view all together in some simple changes in Parent VC.

2)'for' looping UIView for sub views. It works only on a particular VC.

    override func viewWillLayoutSubviews() {
            for view in self.view.subviews  {
                if view.isKindOfClass(UITextField) {
                UITextField.appearance().font =  UIFont(name: "Copperplate", size: 20)
                }
                if view.isKindOfClass(UILabel) {
                    UILabel.appearance().font =  UIFont(name: "Copperplate", size: 20)    
                }               
            }       
        }

Difference between session affinity and sticky session?

I've seen those terms used interchangeably, but there are different ways of implementing it:

  1. Send a cookie on the first response and then look for it on subsequent ones. The cookie says which real server to send to.
    Bad if you have to support cookie-less browsers
  2. Partition based on the requester's IP address.
    Bad if it isn't static or if many come in through the same proxy.
  3. If you authenticate users, partition based on user name (it has to be an HTTP supported authentication mode to do this).
  4. Don't require state.
    Let clients hit any server (send state to the client and have them send it back)
    This is not a sticky session, it's a way to avoid having to do it.

I would suspect that sticky might refer to the cookie way, and that affinity might refer to #2 and #3 in some contexts, but that's not how I have seen it used (or use it myself)

How do I declare class-level properties in Objective-C?

properties have a specific meaning in Objective-C, but I think you mean something that's equivalent to a static variable? E.g. only one instance for all types of Foo?

To declare class functions in Objective-C you use the + prefix instead of - so your implementation would look something like:

// Foo.h
@interface Foo {
}

+ (NSDictionary *)dictionary;

// Foo.m
+ (NSDictionary *)dictionary {
  static NSDictionary *fooDict = nil;
  if (fooDict == nil) {
    // create dict
  }
  return fooDict;
}

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

In Sublime3 (Windows):

Some users may get an inverted screen using the Ctrl+Alt+? in windows. To Solve this go to

Preferences->Key Bindings-User

And add these two lines at the end of the file just before closing brackets:

{ "keys": ["ctrl+alt+pageup"], "command": "select_lines", "args": {"forward": false} },

{ "keys": ["ctrl+alt+pagedown"], "command": "select_lines", "args": {"forward": true} } 

Or use your own keys.

Getting the name / key of a JToken with JSON.net

JToken is the base class for JObject, JArray, JProperty, JValue, etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject. Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty, you can get its Name. (Of course you can also get the Value if desired, which is another JToken.)

Putting it all together we have:

JArray array = JArray.Parse(json);

foreach (JObject content in array.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
        Console.WriteLine(prop.Name);
    }
}

Output:

MobileSiteContent
PageContent

ActionBar text color

These functions work well

In Java

private void setActionbarTextColor(ActionBar actBar, int color) {

    String title = actBar.getTitle().toString();
    Spannable spannablerTitle = new SpannableString(title);
    spannablerTitle.setSpan(new ForegroundColorSpan(color), 0, spannablerTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    actBar.setTitle(spannablerTitle);

}

then to use it just feed it your action bar and the new color i.e.

ActionBar actionBar = getActionBar();    // Or getSupportActionBar() if using appCompat
int red = Color.RED
setActionbarTextColor(actionBar, red);

In Kotlin

You can use an extension function like this:

private fun ActionBar.setTitleColor(color: Int) {
    val text = SpannableString(title ?: "")
    text.setSpan(ForegroundColorSpan(color),0,text.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
    title = text
}

And then apply to your ActionBar with

actionBar?.setTitleColor(Color.RED)

Get file name from a file location in Java

Apache Commons IO provides the FilenameUtils class which gives you a pretty rich set of utility functions for easily obtaining the various components of filenames, although The java.io.File class provides the basics.

Detecting the onload event of a window opened with window.open

onload event handler must be inside popup's HTML <body> markup.

How can I solve ORA-00911: invalid character error?

If a special character other than $, _, and # is used in the name of a column or table, the name must be enclosed in double quotations. Link

Recommendation for compressing JPG files with ImageMagick

I added -adaptive-resize 60% to the suggested command, but with -quality 60%.

convert -strip -interlace Plane -gaussian-blur 0.05 -quality 60% -adaptive-resize 60% img_original.jpg img_resize.jpg

These were my results

  • img_original.jpg = 13,913KB
  • img_resized.jpg = 845KB

I'm not sure if that conversion destroys my image too much, but I honestly didn't think my conversion looked like crap. It was a wide angle panorama and I didn't care for meticulous obstruction.

How to export table as CSV with headings on Postgresql?

This solution worked for me using \copy.

psql -h <host> -U <user> -d <dbname> -c "\copy <table_name> FROM '<path to csvfile/file.csv>' with (format csv,header true, delimiter ',');"

Get the _id of inserted document in Mongo database in NodeJS

@JSideris, sample code for getting insertedId.

db.collection(COLLECTION).insertOne(data, (err, result) => {
    if (err) 
      return err;
    else 
      return result.insertedId;
  });

Highlight Bash/shell code in Markdown files

If I need only to highlight the first word as a command, I often use properties:

```properties
npm run build
```  

I obtain something like:

npm run build

Adding a right click menu to an item

Add a contextmenu to your form and then assign it in the control's properties under ContextMenuStrip. Hope this helps :).

Hope this helps:

ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Item 1");
cm.MenuItems.Add("Item 2");

pictureBox1.ContextMenu = cm;

How to set RelativeLayout layout params in code not in xml?

Something like this..

 RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.widget43);
                // ListView listView = (ListView) findViewById(R.id.ListView01);

                LayoutInflater inflater = (LayoutInflater) this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                // View footer = inflater.inflate(R.layout.footer, null);
                View footer = LayoutInflater.from(this).inflate(R.layout.footer,
                        null);
                final RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.FILL_PARENT,
                        RelativeLayout.LayoutParams.FILL_PARENT);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);
footer.setLayoutParams(layoutParams);

Still Reachable Leak detected by Valgrind

Here is a proper explanation of "still reachable":

"Still reachable" are leaks assigned to global and static-local variables. Because valgrind tracks global and static variables it can exclude memory allocations that are assigned "once-and-forget". A global variable assigned an allocation once and never reassigned that allocation is typically not a "leak" in the sense that it does not grow indefinitely. It is still a leak in the strict sense, but can usually be ignored unless you are pedantic.

Local variables that are assigned allocations and not free'd are almost always leaks.

Here is an example

int foo(void)
{
    static char *working_buf = NULL;
    char *temp_buf;
    if (!working_buf) {
         working_buf = (char *) malloc(16 * 1024);
    }
    temp_buf = (char *) malloc(5 * 1024);

    ....
    ....
    ....

}

Valgrind will report working_buf as "still reachable - 16k" and temp_buf as "definitely lost - 5k".

How to sign an android apk file

Don't worry...! Follow these below steps and you will get your signed .apk file. I was also worry about that, but these step get ride me off from the frustration. Steps to sign your application:

  1. Export the unsigned package:

Right click on the project in Eclipse -> Android Tools -> Export Unsigned Application Package (like here we export our GoogleDriveApp.apk to Desktop)

Sign the application using your keystore and the jarsigner tool (follow below steps):

Open cmd-->change directory where your "jarsigner.exe" exist (like here in my system it exist at "C:\Program Files\Java\jdk1.6.0_17\bin"

Now enter belwo command in cmd:

jarsigner -verbose -keystore c:\users\android\debug.keystore c:\users\pir fahim\Desktops\GoogleDriveApp.apk my_keystore_alias

It will ask you to provide your password: Enter Passphrase for keystore: It will sign your apk.To verify that the signing is successful you can run:

jarsigner -verify c:\users\pir fahim\Desktops\GoogleDriveApp.apk

It should come back with: jar verified.

Method 2

If you are using eclipse with ADT, then it is simple to compiled, signed, aligned, and ready the file for distribution.what you have to do just follow this steps.

  • File > Export.
  • Export android application
  • Browse-->select your project
  • Next-->Next

These steps will compiled, signed and zip aligned your project and now you are ready to distribute your project or upload at Google Play store.

Flask raises TemplateNotFound error even though template file exists

If you run your code from an installed package, make sure template files are present in directory <python root>/lib/site-packages/your-package/templates.


Some details:

In my case I was trying to run examples of project flask_simple_ui and jinja would always say

jinja2.exceptions.TemplateNotFound: form.html

The trick was that sample program would import installed package flask_simple_ui. And ninja being used from inside that package is using as root directory for lookup the package path, in my case ...python/lib/site-packages/flask_simple_ui, instead of os.getcwd() as one would expect.

To my bad luck, setup.py has a bug and doesn't copy any html files, including the missing form.html. Once I fixed setup.py, the problem with TemplateNotFound vanished.

I hope it helps someone.

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

As other people have mentioned, this issue is common when using adblock or similar extensions.

The source of my issues was my Privacy Badger extension.

Scrolling an iframe with JavaScript?

Inspired by Nelson's comment I made this.

Workaround for javascript Same-origin policy with regards to using.ScrollTo( ) on document originating on an external domain.

Very simple workaround for this involves creating a dummy HTML page that hosts the external website within it, then calling .ScrollTo(x,y) on that page once it's loaded. Then the only thing you need to do is have a frame or an iframe bring up this website.

There are a lot of other ways to do it, this is by far the most simplified way to do it.

*note the height must be large to accommodate the scroll bars maximum value.

--home.html

<html>
<head>
<title>Home</title>
</head>

<frameset rows="*,170">
<frame src=body.htm noresize=yes frameborder=0 marginheight=0 marginwidth=0 scrolling="no">
<frame src="weather.htm" noresize=yes frameborder=0 marginheight=0 marginwidth=0 scrolling="no">
</frameset>
</html>

--weather.html

<html>
<head>
<title>Weather</title>
</head>

<body onLoad="window.scrollTo(0,170)">

<iframe id="iframe" src="http://forecast.weather.gov/MapClick.php?CityName=Las+Vegas&state=NV&site=VEF&textField1=36.175&textField2=-115.136&e=0" height=1000 width=100% frameborder=0 marginheight=0 marginwidth=0 scrolling=no>
</iframe>

</body>
</html>

How to convert a string or integer to binary in Ruby?

If you are looking for a Ruby class/method I used this, and I have also included the tests:

class Binary
  def self.binary_to_decimal(binary)
    binary_array = binary.to_s.chars.map(&:to_i)
    total = 0

    binary_array.each_with_index do |n, i|
      total += 2 ** (binary_array.length-i-1) * n
    end
    total
   end
end

class BinaryTest < Test::Unit::TestCase
  def test_1
   test1 = Binary.binary_to_decimal(0001)
   assert_equal 1, test1
  end

 def test_8
    test8 = Binary.binary_to_decimal(1000)
    assert_equal 8, test8
 end

 def test_15
    test15 = Binary.binary_to_decimal(1111)
    assert_equal 15, test15
 end

 def test_12341
    test12341 = Binary.binary_to_decimal(11000000110101)
    assert_equal 12341, test12341
 end
end

How to git-svn clone the last n revisions from a Subversion repository?

You've already discovered the simplest way to specify a shallow clone in Git-SVN, by specifying the SVN revision number that you want to start your clone at ( -r$REV:HEAD).

For example: git svn clone -s -r1450:HEAD some/svn/repo

Git's data structure is based on pointers in a directed acyclic graph (DAG), which makes it trivial to walk back n commits. But in SVN ( and therefore in Git-SVN) you will have to find the revision number yourself.

Remove all classes that begin with a certain string

I also use hyphen'-' and digits for class name. So my version include '\d-'

$('#a')[0].className = $('#a')[0].className.replace(/\bbg.\d-*?\b/g, '');

What is a "method" in Python?

If you think of an object as being similar to a noun, then a method is similar to a verb. Use a method right after an object (i.e. a string or a list) to apply a method's action to it.

Repeating a function every few seconds

For this the System.Timers.Timer works best

// Create a timer
myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += new ElapsedEventHandler(myEvent);
// Set it to go off every five seconds
myTimer.Interval = 5000;
// And start it        
myTimer.Enabled = true;

// Implement a call with the right signature for events going off
private void myEvent(object source, ElapsedEventArgs e) { }

See Timer Class (.NET 4.6 and 4.5) for details

Are loops really faster in reverse?

Love it, lots of marks up but no answer :D

Simply put a comparison against zero is always the fastest comparison

So (a==0) is actually quicker at returning True than (a==5)

It's small and insignificant and with 100 million rows in a collection it's measurable.

i.e on a loop up you might be saying where i <= array.length and be incrementing i

on a down loop you might be saying where i >= 0 and be decrementing i instead.

The comparison is quicker. Not the 'direction' of the loop.

Eclipse Indigo - Cannot install Android ADT Plugin

I've also had this problem. I solved it by going to:

Clicking -> available software sites
Select "Helios" and click Reload.
Select "ADT Plugin" and click Reload.
Then went back, tried again and it worked.

If you still can't get it working there are directions for doing it manually here:
http://developer.android.com/sdk/eclipse-adt.html#installing

(also: I'm using 3.7 64x, it's working fine, not having any issues.)

How to break a while loop from an if condition inside the while loop?

An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".

If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

DateTime.MinValue and SqlDateTime overflow

Basically, don't use DateTime.MinValue to represent a missing value. You can't use DateTime.MinValue in a SQL Server DateTime field, as SQL Server has a minimum value of the start of 1753.

Instead, make your BirthDate property a Nullable<DateTime> (aka DateTime?), and set it to null when you don't have a value. Also make sure your database field is nullable. Then you just need to make sure that that null ends up as a NULL value in the database. Exactly how you do that will depend on your data access, which you haven't told us anything about.

How do I hide a menu item in the actionbar?

According to Android Developer Official site,OnCreateOptionMenu(Menu menu) is not recomended for changing menu items or icons, visibility..etc at Runtime.

After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for some reason. However, you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle.

If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.) --AndroidDeveloper Official Site --

As Recomended You can use this onOptionsItemSelected(MenuItem item) method track user inputs.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.edit) {
        Intent intent = new Intent(this, ExampleActivity.class);
        intent.putExtra(BUNDLE_KEY, mConnection);
        startActivityForResult(intent, PICK_CHANGE_REQUEST);
        return true;
    } else if (id == R.id.delete) {
        showDialog(this);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

If you need to change Menu Items at Run time, You can use onPrepareOptionsMenu(Menu menu) to change them

@Override
public boolean onPrepareOptionsMenu(Menu menu){

    if (Utils.checkNetworkStatus(ExampleActivity.this)) {
        menu.findItem(R.id.edit).setVisible(true);
        menu.findItem(R.id.delete).setVisible(true);
    }else {
        menu.findItem(R.id.edit).setVisible(false);
        menu.findItem(R.id.delete).setVisible(false);
    }
    return true;
} 

Read and overwrite a file in Python

Try writing it in a new file..

f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()

Angular 2: Get Values of Multiple Checked Checkboxes

Since I spent a long time solving a similar problem, I'm answering to share my experience. My problem was the same, to know, getting many checkboxes value after a specified event has been triggered. I tried a lot of solutions but for me the sexiest is using ViewChildren.

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components: QueryList<any>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

Found here: https://stackoverflow.com/a/40165639/4775727

Potential other solutions for ref, there are a lot of similar topic, none of them purpose this solution...:

PHP - Get key name of array value

use array_keys() to get an array of all the unique keys.

Note that an array with named keys like your $arr can also be accessed with numeric indexes, like $arr[0].

http://php.net/manual/en/function.array-keys.php

Detect Safari using jQuery

This will determine whether the browser is Safari or not.

if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
{
    alert(its safari);
}else {
    alert('its not safari');
}

Adding Table rows Dynamically in Android

Activity
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableLayout
            android:id="@+id/mytable"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </TableLayout>
    </HorizontalScrollView>

Your Class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testtable);
    table = (TableLayout)findViewById(R.id.mytable);
    showTableLayout();
}


public  void showTableLayout(){
    Date date = new Date();
    int rows = 80;
    int colums  = 10;
    table.setStretchAllColumns(true);
    table.bringToFront();

    for(int i = 0; i < rows; i++){

        TableRow tr =  new TableRow(this);
        for(int j = 0; j < colums; j++)
        {
            TextView txtGeneric = new TextView(this);
            txtGeneric.setTextSize(18);
            txtGeneric.setText( dateFormat.format(date) + "\t\t\t\t" );
            tr.addView(txtGeneric);
            /*txtGeneric.setHeight(30); txtGeneric.setWidth(50);   txtGeneric.setTextColor(Color.BLUE);*/
        }
        table.addView(tr);
    }
}

Sublime Text 3 how to change the font size of the file sidebar?

I followed these instructions but then found that the menu hover color was wrong.

I am using the Spacegray theme in Sublime 3 beta 3074. So to accomplish the sidebar font color change and also hover color change, on OSX, I created a new file ~/Library/"Application Support"/"Sublime Text 3"/Packages/User/Spacegray.sublime-theme

then added this code to it:

[
    {
        "class": "sidebar_label",
        "color": [192,197,203],
        "font.bold": false,
        "font.size": 15
    },
     {
        "class": "sidebar_label",
        "parents": [{"class": "tree_row","attributes": ["hover"]}],
        "color": [255,255,255] 
    },
]

It is possible to tweak many other settings for your theme if you can see the original default:

https://gist.github.com/nateflink/0355eee823b89fe7681e

I extracted this file from the sublime package zip file by installing the PackageResourceViewer following MattDMo's instructions (https://stackoverflow.com/users/1426065/mattdmo) here:

How to change default code snippets in Sublime Text 3?

How to add screenshot to READMEs in github repository?

With the images located in /screen-shots directory. The outer <div> allows the images to be positioned. Padding is achieved using <img width="desired-padding" height="0">.

<div align="center">
        <img width="45%" src="screen-shots/about.PNG" alt="About screen" title="About screen"</img>
        <img height="0" width="8px">
        <img width="45%" src="screen-shots/list.PNG" alt="List screen" title="List screen"></img>
</div>

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

That's done for header files so that the contents only appear once in each preprocessed source file, even if it's included more than once (usually because it's included from other header files). The first time it's included, the symbol CLASS_H (known as an include guard) hasn't been defined yet, so all the contents of the file are included. Doing this defines the symbol, so if it's included again, the contents of the file (inside the #ifndef/#endif block) are skipped.

There's no need to do this for the source file itself since (normally) that's not included by any other files.

For your last question, class.h should contain the definition of the class, and declarations of all its members, associated functions, and whatever else, so that any file that includes it has enough information to use the class. The implementations of the functions can go in a separate source file; you only need the declarations to call them.

How to COUNT rows within EntityFramework without loading contents?

As I understand it, the selected answer still loads all of the related tests. According to this msdn blog, there is a better way.

http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

Specifically

using (var context = new UnicornsContext())

    var princess = context.Princesses.Find(1);

    // Count how many unicorns the princess owns 
    var unicornHaul = context.Entry(princess)
                      .Collection(p => p.Unicorns)
                      .Query()
                      .Count();
}

"Uncaught Error: [$injector:unpr]" with angular after deployment

I had the same problem but the issue was a different one, I was trying to create a service and pass $scope to it as a parameter.
That's another way to get this error as the documentation of that link says:

Attempting to inject a scope object into anything that's not a controller or a directive, for example a service, will also throw an Unknown provider: $scopeProvider <- $scope error. This might happen if one mistakenly registers a controller as a service, ex.:

angular.module('myModule', [])
       .service('MyController', ['$scope', function($scope) {
        // This controller throws an unknown provider error because
        // a scope object cannot be injected into a service.
}]);

Item frequency count in Python

words = "apple banana apple strawberry banana lemon"
w=words.split()
e=list(set(w))       
word_freqs = {}
for i in e:
    word_freqs[i]=w.count(i)
print(word_freqs)   

Hope this helps!

Using fonts with Rails asset pipeline

Here my approach to using fonts in asset pipeline:

1) Put all your font file under app/assets/fonts/, actually you are not restricted to put it under fonts folder name. You can put any subfolder name you like. E.g. app/assets/abc or app/assets/anotherfonts. But i highly recommend you put it under app/assets/fonts/ for better folder structure.

2) From your sass file, using the sass helper font-path to request your font assets like this

@font-face {
    font-family: 'FontAwesome';
    src: url(font-path('fontawesome-webfont.eot') + '?v=4.4.0');
    src: url(font-path('fontawesome-webfont.eot') + '?#iefix&v=4.4.0') format('embedded-opentype'),
         url(font-path('fontawesome-webfont.woff2') + '?v=4.4.0') format('woff2'),
         url(font-path('fontawesome-webfont.woff') + '?v=4.4.0') format('woff'),
         url(font-path('fontawesome-webfont.ttf') + '?v=4.4.0') format('truetype'),
         url(font-path('fontawesome-webfont.svg') + '?v=4.4.0#fontawesomeregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

3) Run bundle exec rake assets:precompile from your local machine and see your application.css result. You should see something like this:

@font-face {
    font-family: 'FontAwesome';
    src: url("/assets/fontawesome-webfont-d4f5a99224154f2a808e42a441ddc9248ffe78b7a4083684ce159270b30b912a.eot" "?v=4.4.0");
    src: url("/assets/fontawesome-webfont-d4f5a99224154f2a808e42a441ddc9248ffe78b7a4083684ce159270b30b912a.eot" "?#iefix&v=4.4.0") format("embedded-opentype"), url("/assets/fontawesome-webfont-3c4a1bb7ce3234407184f0d80cc4dec075e4ad616b44dcc5778e1cfb1bc24019.woff2" "?v=4.4.0") format("woff2"), url("/assets/fontawesome-webfont-a7c7e4930090e038a280fd61d88f0dc03dad4aeaedbd8c9be3dd9aa4c3b6f8d1.woff" "?v=4.4.0") format("woff"), url("/assets/fontawesome-webfont-1b7f3de49d68b01f415574ebb82e6110a1d09cda2071ad8451bdb5124131a292.ttf" "?v=4.4.0") format("truetype"), url("/assets/fontawesome-webfont-7414288c272f6cc10304aa18e89bf24fb30f40afd644623f425c2c3d71fbe06a.svg" "?v=4.4.0#fontawesomeregular") format("svg");
    font-weight: normal;
    font-style: normal;
}

If you want to know more how asset pipeline work, you can visit the following simple guide: https://designcode.commandrun.com/rails-asset-pipeline-simple-guide-830e2e666f6c#.6lejlayk2

ActiveRecord: size vs count

The following strategies all make a call to the database to perform a COUNT(*) query.

Model.count

Model.all.size

records = Model.all
records.count

The following is not as efficient as it will load all records from the database into Ruby, which then counts the size of the collection.

records = Model.all
records.size

If your models have associations and you want to find the number of belonging objects (e.g. @customer.orders.size), you can avoid database queries (disk reads). Use a counter cache and Rails will keep the cache value up to date, and return that value in response to the size method.

What are all possible pos tags of NLTK?

The book has a note how to find help on tag sets, e.g.:

nltk.help.upenn_tagset()

Others are probably similar. (Note: Maybe you first have to download tagsets from the download helper's Models section for this)

How do I remove all null and empty string values from an object?

Building upon suryaPavan's answer this slight modification can cleanup the empty object after removing the invidival emptys inside the object or array. this ensures that you don't have an empty array or object hanging around.

function removeNullsInObject(obj) {
            if( typeof obj === 'string' || obj === "" ){
                return;
            }
            $.each(obj, function(key, value){
                if (value === "" || value === null){
                    delete obj[key];
                } else if ($.isArray(value)) {
                    if( value.length === 0 ){
                        delete obj[key];
                        return;
                    }
                    $.each(value, function (k,v) {
                        removeNullsInObject(v);
                    });
                    if( value.length === 0 ){
                        delete obj[key];
                    }
                } else if (typeof value === 'object') {
                    if( Object.keys(value).length === 0 ){
                        delete obj[key];
                        return;
                    }
                    removeNullsInObject(value);
                    if( Object.keys(value).length === 0 ){
                        delete obj[key];
                    }
                }
            });
 }

When should I really use noexcept?

As I keep repeating these days: semantics first.

Adding noexcept, noexcept(true) and noexcept(false) is first and foremost about semantics. It only incidentally condition a number of possible optimizations.

As a programmer reading code, the presence of noexcept is akin to that of const: it helps me better grok what may or may not happen. Therefore, it is worthwhile spending some time thinking about whether or not you know if the function will throw. For a reminder, any kind of dynamic memory allocation may throw.


Okay, now on to the possible optimizations.

The most obvious optimizations are actually performed in the libraries. C++11 provides a number of traits that allows knowing whether a function is noexcept or not, and the Standard Library implementation themselves will use those traits to favor noexcept operations on the user-defined objects they manipulate, if possible. Such as move semantics.

The compiler may only shave a bit of fat (perhaps) from the exception handling data, because it has to take into account the fact that you may have lied. If a function marked noexcept does throw, then std::terminate is called.

These semantics were chosen for two reasons:

  • immediately benefiting from noexcept even when dependencies do not use it already (backward compatibility)
  • allowing the specification of noexcept when calling functions that may theoretically throw, but are not expected to for the given arguments

How do I pull from a Git repository through an HTTP proxy?

For me what it worked was:

sudo apt-get install socat

Create a file inside your $BIN_PATH/gitproxy with:

#!/bin/sh 
_proxy=192.168.192.1 
_proxyport=3128 
exec socat STDIO PROXY:$_proxy:$1:$2,proxyport=$_proxyport

Dont forget to give it execution permissions

chmod a+x gitproxy

Run following commands to setup environment:

export PATH=$BIN_PATH:$PATH
git config --global core.gitproxy gitproxy

Interview Question: Merge two sorted singly linked lists without creating new nodes

// Common code for insert at the end
        private void insertEnd(int data) {
                Node newNode = new Node(data);
                if (head == null) {
                    newNode.next = head;
                    head = tail = newNode;
                    return;
                }
                Node tempNode = tail;
                tempNode.next = newNode;
                tail = newNode;
            }

    private void mergerTwoSortedListInAscOrder(Node tempNode1, Node tempNode2) {

            if (tempNode1 == null && tempNode2 == null)
                return;
            if (tempNode1 == null) {
                head3 = tempNode2;
                return;
            }
            if (tempNode2 == null) {
                head3 = tempNode1;
                return;
            }

            while (tempNode1 != null && tempNode2 != null) {

                if (tempNode1.mData < tempNode2.mData) {
                    insertEndForHead3(tempNode1.mData);
                    tempNode1 = tempNode1.next;
                } else if (tempNode1.mData > tempNode2.mData) {
                    insertEndForHead3(tempNode2.mData);
                    tempNode2 = tempNode2.next;
                } else {
                    insertEndForHead3(tempNode1.mData);
                    insertEndForHead3(tempNode2.mData);
                    tempNode1 = tempNode1.next;
                    tempNode2 = tempNode2.next;
                }

            }
            if (tempNode1 != null) {
                while (tempNode1 != null) {
                    insertEndForHead3(tempNode1.mData);
                    tempNode1 = tempNode1.next;
                }
            }
            if (tempNode2 != null) {
                while (tempNode2 != null) {
                    insertEndForHead3(tempNode2.mData);
                    tempNode2 = tempNode2.next;
                }
            }
        }

:)GlbMP

What's is the difference between train, validation and test set, in neural networks?

Cross-validation set is used for model selection, for example, select the polynomial model with the least amount of errors for a given parameter set. The test set is then used to report the generalization error on the selected model. From here: https://www.coursera.org/learn/machine-learning/lecture/QGKbr/model-selection-and-train-validation-test-sets

How to initialize a List<T> to a given size (as opposed to capacity)?

Why are you using a List if you want to initialize it with a fixed value ? I can understand that -for the sake of performance- you want to give it an initial capacity, but isn't one of the advantages of a list over a regular array that it can grow when needed ?

When you do this:

List<int> = new List<int>(100);

You create a list whose capacity is 100 integers. This means that your List won't need to 'grow' until you add the 101th item. The underlying array of the list will be initialized with a length of 100.

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

Get an object attribute

You can do the following:

class User(object):
    fullName = "John Doe"

    def __init__(self, name):
        self.SName = name

    def print_names(self):
        print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)

user = User('Test Name')

user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'

E.g any object attributes could be retrieved using istance.

String formatting: % vs. .format vs. string literal

But one thing is that also if you have nested curly-braces, won't work for format but % will work.

Example:

>>> '{{0}, {1}}'.format(1,2)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    '{{0}, {1}}'.format(1,2)
ValueError: Single '}' encountered in format string
>>> '{%s, %s}'%(1,2)
'{1, 2}'
>>> 

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

nonatomic property means @synthesized methods are not going to be generated threadsafe -- but this is much faster than the atomic property since extra checks are eliminated.

strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

weak ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB; is used and a has weak property , than its value will only be valid till objectB remains in memory.

copy property is very well explained here

strong,weak,retain,copy,assign are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section

hoping this helps you out a bit...

A regex for version number parsing

Another try:

^(((\d+)\.)?(\d+)\.)?(\d+|\*)$

This gives the three parts in groups 4,5,6 BUT: They are aligned to the right. So the first non-null one of 4,5 or 6 gives the version field.

  • 1.2.3 gives 1,2,3
  • 1.2.* gives 1,2,*
  • 1.2 gives null,1,2
  • *** gives null,null,*
  • 1.* gives null,1,*

In vb.net, how to get the column names from a datatable

Look at

For Each c as DataColumn in dt.Columns
  '... = c.ColumnName
Next

or:

dt.GetDataTableSchema(...)

git checkout tag, git pull fails in branch

You might have multiple branch. And your current branch didn't set its upstream in remote.

Steps to fix this:

git checkout branch_name
git branch --set-upstream-to=origin/remote_branch_name local_branch_name

e.g.

// this set upstream of local branch develop to remote branch  origin/develop,
git branch --set-upstream-to=origin/develop develop

After doing this, when you do git pull, it pull from specified branch.

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

I faced the same issue, I tried the below solution and it worked for me In Android SDK Manager Window, click on Tools->Options-> under "Others", check "Force https://... sources to be fetched using http://..."

How to call any method asynchronously in c#

Starting with .Net 4.5 you can use Task.Run to simply start an action:

void Foo(string args){}
...
Task.Run(() => Foo("bar"));

Task.Run vs Task.Factory.StartNew

How to print multiple lines of text with Python

The triple quotes answer is great for ASCII art, but for those wondering - what if my multiple lines are a tuple, list, or other iterable that returns strings (perhaps a list comprehension?), then how about:

print("\n".join(<*iterable*>))

For example:

print("\n".join(["{}={}".format(k, v) for k, v in os.environ.items() if 'PATH' in k]))

Where is adb.exe in windows 10 located?

I know the question was in the context of "android studio 1.5", but I found this answer and have Xamarin installed.

In this case, the location is C:\Program Files (x86)\Android\android-sdk\platform-tools

How do I make a stored procedure in MS Access?

Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).

If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.

For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.

For example:

screenshot

Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table alt text

Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.

What is the difference between %g and %f in C?

They are both examples of floating point input/output.

%g and %G are simplifiers of the scientific notation floats %e and %E.

%g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two.

The output of your print statement will depend on the value of sum.

How to set default values in Go structs

  1. Force a method to get the struct (the constructor way).

    From this post:

    A good design is to make your type unexported, but provide an exported constructor function like NewMyType() in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.

    This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.

  2. Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.

How to customize the back button on ActionBar

I did the below code onCreate() and worked with me

getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_yourindicator);

Hidden features of Windows batch files

Multiple commands in one line, useful in many situations:

& Used to combine two commands, executes command1 and then command2
&& A conditional combination, executes command2 if command1 completes successfully
¦¦ Command2 executes only if command1 does not complete successfully.

Examples:

:: ** Edit the most recent .TXT file and exit, useful in a .CMD / .BAT **
FOR /F %%I IN ('DIR *.TXT /B /O:-N') DO NOTEPAD %%I & EXIT


:: ** If exist any .TXT file, display the list in NOTEPAD, if not it 
:: ** exits without any error (note the && and the 2> error redirection)
DIR *.TXT > TXT.LST 2> NUL && NOTEPAD TXT.LST

Powershell import-module doesn't find modules

My finding with PS 5.0 on Windows 7: $ENV:PsModulePath has to end with a . This normally means it will load all modules in that path.

I'm not able to add a single module to $env:PsModulePath and get it to load with Import-Module ExampleModule. I have to use the full path to the module. e.g. C:\MyModules\ExampleModule. I am sure it used to work.

For example: Say I have the modules:

C:\MyModules\ExampleModule
C:\MyModules\FishingModule

I need to add C:\MyModules\ to $env:PsModulePath, which will allow me to do

Import-Module ExampleModule
Import-Module FishingModule

If for some reason, I didn't want FishingModule, I thought I could add C:\MyModules\ExampleModule only (no trailing \), but this doesn't seem to work now. To load it, I have to Import-Module C:\MyModules\ExampleModule

Interestingly, in both cases, doing Get-Module -ListAvailable, shows the modules, but it won't import. Although, the module's cmdlets seem to work anyway.

AFAIK, to get the automatic import to work, one has to add the name of the function to FunctionsToExport in the manifest (.psd1) file. Adding FunctionsToExport = '*', breaks the auto load. You can still have Export-ModuleMember -Function * in the module file (.psm1).

These are my findings. Whether there's been a change or my computer is broken, remains to be seen. HTH

How to convert date format to milliseconds?

date.setTime(milliseconds);

this is for set milliseconds in date

long milli = date.getTime();

This is for get time in milliseconds.

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT

What is a blob URL and why it is used?

This Javascript function purports to show the difference between the Blob File API and the Data API to download a JSON file in the client browser:

_x000D_
_x000D_
/**_x000D_
 * Save a text as file using HTML <a> temporary element and Blob_x000D_
 * @author Loreto Parisi_x000D_
 */_x000D_
_x000D_
var saveAsFile = function(fileName, fileContents) {_x000D_
    if (typeof(Blob) != 'undefined') { // Alternative 1: using Blob_x000D_
        var textFileAsBlob = new Blob([fileContents], {type: 'text/plain'});_x000D_
        var downloadLink = document.createElement("a");_x000D_
        downloadLink.download = fileName;_x000D_
        if (window.webkitURL != null) {_x000D_
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
        } else {_x000D_
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
            downloadLink.onclick = document.body.removeChild(event.target);_x000D_
            downloadLink.style.display = "none";_x000D_
            document.body.appendChild(downloadLink);_x000D_
        }_x000D_
        downloadLink.click();_x000D_
    } else { // Alternative 2: using Data_x000D_
        var pp = document.createElement('a');_x000D_
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' +_x000D_
            encodeURIComponent(fileContents));_x000D_
        pp.setAttribute('download', fileName);_x000D_
        pp.onclick = document.body.removeChild(event.target);_x000D_
        pp.click();_x000D_
    }_x000D_
} // saveAsFile_x000D_
_x000D_
/* Example */_x000D_
var jsonObject = {"name": "John", "age": 30, "car": null};_x000D_
saveAsFile('out.json', JSON.stringify(jsonObject, null, 2));
_x000D_
_x000D_
_x000D_

The function is called like saveAsFile('out.json', jsonString);. It will create a ByteStream immediately recognized by the browser that will download the generated file directly using the File API URL.createObjectURL.

In the else, it is possible to see the same result obtained via the href element plus the Data API, but this has several limitations that the Blob API has not.

C++/CLI Converting from System::String^ to std::string

Don't roll your own, use these handy (and extensible) wrappers provided by Microsoft.

For example:

#include <msclr\marshal_cppstd.h>

System::String^ managed = "test";
std::string unmanaged = msclr::interop::marshal_as<std::string>(managed);

Archive the artifacts in Jenkins

Also, does Jenkins delete the artifacts after each build ? (not the archived artifacts, I know I can tell it to delete those)

No, Hudson/Jenkins does not, by itself, clear the workspace after a build. You might have actions in your build process that erase, overwrite, or move build artifacts from where you left them. There is an option in the job configuration, in Advanced Project Options (which must be expanded), called "Clean workspace before build" that will wipe the workspace at the beginning of a new build.

EditText underline below text property

You have to use a different background image, not color, for each state of the EditText (focus, enabled, activated).

http://android-holo-colors.com/

In the site above, you can get images from a lot of components in the Holo theme. Just select "EditText" and the color you want. You can see a preview at the bottom of the page.

Download the .zip file, and copy paste the resources in your project (images and the XML).

if your XML is named: apptheme_edit_text_holo_light.xml (or something similar):

  1. Go to your XML "styles.xml" and add the custom EditText style:

    <style name="EditTextCustomHolo" parent="android:Widget.EditText">
       <item name="android:background">@drawable/apptheme_edit_text_holo_light</item>
       <item name="android:textColor">#ffffff</item>
    </style>
    
  2. Just do this in your EditText:

    <EditText
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       style="@style/EditTextCustomHolo"/>
    

And that's it, I hope it helps you.

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

If you are a Windows user you may uninstall Composer. Then install Composer. After that you install Laravel. Maybe it will work.

Adding and removing style attribute from div with jquery

To completely remove the style attribute of the voltaic_holder span, do this:

$("#voltaic_holder").removeAttr("style");

To add an attribute, do this:

$("#voltaic_holder").attr("attribute you want to add", "value you want to assign to attribute");

To remove only the top style, do this:

$("#voltaic_holder").css("top", "");

Centering Bootstrap input fields

Ok, this is best solution for me. Bootstrap includes mobile-first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases. So this worked perfectly on every browser and device:

        <div class="row">
            <div class="col-lg-4"></div>
            <div class="col-lg-4">
                <div class="input-group">
                    <input type="text" class="form-control" /> 
                    <span class="input-group-btn">
                        <button class="btn btn-default" type="button">Go!</button>
                    </span>
                </div><!-- /input-group -->
            </div><!-- /.col-lg-4 -->
            <div class="col-lg-4"></div>
        </div><!-- /.row -->

It means 4 + 4 + 4 =12... so second div will be in the middle that way.

Example: http://jsfiddle.net/jpGwm/embedded/result/

Youtube API Limitations

A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form

Best way to determine user's locale within browser

Combining the multiple ways browsers are using to store the user's language, you get this function :

const getNavigatorLanguage = () => {
  if (navigator.languages && navigator.languages.length) {
    return navigator.languages[0];
  } else {
    return navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
  }
}

We first check the navigator.languages array for its first element.
Then we get either navigator.userLanguage or navigator.language.
If this fails we get navigator.browserLanguage.
Finally, we set it to 'en' if everything else failed.


And here's the sexy one-liner :

const getNavigatorLanguage = () => (navigator.languages && navigator.languages.length) ? navigator.languages[0] : navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';

Error "initializer element is not constant" when trying to initialize variable with const

I had this error in code that looked like this:

int A = 1;
int B = A;

The fix is to change it to this

int A = 1;
#define B A

The compiler assigns a location in memory to a variable. The second is trying a assign a second variable to the same location as the first - which makes no sense. Using the macro preprocessor solves the problem.

How to get highcharts dates in the x axis?

Highcharts will automatically try to find the best format for the current zoom-range. This is done if the xAxis has the type 'datetime'. Next the unit of the current zoom is calculated, it could be one of:

  • second
  • minute
  • hour
  • day
  • week
  • month
  • year

This unit is then used find a format for the axis labels. The default patterns are:

second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'

If you want the day to be part of the "hour"-level labels you should change the dateTimeLabelFormats option for that level include %d or %e. These are the available patters:

  • %a: Short weekday, like 'Mon'.
  • %A: Long weekday, like 'Monday'.
  • %d: Two digit day of the month, 01 to 31.
  • %e: Day of the month, 1 through 31.
  • %b: Short month, like 'Jan'.
  • %B: Long month, like 'January'.
  • %m: Two digit month number, 01 through 12.
  • %y: Two digits year, like 09 for 2009.
  • %Y: Four digits year, like 2009.
  • %H: Two digits hours in 24h format, 00 through 23.
  • %I: Two digits hours in 12h format, 00 through 11.
  • %l (Lower case L): Hours in 12h format, 1 through 11.
  • %M: Two digits minutes, 00 through 59.
  • %p: Upper case AM or PM.
  • %P: Lower case AM or PM.
  • %S: Two digits seconds, 00 through 59

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

MySQL compare now() (only date, not time) with a datetime field

Compare date only instead of date + time (NOW) with:

CURDATE()

Java Initialize an int array in a constructor

You could either do:

public class Data {
    private int[] data;

    public Data() {
        data = new int[]{0, 0, 0};
    }
}

Which initializes data in the constructor, or:

public class Data {
    private int[] data = new int[]{0, 0, 0};

    public Data() {
        // data already initialised
    }
}

Which initializes data before the code in the constructor is executed.

How to run vbs as administrator from vbs?

Nice article for elevation options - http://www.novell.com/support/kb/doc.php?id=7010269

Configuring Applications to Always Request Elevated Rights:

Programs can be configured to always request elevation on the user level via registry settings under HKCU. These registry settings are effective on the fly, so they can be set immediately prior to launching a particular application and even removed as soon as the application is launched, if so desired. Simply create a "String Value" under "HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" for the full path to an executable with a value of "RUN AS ADMIN". Below is an example for CMD.

Windows Registry Editor Version 5.00
[HKEY_Current_User\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"c:\\windows\\system32\\cmd.exe"="RUNASADMIN"

Convert Rtf to HTML

I think you can load it in a Word document object by using .NET office programmability support and Visual Studio tools for office.

And then use the document instance to re-save as an HTML document.

I am not sure how but I believe it is possible entirely in .NET without any 3rd party library.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

What could be the possible cause of this exception?

You may not have appropriate Jar in your class path.

How it could be removed?

By putting HTTPClient jar in your class path. If it's a webapp, copy Jar into WEB-INF/lib if it's standalone, make sure you have this jar in class path or explicitly set using -cp option

as the doc says,

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

Edit:
If you are using a dependency management like Maven/Gradle (see the answer below) or SBT please use it to bring the httpclient jar for you.

Binding arrow keys in JS/jQuery

A terse solution using plain Javascript (thanks to Sygmoral for suggested improvements):

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
    }
};

Also see https://stackoverflow.com/a/17929007/1397061.

How to iterate over columns of pandas dataframe to run regression

Based on the accepted answer, if an index corresponding to each column is also desired:

for i, column in enumerate(df):
    print i, df[column]

The above df[column] type is Series, which can simply be converted into numpy ndarrays:

for i, column in enumerate(df):
    print i, np.asarray(df[column])

How to copy files from host to Docker container?

This is a direct answer to the question 'Copying files from host to Docker container' raised in this question in the title.

Try docker cp. It is the easiest way to do that and works even on my Mac. Usage:

docker cp /root/some-file.txt some-docker-container:/root

This will copy the file some-file.txt in the directory /root on your host machine into the Docker container named some-docker-container into the directory /root. It is very close to the secure copy syntax. And as shown in the previous post, you can use it vice versa. I.e., you also copy files from the container to the host.

And before you downlink this post, please enter docker cp --help. Reading the documentation can be very helpful, sometimes...

If you don't like that way and you want data volumes in your already created and running container, then recreation is your only option today. See also How can I add a volume to an existing Docker container?.

unable to start mongodb local server

Find out from netstat which process is running mongodb port (27017)

command:

sudo netstat -tulpn | grep :27017

Output will be:

tcp        0      0 0.0.0.0:27017           0.0.0.0:* 
LISTEN      6432/mongod

In my case "6432" is the pid, it may be different in your case. Then kill that process using following command:

sudo kill <pid>

Thats it!

Getting last month's date in php

You can use strtotime, which is great in this kind of situations :

$timestamp = strtotime('-1 month');
var_dump(date('Y-m', $timestamp));

Will get you :

string '2009-11' (length=7)

WordPress Get the Page ID outside the loop

This is the correct code.

echo $post->ID;

The remote end hung up unexpectedly while git cloning

It worked for me after I tried it.

git config --global http.postBuffer 2048M
git config --global http.maxRequestBuffer 1024M
git config --global core.compression 9

git config --global ssh.postBuffer 2048M
git config --global ssh.maxRequestBuffer 1024M

git config --global pack.windowMemory 256m 
git config --global pack.packSizeLimit 256m

Thank you for all

How to encode URL parameters?

With urlsearchparams:

const params = new URLSearchParams()
params.append('imageurl', http://www.image.com/?username=unknown&password=unknown)
return `http://www.foobar.com/foo?${params.toString()}`

How to resolve "Could not find schema information for the element/attribute <xxx>"?

Navigate to this : NLog xsd files

Download the appropriate xsd for your project and save it along the NLog.config

The first one did the trick for me.

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

The best and tested solution is to put the following small snippet which will collapse the accordion tab which is already open when you load. In my case the last sixth tab was open so I made it collapsed on page load.

 $(document).ready(){
      $('#collapseSix').collapse("hide");
 }

random number generator between 0 - 1000 in c#

Have you tried this

Random integer between 0 and 1000(1000 not included):

Random random = new Random();
int randomNumber = random.Next(0, 1000);

Loop it as many times you want

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Open soft keyboard programmatically

In your manifest file, try adding the following to the <activity> that you want to show the keyboard when the activity starts:

android:windowSoftInputMode="stateVisible"

This should cause the keyboard to become visible when the activity starts.

For more options, checkout the documentation.

How to check if a file is a valid image file?

Additionally to the PIL image check you can also add file name extension check like this:

filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif'))

Note that this only checks if the file name has a valid image extension, it does not actually open the image to see if it's a valid image, that's why you need to use additionally PIL or one of the libraries suggested in the other answers.

Unfortunately MyApp has stopped. How can I solve this?

Note: This answer is using Android Studio 2.2.2

Note 2: I am considering that your device is successfully connected.


The first thing you do when your application crashes is look into the LogCat, at the bottom of Android Studio there's a toolbar with a list of menus:

image

Click on the "Android Monitor" (The one I underlined in the image above. ^)

Now, you'll get something like this:

image

Change "Verbose" to "Error" Now it will only show you logged errors. Don't worry about all these errors (if you got them) now.

image

Ok. Now, do what you did to crash your app. After your app crashes, go to your logcat. You should find a new crash log that has a lot of at:x.x.x: and Caused by: TrumpIsPresidentException for example. Go to that Caused by: statement in your logcat.

image

Next to that Caused By:, there should be the Exception that happened. In my case, it's a RuntimeException and under it there should be a line which contains a blue link such as:

image

If that Caused by: DOESN'T have a line with a blue text somewhere under it, then look for another Caused by: that does.

Click on that blue link. It should take you to where the problem occured. In my case, it was due to this line:

throw new RuntimeException();

So, now I know why it's crashing. It's because I'm throwing the exception myself. This was an obvious error.


However, let's say I got another error:

java.lang.NullPointerException

I checked my logcat, I clicked on the blue link it gave me, and it took me here:

mTextView.setText(myString);

So, now I want to debug. According to this StackOverflow question, a NullPointerException says that something is null.

So, let's find out what is null. There's two possibilities. Either mTextView is null, or myString is null. To find out, before the mTextView.setText(mString) line, I add these two lines:

Log.d("AppDebug","mTextView is null: " + String.valueOf(mTextView == null);
Log.d("AppDebug","myString is null: " + String.valueOf(myString== null);

Now, like we did previously (We changed Verose to Error), we want to change "Error" to "Debug". Since we're logging by debugging. Here's all the Log methods:

Log.
  d means Debug
  e means error
  w means warning
  v means verbose
  i means information
  wtf means "What a terrible failure". This is similar to Log.e

So, since we used Log.d, we're checking in Debug. That's why we changed it to debug.

Notice Log.d has a first parameter,in our case "AppDebug". Click on the "No Filters" drop down menu on the top-right of the logcat. Select "Edit Filter Configuration", give a name to your filter, and in "Log Tag" put "App Debug". Click "OK". Now, you should see two lines in the logcat:

yourPackageNameAndApp: mTextView is null: true
yourPackageNameAndApp: myString is null: false

So now we know that mTextView is null.

I observe my code, now I notice something.

I have private TextView mTextView declared at the top of my class. But, I'm not defining it.

Basically I forgot to do this in my onCreate():

mTextView = (TextView) findViewById(R.id.textview_id_in_xml);

So THAT'S why mTextView is null, because I forgot to tell my app what it is. So I add that line, run my app, and now the app doesn't crash.


How to add action listener that listens to multiple buttons

The problem is that button1 is a local variable. You could do it by just change the way you add the actionListener.

button.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e)
            {
                //button is pressed
                System.out.println("You clicked the button");
            }});

Or you make button1 a global variable.