Programs & Examples On #Searchdisplaycontroller

Set UITableView content inset permanently

automaticallyAdjustsScrollViewInsets is deprecated in iOS11 (and the accepted solution no longer works). use:

if #available(iOS 11.0, *) {
    scrollView.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

Usage of unicode() and encode() functions in Python

str is text representation in bytes, unicode is text representation in characters.

You decode text from bytes to unicode and encode a unicode into bytes with some encoding.

That is:

>>> 'abc'.decode('utf-8')  # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'

UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str was renamed to bytes, and unicode was renamed to str.

>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'

Import Google Play Services library in Android Studio

Try this once and make sure you are not getting any error in project Structure saying that "ComGoogleAndroidGmsPlay not added"

Open File > Project Structure and check for below all. If error is shown click on Red bulb marked and click on "Add to dependency".

GMS dependency

This is a bug in Android Studio and fixed for the next release(0.4.3)

How to force a line break on a Javascript concatenated string?

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Things you can add to declarations: [] in modules

  • Pipe
  • Directive
  • Component

Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.

subquery in FROM must have an alias

In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.

What does the red exclamation point icon in Eclipse mean?

What I did was peculiar but somehow it fixed the problem. Pick any project and perform a fake edit of the build.properties file (e.g., add and remove a space and then save the file). Clean and rebuild the projects in your workspace.

Hope this solve some of your problems.

Difference between a user and a schema in Oracle?

For most of the people who are more familiar with MariaDB or MySQL this seems little confusing because in MariaDB or MySQL they have different schemas (which includes different tables, view , PLSQL blocks and DB objects etc) and USERS are the accounts which can access those schema. Therefore no specific user can belong to any particular schema. The permission has be to given to that Schema then the user can access it. The Users and Schema is separated in databases like MySQL and MariaDB.

In Oracle schema and users are almost treated as same. To work with that schema you need to have the permission which is where you will feel that the schema name is nothing but user name. Permissions can be given across schemas to access different database objects from different schema. In oracle we can say that a user owns a schema because when you create a user you create DB objects for it and vice a versa.

jQuery Set Select Index

You can also init multiple values if your selectbox is a multipl:

$('#selectBox').val(['A', 'B', 'C']);

offsetting an html anchor to adjust for fixed header

@AlexanderSavin's solution works great in WebKit browsers for me.

I additionally had to use :target pseudo-class which applies style to the selected anchor to adjust padding in FF, Opera & IE9:

a:target {
  padding-top: 40px
}

Note that this style is not for Chrome / Safari so you'll probably have to use css-hacks, conditional comments etc.

Also I'd like to notice that Alexander's solution works due to the fact that targeted element is inline. If you don't want link you could simply change display property:

<div id="myanchor" style="display: inline">
   <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>

Task continuation on UI thread

Call the continuation with TaskScheduler.FromCurrentSynchronizationContext():

    Task UITask= task.ContinueWith(() =>
    {
     this.TextBlock1.Text = "Complete"; 
    }, TaskScheduler.FromCurrentSynchronizationContext());

This is suitable only if the current execution context is on the UI thread.

Python: Continuing to next iteration in outer loop

We want to find something and then stop the inner iteration. I use a flag system.

for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False

how to remove the first two columns in a file using shell (awk, sed, whatever)

This might work for you (GNU sed):

sed -r 's/^([^ ]+ ){2}//' file

or for columns separated by one or more white spaces:

sed -r 's/^(\S+\s+){2}//' file

Set selected option of select box

I have found using the jQuery .val() method to have a significant drawback.

<select id="gate"></select>
$("#gate").val("Gateway 2");

If this select box (or any other input object) is in a form and there is a reset button used in the form, when the reset button is clicked the set value will get cleared and not reset to the beginning value as you would expect.

This seems to work the best for me.

For Select boxes

<select id="gate"></select>
$("#gate option[value='Gateway 2']").attr("selected", true);

For text inputs

<input type="text" id="gate" />
$("#gate").attr("value", "your desired value")

For textarea inputs

<textarea id="gate"></textarea>
$("#gate").html("your desired value")

For checkbox boxes

<input type="checkbox" id="gate" />
$("#gate option[value='Gateway 2']").attr("checked", true);

For radio buttons

<input type="radio" id="gate" value="this"/> or <input type="radio" id="gate" value="that"/>
$("#gate[value='this']").attr("checked", true);

Remove scroll bar track from ScrollView in Android

Solved my problem by adding this to my ListView:

android:scrollbars="none"

How to stop app that node.js express 'npm start'

Yes, npm provides for a stop script too:

npm help npm-scripts

prestop, stop, poststop: Run by the npm stop command.

Set one of the above in your package.json, and then use npm stop

npm help npm-stop

You can make this really simple if you set in app.js,

process.title = myApp;

And, then in scripts.json,

"scripts": {
    "start": "app.js"
    , "stop": "pkill --signal SIGINT myApp"
}

That said, if this was me, I'd be using pm2 or something the automatically handled this on the basis of a git push.

REST vs JSON-RPC?

Great answers - just wanted to clarify on a some of the comments. JSON-RPC is quick and easy to consume, but as mentioned resources and parameters are tightly coupled and it tends to rely on verbs (api/deleteUser, api/addUser) using GET/ POST where-as REST provides loosely coupled resources (api/users) that in a HTTP REST API relies on several HTTP methods (GET, POST, PUT, PATCH, DELETE). REST is slightly harder for inexperienced developers to implement, but the style has become fairly common place now and it provides much more flexibility in the long-run (giving your API a longer life).

Along with not having tightly coupled resources, REST also allows you to avoid being committed to a single content-type- this means if your client needs to receive the data in XML, or JSON, or even YAML - if built into your system you could return any of those using the content-type/ accept headers.

This lets you keep your API flexible enough to support new content types OR client requirements.

But what truly separates REST from JSON-RPC is that it follows a series of carefully thought out constraints- ensuring architectural flexibility. These constraints include ensuring that the client and server are able to evolve independently of each other (you can make changes without messing up your client's application), the calls are stateless (state is represented through hypermedia), a uniform interface is provided for interactions, the API is developed on a layered system, and the response is cacheable by the client. There's also an optional constraint for providing code on demand.

However, with all of this said - MOST APIs are not RESTful (according to Fielding) as they do not incorporate hypermedia (embedded hypertext links in the response that help navigate the API). Most APIs you will find out there are REST-like in that they follow most of the concepts of REST, but ignore this constraint. However, more and more APIs are implementing this and it is becoming more of a main-stream practice.

This also gives you some flexibility as hypermedia driven APIs (such as Stormpath) direct the client to the URIs (meaning if something changes, in certain cases you can modify the URI without negative impact), where-as with RPC URIs are required to be static. With RPC, you will also need to extensively document these different URIs and explain how they work in relation to each other.

In general, I would say REST is the way to go if you want to build an extensible, flexible API that will be long-lived. For that reason, I would say it's the route to go 99% of the time.

Good luck, Mike

Is it still valid to use IE=edge,chrome=1?

<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>

worked for me, to force IE to "snap out of compatibility mode" (so to speak), BUT that meta statement must appear IMMEDIATELY after the <head>, or it won't work!

The default for KeyValuePair

I recommend more understanding way using extension method:

public static class KeyValuePairExtensions
{
    public static bool IsNull<T, TU>(this KeyValuePair<T, TU> pair)
    {
        return pair.Equals(new KeyValuePair<T, TU>());
    }
}

And then just use:

var countries = new Dictionary<string, string>
{
    {"cz", "prague"},
    {"de", "berlin"}
};

var country = countries.FirstOrDefault(x => x.Key == "en");

if(country.IsNull()){

}

Removing empty lines in Notepad++

An easy alternative for removing white space from empty lines:

  1. TextFX>TextFX Edit> Trim Trailing Spaces

This will remove all trailing spaces, including trailing spaces in blank lines. Make sure, no trailing spaces are significant.

Dynamically adding HTML form field using jQuery

something like so might work:

<script type="text/javascript">
$(document).ready(function(){
    var $input = $("<input name='myField' type='text'>");
    $('#section2').append($input);
});
</script>

<form>
    <div id="section1"><!-- some controls--></div>
    <div id="section2"><!-- for dynamic controls--></div>
</form>

How to combine GROUP BY, ORDER BY and HAVING

ORDER BY is always last...

However, you need to pick the fields you ACTUALLY WANT then select only those and group by them. SELECT * and GROUP BY Email will give you RANDOM VALUES for all the fields but Email. Most RDBMS will not even allow you to do this because of the issues it creates, but MySQL is the exception.

SELECT Email, COUNT(*)
FROM user_log
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC

How to convert JSON to string?

You can use the JSON stringify method.

JSON.stringify({x: 5, y: 6}); // '{"x":5,"y":6}' or '{"y":6,"x":5}'

There is pretty good support for this across the board when it comes to browsers, as shown on http://caniuse.com/#search=JSON. You will note, however, that versions of IE earlier than 8 do not support this functionality natively.

If you wish to cater to those users as well you will need a shim. Douglas Crockford has provided his own JSON Parser on github.

How do I get the XML SOAP request of an WCF Web service request?

I just wanted to add this to the answer from Kimberly. Maybe it can save some time and avoid compilation errors for not implementing all methods that the IEndpointBehaviour interface requires.

Best regards

Nicki

    /*
        // This is just to illustrate how it can be implemented on an imperative declarared binding, channel and client.

        string url = "SOME WCF URL";
        BasicHttpBinding wsBinding = new BasicHttpBinding();                
        EndpointAddress endpointAddress = new EndpointAddress(url);

        ChannelFactory<ISomeService> channelFactory = new ChannelFactory<ISomeService>(wsBinding, endpointAddress);
        channelFactory.Endpoint.Behaviors.Add(new InspectorBehavior());
        ISomeService client = channelFactory.CreateChannel();
    */    
        public class InspectorBehavior : IEndpointBehavior
        {
            public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
            {
                // No implementation necessary  
            }

            public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
                clientRuntime.MessageInspectors.Add(new MyMessageInspector());
            }

            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {
                // No implementation necessary  
            }

            public void Validate(ServiceEndpoint endpoint)
            {
                // No implementation necessary  
            }  

        }

        public class MyMessageInspector : IClientMessageInspector
        {
            public object BeforeSendRequest(ref Message request, IClientChannel channel)
            {
                // Do something with the SOAP request
                string request = request.ToString();
                return null;
            }

            public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                // Do something with the SOAP reply
                string replySoap = reply.ToString();
            }
        }

XPath using starts-with function

Use:

//REVENUE_YEAR[starts-with(.,'2552')]/../REGION/text() 

VBA check if object is set

The (un)safe way to do this - if you are ok with not using option explicit - is...

Not TypeName(myObj) = "Empty"

This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...

Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ true, the object exists - TypeName is Object

'Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ false, the object has not been declared

This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

The previous answers are pretty confusing. You don't need a react-state to solve this, nor any special external lib. It can be achieved with pure css/sass:

The style:

.hover {
  position: relative;

  &:hover &__no-hover {
    opacity: 0;
  }

  &:hover &__hover {
    opacity: 1;
  }

  &__hover {
    position: absolute;
    top: 0;
    opacity: 0;
  }

  &__no-hover {
    opacity: 1;
  }
}

The React-Component

A simple Hover Pure-Rendering-Function:

const Hover = ({ onHover, children }) => (
    <div className="hover">
        <div className="hover__no-hover">{children}</div>
        <div className="hover__hover">{onHover}</div>
    </div>
)

Usage

Then use it like this:

    <Hover onHover={<div> Show this on hover </div>}>
        <div> Show on no hover </div>
    </Hover>

React.js: onChange event for contentEditable

I suggest using a mutationObserver to do this. It gives you a lot more control over what is going on. It also gives you more details on how the browse interprets all the keystrokes

Here in TypeScript

import * as React from 'react';

export default class Editor extends React.Component {
    private _root: HTMLDivElement; // Ref to the editable div
    private _mutationObserver: MutationObserver; // Modifications observer
    private _innerTextBuffer: string; // Stores the last printed value

    public componentDidMount() {
        this._root.contentEditable = "true";
        this._mutationObserver = new MutationObserver(this.onContentChange);
        this._mutationObserver.observe(this._root, {
            childList: true, // To check for new lines
            subtree: true, // To check for nested elements
            characterData: true // To check for text modifications
        });
    }

    public render() {
        return (
            <div ref={this.onRootRef}>
                Modify the text here ...
            </div>
        );
    }

    private onContentChange: MutationCallback = (mutations: MutationRecord[]) => {
        mutations.forEach(() => {
            // Get the text from the editable div
            // (Use innerHTML to get the HTML)
            const {innerText} = this._root; 

            // Content changed will be triggered several times for one key stroke
            if (!this._innerTextBuffer || this._innerTextBuffer !== innerText) {
                console.log(innerText); // Call this.setState or this.props.onChange here
                this._innerTextBuffer = innerText;
            }
        });
    }

    private onRootRef = (elt: HTMLDivElement) => {
        this._root = elt;
    }
}

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

It could happen after you update your php version, for instance if you upgrade from php5.6 to php7.1 you need to run these commands:

sudo apt-get install php7.1-mbstring
sudo service apache2 restart

If your destination version is different you need to check if the mbstring package exsit or not, an example for php7.0:

sudo apt-cache search php7.0-mbstring

I found it useful to first check existence of all modules that you working with, then performing an upgrade, in addition to that update phpmyadmin after upgrading your php is a good idea

React-Router open Link in new tab

I think Link component does not have the props for it.

You can have alternative way by create a tag and use the makeHref method of Navigation mixin to create your url

<a target='_blank' href={this.makeHref(routeConsts.CHECK_DOMAIN, {},
   { realm: userStore.getState().realms[0].name })}>
        Share this link to your webmaster
</a>

How to create an 2D ArrayList in java?

1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it

ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();

should be written

List<List<String>> listOfLists = new ArrayList<List<String>>(size); 

Then you will have to instantiate all columns of your 2d array

    for(int i = 0; i < size; i++)  {
        listOfLists.add(new ArrayList<String>());
    }

And you will use it like this :

listOfLists.get(0).add("foobar");

But if you really want to "create a 2D array that each cell is an ArrayList!"

Then you must go the dijkstra way.

Removing character in list of strings

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]

msg = filter(lambda x : x != "8", lst)

print msg

EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.

Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped.

To make this (kinda work?) with how the intent of the question was we could perform something similar to this

msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
  • I am not in an interpreter at the moment so of course mileage may vary, we may have to index so we do list(y[0]) would be the only modification to the above for this explanation purposes.

What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"].

This would result in a data type that looks like this

msg = [["a", "a", "a", "a"], ["b", "b"]...]

So finally to wrap that up we would have to map it to bring them all back into the same type roughly

msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))

I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.

Getting Image from URL (Java)

You are getting an HTTP 400 (Bad Request) error because there is a space in your URL. If you fix it (before the zoom parameter), you will get an HTTP 400 error (Unauthorized). Maybe you need some HTTP header to identify your download as a recognised browser (use the "User-Agent" header) or additional authentication parameter.

For the User-Agent example, then use the ImageIO.read(InputStream) using the connection inputstream:

URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "xxxxxx");

Use whatever needed for xxxxxx

Splitting comma separated string in a PL/SQL stored proc

create or replace procedure pro_ss(v_str varchar2) as
v_str1 varchar2(100); 
v_comma_pos number := 0;    
v_start_pos number := 1;
begin             
    loop        
    v_comma_pos := instr(v_str,',',v_start_pos);   
    if  v_comma_pos = 0 then     
      v_str1 := substr(v_str,v_start_pos);  
      dbms_output.put_line(v_str1);    
      exit;
      end if;    
    v_str1 := substr(v_str,v_start_pos,(v_comma_pos - v_start_pos)); 
    dbms_output.put_line(v_str1);       
    v_start_pos := v_comma_pos + 1;    
    end loop; 
end;
/

call pro_ss('aa,bb,cc,dd,ee,ff,gg,hh,ii,jj');

outout: aa bb cc dd ee ff gg hh ii jj

Using a cursor with dynamic SQL in a stored procedure

Working with a non-relational database (IDMS anyone?) over an ODBC connection qualifies as one of those times where cursors and dynamic SQL seems the only route.

select * from a where a=1 and b in (1,2)

takes 45 minutes to respond while re-written to use keysets without the in clause will run in under 1 second:

select * from a where (a=1 and b=1)
union all
select * from a where (a=1 and b=2)

If the in statement for column B contains 1145 rows, using a cursor to create indidivudal statements and execute them as dynamic SQL is far faster than using the in clause. Silly hey?

And yes, there's no time in a relational database that cursor's should be used. I just can't believe I've come across an instance where a cursor loop is several magnitudes quicker.

Can Python test the membership of multiple values in a list?

Both of the answers presented here will not handle repeated elements. For example, if you are testing whether [1,2,2] is a sublist of [1,2,3,4], both will return True. That may be what you mean to do, but I just wanted to clarify. If you want to return false for [1,2,2] in [1,2,3,4], you would need to sort both lists and check each item with a moving index on each list. Just a slightly more complicated for loop.

Chrome javascript debugger breakpoints don't do anything?

Make sure the script with the "debugger;" statement in it is not blackboxed by Chrome. You can go to the Sources tab to check and turn off blackboxing if so.

EDIT: Added screenshot.

How to turn off blackboxing.

jQuery get values of checked checkboxes into array

Needed the form elements named in the HTML as an array to be an array in the javascript object, as if the form was actually submitted.

If there is a form with multiple checkboxes such as:

<input name='breath[0]' type='checkbox' value='presence0'/>
<input name='breath[1]' type='checkbox' value='presence1'/>
<input name='breath[2]' type='checkbox' value='presence2'/>
<input name='serenity'  type='text' value='Is within the breath.'/>
...

The result is an object with:

data = {
   'breath':['presence0','presence1','presence2'],
   'serenity':'Is within the breath.'
}


var $form = $(this),
    data  = {};

$form.find("input").map(function()
{
    var $el  = $(this),
        name = $el.attr("name");

    if (/radio|checkbox/i.test($el.attr('type')) && !$el.prop('checked'))return;

    if(name.indexOf('[') > -1)
    {
        var name_ar = name.split(']').join('').split('['),
            name    = name_ar[0],
            index   = name_ar[1];

        data[name]  = data[name] || [];
        data[name][index] = $el.val();
    }
    else data[name] = $el.val();
});

And there are tons of answers here which helped improve my code, but they were either too complex or didn't do exactly want I wanted: Convert form data to JavaScript object with jQuery

Works but can be improved: only works on one-dimensional arrays and the resulting indexes may not be sequential. The length property of an array returns the next index number as the length of the array, not the actually length.

Hope this helped. Namaste!

How to pass all arguments passed to my bash script to a function of mine?

It's worth mentioning that you can specify argument ranges with this syntax.

function example() {
    echo "line1 ${@:1:1}"; #First argument
    echo "line2 ${@:2:1}"; #Second argument
    echo "line3 ${@:3}"; #Third argument onwards
}

I hadn't seen it mentioned.

Adding an external directory to Tomcat classpath

In Tomcat 6, the CLASSPATH in your environment is ignored. In setclasspath.bat you'll see

set CLASSPATH=%JAVA_HOME%\lib\tools.jar

then in catalina.bat, it's used like so

%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS% 
-Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" 
-Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" 
-Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%

I don't see any other vars that are included, so I think you're stuck with editing setclasspath.bat and changing how CLASSPATH is built. For Tomcat 6.0.20, this change was on like 74 of setclasspath.bat

set CLASSPATH=C:\app_config\java_app;%JAVA_HOME%\lib\tools.jar

Overcoming "Display forbidden by X-Frame-Options"

i had this problem, and resolved it editing httd.conf

<IfModule headers_module>
    <IfVersion >= 2.4.7 >
        Header always setifempty X-Frame-Options GOFORIT
    </IfVersion>
    <IfVersion < 2.4.7 >
        Header always merge X-Frame-Options GOFORIT
    </IfVersion>
</IfModule>

i changed SAMEORIGIN to GOFORIT and restarted server

Standard way to embed version into python package?

If you use CVS (or RCS) and want a quick solution, you can use:

__version__ = "$Revision: 1.1 $"[11:-2]
__version_info__ = tuple([int(s) for s in __version__.split(".")])

(Of course, the revision number will be substituted for you by CVS.)

This gives you a print-friendly version and a version info that you can use to check that the module you are importing has at least the expected version:

import my_module
assert my_module.__version_info__ >= (1, 1)

How to draw text using only OpenGL methods?

I think that the best solution for drawing text in OpenGL is texture fonts, I work with them for a long time. They are flexible, fast and nice looking (with some rear exceptions). I use special program for converting font files (.ttf for example) to texture, which is saved to file of some internal "font" format (I've developed format and program based on http://content.gpwiki.org/index.php/OpenGL:Tutorials:Font_System though my version went rather far from the original supporting Unicode and so on). When starting the main app, fonts are loaded from this "internal" format. Look link above for more information.

With such approach the main app doesn't use any special libraries like FreeType, which is undesirable for me also. Text is being drawn using standard OpenGL functions.

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

plt.box(False)
plt.xticks([])
plt.yticks([])
plt.savefig('fig.png')

should do the trick.

Why std::cout instead of simply cout?

You probably had using namespace std; before in your code you did in class. That explicitly tells the precompiler to look for the symbols in std, which means you don't need to std::. Though it is good practice to std::cout instead of cout so you explicitly invoke std::cout every time. That way if you are using another library that redefines cout, you still have the std::cout behavior instead of some other custom behavior.

Python - Extracting and Saving Video Frames

After a lot of research on how to convert frames to video I have created this function hope this helps. We require opencv for this:

import cv2
import numpy as np
import os

def frames_to_video(inputpath,outputpath,fps):
   image_array = []
   files = [f for f in os.listdir(inputpath) if isfile(join(inputpath, f))]
   files.sort(key = lambda x: int(x[5:-4]))
   for i in range(len(files)):
       img = cv2.imread(inputpath + files[i])
       size =  (img.shape[1],img.shape[0])
       img = cv2.resize(img,size)
       image_array.append(img)
   fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')
   out = cv2.VideoWriter(outputpath,fourcc, fps, size)
   for i in range(len(image_array)):
       out.write(image_array[i])
   out.release()


inputpath = 'folder path'
outpath =  'video file path/video.mp4'
fps = 29
frames_to_video(inputpath,outpath,fps)

change the value of fps(frames per second),input folder path and output folder path according to your own local locations

How to return a result from a VBA function

VBA functions treat the function name itself as a sort of variable. So instead of using a "return" statement, you would just say:

test = 1

Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test, and whatever the value is when you reach the end of the function will be the value returned.

how to compare two elements in jquery

Every time you call the jQuery() function, a new object is created and returned. So even equality checks on the same selectors will fail.

<div id="a">test</div>

$('#a') == $('#a') // false

The resulting jQuery object contains an array of matching elements, which are basically native DOM objects like HTMLDivElement that always refer to the same object, so you should check those for equality using the array index as Darin suggested.

$('#a')[0] == $('#a')[0] // true

Using switch statement with a range of value in each case?

This type of behavior is not supported in Java. However, if you have a large project that needs this, consider blending in Groovy code in your project. Groovy code is compiled into byte code and can be run with JVM. The company I work for uses Groovy to write service classes and Java to write everything else.

How to append text to an existing file in Java?

If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

There are few points to note:

  1. It is always a good habit to specify charset encoding and for that we have constant in class StandardCharsets.
  2. The code uses try-with-resource statement in which resources are automatically closed after the try.

Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential we can make use of stream APIs in Java:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}

Regex: Check if string contains at least one digit

you could use look-ahead assertion for this:

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

Why my regexp for hyphenated words doesn't work?

A couple of things:

  1. Your regexes need to be anchored by separators* or you'll match partial words, as is the case now
  2. You're not using the proper syntax for a non-capturing group. It's (?: not (:?

If you address the first problem, you won't need groups at all.

*That is, a blank or beginning/end of string.

How to list only top level directories in Python?

[x for x in os.listdir(somedir) if os.path.isdir(os.path.join(somedir, x))]

How to map with index in Ruby?

In ruby 1.9.3 there is a chainable method called with_index which can be chained to map.

For example:

array.map.with_index { |item, index| ... }

Setting java locale settings

You could call during init or whatever Locale.setDefault() or -Duser.language=, -Duser.country=, and -Duser.variant= at the command line. Here's something on Sun's site.

Android: How to stretch an image to the screen width while maintaining aspect ratio?

You can use my StretchableImageView preserving the aspect ratio (by width or by height) depending on width and height of drawable:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

public class StretchableImageView extends ImageView{

    public StretchableImageView(Context context) {
        super(context);
    }

    public StretchableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public StretchableImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if(getDrawable()!=null){
            if(getDrawable().getIntrinsicWidth()>=getDrawable().getIntrinsicHeight()){
                int width = MeasureSpec.getSize(widthMeasureSpec);
                int height = width * getDrawable().getIntrinsicHeight()
                            / getDrawable().getIntrinsicWidth();
                setMeasuredDimension(width, height);
            }else{
                int height = MeasureSpec.getSize(heightMeasureSpec);
                int width = height * getDrawable().getIntrinsicWidth()
                            / getDrawable().getIntrinsicHeight();
                setMeasuredDimension(width, height);
            }
        }
    }
}

Delete default value of an input text on click

EDIT: Although, this solution works, I would recommend you try MvanGeest's solution below which uses the placeholder-attribute and a javascript fallback for browsers which don't support it yet.

If you are looking for a Mootools equivalent to the JQuery fallback in MvanGeest's reply, here is one.

--

You should probably use onfocus and onblur events in order to support keyboard users who tab through forms.

Here's an example:

<input type="text" value="[email protected]" name="Email" id="Email"
 onblur="if (this.value == '') {this.value = '[email protected]';}"
 onfocus="if (this.value == '[email protected]') {this.value = '';}" />

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

Don't worry... Its much easy to solve your problem. Just SET you SDK-LOCATION and JDK-LOCATION.

  • Click on Configure ( As Soon Android studio open )
  • Click Project Default
  • Click Project Structure
  • Clik Android Sdk Location

  • Select & Browse your Android SDK Location (Like: C:\Android\sdk)

  • Uncheck USE EMBEDDED JDK LOCATION

  • Set & Browse JDK Location, Like C:\Program Files\Java\jdk1.8.0_121

Python 3 Online Interpreter / Shell

I recently came across Python 3 interpreter at CompileOnline.

Find size and free space of the filesystem containing a given file

import os

def get_mount_point(pathname):
    "Get the mount point of the filesystem containing pathname"
    pathname= os.path.normcase(os.path.realpath(pathname))
    parent_device= path_device= os.stat(pathname).st_dev
    while parent_device == path_device:
        mount_point= pathname
        pathname= os.path.dirname(pathname)
        if pathname == mount_point: break
        parent_device= os.stat(pathname).st_dev
    return mount_point

def get_mounted_device(pathname):
    "Get the device mounted at pathname"
    # uses "/proc/mounts"
    pathname= os.path.normcase(pathname) # might be unnecessary here
    try:
        with open("/proc/mounts", "r") as ifp:
            for line in ifp:
                fields= line.rstrip('\n').split()
                # note that line above assumes that
                # no mount points contain whitespace
                if fields[1] == pathname:
                    return fields[0]
    except EnvironmentError:
        pass
    return None # explicit

def get_fs_freespace(pathname):
    "Get the free space of the filesystem containing pathname"
    stat= os.statvfs(pathname)
    # use f_bfree for superuser, or f_bavail if filesystem
    # has reserved space for superuser
    return stat.f_bfree*stat.f_bsize

Some sample pathnames on my computer:

path 'trash':
  mp /home /dev/sda4
  free 6413754368
path 'smov':
  mp /mnt/S /dev/sde
  free 86761562112
path '/usr/local/lib':
  mp / rootfs
  free 2184364032
path '/proc/self/cmdline':
  mp /proc proc
  free 0

PS

if on Python =3.3, there's shutil.disk_usage(path) which returns a named tuple of (total, used, free) expressed in bytes.

jQuery, checkboxes and .is(":checked")

Well, to match the first scenario, this is something I've come up with.

http://jsbin.com/uwupa/edit

Essentially, instead of binding the "click" event, you bind the "change" event with the alert.

Then, when you trigger the event, first you trigger click, then trigger change.

When to use %r instead of %s in Python?

This is a version of Ben James's answer, above:

>>> import datetime
>>> x = datetime.date.today()
>>> print x
2013-01-11
>>> 
>>> 
>>> print "Today's date is %s ..." % x
Today's date is 2013-01-11 ...
>>> 
>>> print "Today's date is %r ..." % x
Today's date is datetime.date(2013, 1, 11) ...
>>>

When I ran this, it helped me see the usefulness of %r.

How to convert a Django QuerySet to a list

You can directly convert using the list keyword. For example:

obj=emp.objects.all()
list1=list(obj)

Using the above code you can directly convert a query set result into a list.

Here list is keyword and obj is result of query set and list1 is variable in that variable we are storing the converted result which in list.

Hide header in stack navigator React navigation

You can hide header like this:

<Stack.Screen name="Login" component={Login} options={{headerShown: false}}  />

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

SQL Server Text type vs. varchar data type

If you're using SQL Server 2005 or later, use varchar(MAX). The text datatype is deprecated and should not be used for new development work. From the docs:

Important

ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

How to print all session variables currently set?

<?php
    session_start();
    echo "<h3> PHP List All Session Variables</h3>";
    foreach ($_SESSION as $key=>$val)
    echo $key." ".$val."<br/>";
?>

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

You can try this:

NSLog(@"%@", NSStringFromCGPoint(cgPoint));

There are a number of functions provided by UIKit that convert the various CG structs into NSStrings. The reason it doesn't work is because %@ signifies an object. A CGPoint is a C struct (and so are CGRects and CGSizes).

Creating temporary files in bash

The mktemp(1) man page explains it fairly well:

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win. A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.

In a script, I invoke mktemp something like

mydir=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")

which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.

mktemp is not standard, but it does exist on many platforms. The "X"s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others


By the way, safe creation of temporary files is important for more than just shell scripting. That's why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…

What does O(log n) mean exactly?

O(logn) is one of the polynomial time complexity to measure the runtime performance of any code.

I hope you have already heard of Binary search algorithm.

Let's assume you have to find an element in the array of size N.

Basically, the code execution is like N N/2 N/4 N/8....etc

If you sum all the work done at each level you will end up with n(1+1/2+1/4....) and that is equal to O(logn)

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

Step by step solution:

  1. Open your command prompt or Terminal for Mac
  2. Change directory to directory of the keytool file location. Change directory by using command cd <directory path>. (Note: if any directory name has space then add \ between the two words. Example cd /Applications/Android\ Studio.app//Contents/jre/jdk/Contents/Home/bin/)

    • To find the location of your keytool, you go to android studio..open your project. And go to

    • File>project Structure>SDK location..and find JDK location.

  3. Run the keytool by this command: keytool -list -v –keystore <your jks file path> (Note: if any directory name has space then add \ between the two words. example keytool -list -v -keystore /Users/username/Desktop/tasmiah\ mobile/v3/jordanos.jks)

  4. Command prompt you to key in the password.. so key in your password.. then you get the result

What's the difference between process.cwd() vs __dirname?

Knowing the scope of each can make things easier to remember.

process is node's global object, and .cwd() returns where node is running.

__dirname is module's property, and represents the file path of the module. In node, one module resides in one file.

Similarly, __filename is another module's property, which holds the file name of the module.

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

I had the problem whereby I was having to run a Maven compilation on my project from the command line in order to run my unit tests; if I made a change to the test class and let Eclipse automatically recompile it, then I got the "Unsupported major.minor version 51.0" error.

I do have both JDK6 and JDK7 installed, but all my JRE settings were pointing at 1.6, both in the pom and from the project properties page in Eclipse. No amount of Maven Update Project and/or refreshing solved this.

Finally I tried closing the project and re-opening it, and this seemed to fix it! HTH

android: stretch image in imageview to fit screen

Give in the xml file of your layout android:scaleType="fitXY"
P.S : this applies to when the image is set with android:src="..." rather than android:background="..." as backgrounds are set by default to stretch and fit to the View.

Effects of the extern keyword on C functions

The extern keyword takes on different forms depending on the environment. If a declaration is available, the extern keyword takes the linkage as that specified earlier in the translation unit. In the absence of any such declaration, extern specifies external linkage.

static int g();
extern int g(); /* g has internal linkage */

extern int j(); /* j has tentative external linkage */

extern int h();
static int h(); /* error */

Here are the relevant paragraphs from the C99 draft (n1256):

6.2.2 Linkages of identifiers

[...]

4 For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,23) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

5 If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

How to get package name from anywhere?

An idea is to have a static variable in your main activity, instantiated to be the package name. Then just reference that variable.

You will have to initialize it in the main activity's onCreate() method:

Global to the class:

public static String PACKAGE_NAME;

Then..

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    PACKAGE_NAME = getApplicationContext().getPackageName();
}

You can then access it via Main.PACKAGE_NAME.

How do I get values from a SQL database into textboxes using C#?

If you want to display single value access from database into textbox, please refer to the code below:

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
TextBox1.Text=cmd.ExecuteScalar();
Con.Close();

or

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
SqlDataReader dr=new SqlDataReadr();
dr=cmd.Executereader();
if(dr.read())
{
    TextBox1.Text=dr.GetValue(0).Tostring();
}
Con.Close();

React - how to pass state to another component

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

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

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

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

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

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

How to compare two JSON objects with the same elements in a different order equal?

You can write your own equals function:

  • dicts are equal if: 1) all keys are equal, 2) all values are equal
  • lists are equal if: all items are equal and in the same order
  • primitives are equal if a == b

Because you're dealing with json, you'll have standard python types: dict, list, etc., so you can do hard type checking if type(obj) == 'dict':, etc.

Rough example (not tested):

def json_equals(jsonA, jsonB):
    if type(jsonA) != type(jsonB):
        # not equal
        return False
    if type(jsonA) == dict:
        if len(jsonA) != len(jsonB):
            return False
        for keyA in jsonA:
            if keyA not in jsonB or not json_equal(jsonA[keyA], jsonB[keyA]):
                return False
    elif type(jsonA) == list:
        if len(jsonA) != len(jsonB):
            return False
        for itemA, itemB in zip(jsonA, jsonB):
            if not json_equal(itemA, itemB):
                return False
    else:
        return jsonA == jsonB

How do I check if a Sql server string is null or empty

Use the LEN function to check for null or empty values. You can just use LEN(@SomeVarcharParm) > 0. This will return false if the value is NULL, '', or ' '. This is because LEN(NULL) returns NULL and NULL > 0 returns false. Also, LEN(' ') returns 0. See for yourself run:

SELECT 
 CASE WHEN NULL > 0 THEN 'NULL > 0 = true' ELSE 'NULL > 0 = false' END,
 CASE WHEN LEN(NULL) > 0 THEN 'LEN(NULL) = true' ELSE 'LEN(NULL) = false' END,
 CASE WHEN LEN('') > 0 THEN 'LEN('''') > 0 = true' ELSE 'LEN('''') > 0 = false' END,
 CASE WHEN LEN(' ') > 0 THEN 'LEN('' '') > 0 = true' ELSE 'LEN('' '') > 0 = false' END,
 CASE WHEN LEN(' test ') > 0 THEN 'LEN('' test '') > 0 = true' ELSE 'LEN('' test '') > 0 = false' END

Sqlite primary key on multiple columns

The following code creates a table with 2 column as a primary key in SQLite.

SOLUTION:

CREATE TABLE IF NOT EXISTS users (
    id TEXT NOT NULL, 
    name TEXT NOT NULL, 
    pet_name TEXT, 
    PRIMARY KEY (id, name)
)

How to get tf.exe (TFS command line client)?

For reference: these are the required DLLs for Visual Studio 2017 (as did @ijprest for the VS 2010)

TF.exe
TF.exe.config
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Core.WebApi.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.TeamFoundation.VersionControl.Common.dll
Microsoft.TeamFoundation.VersionControl.Controls.dll
Microsoft.VisualStudio.Services.Client.Interactive.dll
Microsoft.VisualStudio.Services.Common.dll
Microsoft.VisualStudio.Services.WebApi.dll

They will be in my base VM image. I'm going to use it to pull the latest deployment scripts from VC to a temporary local workspace folder when installing a new server.

tf workspace /new ... 
tf workfold /map ...
tf get "%WorkSpaceLocalFolder%" /recursive
tf workfold /unmap 
tf workspace /delete

<run deployment scripts from "%WorkSpaceLocalFolder%" >

rmdir "%WorkSpaceLocalFolder%"

(Sorry to post this as an answer, but I don't have enough reputation to comment, which I believe it should have been)

Read XML file using javascript

You can use below script for reading child of the above xml. It will work with IE and Mozila Firefox both.

<script type="text/javascript">

function readXml(xmlFile){

var xmlDoc;

if(typeof window.DOMParser != "undefined") {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET",xmlFile,false);
    if (xmlhttp.overrideMimeType){
        xmlhttp.overrideMimeType('text/xml');
    }
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;
}
else{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.load(xmlFile);
}
var tagObj=xmlDoc.getElementsByTagName("marker");
var typeValue = tagObj[0].getElementsByTagName("type")[0].childNodes[0].nodeValue;
var titleValue = tagObj[0].getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
</script>

Convert String[] to comma separated string in java

if (name.length > 0) {
    StringBuilder nameBuilder = new StringBuilder();

    for (String n : name) {
        nameBuilder.append("'").append(n.replace("'", "\\'")).append("',");
        // can also do the following
        // nameBuilder.append("'").append(n.replace("'", "''")).append("',");
    }

    nameBuilder.deleteCharAt(nameBuilder.length() - 1);

    return nameBuilder.toString();
} else {
    return "";
}

How to convert wstring into string?

I am using below to convert wstring to string.

std::string strTo;
char *szTo = new char[someParam.length() + 1];
szTo[someParam.size()] = '\0';
WideCharToMultiByte(CP_ACP, 0, someParam.c_str(), -1, szTo, (int)someParam.length(), NULL, NULL);
strTo = szTo;
delete szTo;

Regular expression to extract numbers from a string

if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use

\d+

How to comment lines in rails html.erb files?

This is CLEANEST, SIMPLEST ANSWER for CONTIGUOUS NON-PRINTING Ruby Code:

The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.


  1. CONTIGUOUS NON-PRINTING Ruby Code

    • This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml, etc.

    • This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>

    • DETAILS:

      Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:

        <%# if flash[:myErrors] %>
          <%# if flash[:myErrors].any? %>
            <%# if @post.id.nil? %>
              <%# if @myPost!=-1 %>
                <%# @post = @myPost %>
              <%# else %>
                <%# @post = Post.new %>
              <%# end %>
            <%# end %>
          <%# end %>
        <%# end %>
      

      YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:

        <%# 
          if flash[:myErrors] then
            if flash[:myErrors].any? then
              if @post.id.nil? then
                if @myPost!=-1 then
                  @post = @myPost 
                else 
                  @post = Post.new 
                end 
              end 
            end 
          end 
        %>
      

Find largest and smallest number in an array

Unless you really must implement your own solution, you can use std::minmax_element. This returns a pair of iterators, one to the smallest element and one to the largest.

#include <algorithm>

auto minmax = std::minmax_element(std::begin(values), std::end(values));

std::cout << "min element " << *(minmax.first) << "\n";
std::cout << "max element " << *(minmax.second) << "\n";

What is the meaning of prepended double colon "::"?

"::" represents scope resolution operator. Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.

Fastest way to get the first n elements of a List into an Array

Assumption:

list - List<String>

Using Java 8 Streams,

  • to get first N elements from a list into a list,

    List<String> firstNElementsList = list.stream().limit(n).collect(Collectors.toList());

  • to get first N elements from a list into an Array,

    String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);

Changing the page title with Jquery

Some code to walk through a list of titles (circularily or one-shot):

    var titles = [
            " title",
            "> title",
            ">> title",
            ">>> title"
    ];

    // option 1:
    function titleAniCircular(i) {
            // from first to last title and back again, forever
            i = (!i) ? 0 : (i*1+1) % titles.length;
            $('title').html(titles[i]);
            setTimeout(titleAniCircular, 1000, [i]);
    };

    // option 2:
    function titleAniSequence(i) {
            // from first to last title and stop
            i = (!i) ? 0 : (i*1+1);
            $('title').html(titles[i]);
            if (i<titles.length-1) setTimeout(titleAniSequence, 1000, [i]);
    };

    // then call them when you like.
    // e.g. to call one on document load, uncomment one of the rows below:

    //$(document).load( titleAniCircular() );
    //$(document).load( titleAniSequence() );

Push local Git repo to new remote including all branches and tags

To push all your branches, use either (replace REMOTE with the name of the remote, for example "origin"):

git push REMOTE '*:*'
git push REMOTE --all

To push all your tags:

git push REMOTE --tags

Finally, I think you can do this all in one command with:

git push REMOTE --mirror

However, in addition --mirror, will also push your remotes, so this might not be exactly what you want.

How do I find the maximum of 2 numbers?

You could also achieve the same result by using a Conditional Expression:

maxnum = run if run > value else value

a bit more flexible than max but admittedly longer to type.

What is C# analog of C++ std::pair?

Unfortunately, there is none. You can use the System.Collections.Generic.KeyValuePair<K, V> in many situations.

Alternatively, you can use anonymous types to handle tuples, at least locally:

var x = new { First = "x", Second = 42 };

The last alternative is to create an own class.

How to test the `Mosquitto` server?

If you wish to have an GUI based broker testing without installing any tool you can use Hive Mqtt web socket for testing your Mosquitto server

just visit http://www.hivemq.com/demos/websocket-client/ and enter server connection details.

If you got connected means your server is configured properly.

You can also test publish and subscribe of messages using this mqtt web socket

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

Here is a modified JSBin with a working sample:

http://jsbin.com/sezamuja/1/edit

Here is what I did with filters in the input:

<input ng-model="(results.subjects | filter:{grade:'C'})[0].title">

Correct way of using log4net (logger naming)

Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.

class << self idiom in Ruby

What class << thing does:

class Hi
  self #=> Hi
  class << self #same as 'class << Hi'
    self #=> #<Class:Hi>
    self == Hi.singleton_class #=> true
  end
end

[it makes self == thing.singleton_class in the context of its block].


What is thing.singleton_class?

hi = String.new
def hi.a
end

hi.class.instance_methods.include? :a #=> false
hi.singleton_class.instance_methods.include? :a #=> true

hi object inherits its #methods from its #singleton_class.instance_methods and then from its #class.instance_methods.
Here we gave hi's singleton class instance method :a. It could have been done with class << hi instead.
hi's #singleton_class has all instance methods hi's #class has, and possibly some more (:a here).

[instance methods of thing's #class and #singleton_class can be applied directly to thing. when ruby sees thing.a, it first looks for :a method definition in thing.singleton_class.instance_methods and then in thing.class.instance_methods]


By the way - they call object's singleton class == metaclass == eigenclass.

Composer Warning: openssl extension is missing. How to enable in WAMP

For installing Composer below steps worked me:(WAMP version 2.4 x64bit)

edit ->
**C:\wamp\bin\php\php5.4.12\php.ini**
;;uncomment below line or remove the semicolons ';'
extension=php_openssl.dll

**C:\wamp\bin\apache\Apache2.4.4\bin\php.ini**

extension=php_openssl.dll

How to know the version of pip itself

For windows:

import pip

help(pip) 

shows the version at the end of the help file.

How to use org.apache.commons package?

Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.

TypeError: Converting circular structure to JSON in nodejs

I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.

Reactjs: Unexpected token '<' Error

heres another way you can do it html

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
</head>

<body>
     <div id="app"></div>

    <script src="src/index.js"></script>
</body>

</html>

index.js file with path src/index.js

import React from "react";
import { render } from "react-dom";

import "./styles.scss";

const App = () => (
  <div>
    <h1>Hello test</h1>
  </div>
);

render(<App />, document.getElementById("app"));

use this package.json will get u up and running quickly

{
  "name": "test-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.html",
  "scripts": {
    "start": "parcel index.html --open",
    "build": "parcel build index.html"
  },
  "dependencies": {
    "react": "16.2.0",
    "react-dom": "16.2.0",
    "react-native": "0.57.5"
  },
  "devDependencies": {
    "@types/react-native": "0.57.13",
    "parcel-bundler": "^1.6.1"
  },
  "keywords": []
}

How can I sharpen an image in OpenCV?

You can sharpen an image using an unsharp mask. You can find more information about unsharp masking here. And here's a Python implementation using OpenCV:

import cv2 as cv
import numpy as np

def unsharp_mask(image, kernel_size=(5, 5), sigma=1.0, amount=1.0, threshold=0):
    """Return a sharpened version of the image, using an unsharp mask."""
    blurred = cv.GaussianBlur(image, kernel_size, sigma)
    sharpened = float(amount + 1) * image - float(amount) * blurred
    sharpened = np.maximum(sharpened, np.zeros(sharpened.shape))
    sharpened = np.minimum(sharpened, 255 * np.ones(sharpened.shape))
    sharpened = sharpened.round().astype(np.uint8)
    if threshold > 0:
        low_contrast_mask = np.absolute(image - blurred) < threshold
        np.copyto(sharpened, image, where=low_contrast_mask)
    return sharpened

def example():
    image = cv.imread('my-image.jpg')
    sharpened_image = unsharp_mask(image)
    cv.imwrite('my-sharpened-image.jpg', sharpened_image)

What is a web service endpoint?

A web service endpoint is the URL that another program would use to communicate with your program. To see the WSDL you add ?wsdl to the web service endpoint URL.

Web services are for program-to-program interaction, while web pages are for program-to-human interaction.

So: Endpoint is: http://www.blah.com/myproject/webservice/webmethod

Therefore, WSDL is: http://www.blah.com/myproject/webservice/webmethod?wsdl


To expand further on the elements of a WSDL, I always find it helpful to compare them to code:

A WSDL has 2 portions (physical & abstract).

Physical Portion:

Definitions - variables - ex: myVar, x, y, etc.

Types - data types - ex: int, double, String, myObjectType

Operations - methods/functions - ex: myMethod(), myFunction(), etc.

Messages - method/function input parameters & return types

  • ex: public myObjectType myMethod(String myVar)

Porttypes - classes (i.e. they are a container for operations) - ex: MyClass{}, etc.

Abstract Portion:

Binding - these connect to the porttypes and define the chosen protocol for communicating with this web service. - a protocol is a form of communication (so text/SMS, vs. phone vs. email, etc.).

Service - this lists the address where another program can find your web service (i.e. your endpoint).

Java SecurityException: signer information does not match

This also happens if you include one file with different names or from different locations twice, especially if these are two different versions of the same file.

Define make variable at rule execution time

A relatively easy way of doing this is to write the entire sequence as a shell script.

out.tar:
   set -e ;\
   TMP=$$(mktemp -d) ;\
   echo hi $$TMP/hi.txt ;\
   tar -C $$TMP cf $@ . ;\
   rm -rf $$TMP ;\

I have consolidated some related tips here: https://stackoverflow.com/a/29085684/86967

Concatenating strings in C, which method is more efficient?

The difference is unlikely to matter:

  • If your strings are small, the malloc will drown out the string concatenations.
  • If your strings are large, the time spent copying the data will drown out the differences between strcat / sprintf.

As other posters have mentioned, this is a premature optimization. Concentrate on algorithm design, and only come back to this if profiling shows it to be a performance problem.

That said... I suspect method 1 will be faster. There is some---admittedly small---overhead to parse the sprintf format-string. And strcat is more likely "inline-able".

Executing JavaScript after X seconds

onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"

Change 1000 to the number of milliseconds you want to delay.

How to gracefully handle the SIGKILL signal in Java

It is impossible for any program, in any language, to handle a SIGKILL. This is so it is always possible to terminate a program, even if the program is buggy or malicious. But SIGKILL is not the only means for terminating a program. The other is to use a SIGTERM. Programs can handle that signal. The program should handle the signal by doing a controlled, but rapid, shutdown. When a computer shuts down, the final stage of the shutdown process sends every remaining process a SIGTERM, gives those processes a few seconds grace, then sends them a SIGKILL.

The way to handle this for anything other than kill -9 would be to register a shutdown hook. If you can use (SIGTERM) kill -15 the shutdown hook will work. (SIGINT) kill -2 DOES cause the program to gracefully exit and run the shutdown hooks.

Registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

I tried the following test program on OSX 10.6.3 and on kill -9 it did NOT run the shutdown hook, as expected. On a kill -15 it DOES run the shutdown hook every time.

public class TestShutdownHook
{
    public static void main(String[] args) throws InterruptedException
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("Shutdown hook ran!");
            }
        });

        while (true)
        {
            Thread.sleep(1000);
        }
    }
}

There isn't any way to really gracefully handle a kill -9 in any program.

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows.

The only real option to handle a kill -9 is to have another watcher program watch for your main program to go away or use a wrapper script. You could do with this with a shell script that polled the ps command looking for your program in the list and act accordingly when it disappeared.

#!/usr/bin/env bash

java TestShutdownHook
wait
# notify your other app that you quit
echo "TestShutdownHook quit"

How to sort a Ruby Hash by number value?

No idea how you got your results, since it would not sort by string value... You should reverse a1 and a2 in your example

Best way in any case (as per Mladen) is:

metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" => 10 }
metrics.sort_by {|_key, value| value}
  # ==> [["siteb.com", 9], ["sitec.com", 10], ["sitea.com", 745]]

If you need a hash as a result, you can use to_h (in Ruby 2.0+)

metrics.sort_by {|_key, value| value}.to_h
  # ==> {"siteb.com" => 9, "sitec.com" => 10, "sitea.com", 745}

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

When to use margin vs padding in CSS

One thing to note is when auto collapsing margins annoy you (and you are not using background colours on your elements), something it's just easier to use padding.

Java logical operator short-circuiting

SET A uses short-circuiting boolean operators.

What 'short-circuiting' means in the context of boolean operators is that for a set of booleans b1, b2, ..., bn, the short circuit versions will cease evaluation as soon as the first of these booleans is true (||) or false (&&).

For example:

// 2 == 2 will never get evaluated because it is already clear from evaluating
// 1 != 1 that the result will be false.
(1 != 1) && (2 == 2)

// 2 != 2 will never get evaluated because it is already clear from evaluating
// 1 == 1 that the result will be true.
(1 == 1) || (2 != 2)

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

how to convert JSONArray to List of Object using camel-jackson

I had similar json response coming from client. Created one main list class, and one POJO class.

Regex for checking if a string is strictly alphanumeric

See the documentation of Pattern.

Assuming US-ASCII alphabet (a-z, A-Z), you could use \p{Alnum}.

A regex to check that a line contains only such characters is "^[\\p{Alnum}]*$".

That also matches empty string. To exclude empty string: "^[\\p{Alnum}]+$".

Replace None with NaN in pandas dataframe

You can use DataFrame.fillna or Series.fillna which will replace the Python object None, not the string 'None'.

import pandas as pd
import numpy as np

For dataframe:

df = df.fillna(value=np.nan)

For column or series:

df.mycol.fillna(value=np.nan, inplace=True)

C# Create New T()

Another way is to use reflection:

protected T GetObject<T>(Type[] signature, object[] args)
{
    return (T)typeof(T).GetConstructor(signature).Invoke(args);
}

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

Example #1:

class A{
 void met(){
   Class.forName("com.example.Class1");
 }
}

If com/example/Class1 doesn't exist in any of the classpaths, then It throws ClassNotFoundException.

Example #2:

Class B{
  void met(){
   com.example.Class2 c = new com.example.Class2();
 }
}

If com/example/Class2 existed while compiling B, but not found while execution, then It throws NoClassDefFoundError.

Both are run time exceptions.

How do I make text bold in HTML?

Another option is to do it via CSS ...

E.g. 1

<span style="font-weight: bold;">Hello stackoverflow!</span>

E.g. 2

<style type="text/css">
    #text
    {
        font-weight: bold;
    }
</style>

<div id="text">
    Hello again!
</div>

Python dictionary: Get list of values for list of keys

Try this:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one'] # if there are many keys, use a set

[mydict[k] for k in mykeys]
=> [3, 1]

How can I define fieldset border color?

It does appear red on Firefox and IE 8. But perhaps you need to change the border-style too.

_x000D_
_x000D_
.field_set{_x000D_
  border-color: #F00;_x000D_
  border-style: solid;_x000D_
}
_x000D_
<fieldset class="field_set">_x000D_
  <legend>box</legend>_x000D_
  <table width="100%" border="0" cellspacing="0" cellpadding="0">_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

alt text

Link a .css on another folder

_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
_x000D_
.tree-view-com ul li {_x000D_
  position: relative;_x000D_
  list-style: none;_x000D_
}_x000D_
.tree-view-com .tree-view-child > li{_x000D_
  padding-bottom: 30px;_x000D_
}_x000D_
.tree-view-com .tree-view-child > li:last-of-type{_x000D_
  padding-bottom: 0px;_x000D_
}_x000D_
 _x000D_
.tree-view-com ul li a .c-icon {_x000D_
  margin-right: 10px;_x000D_
  position: relative;_x000D_
  top: 2px;_x000D_
}_x000D_
.tree-view-com ul > li > ul {_x000D_
  margin-top: 20px;_x000D_
  position: relative;_x000D_
}_x000D_
.tree-view-com > ul > li:before {_x000D_
  content: "";_x000D_
  border-left: 1px dashed #ccc;_x000D_
  position: absolute;_x000D_
  height: calc(100% - 30px - 5px);_x000D_
  z-index: 1;_x000D_
  left: 8px;_x000D_
  top: 30px;_x000D_
}_x000D_
.tree-view-com > ul > li > ul > li:before {_x000D_
  content: "";_x000D_
  border-top: 1px dashed #ccc;_x000D_
  position: absolute;_x000D_
  width: 25px;_x000D_
  left: -32px;_x000D_
  top: 12px;_x000D_
}
_x000D_
<div class="tree-view-com">_x000D_
    <ul class="tree-view-parent">_x000D_
        <li>_x000D_
            <a href=""><i class="fa fa-folder c-icon c-icon-list" aria-hidden="true"></i> folder</a>_x000D_
            <ul class="tree-view-child">_x000D_
                <li>_x000D_
                    <a href="" class="document-title">_x000D_
                        <i class="fa fa-folder c-icon" aria-hidden="true"></i>_x000D_
                        sub folder 1_x000D_
                    </a>_x000D_
                </li>_x000D_
                <li>_x000D_
                    <a href="" class="document-title">_x000D_
                        <i class="fa fa-folder c-icon" aria-hidden="true"></i>_x000D_
                        sub folder 2_x000D_
                    </a>_x000D_
                </li>_x000D_
                <li>_x000D_
                    <a href="" class="document-title">_x000D_
                        <i class="fa fa-folder c-icon" aria-hidden="true"></i>_x000D_
                        sub folder 3_x000D_
                    </a>_x000D_
                </li>_x000D_
            </ul>_x000D_
        </li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CURL and HTTPS, "Cannot resolve host"

After tried all above, still can't resolved my issue yet. But got new solution for my problem.

At server where you are going to make a request, there should be a entry of your virtual host.

sudo vim /etc/hosts

and insert

192.xxx.x.xx www.domain.com

The reason if you are making request from server to itself then, to resolve your virtual host or to identify it, server would need above stuff, otherwise server won't understand your requesting(origin) host.

How do Python functions handle the types of the parameters that you pass in?

I have implemented a wrapper if anyone would like to specify variable types.

import functools
    
def type_check(func):

    @functools.wraps(func)
    def check(*args, **kwargs):
        for i in range(len(args)):
            v = args[i]
            v_name = list(func.__annotations__.keys())[i]
            v_type = list(func.__annotations__.values())[i]
            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
            if not isinstance(v, v_type):
                raise TypeError(error_msg)

        result = func(*args, **kwargs)
        v = result
        v_name = 'return'
        v_type = func.__annotations__['return']
        error_msg = 'Variable `' + str(v_name) + '` should be type ('
        error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
        if not isinstance(v, v_type):
                raise TypeError(error_msg)
        return result

    return check

Use it as:

@type_check
def test(name : str) -> float:
    return 3.0

@type_check
def test2(name : str) -> str:
    return 3.0

>> test('asd')
>> 3.0

>> test(42)
>> TypeError: Variable `name` should be type (<class 'str'>) but instead is type (<class 'int'>)

>> test2('asd')
>> TypeError: Variable `return` should be type (<class 'str'>) but instead is type (<class 'float'>)

EDIT

The code above does not work if any of the arguments' (or return's) type is not declared. The following edit can help, on the other hand, it only works for kwargs and does not check args.

def type_check(func):

    @functools.wraps(func)
    def check(*args, **kwargs):
        for name, value in kwargs.items():
            v = value
            v_name = name
            if name not in func.__annotations__:
                continue
                
            v_type = func.__annotations__[name]

            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ') '
            if not isinstance(v, v_type):
                raise TypeError(error_msg)

        result = func(*args, **kwargs)
        if 'return' in func.__annotations__:
            v = result
            v_name = 'return'
            v_type = func.__annotations__['return']
            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
            if not isinstance(v, v_type):
                    raise TypeError(error_msg)
        return result

    return check

How to make inline plots in Jupyter Notebook larger?

Yes, play with figuresize and dpi like so (before you call your subplot):

fig=plt.figure(figsize=(12,8), dpi= 100, facecolor='w', edgecolor='k')

As @tacaswell and @Hagne pointed out, you can also change the defaults if it's not a one-off:

plt.rcParams['figure.figsize'] = [12, 8]
plt.rcParams['figure.dpi'] = 100 # 200 e.g. is really fine, but slower

Modulo operator in Python

In addition to the other answers, the fmod documentation has some interesting things to say on the subject:

math.fmod(x, y)

Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

npm ERR! network getaddrinfo ENOTFOUND

Maybe it's because the proxy do not stand for https. What I do is clear the proxy content of ~/.npmrc, or use

    npm config delete proxy

What's more, nrm is recommended for this problem.

Stop MySQL service windows

I got the same problem and here my solution:

  1. go to service.msc and find mysql service. set it as start manually.
  2. go to task manager - processes tab and find mysqld. stop it
  3. go to task manager - services tab find mysql service and stop it

How to move child element from one parent to another using jQuery

Detach is unnecessary.

The answer (as of 2013) is simple:

$('#parentNode').append($('#childNode'));

According to http://api.jquery.com/append/

You can also select an element on the page and insert it into another:

$('.container').append($('h2'));

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).

How to filter rows containing a string pattern from a Pandas dataframe

df[df['ids'].str.contains('ball', na = False)] # valid for (at least) pandas version 0.17.1

Step-by-step explanation (from inner to outer):

  • df['ids'] selects the ids column of the data frame (technically, the object df['ids'] is of type pandas.Series)
  • df['ids'].str allows us to apply vectorized string methods (e.g., lower, contains) to the Series
  • df['ids'].str.contains('ball') checks each element of the Series as to whether the element value has the string 'ball' as a substring. The result is a Series of Booleans indicating True or False about the existence of a 'ball' substring.
  • df[df['ids'].str.contains('ball')] applies the Boolean 'mask' to the dataframe and returns a view containing appropriate records.
  • na = False removes NA / NaN values from consideration; otherwise a ValueError may be returned.

how to get curl to output only http response body (json) and no other headers etc

You are specifying the -i option:

-i, --include

(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...

Simply remove that option from your command line:

response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")

jQuery changing css class to div

Yep, easily.

$("#mydiv").attr("class", "second");

How to write a stored procedure using phpmyadmin and how to use it through php?

/*what is wrong with the following?*/
DELIMITER $$

CREATE PROCEDURE GetStatusDescr(
    in  pStatus char(1), 
    out pStatusDescr  char(10))
BEGIN 
    IF (pStatus == 'Y THEN
 SET pStatusDescr = 'Active';
    ELSEIF (pStatus == 'N') THEN
        SET pStatusDescr = 'In-Active';
    ELSE
        SET pStatusDescr = 'Unknown';
    END IF;

END$$

Dynamic instantiation from string name of a class in dynamically imported module?

One can simply use the pydoc.locate function.

from pydoc import locate
my_class = locate("module.submodule.myclass")
instance = my_class()

How to change root logging level programmatically for logback

I seem to be having success doing

org.jboss.logmanager.Logger logger = org.jboss.logmanager.Logger.getLogger("");
logger.setLevel(java.util.logging.Level.ALL);

Then to get detailed logging from netty, the following has done it

org.slf4j.impl.SimpleLogger.setLevel(org.slf4j.impl.SimpleLogger.TRACE);

Inserting data to table (mysqli insert)

In mysqli_query(first parameter should be connection,your sql statement) so

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');

but best practice is

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);

Pushing from local repository to GitHub hosted remote

Subversion implicitly has the remote repository associated with it at all times. Git, on the other hand, allows many "remotes", each of which represents a single remote place you can push to or pull from.

You need to add a remote for the GitHub repository to your local repository, then use git push ${remote} or git pull ${remote} to push and pull respectively - or the GUI equivalents.

Pro Git discusses remotes here: http://git-scm.com/book/ch2-5.html

The GitHub help also discusses them in a more "task-focused" way here: http://help.github.com/remotes/

Once you have associated the two you will be able to push or pull branches.

Is there a CSS parent selector?

The pseudo element :focus-within allows a parent to be selected if a descendent has focus.

An element can be focused if it has a tabindex attribute.

Browser support for focus-within

Tabindex

Example

_x000D_
_x000D_
.click {_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.color:focus-within .change {_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
.color:focus-within p {_x000D_
  outline: 0;_x000D_
}
_x000D_
<div class="color">_x000D_
  <p class="change" tabindex="0">_x000D_
    I will change color_x000D_
  </p>_x000D_
  <p class="click" tabindex="1">_x000D_
    Click me_x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Check if string has space in between (or anywhere)

It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.

var text = "sossjj ssskkk";
var regex = new Regex(@"\s");
regex.IsMatch(text); // true

On - window.location.hash - Change?

I was using this in a react application to make the URL display different parameters depending what view the user was on.

I watched the hash parameter using

window.addEventListener('hashchange', doSomethingWithChangeFunction());

Then

doSomethingWithChangeFunction () { 
    // Get new hash value
    let urlParam = window.location.hash;
    // Do something with new hash value
};

Worked a treat, works with forward and back browser buttons and also in browser history.

Reading rows from a CSV file in Python

#  This program reads columns in a csv file
import csv
ifile = open('years.csv', "r")
reader = csv.reader(ifile)

# initialization and declaration of variables
rownum = 0
year = 0
dec = 0
jan = 0
total_years = 0`

for row in reader:
    if rownum == 0:
        header = row  #work with header row if you like
    else:
    colnum = 0
    for col in row:
        if colnum == 0:
            year = float(col)
        if colnum == 1:
            dec = float(col)
        if colnum == 2:
            jan = float(col)
        colnum += 1
    # end of if structure

# now we can process results
if rownum != 0:
    print(year, dec, jan)
    total_years = total_years + year
    print(total_years)

# time to go after the next row/bar
rownum += 1

ifile.close()

A bit late but nonetheless... You need to create and identify the csv file named "years.csv":

Year Dec Jan 1 50 60 2 25 50 3 30 30 4 40 20 5 10 10

Deleting Objects in JavaScript

delete is not used for deleting an object in java Script.

delete used for removing an object key in your case

var obj = { helloText: "Hello World!" }; 
var foo = obj;
delete obj;

object is not deleted check obj still take same values delete usage:

delete obj.helloText

and then check obj, foo, both are empty object.

Is it possible to apply CSS to half of a character?

Edit (oct 2017): background-clip or rather background-image options are now supported by every major browser: CanIUse

Yes, you can do this with only one character and only CSS.

Webkit (and Chrome) only, though:

http://jsbin.com/rexoyice/1/

_x000D_
_x000D_
h1 {_x000D_
  display: inline-block;_x000D_
  margin: 0; /* for demo snippet */_x000D_
  line-height: 1em; /* for demo snippet */_x000D_
  font-family: helvetica, arial, sans-serif;_x000D_
  font-weight: bold;_x000D_
  font-size: 300px;_x000D_
  background: linear-gradient(to right, #7db9e8 50%,#1e5799 50%);_x000D_
  -webkit-background-clip: text;_x000D_
  -webkit-text-fill-color: transparent;_x000D_
}
_x000D_
<h1>X</h1>
_x000D_
_x000D_
_x000D_

Visually, all the examples that use two characters (be it via JS, CSS pseudo elements, or just HTML) look fine, but note that that all adds content to the DOM which may cause accessibility--as well as text selection/cut/paste issues.

How do I get the parent directory in Python?

Using os.path.dirname:

>>> os.path.dirname(r'C:\Program Files')
'C:\\'
>>> os.path.dirname('C:\\')
'C:\\'
>>>

Caveat: os.path.dirname() gives different results depending on whether a trailing slash is included in the path. This may or may not be the semantics you want. Cf. @kender's answer using os.path.join(yourpath, os.pardir).

What is the C# equivalent of NaN or IsNumeric?

Yeah, IsNumeric is VB. Usually people use the TryParse() method, though it is a bit clunky. As you suggested, you can always write your own.

int i;
if (int.TryParse(string, out i))
{

}

How to query DATETIME field using only date in Microsoft SQL Server?

-- Reverse the date format
-- this false:
    select * from test where date = '28/10/2015'
-- this true:
    select * from test where date = '2015/10/28'

How to generate random positive and negative numbers in Java

This is an old question I know but um....

n=n-(n*2)

What are the differences between the urllib, urllib2, urllib3 and requests module?

I think all answers are pretty good. But fewer details about urllib3.urllib3 is a very powerful HTTP client for python. For installing both of the following commands will work,

urllib3

using pip,

pip install urllib3

or you can get the latest code from Github and install them using,

$ git clone git://github.com/urllib3/urllib3.git
$ cd urllib3
$ python setup.py install

Then you are ready to go,

Just import urllib3 using,

import urllib3

In here, Instead of creating a connection directly, You’ll need a PoolManager instance to make requests. This handles connection pooling and thread-safety for you. There is also a ProxyManager object for routing requests through an HTTP/HTTPS proxy Here you can refer to the documentation. example usage :

>>> from urllib3 import PoolManager
>>> manager = PoolManager(10)
>>> r = manager.request('GET', 'http://google.com/')
>>> r.headers['server']
'gws'
>>> r = manager.request('GET', 'http://yahoo.com/')
>>> r.headers['server']
'YTS/1.20.0'
>>> r = manager.request('POST', 'http://google.com/mail')
>>> r = manager.request('HEAD', 'http://google.com/calendar')
>>> len(manager.pools)
2
>>> conn = manager.connection_from_host('google.com')
>>> conn.num_requests
3

As mentioned in urrlib3 documentations,urllib3 brings many critical features that are missing from the Python standard libraries.

  • Thread safety.
  • Connection pooling.
  • Client-side SSL/TLS verification.
  • File uploads with multipart encoding.
  • Helpers for retrying requests and dealing with HTTP redirects.
  • Support for gzip and deflate encoding.
  • Proxy support for HTTP and SOCKS.
  • 100% test coverage.

Follow the user guide for more details.

requests

requests uses urllib3 under the hood and make it even simpler to make requests and retrieve data. For one thing, keep-alive is 100% automatic, compared to urllib3 where it's not. It also has event hooks which call a callback function when an event is triggered, like receiving a response In requests, each request type has its own function. So instead of creating a connection or a pool, you directly GET a URL.


For install requests using pip just run

pip install requests

or you can just install from source code,

$ git clone git://github.com/psf/requests.git
$ cd requests
$ python setup.py install

Then, import requests

Here you can refer the official documentation, For some advanced usage like session object, SSL verification, and Event Hooks please refer to this url.

Output in a table format in Java's System.out

Because most of solutions is bit outdated I could also suggest asciitable which already available in maven (de.vandermeer:asciitable:0.3.2) and may produce very complicated configurations.

Features (by offsite):

  • Text table with some flexibility for rules and content, alignment, format, padding, margins, and frames:
  • add text, as often as required in many different formats (string, text provider, render provider, ST, clusters),
  • removes all excessive white spaces (tabulators, extra blanks, combinations of carriage return and line feed),
  • 6 different text alignments: left, right, centered, justified, justified last line left, justified last line right,
  • flexible width, set for text and calculated in many different ways for rendering
  • padding characters for left and right padding (configurable separately)
  • padding characters for top and bottom padding (configurable separately)
  • several options for drawing grids
  • rules with different styles (as supported by the used grid theme: normal, light, strong, heavy)
  • top/bottom/left/right margins outside a frame
  • character conversion to generated text suitable for further process, e.g. for LaTeX and HTML

And usage still looks easy:

AsciiTable at = new AsciiTable();

at.addRule();
at.addRow("row 1 col 1", "row 1 col 2");
at.addRule();
at.addRow("row 2 col 1", "row 2 col 2");
at.addRule();

System.out.println(at.render()); // Finally, print the table to standard out.

is python capable of running on multiple cores?

Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

No you can't use bind variables that way. In your second example :into_bind in v_query_str is just a placeholder for value of variable v_num_of_employees. Your select into statement will turn into something like:

SELECT COUNT(*) INTO  FROM emp_...

because the value of v_num_of_employees is null at EXECUTE IMMEDIATE.

Your first example presents the correct way to bind the return value to a variable.

Edit

The original poster has edited the second code block that I'm referring in my answer to use OUT parameter mode for v_num_of_employees instead of the default IN mode. This modification makes the both examples functionally equivalent.

Python conversion from binary string to hexadecimal

Converting Binary into hex without ignoring leading zeros:

You could use the format() built-in function like this:

"{0:0>4X}".format(int("0000010010001101", 2))

How to mkdir only if a directory does not already exist?

mkdir -p sam
  • mkdir = Make Directory
  • -p = --parents
  • (no error if existing, make parent directories as needed)

Entity Framework code first unique column

From your code it becomes apparent that you use POCO. Having another key is unnecessary: you can add an index as suggested by juFo.
If you use Fluent API instead of attributing UserName property your column annotation should look like this:

this.Property(p => p.UserName)
    .HasColumnAnnotation("Index", new IndexAnnotation(new[] { 
        new IndexAttribute("Index") { IsUnique = true } 
    }
));

This will create the following SQL script:

CREATE UNIQUE NONCLUSTERED INDEX [Index] ON [dbo].[Users]
(
    [UserName] ASC
)
WITH (
    PAD_INDEX = OFF, 
    STATISTICS_NORECOMPUTE = OFF, 
    SORT_IN_TEMPDB = OFF, 
    IGNORE_DUP_KEY = OFF, 
    DROP_EXISTING = OFF, 
    ONLINE = OFF, 
    ALLOW_ROW_LOCKS = ON, 
    ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]

If you attempt to insert multiple Users having the same UserName you'll get a DbUpdateException with the following message:

Cannot insert duplicate key row in object 'dbo.Users' with unique index 'Index'. 
The duplicate key value is (...).
The statement has been terminated.

Again, column annotations are not available in Entity Framework prior to version 6.1.

Parsing JSON with Unix tools

You can use bashJson

It’s a wrapper for the Python's JSON module and can handle complex JSON data.

Let's consider this exmaple JSON data from the file test.json

{
    "name":"Test tool",
    "author":"hack4mer",
    "supported_os":{
        "osx":{
            "foo":"bar",
            "min_version" : 10.12,
            "tested_on" : [10.1,10.13]
        },
        "ubuntu":{
            "min_version":14.04,
            "tested_on" : 16.04
        }
    }
}

Following commands read data from this example JSON file

./bashjson.sh test.json name

Prints: Test Tool

./bashjson.sh test.json supported_os osx foo

Prints: bar

./bashjson.sh test.json supported_os osx tested_on

Prints: [10.1,10.13]

Failed to execute removeChild on Node

As others have mentioned, myCoolDiv is a child of markerDiv not playerContainer. If you want to remove myCoolDiv but keep markerDiv for some reason you can do the following

myCoolDiv.parentNode.removeChild(myCoolDiv);

JSFiddle

Convert char* to string C++

std::string str(buffer, buffer + length);

Or, if the string already exists:

str.assign(buffer, buffer + length);

Edit: I'm still not completely sure I understand the question. But if it's something like what JoshG is suggesting, that you want up to length characters, or until a null terminator, whichever comes first, then you can use this:

std::string str(buffer, std::find(buffer, buffer + length, '\0'));

Convert all first letter to upper case, rest lower for each word

Try this technique; It returns the desired result

CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());

And don't forget to use System.Globalization.

How to fix git error: RPC failed; curl 56 GnuTLS

I tried all the above without success. Eventually I realised I had a weak WiFi connection and therefore slow download speed. I connected my device VIA Ethernet and that solved my problem straight away.

What does '?' do in C++?

It is called the conditional operator.

You can replace it with:

int qempty(){ 
    if (f == r) return 1;
    else return 0;
}

How to get the top 10 values in postgresql?

Seems you are looking for ORDER BY in DESCending order with LIMIT clause:

SELECT
 *
FROM
  scores
ORDER BY score DESC
LIMIT 10

Of course SELECT * could seriously affect performance, so use it with caution.

Excel VBA Open a Folder

If you want to open a windows file explorer, you should call explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

Equivalent syxntax

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

Remove a specific character using awk or sed

Use sed's substitution: sed 's/"//g'

s/X/Y/ replaces X with Y.

g means all occurrences should be replaced, not just the first one.

Proper use of errors

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

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

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

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

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

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

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

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

find files by extension, *.html under a folder in nodejs

Take a look into file-regex

let findFiles = require('file-regex')
let pattern = '\.js'

findFiles(__dirname, pattern, (err, files) => {  
   console.log(files);
})

This above snippet would print all the js files in the current directory.

What is the memory consumption of an object in Java?

Mindprod points out that this is not a straightforward question to answer:

A JVM is free to store data any way it pleases internally, big or little endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes.
For example, the JVM or native compiler might decide to store a boolean[] in 64-bit long chunks like a BitSet. It does not have to tell you, so long as the program gives the same answers.

  • It might allocate some temporary Objects on the stack.
  • It may optimize some variables or method calls totally out of existence replacing them with constants.
  • It might version methods or loops, i.e. compile two versions of a method, each optimized for a certain situation, then decide up front which one to call.

Then of course the hardware and OS have multilayer caches, on chip-cache, SRAM cache, DRAM cache, ordinary RAM working set and backing store on disk. Your data may be duplicated at every cache level. All this complexity means you can only very roughly predict RAM consumption.

Measurement methods

You can use Instrumentation.getObjectSize() to obtain an estimate of the storage consumed by an object.

To visualize the actual object layout, footprint, and references, you can use the JOL (Java Object Layout) tool.

Object headers and Object references

In a modern 64-bit JDK, an object has a 12-byte header, padded to a multiple of 8 bytes, so the minimum object size is 16 bytes. For 32-bit JVMs, the overhead is 8 bytes, padded to a multiple of 4 bytes. (From Dmitry Spikhalskiy's answer, Jayen's answer, and JavaWorld.)

Typically, references are 4 bytes on 32bit platforms or on 64bit platforms up to -Xmx32G; and 8 bytes above 32Gb (-Xmx32G). (See compressed object references.)

As a result, a 64-bit JVM would typically require 30-50% more heap space. (Should I use a 32- or a 64-bit JVM?, 2012, JDK 1.7)

Boxed types, arrays, and strings

Boxed wrappers have overhead compared to primitive types (from JavaWorld):

  • Integer: The 16-byte result is a little worse than I expected because an int value can fit into just 4 extra bytes. Using an Integer costs me a 300 percent memory overhead compared to when I can store the value as a primitive type

  • Long: 16 bytes also: Clearly, actual object size on the heap is subject to low-level memory alignment done by a particular JVM implementation for a particular CPU type. It looks like a Long is 8 bytes of Object overhead, plus 8 bytes more for the actual long value. In contrast, Integer had an unused 4-byte hole, most likely because the JVM I use forces object alignment on an 8-byte word boundary.

Other containers are costly too:

  • Multidimensional arrays: it offers another surprise.
    Developers commonly employ constructs like int[dim1][dim2] in numerical and scientific computing.

    In an int[dim1][dim2] array instance, every nested int[dim2] array is an Object in its own right. Each adds the usual 16-byte array overhead. When I don't need a triangular or ragged array, that represents pure overhead. The impact grows when array dimensions greatly differ.

    For example, a int[128][2] instance takes 3,600 bytes. Compared to the 1,040 bytes an int[256] instance uses (which has the same capacity), 3,600 bytes represent a 246 percent overhead. In the extreme case of byte[256][1], the overhead factor is almost 19! Compare that to the C/C++ situation in which the same syntax does not add any storage overhead.

  • String: a String's memory growth tracks its internal char array's growth. However, the String class adds another 24 bytes of overhead.

    For a nonempty String of size 10 characters or less, the added overhead cost relative to useful payload (2 bytes for each char plus 4 bytes for the length), ranges from 100 to 400 percent.

Alignment

Consider this example object:

class X {                      // 8 bytes for reference to the class definition
   int a;                      // 4 bytes
   byte b;                     // 1 byte
   Integer c = new Integer();  // 4 bytes for a reference
}

A naïve sum would suggest that an instance of X would use 17 bytes. However, due to alignment (also called padding), the JVM allocates the memory in multiples of 8 bytes, so instead of 17 bytes it would allocate 24 bytes.

How to redirect to logon page when session State time out is completed in asp.net mvc

I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.

In short, I catch session end in _Layout 1 minute before and make redirection.

I try to explain everything step by step.

If we want to session end 30 minute after and redirect to loginPage see this steps:

  1. Change the web config like this (set 31 minute):

     <system.web>
        <sessionState timeout="31"></sessionState>
     </system.web>
    
  2. Add this JavaScript in _Layout (when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)

    <script>
        //session end 
        var sessionTimeoutWarning = @Session.Timeout- 1;
    
        var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
        setTimeout('SessionEnd()', sTimeout);
    
        function SessionEnd() {
            window.location = "/Account/LogOff";
        }
    </script>
    
  3. Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page

    public ActionResult LogOff()
    {
        Session["User"] = null; //it's my session variable
        Session.Clear();
        Session.Abandon();
        FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
        return RedirectToAction("Login", "Account");
    } 
    

I hope this is a very useful code for you.

Set focus on textbox in WPF

None of this worked for me as I was using a grid rather than a StackPanel.

I finally found this example: http://spin.atomicobject.com/2013/03/06/xaml-wpf-textbox-focus/

and modified it to this:

In the 'Resources' section:

    <Style x:Key="FocusTextBox" TargetType="Grid">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=textBoxName, Path=IsVisible}" Value="True">
                <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=textBoxName}"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

In my grid definition:

<Grid Style="{StaticResource FocusTextBox}" />

How can I use an http proxy with node.js http.Client?

One thing that took me a while to figure out, use 'http' to access the proxy, even if you're trying to proxy through to a https server. This works for me using Charles (osx protocol analyser):

var http = require('http');

http.get ({
    host: '127.0.0.1',
    port: 8888,
    path: 'https://www.google.com/accounts/OAuthGetRequestToken'
}, function (response) {
    console.log (response);
});

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

When your browser redirects the user to Google's oAuth page, are you passing as a parameter the redirect URI you want Google's server to return to with the token response? Setting a redirect URI in the console is not a way of telling Google where to go when a login attempt comes in, but rather it's a way of telling Google what the allowed redirect URIs are (so if someone else writes a web app with your client ID but a different redirect URI it will be disallowed); your web app should, when someone clicks the "login" button, send the browser to:

https://accounts.google.com/o/oauth2/auth?client_id=XXXXX&redirect_uri=http://localhost:8080/WEBAPP/youtube-callback.html&response_type=code&scope=https://www.googleapis.com/auth/youtube.upload

(the callback URI passed as a parameter must be url-encoded, btw).

When Google's server gets authorization from the user, then, it'll redirect the browser to whatever you sent in as the redirect_uri. It'll include in that request the token as a parameter, so your callback page can then validate the token, get an access token, and move on to the other parts of your app.

If you visit:

http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow

You can see better samples of the java client there, demonstrating that you have to override the getRedirectUri method to specify your callback path so the default isn't used.

The redirect URIs are in the client_secrets.json file for multiple reasons ... one big one is so that the oAuth flow can verify that the redirect your app specifies matches what your app allows.

If you visit https://developers.google.com/api-client-library/java/apis/youtube/v3 You can generate a sample application for yourself that's based directly off your app in the console, in which (again) the getRedirectUri method is overwritten to use your specific callbacks.

Can we create an instance of an interface in Java?

Short answer...yes. You can use an anonymous class when you initialize a variable. Take a look at this question: Anonymous vs named inner classes? - best practices?

How to check if a column exists in Pandas

To check if one or more columns all exist, you can use set.issubset, as in:

if set(['A','C']).issubset(df.columns):
   df['sum'] = df['A'] + df['C']                

As @brianpck points out in a comment, set([]) can alternatively be constructed with curly braces,

if {'A', 'C'}.issubset(df.columns):

See this question for a discussion of the curly-braces syntax.

Or, you can use a list comprehension, as in:

if all([item in df.columns for item in ['A','C']]):

What does the "+" (plus sign) CSS selector mean?

It's the Adjacent sibling selector.

From Splash of Style blog.

To define a CSS adjacent selector, the plus sign is used.

h1+p {color:blue;}

The above CSS code will format the first paragraph after (not inside) any h1 headings as blue.

h1>p selects any p element that is a direct (first generation) child (inside) of an h1 element.

  • h1>p matches <h1> <p></p> </h1> (<p> inside <h1>)

h1+p will select the first p element that is a sibling (at the same level of the dom) as an h1 element.

  • h1+p matches <h1></h1> <p><p/> (<p> next to/after <h1>)

Installing tkinter on ubuntu 14.04

Try writing the following in the terminal:

sudo apt-get install python-tk

Don't forget to actually import Tkinter module at the beginning of your program:

import Tkinter

Displaying output of a remote command with Ansible

If you pass the -v flag to the ansible-playbook command, then ansible will show the output on your terminal.

For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.

In Jinja2, how do you test if a variable is undefined?

In the Environment setup, we had undefined = StrictUndefined, which prevented undefined values from being set to anything. This fixed it:

from jinja2 import Undefined
JINJA2_ENVIRONMENT_OPTIONS = { 'undefined' : Undefined }

Android Material Design Button Styles

Here is how I got what I wanted.

First, made a button (in styles.xml):

<style name="Button">
    <item name="android:textColor">@color/white</item>
    <item name="android:padding">0dp</item>
    <item name="android:minWidth">88dp</item>
    <item name="android:minHeight">36dp</item>
    <item name="android:layout_margin">3dp</item>
    <item name="android:elevation">1dp</item>
    <item name="android:translationZ">1dp</item>
    <item name="android:background">@drawable/primary_round</item>
</style>

The ripple and background for the button, as a drawable primary_round.xml:

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/primary_600">
  <item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <corners android:radius="1dp" />
        <solid android:color="@color/primary" />
    </shape>
  </item>
</ripple>

This added the ripple effect I was looking for.

Trying to use Spring Boot REST to Read JSON String from POST

To add on to Andrea's solution, if you are passing an array of JSONs for instance

[
    {"name":"value"},
    {"name":"value2"}
]

Then you will need to set up the Spring Boot Controller like so:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object>[] payload) 
    throws Exception {

    System.out.println(payload);

}

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

Could not resolve placeholder in string value

With Spring Boot :

In the pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <addResources>true</addResources>
            </configuration>
        </plugin>
    </plugins>
</build>

Example in class Java

@Configuration
@Slf4j
public class MyAppConfig {
    @Value("${foo}")
    private String foo;
    @Value("${bar}")
    private String bar;
    @Bean("foo")
    public String foo() {
        log.info("foo={}", foo);
        return foo;
    }
    @Bean("bar")
    public String bar() {
        log.info("bar={}", bar);
        return bar;
    }
    [ ... ]

In the properties files :

src/main/resources/application.properties

foo=all-env-foo

src/main/resources/application-rec.properties

bar=rec-bar

src/main/resources/application-prod.properties

bar=prod-bar

In the VM arguments of Application.java

-Dspring.profiles.active=[rec|prod]

Don't forget to run mvn command after modifying the properties !

mvn clean package -Dmaven.test.skip=true

In the log file for -Dspring.profiles.active=rec :

The following profiles are active: rec
foo=all-env-foo
bar=rec-bar

In the log file for -Dspring.profiles.active=prod :

The following profiles are active: prod
foo=all-env-foo
bar=prod-bar

In the log file for -Dspring.profiles.active=local :

Could not resolve placeholder 'bar' in value "${bar}"

Oups, I forget to create application-local.properties.

How do I ignore ampersands in a SQL script running from SQL Plus?

I resolved with the code below:

set escape on

and put a \ beside & in the left 'value_\&_intert'

Att

How to create custom view programmatically in swift having controls text field, button etc

The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.

But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:

customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)

Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.

Docker how to change repository name or rename image?

docker run -it --name NEW_NAME Existing_name

To change the existing image name.

android View not attached to window manager

when you declare activity in the manifest you need android:configChanges="orientation"

example:

<activity android:theme="@android:style/Theme.Light.NoTitleBar" android:configChanges="orientation"  android:label="traducción" android:name=".PantallaTraductorAppActivity"></activity>

Download & Install Xcode version without Premium Developer Account

Yes,
You can download Xcode with/without Paid (Premium) Apple Developer Account from below links.

Xcode 11

Xcode 10


For non-premium account/apple id: (Download Xcode 10 without Paid (Premium) Apple Developer Account from below link)

Apple Download Portal

Look at here: How to install & set command line tool


See here for older versions of Xcode (Which may need to authenticate your apple account):

Make view 80% width of parent in React Native

This is the way I got the solution. Simple and Sweet. Independent of Screen density:

export default class AwesomeProject extends Component {
    constructor(props){
        super(props);
        this.state = {text: ""}
    }
  render() {
    return (
       <View
          style={{
            flex: 1,
            backgroundColor: "#ececec",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <View style={{ padding: 10, flexDirection: "row" }}>
            <TextInput
              style={{ flex: 0.8, height: 40, borderWidth: 1 }}
              onChangeText={text => this.setState({ text })}
              placeholder="Text 1"
              value={this.state.text}
            />
          </View>
          <View style={{ padding: 10, flexDirection: "row" }}>
            <TextInput
              style={{ flex: 0.8, height: 40, borderWidth: 1 }}
              onChangeText={text => this.setState({ text })}
              placeholder="Text 2"
              value={this.state.text}
            />
          </View>
          <View style={{ padding: 10, flexDirection: "row" }}>
            <Button
              onPress={onButtonPress}
              title="Press Me"
              accessibilityLabel="See an Information"
            />
          </View>
        </View>
    );
  }
}

CSS Div Background Image Fixed Height 100% Width

See my answer to a similar question here.

It sounds like you want a background-image to keep it's own aspect ratio while expanding to 100% width and getting cropped off on the top and bottom. If that's the case, do something like this:

.chapter {
    position: relative;
    height: 1200px;
    z-index: 1;
}

#chapter1 {
    background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
}

jsfiddle: http://jsfiddle.net/ndKWN/3/

The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.

If you want the height to keep the image's aspect ratio, you'll have to do something like what I wrote in an edit to the answer I linked to above. Set the container's height to 0 and set the padding-bottom to the percentage of the width:

.chapter {
    position: relative;
    height: 0;
    padding-bottom: 75%;
    z-index: 1;
}

#chapter1 {
    background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
}

jsfiddle: http://jsfiddle.net/ndKWN/4/

You could also put the padding-bottom percentage into each #chapter style if each image has a different aspect ratio. In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value.

Markdown `native` text alignment

I known this isn't markdown, but <p align="center"> worked for me, so if anyone figures out the markdown syntax instead I'll be happy to use that. Until then I'll use the HTML tag.

Counting the Number of keywords in a dictionary in python

If the question is about counting the number of keywords then would recommend something like

def countoccurrences(store, value):
    try:
        store[value] = store[value] + 1
    except KeyError as e:
        store[value] = 1
    return

in the main function have something that loops through the data and pass the values to countoccurrences function

if __name__ == "__main__":
    store = {}
    list = ('a', 'a', 'b', 'c', 'c')
    for data in list:
        countoccurrences(store, data)
    for k, v in store.iteritems():
        print "Key " + k + " has occurred "  + str(v) + " times"

The code outputs

Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times

Combine two columns of text in pandas dataframe

Although the @silvado answer is good if you change df.map(str) to df.astype(str) it will be faster:

import pandas as pd
df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})

In [131]: %timeit df["Year"].map(str)
10000 loops, best of 3: 132 us per loop

In [132]: %timeit df["Year"].astype(str)
10000 loops, best of 3: 82.2 us per loop

Draw Circle using css alone

yes it is possible you can use border-radius CSS property. For more info have a look at http://zeeshanmkhan.com/post/2/css-rounded-corner-gradient-drop-shadow-and-opacity

How to detect if JavaScript is disabled?

Detect it in what? JavaScript? That would be impossible. If you just want it for logging purposes, you could use some sort of tracking scheme, where each page has JavaScript that will make a request for a special resource (probably a very small gif or similar). That way you can just take the difference between unique page requests and requests for your tracking file.

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

Converting pixels to dp

This workds for me (C#):

int pixels = (int)((dp) * Resources.System.DisplayMetrics.Density + 0.5f);

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Return values from the row above to the current row

I followed BEN and Thanks and Lot for the Answer,So I used his idea to get my solution, I am posting the same hence if some one else has similar requirement, then you also can use my solution as well, My requirement was something like I want to get the sum of entire data from the first row to the last row, and I was generating the spreadsheet programmatically so don't and can't hard code the row names in sum as the data is always dynamic and number of rows are never constant. My formula was something like as follows.

=SUM(B1:INDIRECT("B"&ROW()-4))

Executing command line programs from within python

I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.