Programs & Examples On #Accordion

An accordion is a type of menu that allows for additional content to be shown below the heading upon mouse action. Only one heading's content can be open at a time. When the next heading is selected, the previous heading's content will close.

jQuery UI Accordion Expand/Collapse All

As discussed in the jQuery UI forums, you should not use accordions for this.

If you want something that looks and acts like an accordion, that is fine. Use their classes to style them, and implement whatever functionality you need. Then adding a button to open or close them all is pretty straightforward. Example

HTML

By using the jquery-ui classes, we keep our accordions looking just like the "real" accordions.

<div id="accordion" class="ui-accordion ui-widget ui-helper-reset">
    <h3 class="accordion-header ui-accordion-header ui-helper-reset ui-state-default ui-accordion-icons ui-corner-all">
        <span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-e"></span>
        Section 1
    </h3>
    <div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom">
        Content 1
    </div>
</div>?

Roll your own accordions

Mostly we just want accordion headers to toggle the state of the following sibling, which is it's content area. We have also added two custom events "show" and "hide" which we will hook into later.

var headers = $('#accordion .accordion-header');
var contentAreas = $('#accordion .ui-accordion-content ').hide();
var expandLink = $('.accordion-expand-all');

headers.click(function() {
    var panel = $(this).next();
    var isOpen = panel.is(':visible');

    // open or close as necessary
    panel[isOpen? 'slideUp': 'slideDown']()
        // trigger the correct custom event
        .trigger(isOpen? 'hide': 'show');

    // stop the link from causing a pagescroll
    return false;
});

Expand/Collapse All

We use a boolean isAllOpen flag to mark when the button has been changed, this could just as easily have been a class, or a state variable on a larger plugin framework.

expandLink.click(function(){
    var isAllOpen = $(this).data('isAllOpen');

    contentAreas[isAllOpen? 'hide': 'show']()
        .trigger(isAllOpen? 'hide': 'show');
});

Swap the button when "all open"

Thanks to our custom "show" and "hide" events, we have something to listen for when panels are changing. The only special case is "are they all open", if yes the button should be a "Collapse all", if not it should be "Expand all".

contentAreas.on({
    // whenever we open a panel, check to see if they're all open
    // if all open, swap the button to collapser
    show: function(){
        var isAllOpen = !contentAreas.is(':hidden');   
        if(isAllOpen){
            expandLink.text('Collapse All')
                .data('isAllOpen', true);
        }
    },
    // whenever we close a panel, check to see if they're all open
    // if not all open, swap the button to expander
    hide: function(){
        var isAllOpen = !contentAreas.is(':hidden');
        if(!isAllOpen){
            expandLink.text('Expand all')
            .data('isAllOpen', false);
        } 
    }
});?

Edit for comment: Maintaining "1 panel open only" unless you hit the "Expand all" button is actually much easier. Example

Bootstrap Accordion button toggle "data-parent" not working

Here is a (hopefully) universal patch I developed to fix this problem for BootStrap V3. No special requirements other than plugging in the script.

$(':not(.panel) > [data-toggle="collapse"][data-parent]').click(function() {
    var parent = $(this).data('parent');
    var items = $('[data-toggle="collapse"][data-parent="' + parent + '"]').not(this);
    items.each(function() {
        var target = $(this).data('target') || '#' + $(this).prop('href').split('#')[1];
        $(target).filter('.in').collapse('hide');
    });
});

EDIT: Below is a simplified answer which still meets my needs, and I'm now using a delegated click handler:

$(document.body).on('click', ':not(.panel) > [data-toggle="collapse"][data-parent]', function() {
    var parent = $(this).data('parent');
    var target = $(this).data('target') || $(this).prop('hash');
    $(parent).find('.collapse.in').not(target).collapse('hide');
});

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

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

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

How to use in jQuery :not and hasClass() to get a specific element without a class

Use the not function instead:

var lastOpenSite = $(this).siblings().not('.closedTab');

hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.

Save file to specific folder with curl command

I don't think you can give a path to curl, but you can CD to the location, download and CD back.

cd target/path && { curl -O URL ; cd -; }

Or using subshell.

(cd target/path && curl -O URL)

Both ways will only download if path exists. -O keeps remote file name. After download it will return to original location.

If you need to set filename explicitly, you can use small -o option:

curl -o target/path/filename URL

How to enter special characters like "&" in oracle database?

you can simply escape & by following a dot. try this:

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 &. Oracle_14');

How to get substring from string in c#?

string newString = str.Substring(0,10)

will give you the first 10 characters (from position 0 to position 9).

See here.

How to add an extra source directory for maven to compile and include in the build jar?

NOTE: This solution will just move the java source files to the target/classes directory and will not compile the sources.

Update the pom.xml as -

<project>   
 ....
    <build>
      <resources>
        <resource>
          <directory>src/main/config</directory>
        </resource>
      </resources>
     ...
    </build>
...
</project>

How to enable zoom controls and pinch zoom in a WebView?

Strange. Inside OnCreate method, I'm using

webView.getSettings().setBuiltInZoomControls(true);

And it's working fine here. Anything particular in your webview ?

replace \n and \r\n with <br /> in java

Since my account is new I can't up-vote Nino van Hooff's answer. If your strings are coming from a Windows based source such as an aspx based server, this solution does work:

rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "<br />");

Seems to be a weird character set issue as the double back-slashes are being interpreted as single slash escape characters. Hence the need for the quadruple slashes above.

Again, under most circumstances "(\\r\\n|\\n)" should work, but if your strings are coming from a Windows based source try the above.

Just an FYI tried everything to correct the issue I was having replacing those line endings. Thought at first was failed conversion from Windows-1252 to UTF-8. But that didn't working either. This solution is what finally did the trick. :)

How to remove \n from a list element?

from this link:

you can use rstrip() method. Example

mystring = "hello\n"    
print(mystring.rstrip('\n'))

How do I rotate text in css?

I guess this is what you are looking for?

Added an example:

The html:

<div class="example-date">
  <span class="day">31</span> 
  <span class="month">July</span> 
  <span class="year">2009</span>
</div>

The css:

.year
{
    display:block;
    -webkit-transform: rotate(-90deg); 
    -moz-transform: rotate(-90deg); 
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); //For IE support
}

Alle examples are from the mentioned site.

How do I get a python program to do nothing?

The pass command is what you are looking for. Use pass for any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.

For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:

if num2 != num5:
    make_some_changes()

This will be the same as this:

if num2 == num5:
    pass
else:
    make_some_changes()

That way you won't even have to use pass and you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.


You can read more about the pass statement in the documentation:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

if condition:
    pass
try:
    make_some_changes()
except Exception:
    pass # do nothing
class Foo():
    pass # an empty class definition
def bar():
    pass # an empty function definition

Ruby optional parameters

Time has moved on and since version 2 Ruby supports named parameters:

def ldap_get ( base_dn, filter, scope: "some_scope", attrs: nil )
  p attrs
end

ldap_get("first_arg", "second_arg", attrs: "attr1, attr2") # => "attr1, attr2"

XML parsing of a variable string in JavaScript

I've always used the approach below which works in IE and Firefox.

Example XML:

<fruits>
  <fruit name="Apple" colour="Green" />
  <fruit name="Banana" colour="Yellow" />
</fruits>

JavaScript:

function getFruits(xml) {
  var fruits = xml.getElementsByTagName("fruits")[0];
  if (fruits) {
    var fruitsNodes = fruits.childNodes;
    if (fruitsNodes) {
      for (var i = 0; i < fruitsNodes.length; i++) {
        var name = fruitsNodes[i].getAttribute("name");
        var colour = fruitsNodes[i].getAttribute("colour");
        alert("Fruit " + name + " is coloured " + colour);
      }
    }
  }
}

What is memoization and how can I use it in Python?

Solution that works with both positional and keyword arguments independently of order in which keyword args were passed (using inspect.getargspec):

import inspect
import functools

def memoize(fn):
    cache = fn.cache = {}
    @functools.wraps(fn)
    def memoizer(*args, **kwargs):
        kwargs.update(dict(zip(inspect.getargspec(fn).args, args)))
        key = tuple(kwargs.get(k, None) for k in inspect.getargspec(fn).args)
        if key not in cache:
            cache[key] = fn(**kwargs)
        return cache[key]
    return memoizer

Similar question: Identifying equivalent varargs function calls for memoization in Python

Getting the text from a drop-down box

Here is an easy and short method

document.getElementById('elementID').selectedOptions[0].innerHTML

Why do we need C Unions?

I used union when I was coding for embedded devices. I have C int that is 16 bit long. And I need to retrieve the higher 8 bits and the lower 8 bits when I need to read from/store to EEPROM. So I used this way:

union data {
    int data;
    struct {
        unsigned char higher;
        unsigned char lower;
    } parts;
};

It doesn't require shifting so the code is easier to read.

On the other hand, I saw some old C++ stl code that used union for stl allocator. If you are interested, you can read the sgi stl source code. Here is a piece of it:

union _Obj {
    union _Obj* _M_free_list_link;
    char _M_client_data[1];    /* The client sees this.        */
};

Recommendations of Python REST (web services) framework?

I really like CherryPy. Here's an example of a restful web service:

import cherrypy
from cherrypy import expose

class Converter:
    @expose
    def index(self):
        return "Hello World!"

    @expose
    def fahr_to_celc(self, degrees):
        temp = (float(degrees) - 32) * 5 / 9
        return "%.01f" % temp

    @expose
    def celc_to_fahr(self, degrees):
        temp = float(degrees) * 9 / 5 + 32
        return "%.01f" % temp

cherrypy.quickstart(Converter())

This emphasizes what I really like about CherryPy; this is a completely working example that's very understandable even to someone who doesn't know the framework. If you run this code, then you can immediately see the results in your web browser; e.g. visiting http://localhost:8080/celc_to_fahr?degrees=50 will display 122.0 in your web browser.

How to know if a DateTime is between a DateRange in C#

Usually I create Fowler's Range implementation for such things.

public interface IRange<T>
{
    T Start { get; }
    T End { get; }
    bool Includes(T value);
    bool Includes(IRange<T> range);
}

public class DateRange : IRange<DateTime>         
{
    public DateRange(DateTime start, DateTime end)
    {
        Start = start;
        End = end;
    }

    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public bool Includes(DateTime value)
    {
        return (Start <= value) && (value <= End);
    }

    public bool Includes(IRange<DateTime> range)
    {
        return (Start <= range.Start) && (range.End <= End);
    }
}

Usage is pretty simple:

DateRange range = new DateRange(startDate, endDate);
range.Includes(date)

How can I get table names from an MS Access Database?

Best not to mess with msysObjects (IMHO).

CurrentDB.TableDefs
CurrentDB.QueryDefs
CurrentProject.AllForms
CurrentProject.AllReports
CurrentProject.AllMacros

How to correctly link php-fpm and Nginx Docker containers?

I think we also need to give the fpm container the volume, dont we? So =>

fpm:
    image: php:fpm
    volumes:
        - ./:/var/www/test/

If i dont do this, i run into this exception when firing a request, as fpm cannot find requested file:

[error] 6#6: *4 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.17.42.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.17.0.81:9000", host: "localhost"

Searching for Text within Oracle Stored Procedures

If you use UPPER(text), the like '%lah%' will always return zero results. Use '%LAH%'.

How to remove indentation from an unordered list item?

I have the same problem with a footer I'm trying to divide up. I found that this worked for me by trying few of above suggestions combined:

footer div ul {
    list-style-position: inside;
    padding-left: 0;
}

This seems to keep it to the left under my h1 and the bullet points inside the div rather than outside to the left.

Folder is locked and I can't unlock it

I research a lot on this issue but no solution fix my problem until I try this:

My repo folder is shared with a Windows xp virtual machine, so I execute the clean up from the VM and then execute SVN UPDATE from the host.

It worked for me.

Greetings from Costa Rica.

What is the use of ByteBuffer in Java?

This is a good description of its uses and shortcomings. You essentially use it whenever you need to do fast low-level I/O. If you were going to implement a TCP/IP protocol or if you were writing a database (DBMS) this class would come in handy.

How to get the Power of some Integer in Swift language?

Or just :

var a:Int = 3
var b:Int = 3
println(pow(Double(a),Double(b)))

How do I download code using SVN/Tortoise from Google Code?

After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".

Detect Close windows event by jQuery

You can use:

$(window).unload(function() {
    //do something
}

Unload() is deprecated in jQuery version 1.8, so if you use jQuery > 1.8 you can use even beforeunload instead.

The beforeunload event fires whenever the user leaves your page for any reason.

$(window).on("beforeunload", function() { 
    return confirm("Do you really want to close?"); 
})

Source Browser window close event

Get value of a specific object property in C# without knowing the class behind

Reflection can help you.

var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);

How do I split a string into an array of characters?

Old question but I should warn:

Do NOT use .split('')

You'll get weird results with non-BMP (non-Basic-Multilingual-Plane) character sets.

Reason is that methods like .split() and .charCodeAt() only respect the characters with a code point below 65536; bec. higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters.

''.length     // —> 6
''.split('')  // —> ["?", "?", "?", "?", "?", "?"]

''.length      // —> 2
''.split('')   // —> ["?", "?"]

Use ES2015 (ES6) features where possible:

Using the spread operator:

let arr = [...str];

Or Array.from

let arr = Array.from(str);

Or split with the new u RegExp flag:

let arr = str.split(/(?!$)/u);

Examples:

[...'']        // —> ["", "", ""]
[...'']     // —> ["", "", ""]

For ES5, options are limited:

I came up with this function that internally uses MDN example to get the correct code point of each character.

function stringToArray() {
  var i = 0,
    arr = [],
    codePoint;
  while (!isNaN(codePoint = knownCharCodeAt(str, i))) {
    arr.push(String.fromCodePoint(codePoint));
    i++;
  }
  return arr;
}

This requires knownCharCodeAt() function and for some browsers; a String.fromCodePoint() polyfill.

if (!String.fromCodePoint) {
// ES6 Unicode Shims 0.1 , © 2012 Steven Levithan , MIT License
    String.fromCodePoint = function fromCodePoint () {
        var chars = [], point, offset, units, i;
        for (i = 0; i < arguments.length; ++i) {
            point = arguments[i];
            offset = point - 0x10000;
            units = point > 0xFFFF ? [0xD800 + (offset >> 10), 0xDC00 + (offset & 0x3FF)] : [point];
            chars.push(String.fromCharCode.apply(null, units));
        }
        return chars.join("");
    }
}

Examples:

stringToArray('')     // —> ["", "", ""]
stringToArray('')  // —> ["", "", ""]

Note: str[index] (ES5) and str.charAt(index) will also return weird results with non-BMP charsets. e.g. ''.charAt(0) returns "?".

UPDATE: Read this nice article about JS and unicode.

How to break out of while loop in Python?

A couple of changes mean that only an R or r will roll. Any other character will quit

import random

while True:
    print('Your score so far is {}.'.format(myScore))
    print("Would you like to roll or quit?")
    ans = input("Roll...")
    if ans.lower() == 'r':
        R = np.random.randint(1, 8)
        print("You rolled a {}.".format(R))
        myScore = R + myScore
    else:
        print("Now I'll see if I can break your score...")
        break

How can I check if a value is of type Integer?

Try this snippet of code

private static boolean isStringInt(String s){
    Scanner in=new Scanner(s);
    return in.hasNextInt();
}

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

DAYS(start_date,end_date):

For example:

DAYS(A1,TODAY())

C# static class why use?

If a class is declared as static then the variables and methods need to be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

->The main features of a static class are:

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.

Example

static class CollegeRegistration
{
  //All static member variables
   static int nCollegeId; //College Id will be same for all the students studying
   static string sCollegeName; //Name will be same
   static string sColegeAddress; //Address of the college will also same

    //Member functions
   public static int GetCollegeId()
   {
     nCollegeId = 100;
     return (nCollegeID);
   }
    //similarly implementation of others also.
} //class end


public class student
{
    int nRollNo;
    string sName;

    public GetRollNo()
    {
       nRollNo += 1;
       return (nRollNo);
    }
    //similarly ....
    public static void Main()
   {
     //Not required.
     //CollegeRegistration objCollReg= new CollegeRegistration();

     //<ClassName>.<MethodName>
     int cid= CollegeRegistration.GetCollegeId();
    string sname= CollegeRegistration.GetCollegeName();


   } //Main end
}

Shall we always use [unowned self] inside closure in Swift

According to Apple-doc

  • Weak references are always of an optional type, and automatically become nil when the instance they reference is deallocated.

  • If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference

Example -

    // if my response can nil use  [weak self]
      resource.request().onComplete { [weak self] response in
      guard let strongSelf = self else {
        return
      }
      let model = strongSelf.updateModel(response)
      strongSelf.updateUI(model)
     }

    // Only use [unowned self] unowned if guarantees that response never nil  
      resource.request().onComplete { [unowned self] response in
      let model = self.updateModel(response)
      self.updateUI(model)
     }

How to set lifetime of session

Sessions can be configured in your php.ini file or in your .htaccess file. Have a look at the PHP session documentation.

What you basically want to do is look for the line session.cookie_lifetime in php.ini and make it's value is 0 so that the session cookie is valid until the browser is closed. If you can't edit that file, you could add php_value session.cookie_lifetime 0 to your .htaccess file.

Does delete on a pointer to a subclass call the base class destructor?

You have something like

class B
{
   A * a;
}
B * b = new B;
b->a = new A;

If you then call delete b;, nothing happens to a, and you have a memory leak. Trying to remember to delete b->a; is not a good solution, but there are a couple of others.

B::~B() {delete a;}

This is a destructor for B that will delete a. (If a is 0, that delete does nothing. If a is not 0 but doesn't point to memory from new, you get heap corruption.)

auto_ptr<A> a;
...
b->a.reset(new A);

This way you don't have a as a pointer, but rather an auto_ptr<> (shared_ptr<> will do as well, or other smart pointers), and it is automatically deleted when b is.

Either of these ways works well, and I've used both.

How to get file path in iPhone app

You need to add your tiles into your resource bundle. I mean add all those files to your project make sure to copy all files to project directory option checked.

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

What does file:///android_asset/www/index.html mean?

file:/// is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://.

It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www has a file called index.html located in the assets folder in the root of the project".

That is how assets are loaded at runtime, for example, a WebView widget would know exactly where to load the embedded resource file by specifying the file:/// URI.

Consider the code example:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/www/index.html");

A very easy mistake to make here is this, some would infer it to as file:///android_assets, notice the plural of assets in the URI and wonder why the embedded resource is not working!

How to outline text in HTML / CSS

from: Outline effect to text

.strokeme
{
    color: white;
    text-shadow:
    -1px -1px 0 #000,
    1px -1px 0 #000,
    -1px 1px 0 #000,
    1px 1px 0 #000;  
}

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

MySQL: NOT LIKE

categories_posts and categories_news start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique starts with 'categories' instead of check if it contains the given substring. Translating all that into a query:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'

Java equivalent to #region in C#

I were coming from C# to java and had the same problem and the best and exact alternative for region is something like below (working in Android Studio, dont know about intelliJ):

 //region [Description]
 int a;
 int b;
 int c;
//endregion

the shortcut is like below:

1- select the code

2- press ctrl + alt + t

3- press c and write your description

How to parse JSON in Kotlin?

i am using my custom implementation in kotlin:

/**
 * Created by Anton Kogan on 10/9/2020
 */
object JsonParser {

    val TAG = "JsonParser"
    /**
 * parse json object
 * @param objJson
 * @param include - all  keys, that you want to display
 * @return  Map<String, String>
 * @throws JSONException
 */
    @Throws(JSONException::class)
    fun parseJson(objJson: Any?, map :HashMap<String, String>, include : Array<String>?): Map<String, String> {
        // If obj is a json array
        if (objJson is JSONArray) {
            for (i in 0 until objJson.length()) {
                parseJson(objJson[i], map, include)
            }
        } else if (objJson is JSONObject) {
            val it: Iterator<*> = objJson.keys()
            while (it.hasNext()) {
                val key = it.next().toString()
                // If you get an array
                when (val jobject = objJson[key]) {
                    is JSONArray -> {
                        Log.e(TAG, " JSONArray: $jobject")
                        parseJson(
                            jobject, map, include
                        )
                    }
                    is JSONObject -> {
                        Log.e(TAG, " JSONObject: $jobject")
                        parseJson(
                            jobject, map, include
                        )
                    }
                    else -> {
//
                        if(include == null || include.contains(key)) // here is check for include param
                        {
                            map[key] = jobject.toString()
                            Log.e(TAG, " adding to map: $key $jobject")
                        }
                    }
                }
            }
        }
        return map
    }

    /**
     * parse json object
     * @param objJson
     * @param include - all  keys, that you want to display
     * @return  Map<String, String>
     * @throws JSONException
     */
    @Throws(JSONException::class)
    fun parseJson(objJson: Any?, map :HashMap<String, String>): Map<String, String> {
        return parseJson(objJson, map, null)
    }
}

You can use it like:

    val include= arrayOf(
        "atHome",//JSONArray
        "cat",
        "dog",
        "persons",//JSONArray
        "man",
        "woman"
    )
    JsonParser.parseJson(jsonObject, map, include)
    val linearContent: LinearLayout = taskInfoFragmentBinding.infoContainer

here is some useful links:

json parsing :

plugin: https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-

create POJOs from json: https://codebeautify.org/jsonviewer

Retrofit: https://square.github.io/retrofit/

Gson: https://github.com/google/gson

How to delete stuff printed to console by System.out.println()?

To clear the Output screen, you can simulate a real person pressing CTRL + L (which clears the output). You can achieve this by using the Robot() class, here is how you can do this:

try {
        Robot robbie = new Robot();
        robbie.keyPress(17); // Holds CTRL key.
        robbie.keyPress(76); // Holds L key.
        robbie.keyRelease(17); // Releases CTRL key.
        robbie.keyRelease(76); // Releases L key.
    } catch (AWTException ex) {
        Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex);
}

IntelliJ: Error:java: error: release version 5 not supported

If you are using spring boot as a parent, you should set the java.version property, because this will automatically set the correct versions.

<properties>
   <java.version>11</java.version>
</properties>

The property defined in your own project overrides whatever is set in the parent pom. This overrides all needed properties to compile to the correct version.

Some information can be found here: https://www.baeldung.com/maven-java-version

Is there an "if -then - else " statement in XPath?

How about using fn:replace(string,pattern,replace) instead?

XPATH is very often used in XSLTs and if you are in that situation and does not have XPATH 2.0 you could use:

  <xsl:choose>
    <xsl:when test="condition1">
      condition1-statements
    </xsl:when>
    <xsl:when test="condition2">
      condition2-statements
    </xsl:when>
    <xsl:otherwise>
      otherwise-statements
    </xsl:otherwise>
  </xsl:choose>

pull access denied repository does not exist or may require docker login

I had this because I inadvertantly remove the AS tag from my first image:

ex:

FROM mcr.microsoft.com/windows/servercore:1607-KB4546850-amd64
...
.. etc ...
...
FROM mcr.microsoft.com/windows/servercore:1607-KB4546850-amd64
COPY --from=installer ["/dotnet", "/Program Files/dotnet"]
... etc ...

should have been:

FROM mcr.microsoft.com/windows/servercore:1607-KB4546850-amd64 AS installer
...
.. etc ...
...
FROM mcr.microsoft.com/windows/servercore:1607-KB4546850-amd64
COPY --from=installer ["/dotnet", "/Program Files/dotnet"]
... etc ...

Trim Whitespaces (New Line and Tab space) in a String in Oracle

Below code can be used to Remove New Line and Table Space in text column

Select replace(replace(TEXT,char(10),''),char(13),'')

Get time difference between two dates in seconds

Below code will give the time difference in second.

var date1 = new Date(); // current date
var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second

alert(timeDiffInSecond );

Combating AngularJS executing controller twice

If you know your controller is unintentionally executing more than once, try a search through your files for the name of the offending controller, ex: search: MyController through all files. Likely it got copy-pasted in some other html/js file and you forgot to change it when you got to developing or using those partials/controllers. Source: I made this mistake

How do I remove carriage returns with Ruby?

What do you get when you do puts lines? That will give you a clue.

By default File.open opens the file in text mode, so your \r\n characters will be automatically converted to \n. Maybe that's the reason lines are always equal to lines2. To prevent Ruby from parsing the line ends use the rb mode:

C:\> copy con lala.txt
a
file
with
many
lines
^Z

C:\> irb
irb(main):001:0> text = File.open('lala.txt').read
=> "a\nfile\nwith\nmany\nlines\n"
irb(main):002:0> bin = File.open('lala.txt', 'rb').read
=> "a\r\nfile\r\nwith\r\nmany\r\nlines\r\n"
irb(main):003:0>

But from your question and code I see you simply need to open the file with the default modifier. You don't need any conversion and may use the shorter File.read.

Case-Insensitive List Search

Instead of String.IndexOf, use String.Equals to ensure you don't have partial matches. Also don't use FindAll as that goes through every element, use FindIndex (it stops on the first one it hits).

if(testList.FindIndex(x => x.Equals(keyword,  
    StringComparison.OrdinalIgnoreCase) ) != -1) 
    Console.WriteLine("Found in list"); 

Alternately use some LINQ methods (which also stops on the first one it hits)

if( testList.Any( s => s.Equals(keyword, StringComparison.OrdinalIgnoreCase) ) )
    Console.WriteLine("found in list");

Any good, visual HTML5 Editor or IDE?

NetBeans 7 has nice support for HTML5. Previously I was a heavy user of Eclipse, but spend more time with NetBeans to play with HTML5 and Servlet.

Binding a Button's visibility to a bool value in ViewModel

This can be achieved in a very simple way 1. Write this in the view.

<Button HorizontalAlignment="Center" VerticalAlignment="Center" Width="50" Height="30">
<Button.Style>
        <Style TargetType="Button">
                <Setter Property="Visibility" Value="Collapsed"/>
                        <Style.Triggers>
                                <DataTrigger Binding="{Binding IsHide}" Value="True">
                                        <Setter Property="Visibility" Value="Visible"/>
                                    </DataTrigger>
                            </Style.Triggers>
            </Style>
    </Button.Style>

  1. The following is the Boolean property which holds the true/ false value. The following is the code snippet. In my example this property is in UserNote class.

    public bool _isHide = false;
    
    public bool IsHide
    {
    
    get { return _isHide; }
    
    set
        {
            _isHide = value;
                OnPropertyChanged("IsHide");
        }
    } 
    
  2. This is the way the IsHide property gets the value.

    userNote.IsHide = userNote.IsNoteDeleted;
    

Iterating through map in template

Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:

{{ range $key, $value := . }}
   <li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}

How do I add files and folders into GitHub repos?

You need to checkout the repository onto your local machine. Then you can change that folder on your local machine.

git commit -am "added files"

That command will commit all files to the repo.

git push origin master

that will push all changes in your master branch (which I assume is the one you're using) to the remote repository origin (in this case github)

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

This is worked for me, Hope to help someone (Using my own button not FB login button )

CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_sign_in_user);



     LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {


            GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    try {
                        Log.i("RESAULTS : ", object.getString("email"));
                    }catch (Exception e){

                    }
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "email");
            request.setParameters(parameters);
            request.executeAsync();

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {
            Log.i("RESAULTS : ", error.getMessage());
        }
    });


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    callbackManager.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}


boolean isEmailValid(CharSequence email) {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

public void signupwith_facebook(View view) {

    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email"));
}
}

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Request Dispatcher is an Interface which is used to dispatch the request or response from web resource to the another web resource. It contains mainly two methods.

  1. request.forward(req,res): This method is used forward the request from one web resource to another resource. i.e from one servlet to another servlet or from one web application to another web appliacation.

  2. response.include(req,res): This method is used include the response of one servlet to another servlet

NOTE: BY using Request Dispatcher we can forward or include the request or responses with in the same server.

request.sendRedirect(): BY using this we can forward or include the request or responses across the different servers. In this the client gets a intimation while redirecting the page but in the above process the client will not get intimation

Paste multiple columns together

# your starting data..
data <- data.frame('a' = 1:3, 'b' = c('a','b','c'), 'c' = c('d', 'e', 'f'), 'd' = c('g', 'h', 'i')) 

# columns to paste together
cols <- c( 'b' , 'c' , 'd' )

# create a new column `x` with the three columns collapsed together
data$x <- apply( data[ , cols ] , 1 , paste , collapse = "-" )

# remove the unnecessary columns
data <- data[ , !( names( data ) %in% cols ) ]

How to update json file with python

The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.

The easiest solution would be to close the file after you've read it in, then reopen it for writing.

with open("replayScript.json", "r") as jsonFile:
    data = json.load(jsonFile)

data["location"] = "NewPath"

with open("replayScript.json", "w") as jsonFile:
    json.dump(data, jsonFile)

Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.

with open("replayScript.json", "r+") as jsonFile:
    data = json.load(jsonFile)

    data["location"] = "NewPath"

    jsonFile.seek(0)  # rewind
    json.dump(data, jsonFile)
    jsonFile.truncate()

How do I create an array of strings in C?

In ANSI C:

char* strings[3];
strings[0] = "foo";
strings[1] = "bar";
strings[2] = "baz";

Which maven dependencies to include for spring 3.0?

You can try this

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>
</dependencies>`

Download history stock prices automatically from yahoo finance in python

You can check out the yahoo_fin package. It was initially created after Yahoo Finance changed their API (documentation is here: http://theautomatic.net/yahoo_fin-documentation).

from yahoo_fin import stock_info as si

aapl_data = si.get_data("aapl")

nflx_data = si.get_data("nflx")

aapl_data.head()

nflx_data.head()

aapl.to_csv("aapl_data.csv")

nflx_data.to_csv("nflx_data.csv")

Add column with number of days between dates in DataFrame pandas

To remove the 'days' text element, you can also make use of the dt() accessor for series: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html

So,

df[['A','B']] = df[['A','B']].apply(pd.to_datetime) #if conversion required
df['C'] = (df['B'] - df['A']).dt.days

which returns:

             A          B   C
one 2014-01-01 2014-02-28  58
two 2014-02-03 2014-03-01  26

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

refresh both the External data source and pivot tables together within a time schedule

I found this solution online, and it addressed this pretty well. My only concern is looping through all the pivots and queries might become time consuming if there's a lot of them:

Sub RefreshTables()

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Dim objList As ListObject
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
    For Each objList In ws.ListObjects
        If objList.SourceType = 3 Then
            With objList.QueryTable
                .BackgroundQuery = False
                .Refresh
            End With
        End If
    Next objList
Next ws

Call UpdateAllPivots

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

Sub UpdateAllPivots()
Dim pt As PivotTable
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
    For Each pt In ws.PivotTables
        pt.RefreshTable
    Next pt
Next ws

End Sub

How do I add target="_blank" to a link within a specified div?

Bear in mind that doing this is considered bad practice in general by web developers and usability experts. Jakob Nielson has this to say about removing control of the users browsing experience:

Avoid spawning multiple browser windows if at all possible — taking the "Back" button away from users can make their experience so painful that it usually far outweighs whatever benefit you're trying to provide. One common theory in favor of spawning the second window is that it keeps users from leaving your site, but ironically it may have just the opposite effect by preventing them from returning when they want to.

I believe this is the rationale for the target attribute being removed by the W3C from the XHTML 1.1 spec.

If you're dead set on taking this approach, Pim Jager's solution is good.

A nicer, more user friendly idea, would be to append a graphic to all of your external links, indicating to the user that following the link will take them externally.

You could do this with jquery:

$('a[href^="http://"]').each(function() {
    $('<img width="10px" height="10px" src="/images/skin/external.png" alt="External Link" />').appendTo(this)

});

Can't connect to local MySQL server through socket homebrew

I faced the same problem on my mac and solved it, by following the following tutorials

https://mariadb.com/resources/blog/installing-mariadb-10116-mac-os-x-homebrew

But don't forget to kill or uninstall the old version before continuing.

Commands:

brew uninstall mariadb

xcode-select --install

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" - See more at: https://mariadb.com/resources/blog/installing-mariadb-10116-mac-os-x-homebrew#sthash.XQoxRoJp.dpuf

brew doctor

brew update

brew info mariadb

brew install mariadb

mysql_install_db

mysql.server start

Select tableview row programmatically

There are two different methods for iPad and iPhone platforms, so you need to implement both:

  • selection handler and
  • segue.

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    
    // Selection handler (for horizontal iPad)
    [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
    
    // Segue (for iPhone and vertical iPad)
    [self performSegueWithIdentifier:"showDetail" sender:self];
    

MySQL the right syntax to use near '' at line 1 error

INSERT INTO wp_bp_activity
            (
            user_id,
             component,
             `type`,
             `action`,
             content,
             primary_link,
             item_id,
             secondary_item_id,
             date_recorded,
             hide_sitewide,
             mptt_left,
             mptt_right
             )
             VALUES(
             1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
             )

How to fit in an image inside span tag?

Try this.

<span style="padding-right:3px; padding-top: 3px; display:inline-block;">

<img class="manImg" src="images/ico_mandatory.gif"></img>

</span>

Scala list concatenation, ::: vs ++

A different point is that the first sentence is parsed as:

scala> List(1,2,3).++(List(4,5))
res0: List[Int] = List(1, 2, 3, 4, 5)

Whereas the second example is parsed as:

scala> List(4,5).:::(List(1,2,3))
res1: List[Int] = List(1, 2, 3, 4, 5)

So if you are using macros, you should take care.

Besides, ++ for two lists is calling ::: but with more overhead because it is asking for an implicit value to have a builder from List to List. But microbenchmarks did not prove anything useful in that sense, I guess that the compiler optimizes such calls.

Micro-Benchmarks after warming up.

scala>def time(a: => Unit): Long = { val t = System.currentTimeMillis; a; System.currentTimeMillis - t}
scala>def average(a: () => Long) = (for(i<-1 to 100) yield a()).sum/100

scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ++ List(e) } })
res1: Long = 46
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ::: List(e ) } })
res2: Long = 46

As Daniel C. Sobrai said, you can append the content of any collection to a list using ++, whereas with ::: you can only concatenate lists.

Multiple argument IF statement - T-SQL

That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.

How to distinguish mouse "click" and "drag"

In case you are already using jQuery:

var $body = $('body');
$body.on('mousedown', function (evt) {
  $body.on('mouseup mousemove', function handler(evt) {
    if (evt.type === 'mouseup') {
      // click
    } else {
      // drag
    }
    $body.off('mouseup mousemove', handler);
  });
});

How do I format date in jQuery datetimepicker?

This works for me. Since it "extends" datepicker we can still use dateFormat:'dd/mm/yy'.

$(function() {
    $('.jqueryui-marker-datepicker').datetimepicker({
        showSecond: true,
        dateFormat: 'dd/mm/yy',
      timeFormat: 'hh:mm:ss',
      stepHour: 2,
      stepMinute: 10,
      stepSecond: 10

     });
});

Refreshing data in RecyclerView and keeping its scroll position

If you have one or more EditTexts inside of a recyclerview items, disable the autofocus of these, putting this configuration in the parent view of recyclerview:

android:focusable="true"
android:focusableInTouchMode="true"

I had this issue when I started another activity launched from a recyclerview item, when I came back and set an update of one field in one item with notifyItemChanged(position) the scroll of RV moves, and my conclusion was that, the autofocus of EditText Items, the code above solved my issue.

best.

'ng' is not recognized as an internal or external command, operable program or batch file

I just installed angular cli and it solved my issue, simply run:

npm install -g @angular/cli

AngularJS : automatically detect change in model

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true);

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... });

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

How can you tell when a layout has been drawn?

When onMeasure is called the view gets its measured width/height. After this, you can call layout.getMeasuredHeight().

The data-toggle attributes in Twitter Bootstrap

The presence of this data-attribute tells Bootstrap to switch between visual or a logical states of another element on user interaction.

It is used to show modals, tab content, tooltips and popover menus as well as setting a pressed-state for a toggle-button. It is used in multiple ways without a clear documentation.

ModalPopupExtender OK Button click event not firing?

Put into the Button-Control the Attribute "UseSubmitBehavior=false".

How do I compile jrxml to get jasper?

For anyone coming across this question who uses Jaspersoft Studio (which, I think, is replacing iReports; it's quite similar, still freeware, just based on eclipse), look for the "Compile Report" icon on top of the editor area of your .jrxml file. Its icon, first in that line of icons, is a file with binary numbers on it (at least in version 5.6.2):

Jaspersoft Studio - compile report

Clicking this icon will generate the .jasper file in the same directory as the .jrxml file.

How to list only the file names that changed between two commits?

In case someone is looking for list of files changed including staged files

git diff HEAD --name-only --relative --diff-filter=AMCR

git diff HEAD --name-only --relative --diff-filter=AMCR sha-1 sha-2

Remove --relative if you want absolute paths.

How to configure log4j.properties for SpringJUnit4ClassRunner?

If you don't want to bother with a file, you can do something like this in your code:

static
{
    Logger rootLogger = Logger.getRootLogger();
    rootLogger.setLevel(Level.INFO);
    rootLogger.addAppender(new ConsoleAppender(
               new PatternLayout("%-6r [%p] %c - %m%n")));
}

Javascript seconds to minutes and seconds

To get the number of full minutes, divide the number of total seconds by 60 (60 seconds/minute):

var minutes = Math.floor(time / 60);

And to get the remaining seconds, multiply the full minutes with 60 and subtract from the total seconds:

var seconds = time - minutes * 60;

Now if you also want to get the full hours too, divide the number of total seconds by 3600 (60 minutes/hour · 60 seconds/minute) first, then calculate the remaining seconds:

var hours = Math.floor(time / 3600);
time = time - hours * 3600;

Then you calculate the full minutes and remaining seconds.

Bonus:

Use the following code to pretty-print the time (suggested by Dru)

function str_pad_left(string,pad,length) {
    return (new Array(length+1).join(pad)+string).slice(-length);
}

var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);

What is the strict aliasing rule?

A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to uint32_ts or uint16_ts). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.

So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:

typedef struct Msg
{
    unsigned int a;
    unsigned int b;
} Msg;

void SendWord(uint32_t);

int main(void)
{
    // Get a 32-bit buffer from the system
    uint32_t* buff = malloc(sizeof(Msg));
    
    // Alias that buffer through message
    Msg* msg = (Msg*)(buff);
    
    // Send a bunch of messages    
    for (int i = 0; i < 10; ++i)
    {
        msg->a = i;
        msg->b = i+1;
        SendWord(buff[0]);
        SendWord(buff[1]);   
    }
}

The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a compatible type or one of the other types allowed by C 2011 6.5 paragraph 71 is undefined behavior. Unfortunately, you can still code this way, maybe get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code.

(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)

To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of buff every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load buff[0] and buff[1] into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of buff could change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.

Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.

void SendMessage(uint32_t* buff, size_t size32)
{
    for (int i = 0; i < size32; ++i) 
    {
        SendWord(buff[i]);
    }
}

And rewrote our earlier loop to take advantage of this convenient function

for (int i = 0; i < 10; ++i)
{
    msg->a = i;
    msg->b = i+1;
    SendMessage(buff, 2);
}

The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If SendMessage is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.

So how do I get around this?

  • Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.

      union {
          Msg msg;
          unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];
      };
    
  • You can disable strict aliasing in your compiler (f[no-]strict-aliasing in gcc))

  • You can use char* for aliasing instead of your system's word. The rules allow an exception for char* (including signed char and unsigned char). It's always assumed that char* aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.

Beginner beware

This is only one potential minefield when overlaying two types onto each other. You should also learn about endianness, word alignment, and how to deal with alignment issues through packing structs correctly.

Footnote

1 The types that C 2011 6.5 7 allows an lvalue to access are:

  • a type compatible with the effective type of the object,
  • a qualified version of a type compatible with the effective type of the object,
  • a type that is the signed or unsigned type corresponding to the effective type of the object,
  • a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
  • a character type.

How to remove files that are listed in the .gitignore but still on the repository?

I did a very straightforward solution by manipulating the output of the .gitignore statement with sed:

cat .gitignore | sed '/^#.*/ d' | sed '/^\s*$/ d' | sed 's/^/git rm -r /' | bash

Explanation:

  1. print the .gitignore file
  2. remove all comments from the print
  3. delete all empty lines
  4. add 'git rm -r ' to the start of the line
  5. execute every line.

How can I add 1 day to current date?

To add one day to a date object:

var date = new Date();

// add a day
date.setDate(date.getDate() + 1);

Python TypeError: not enough arguments for format string

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

$.ajax( type: "POST" POST method to php

Check whether title has any value or not. If not, then retrive the value using Id.

<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
    var title=jQuery('#title').val();
    $.ajax({
      type: "POST",
      url: "edit.php",
      data: {title:title} ,
      success: function(data) {
    $('.center').html(data); 
}
});
}
</script>

Try this code.

In php code, use echo instead of return. Only then, javascript data will have its value.

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

How to check if a string is a number?

  if(tmp[j] >= '0' && tmp[j] <= '9') // should do the trick

How to detect the OS from a Bash script?

Try using "uname". For example, in Linux: "uname -a".

According to the manual page, uname conforms to SVr4 and POSIX, so it should be available on Mac OS X and Cygwin too, but I can't confirm that.

BTW: $OSTYPE is also set to linux-gnu here :)

TypeError: coercing to Unicode: need string or buffer

For the less specific case (not just the code in the question - since this is one of the first results in Google for this generic error message. This error also occurs when running certain os command with None argument.

For example:

os.path.exists(arg)  
os.stat(arg)

Will raise this exception when arg is None.

Get exception description and stack trace which caused an exception, all as a string

I defined following helper class:

import traceback
class TracedExeptions(object):
    def __init__(self):
        pass
    def __enter__(self):
        pass

    def __exit__(self, etype, value, tb):
      if value :
        if not hasattr(value, 'traceString'):
          value.traceString = "\n".join(traceback.format_exception(etype, value, tb))
        return False
      return True

Which I can later use like this:

with TracedExeptions():
  #some-code-which-might-throw-any-exception

And later can consume it like this:

def log_err(ex):
  if hasattr(ex, 'traceString'):
    print("ERROR:{}".format(ex.traceString));
  else:
    print("ERROR:{}".format(ex));

(Background: I was frustraded because of using Promises together with Exceptions, which unfortunately passes exceptions raised in one place to a on_rejected handler in another place, and thus it is difficult to get the traceback from original location)

javascript regex : only english letters allowed

_x000D_
_x000D_
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
_x000D_
_x000D_

Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w covers a-zA-Z and some other word characters. It all depends on what you need specifically.

Get list of all input objects using JavaScript, without accessing a form object

var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
  // ...
}

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

What is recursion and when should I use it?

Recursion is when you have an operation that uses itself. It probably will have a stopping point, otherwise it would go on forever.

Let's say you want to look up a word in the dictionary. You have an operation called "look-up" at your disposal.

Your friend says "I could really spoon up some pudding right now!" You don't know what he means, so you look up "spoon" in the dictionary, and it reads something like this:

Spoon: noun - a utensil with a round scoop at the end. Spoon: verb - to use a spoon on something Spoon: verb - to cuddle closely from behind

Now, being that you're really not good with English, this points you in the right direction, but you need more info. So you select "utensil" and "cuddle" to look up for some more information.

Cuddle: verb - to snuggle Utensil: noun - a tool, often an eating utensil

Hey! You know what snuggling is, and it has nothing to do with pudding. You also know that pudding is something you eat, so it makes sense now. Your friend must want to eat pudding with a spoon.

Okay, okay, this was a very lame example, but it illustrates (perhaps poorly) the two main parts of recursion. 1) It uses itself. In this example, you haven't really looked up a word meaningfully until you understand it, and that might mean looking up more words. This brings us to point two, 2) It stops somewhere. It has to have some kind of base-case. Otherwise, you'd just end up looking up every word in the dictionary, which probably isn't too useful. Our base-case was that you got enough information to make a connection between what you previously did and did not understand.

The traditional example that's given is factorial, where 5 factorial is 1*2*3*4*5 (which is 120). The base case would be 0 (or 1, depending). So, for any whole number n, you do the following

is n equal to 0? return 1 otherwise, return n * (factorial of n-1)

let's do this with the example of 4 (which we know ahead of time is 1*2*3*4 = 24).

factorial of 4 ... is it 0? no, so it must be 4 * factorial of 3 but what's factorial of 3? it's 3 * factorial of 2 factorial of 2 is 2 * factorial of 1 factorial of 1 is 1 * factorial of 0 and we KNOW factorial of 0! :-D it's 1, that's the definition factorial of 1 is 1 * factorial of 0, which was 1... so 1*1 = 1 factorial of 2 is 2 * factorial of 1, which was 1... so 2*1 = 2 factorial of 3 is 3 * factorial of 2, which was 2... so 3*2 = 6 factorial of 4 (finally!!) is 4 * factorial of 3, which was 6... 4*6 is 24

Factorial is a simple case of "base case, and uses itself".

Now, notice we were still working on factorial of 4 the entire way down... If we wanted factorial of 100, we'd have to go all the way down to 0... which might have a lot of overhead to it. In the same manner, if we find an obscure word to look up in the dictionary, it might take looking up other words and scanning for context clues until we find a connection we're familiar with. Recursive methods can take a long time to work their way through. However, when they're used correctly, and understood, they can make complicated work surprisingly simple.

What is the C# version of VB.net's InputDialog?

There isn't one. If you really wanted to use the VB InputBox in C# you can. Just add reference to Microsoft.VisualBasic.dll and you'll find it there.

But I would suggest to not use it. It is ugly and outdated IMO.

Python: read all text file lines in loop

There are situations where you can't use the (quite convincing) with... for... structure. In that case, do the following:

line = self.fo.readline()
if len(line) != 0:
     if 'str' in line:
         break

This will work because the the readline() leaves a trailing newline character, where as EOF is just an empty string.

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

You don't need to run Xcode 10.2 for iOS 12.2 support. You just need access to the appropriate folder in DeviceSupport.

A possible solution is

  • Download Xcode 10.2 from a direkt link (not from App Store).
  • Rename it for example to Xcode102.
  • Put it into /Applications. It's possible to have multiple Xcode versions in the same directory.
  • Create a symbolic link in Terminal.app to have access to the 12.2 device support folder in Xcode 10.2

    ln -s /Applications/Xcode102.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/12.2\ \(16E226\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
    

You can move Xcode 10.2 to somewhere else but then you have to adjust the path.

Now Xcode 10.1 supports devices running iOS 12.2

What is an unhandled promise rejection?

Try not closing the connection before you send data to your database. Remove client.close(); from your code and it'll work fine.

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

Is it possible to program iPhone in C++

I use Objective-C to slap the UI together.
But the hard guts of the code is still written in C++.

That is the main purpose of Objective-C the UI interface and handling the events.
And it works great for that purpose.

I still like C++ as the backend for the code though (but that's mainly becuase I like C++) you could quite easily use Objective-C for the backend of the application as well.

Removing multiple files from a Git repo that have already been deleted from disk

I needed the same and used git gui "stage changed" button. it also adds all.

And after "stage changed" I made "commit" ...

so my working directory is clean again.

Rails 3 migrations: Adding reference column?

That will do the trick:

rails g migration add_user_to_tester user_id:integer:index

How to use querySelectorAll only for elements that have a specific attribute set?

With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples directly with:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

Uint8Array to string in Javascript

This should work:

// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

/* utf.js - UTF-8 <=> UTF-16 convertion
 *
 * Copyright (C) 1999 Masanao Izumo <[email protected]>
 * Version: 1.0
 * LastModified: Dec 25 1999
 * This library is free.  You can redistribute it and/or modify it.
 */

function Utf8ArrayToStr(array) {
    var out, i, len, c;
    var char2, char3;

    out = "";
    len = array.length;
    i = 0;
    while(i < len) {
    c = array[i++];
    switch(c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                       ((char2 & 0x3F) << 6) |
                       ((char3 & 0x3F) << 0));
        break;
    }
    }

    return out;
}

It's somewhat cleaner as the other solutions because it doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments.

Check out the JSFiddle demo.

Also see the related questions: here and here

Argument list too long error for rm, cp, mv commands

The below option seems simple to this problem. I got this info from some other thread but it helped me.

for file in /usr/op/data/Software/temp/application/openpages-storage/*; do
    cp "$file" /opt/sw/op-storage/
done

Just run the above one command and it will do the task.

mySQL Error 1040: Too Many Connection

Try this :

open the terminal and type this command : sudo gedit /etc/mysql/my.cnf

Paste the line in my.cnf file: set-variable=max_connections=500

JavaScript chop/slice/trim off last character in string

You can use the substring method of JavaScript string objects:

s = s.substring(0, s.length - 4)

It unconditionally removes the last four characters from string s.

However, if you want to conditionally remove the last four characters, only if they are exactly _bar:

var re = /_bar$/;
s.replace(re, "");

Copying and pasting data using VBA code

Use the PasteSpecial method:

sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues

BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).

Make the current commit the only (initial) commit in a Git repository?

The only solution that works for me (and keeps submodules working) is

git checkout --orphan newBranch
git add -A  # Add all files and commit them
git commit
git branch -D master  # Deletes the master branch
git branch -m master  # Rename the current branch to master
git push -f origin master  # Force push master branch to github
git gc --aggressive --prune=all     # remove the old files

Deleting .git/ always causes huge issues when I have submodules. Using git rebase --root would somehow cause conflicts for me (and take long since I had a lot of history).

Send Email to multiple Recipients with MailMessage?

I've tested this using the following powershell script and using (,) between the addresses. It worked for me!

$EmailFrom = "<[email protected]>";
$EmailPassword = "<password>";
$EmailTo = "<[email protected]>,<[email protected]>";
$SMTPServer = "<smtp.server.com>";
$SMTPPort = <port>;
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,$SMTPPort);
$SMTPClient.EnableSsl = $true;
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $EmailPassword);
$Subject = "Notification from XYZ";
$Body = "this is a notification from XYZ Notifications..";
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body);

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'

Adding a caption to an equation in LaTeX

The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:

\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}

The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:

\[ E = m c^2 \]
\captionof{figure}{A famous equation}

This will also produce an entry for the \listoffigures, if your document has one.

To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...

Generate random numbers uniformly over an entire range

Check what RAND_MAX is on your system -- I'm guessing it is only 16 bits, and your range is too big for it.

Beyond that see this discussion on: Generating Random Integers within a Desired Range and the notes on using (or not) the C rand() function.

Bootstrap 3 Horizontal Divider (not in a dropdown)

Yes there is, you can simply put <hr> in your code where you want it, I already use it in one of my admin panel side bar.

Retrieving JSON Object Literal from HttpServletRequest

If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..

If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.

How to add additional fields to form before submit?

Yes.You can try with some hidden params.

  $("#form").submit( function(eventObj) {
      $("<input />").attr("type", "hidden")
          .attr("name", "something")
          .attr("value", "something")
          .appendTo("#form");
      return true;
  });

How to create a JavaScript callback for knowing when an image is loaded?

these functions will solve the problem, you need to implement the DrawThumbnails function and have a global variable to store the images. I love to get this to work with a class object that has the ThumbnailImageArray as a member variable, but am struggling!

called as in addThumbnailImages(10);

var ThumbnailImageArray = [];

function addThumbnailImages(MaxNumberOfImages)
{
    var imgs = [];

    for (var i=1; i<MaxNumberOfImages; i++)
    {
        imgs.push(i+".jpeg");
    }

    preloadimages(imgs).done(function (images){
            var c=0;

            for(var i=0; i<images.length; i++)
            {
                if(images[i].width >0) 
                {
                    if(c != i)
                        images[c] = images[i];
                    c++;
                }
            }

            images.length = c;

            DrawThumbnails();
        });
}



function preloadimages(arr)
{
    var loadedimages=0
    var postaction=function(){}
    var arr=(typeof arr!="object")? [arr] : arr

    function imageloadpost()
    {
        loadedimages++;
        if (loadedimages==arr.length)
        {
            postaction(ThumbnailImageArray); //call postaction and pass in newimages array as parameter
        }
    };

    for (var i=0; i<arr.length; i++)
    {
        ThumbnailImageArray[i]=new Image();
        ThumbnailImageArray[i].src=arr[i];
        ThumbnailImageArray[i].onload=function(){ imageloadpost();};
        ThumbnailImageArray[i].onerror=function(){ imageloadpost();};
    }
    //return blank object with done() method    
    //remember user defined callback functions to be called when images load
    return  { done:function(f){ postaction=f || postaction } };
}

How do I make a matrix from a list of vectors in R?

t(sapply(a, '[', 1:max(sapply(a, length))))

where 'a' is a list. Would work for unequal row size

Rails :include vs. :joins

tl;dr

I contrast them in two ways:

joins - For conditional selection of records.

includes - When using an association on each member of a result set.

Longer version

Joins is meant to filter the result set coming from the database. You use it to do set operations on your table. Think of this as a where clause that performs set theory.

Post.joins(:comments)

is the same as

Post.where('id in (select post_id from comments)')

Except that if there are more than one comment you will get duplicate posts back with the joins. But every post will be a post that has comments. You can correct this with distinct:

Post.joins(:comments).count
=> 10
Post.joins(:comments).distinct.count
=> 2

In contract, the includes method will simply make sure that there are no additional database queries when referencing the relation (so that we don't make n + 1 queries)

Post.includes(:comments).count
=> 4 # includes posts without comments so the count might be higher.

The moral is, use joins when you want to do conditional set operations and use includes when you are going to be using a relation on each member of a collection.

How do I use a regex in a shell script?

the problem is you're trying to use regex features not supported by grep. namely, your \d won't work. use this instead:

REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?

you need the -E flag to get ERE in order to use {#} style.

What is the difference between vmalloc and kmalloc?

In short, vmalloc and kmalloc both could fix fragmentation. vmalloc use memory mappings to fix external fragmentation; kmalloc use slab to fix internal frgamentation. Fot what it's worth, kmalloc also has many other advantages.

Android new Bottom Navigation bar or BottomNavigationView

As Sanf0rd mentioned, Google launched the BottomNavigationView as part of the Design Support Library version 25.0.0. The limitations he mentioned are mostly true, except that you CAN change the background color of the view and even the text color and icon tint color. It also has an animation when you add more than 4 items (sadly it cannot be enabled or disabled manually).

I wrote a detailed tutorial about it with examples and an accompanying repository, which you can read here: https://blog.autsoft.hu/now-you-can-use-the-bottom-navigation-view-in-the-design-support-library/


The gist of it

You have to add these in your app level build.gradle:

compile 'com.android.support:appcompat-v7:25.0.0'  
compile 'com.android.support:design:25.0.0'

You can include it in your layout like this:

<android.support.design.widget.BottomNavigationView  
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/bottom_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemBackground="@color/darkGrey"
        app:itemIconTint="@color/bottom_navigation_item_background_colors"
        app:itemTextColor="@color/bottom_navigation_item_background_colors"
        app:menu="@menu/menu_bottom_navigation" />

You can specify the items via a menu resource like this:

<?xml version="1.0" encoding="utf-8"?>  
<menu  
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_one"
        android:icon="@android:drawable/ic_dialog_map"
        android:title="One"/>
    <item
        android:id="@+id/action_two"
        android:icon="@android:drawable/ic_dialog_info"
        android:title="Two"/>
    <item
        android:id="@+id/action_three"
        android:icon="@android:drawable/ic_dialog_email"
        android:title="Three"/>
    <item
        android:id="@+id/action_four"
        android:icon="@android:drawable/ic_popup_reminder"
        android:title="Four"/>
</menu>

And you can set the tint and text color as a color list, so the currently selected item is highlighted:

<?xml version="1.0" encoding="utf-8"?>  
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:color="@color/colorAccent"
        android:state_checked="false"/>
    <item
        android:color="@android:color/white"
        android:state_checked="true"/>

</selector>

Finally, you can handle the selection of the items with an OnNavigationItemSelectedListener:

bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {  
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment fragment = null;
        switch (item.getItemId()) {
            case R.id.action_one:
                // Switch to page one
                break;
            case R.id.action_two:
                // Switch to page two
                break;
            case R.id.action_three:
                // Switch to page three
                break;
        }
        return true;
    }
});

Do I use <img>, <object>, or <embed> for SVG files?

From IE9 and above you can use SVG in a ordinary IMG tag..

https://caniuse.com/svg-img

<img src="/static/image.svg">

What does the ELIFECYCLE Node.js error mean?

I had this issue when I was running two projects that had the same set up and I already had one running. This meant that the other project couldn't use that port number. As soon as I stopped the other project running I had no issues.

How to pip or easy_install tkinter on Windows

In python, Tkinter was a default package, you can repair the installation and select Tcl/Tk. repair When you run this, DDL should be installed like so: enter image description here

Cloning an array in Javascript/Typescript

Try this

const returnedTarget = Object.assign(target, source);

and pass empty array to target

in case complex objects this way works for me

$.extend(true, [], originalArray) in case of array

$.extend(true, {}, originalObject) in case of object

How to import large sql file in phpmyadmin

Solution for LINUX USERS (run with sudo)

Create 'upload' and 'save' directories:

mkdir /etc/phpmyadmin/upload
mkdir /etc/phpmyadmin/save
chmod a+w /etc/phpmyadmin/upload
chmod a+w /etc/phpmyadmin/save

Then edit phpmyadmin's config file:

gedit /etc/phpmyadmin/config.inc.php

Finally add absolute path for both 'upload' and 'save' directories:

$cfg['UploadDir'] = '/etc/phpmyadmin/upload';
$cfg['SaveDir'] = '/etc/phpmyadmin/save';

Now, just drop files on /etc/phpmyadmin/upload folder and then you'll be able to select them from phpmyadmin.

enter image description here

Hope this help.

How to open existing project in Eclipse

File > Import > General > Existing Projects into workspace. Select the root folder that has your project(s). It lists all the projects available in the selected folder. Select the ones you would like to import and click Finish. This should work just fine.

How can I update the current line in a C# Windows Console App?

    public void Update(string data)
    {
        Console.Write(string.Format("\r{0}", "".PadLeft(Console.CursorLeft, ' ')));
        Console.Write(string.Format("\r{0}", data));
    }

Run javascript script (.js file) in mongodb including another file inside js

Another way is to pass the file into mongo in your terminal prompt.

$ mongo < myjstest.js

This will start a mongo session, run the file, then exit. Not sure about calling a 2nd file from the 1st however. I haven't tried it.

add controls vertically instead of horizontally using flow layout

JPanel testPanel = new JPanel();
testPanel.setLayout(new BoxLayout(testPanel, BoxLayout.Y_AXIS));
/*add variables here and add them to testPanel
        e,g`enter code here`
        testPanel.add(nameLabel);
        testPanel.add(textName);
*/
testPanel.setVisible(true);

How to define Singleton in TypeScript

In Typescript, one doesn't necessarily have to follow the new instance() Singleton methodology. An imported, constructor-less static class can work equally as well.

Consider:

export class YourSingleton {

   public static foo:bar;

   public static initialise(_initVars:any):void {
     YourSingleton.foo = _initvars.foo;
   }

   public static doThing():bar {
     return YourSingleton.foo
   }
}

You can import the class and refer to YourSingleton.doThing() in any other class. But remember, because this is a static class, it has no constructor so I usually use an intialise() method that is called from a class that imports the Singleton:

import {YourSingleton} from 'singleton.ts';

YourSingleton.initialise(params);
let _result:bar = YourSingleton.doThing();

Don't forget that in a static class, every method and variable needs to also be static so instead of this you would use the full class name YourSingleton.

Razor-based view doesn't see referenced assemblies

This solution worked for me (It's funny, but works)

I edited the view pages and copied the contents and pasted in it,i didn't change any content of the views, but just edited so the visual studio could do it's thing to track the pages, and afterwards every thing started working

Solution - Just edit the pages and replace with the same pages (Worked for me)

Convert UTC dates to local time in PHP

First, get the date in UTC -- you've already done that so this step would really just be a database call:

$timezone = "UTC";
date_default_timezone_set($timezone);

$utc = gmdate("M d Y h:i:s A");
print "UTC: " . date('r', strtotime($utc)) . "\n";

Next, set your local time zone in PHP:

$timezone = "America/Guayaquil";
date_default_timezone_set($timezone);

And now get the offset in seconds:

$offset = date('Z', strtotime($utc));
print "offset: $offset \n";

Finally, add the offset to the integer timestamp of your original datetime:

print "LOCAL: " . date('r', strtotime($utc) + $offset) . "\n";

Filter element based on .data() key/value

Sounds like more work than its worth.

1) Why not just have a single JavaScript variable that stores a reference to the currently selected element\jQuery object.

2) Why not add a class to the currently selected element. Then you could query the DOM for the ".active" class or something.

How do I plot only a table in Matplotlib?

If you just wanted to change the example and put the table at the top, then loc='top' in the table declaration is what you need,

the_table = ax.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='top')

Then adjusting the plot with,

plt.subplots_adjust(left=0.2, top=0.8)

A more flexible option is to put the table in its own axis using subplots,

import numpy as np
import matplotlib.pyplot as plt


fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')

axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()

which looks like this,

enter image description here

You are then free to adjust the locations of the axis as required.

How to find array / dictionary value using key?

It looks like you're writing PHP, in which case you want:

<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>

Notice that the ('us'=>'United', 'ca'=>'canada') needs to be a parameter to the array function in PHP.

Most programming languages that support associative arrays or dictionaries use arr['key'] to retrieve the item specified by 'key'

For instance:

Ruby

ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
 => {"us"=>"USA", "ca"=>"Canada"} 
ruby-1.9.1-p378 > h['ca']
 => "Canada" 

Python

>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'

C#

class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
        System.Console.WriteLine(d["ca"]);
    }
}

Lua

t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables

How to identify platform/compiler from preprocessor macros?

See: http://predef.sourceforge.net/index.php

This project provides a reasonably comprehensive listing of pre-defined #defines for many operating systems, compilers, language and platform standards, and standard libraries.

Display all post meta keys and meta values of the same post ID in wordpress

To get all rows, don't specify the key. Try this:

$meta_values = get_post_meta( get_the_ID() );

var_dump( $meta_values );

Hope it helps!

Where does Chrome store cookies?

For Google chrome Version 56.0.2924.87 (Latest Release) cookies are found inside profile1 folder.

If you browse that you can find variety of information.

There is a separate file called "Cookies". Also the Cache folder is inside this folder.

Path : C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Profile 1

Remember to replace user_name.

For Version 61.0.3163.100
Path : C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Default

Inside this folder there is Cookies file and Cache folder.

How to convert HH:mm:ss.SSS to milliseconds?

If you want to parse the format yourself you could do it easily with a regex such as

private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");

public static long dateParseRegExp(String period) {
    Matcher matcher = pattern.matcher(period);
    if (matcher.matches()) {
        return Long.parseLong(matcher.group(1)) * 3600000L 
            + Long.parseLong(matcher.group(2)) * 60000 
            + Long.parseLong(matcher.group(3)) * 1000 
            + Long.parseLong(matcher.group(4)); 
    } else {
        throw new IllegalArgumentException("Invalid format " + period);
    }
}

However, this parsing is quite lenient and would accept 99:99:99.999 and just let the values overflow. This could be a drawback or a feature.

Twitter Bootstrap add active class to li

The solution is simple and there is no need for server side or ajax, you only need jQuery and Bootstrap. On every page add an id to the body tag. Use that id to find a tag that contains the page name (value of a tag).

Example:

page1.html

<body id="page1">
    <ul class="nav navbar-nav">
        <li><a href="page1.html">Page1</a></li>
        <li><a href="page2.html">Page2</a></li>
    </ul>
    <script src="script.js"></script>
</body>

page2.html

<body id="page2">
    <ul class="nav navbar-nav">
        <li><a href="page1.html">Page1</a></li>
        <li><a href="page2.html">Page2</a></li>
    </ul>
    <script src="script.js"></script>
</body>

script.js

<script>
    $(function () {
        $("#page1 a:contains('Page1')").parent().addClass('active');
        $("#page2 a:contains('Page2')").parent().addClass('active');
     });
</script>

Big thanks to Ben! YouTube

Parse an HTML string with JS

Create a dummy DOM element and add the string to it. Then, you can manipulate it like any DOM element.

var el = document.createElement( 'html' );
el.innerHTML = "<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>";

el.getElementsByTagName( 'a' ); // Live NodeList of your anchor elements

Edit: adding a jQuery answer to please the fans!

var el = $( '<div></div>' );
el.html("<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>");

$('a', el) // All the anchor elements

Base64 length calculation?

If there is someone interested in achieve the @Pedro Silva solution in JS, I just ported this same solution for it:

const getBase64Size = (base64) => {
  let padding = base64.length
    ? getBase64Padding(base64)
    : 0
  return ((Math.ceil(base64.length / 4) * 3 ) - padding) / 1000
}

const getBase64Padding = (base64) => {
  return endsWith(base64, '==')
    ? 2
    : 1
}

const endsWith = (str, end) => {
  let charsFromEnd = end.length
  let extractedEnd = str.slice(-charsFromEnd)
  return extractedEnd === end
}

Undo git update-index --assume-unchanged <file>

If you want to undo all files that was applied assume unchanged with any status, not only cached (git marks them by character in lower case), you can use the following command:

git ls-files -v | grep '^[a-z]' | cut -c 3- | tr '\012' '\000' | xargs -0 git update-index --no-assume-unchanged
  1. git ls-files -v will print all files with their status
  2. grep '^[a-z]' will filter files and select only assume unchanged
  3. cut -c 3- will remove status and leave only paths, cutting from the 3-rd character to the end
  4. tr '\012' '\000' will replace end of line character (\012) to zero character (\000)
  5. xargs -0 git update-index --no-assume-unchanged will pass all paths separated by zero character to git update-index --no-assume-unchanged to undo

How to do a FULL OUTER JOIN in MySQL?

Modified shA.t's query for more clarity:

-- t1 left join t2
SELECT t1.value, t2.value
FROM t1 LEFT JOIN t2 ON t1.value = t2.value   

    UNION ALL -- include duplicates

-- t1 right exclude join t2 (records found only in t2)
SELECT t1.value, t2.value
FROM t1 RIGHT JOIN t2 ON t1.value = t2.value
WHERE t1.value IS NULL 

Regex - Does not contain certain Characters

^[^<>]+$

The caret in the character class ([^) means match anything but, so this means, beginning of string, then one or more of anything except < and >, then the end of the string.

HTML - Arabic Support

If you don't even know where to get Arabic characters, but you want to display them, then you're doing something wrong.

Save files containing Arabic characters with encoding UTF-8. A good editor allows you to set the character encoding. In the HTML page, place the following after <head>:

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

If you're using XHTML:

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

That's it.

An alternative way (without messing with the encoding of a file), is using HTML escape sequences. This website does that jobs for you: http://www.htmlescape.net/

How to call a Python function from Node.js

The Boa is good for your needs, see the example which extends Python tensorflow keras.Sequential class in JavaScript.

const fs = require('fs');
const boa = require('@pipcook/boa');
const { tuple, enumerate } = boa.builtins();

const tf = boa.import('tensorflow');
const tfds = boa.import('tensorflow_datasets');

const { keras } = tf;
const { layers } = keras;

const [
  [ train_data, test_data ],
  info
] = tfds.load('imdb_reviews/subwords8k', boa.kwargs({
  split: tuple([ tfds.Split.TRAIN, tfds.Split.TEST ]),
  with_info: true,
  as_supervised: true
}));

const encoder = info.features['text'].encoder;
const padded_shapes = tuple([
  [ null ], tuple([])
]);
const train_batches = train_data.shuffle(1000)
  .padded_batch(10, boa.kwargs({ padded_shapes }));
const test_batches = test_data.shuffle(1000)
  .padded_batch(10, boa.kwargs({ padded_shapes }));

const embedding_dim = 16;
const model = keras.Sequential([
  layers.Embedding(encoder.vocab_size, embedding_dim),
  layers.GlobalAveragePooling1D(),
  layers.Dense(16, boa.kwargs({ activation: 'relu' })),
  layers.Dense(1, boa.kwargs({ activation: 'sigmoid' }))
]);

model.summary();
model.compile(boa.kwargs({
  optimizer: 'adam',
  loss: 'binary_crossentropy',
  metrics: [ 'accuracy' ]
}));

The complete example is at: https://github.com/alibaba/pipcook/blob/master/example/boa/tf2/word-embedding.js

I used Boa in another project Pipcook, which is to address the machine learning problems for JavaScript developers, we implemented ML/DL models upon the Python ecosystem(tensorflow,keras,pytorch) by the boa library.

Is there StartsWith or Contains in t sql with variables?

StartsWith

a) left(@edition, 15) = 'Express Edition'
b) charindex('Express Edition', @edition) = 1

Contains

charindex('Express Edition', @edition) >= 1

Examples

left function

set @isExpress = case when left(@edition, 15) = 'Express Edition' then 1 else 0 end

iif function (starting with SQL Server 2012)

set @isExpress = iif(left(@edition, 15) = 'Express Edition', 1, 0);

charindex function

set @isExpress = iif(charindex('Express Edition', @edition) = 1, 1, 0);

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

What basically happens is,According to default updatePolicy of maven.Maven will fetch the jars from repo on daily basis.So if during 1st attempt your internet was not working then it would not try to fetch this jar again untill 24hours spent.

Resolution :

Either use

mvn -U clean install

where -U will force update the repo

or use

<profiles>
    <profile>
      ...
      <repositories>
        <repository>
          <id>myRepo</id>
          <name>My Repository</name>
          <releases>
            <enabled>false</enabled>
            <updatePolicy>always</updatePolicy>
            <checksumPolicy>warn</checksumPolicy>
          </releases>
         </repository>
      </repositories>
      ...
    </profile>
  </profiles>

in your settings.xml

Compare two List<T> objects for equality, ignoring order

If you want them to be really equal (i.e. the same items and the same number of each item), I think that the simplest solution is to sort before comparing:

Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))

Edit:

Here is a solution that performs a bit better (about ten times faster), and only requires IEquatable, not IComparable:

public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2) {
  var cnt = new Dictionary<T, int>();
  foreach (T s in list1) {
    if (cnt.ContainsKey(s)) {
      cnt[s]++;
    } else {
      cnt.Add(s, 1);
    }
  }
  foreach (T s in list2) {
    if (cnt.ContainsKey(s)) {
      cnt[s]--;
    } else {
      return false;
    }
  }
  return cnt.Values.All(c => c == 0);
}

Edit 2:

To handle any data type as key (for example nullable types as Frank Tzanabetis pointed out), you can make a version that takes a comparer for the dictionary:

public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer) {
  var cnt = new Dictionary<T, int>(comparer);
  ...

jquery: get id from class selector

Nothing from this examples , works for me

for (var i = 0; i < res.results.length; i++) {
        $('#list_tags').append('<li class="dd-item" id="'+ res.results[i].id + '"><div class="dd-handle root-group">' + res.results[i].name + '</div></li>');
}

    $('.dd-item').click(function () {
    console.log($(this).attr('id'));
    });

Opening a CHM file produces: "navigation to the webpage was canceled"

The definitive solution is to allow the InfoTech protocol to work in the intranet zone.

Add the following value to the registry and the problem should be solved:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000001

More info here: http://support.microsoft.com/kb/896054

How I can check whether a page is loaded completely or not in web driver?

Here is how I would fix it, using a code snippet to give you a basic idea:

public class IFrame1 extends LoadableComponent<IFrame1> {

    private RemoteWebDriver driver;

    @FindBy(id = "iFrame1TextFieldTestInputControlID" ) public WebElement iFrame1TextFieldInput;
    @FindBy(id = "iFrame1TextFieldTestProcessButtonID" ) public WebElement copyButton;

    public IFrame1( RemoteWebDriver drv ) {
        super();
        this.driver = drv;
        this.driver.switchTo().defaultContent();
        waitTimer(1, 1000);
        this.driver.switchTo().frame("BodyFrame1");
        LOGGER.info("IFrame1 constructor...");
    }

    @Override
    protected void isLoaded() throws Error {        
        LOGGER.info("IFrame1.isLoaded()...");
        PageFactory.initElements( driver, this );
        try {
            assertTrue( "Page visible title is not yet available.", 
                    driver.findElementByCssSelector("body form#webDriverUnitiFrame1TestFormID h1")
                    .getText().equals("iFrame1 Test") );
        } catch ( NoSuchElementException e) {
            LOGGER.info("No such element." );
            assertTrue("No such element.", false);
        }
    }

    /**
     * Method: load
     * Overidden method from the LoadableComponent class.
     * @return  void
     * @throws  null
     */
    @Override
    protected void load() {
        LOGGER.info("IFrame1.load()...");
        Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
                .withTimeout(30, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring( NoSuchElementException.class ) 
                .ignoring( StaleElementReferenceException.class ) ;
        wait.until( ExpectedConditions.presenceOfElementLocated( 
                By.cssSelector("body form#webDriverUnitiFrame1TestFormID h1") ) );
    }
....

Best equivalent VisualStudio IDE for Mac to program .NET/C#

MonoDevelop from: http://monodevelop.com/

There is no equivalent to Visual Studio. However, for writing C# on Mac or Linux, you can't get better than MonoDevelop.

The Mac build is pre beta. From the MonoDevelop site on Mac:

The Mac OS X port of MonoDevelop is under active development and has not seen a stable release yet. Recent work described by Michael Hutchinson has focussed on improving the usability and stability of Monodevelop on the Mac. This work will be released in MonoDevelop 2.2. Right now it's not finished, and is very much an alpha.

Excel Date to String conversion

Here is a VBA approach:

Sub change()
    toText Sheets(1).Range("A1:F20")
End Sub

Sub toText(target As Range)
Dim cell As Range
    For Each cell In target
        cell.Value = cell.Text
        cell.NumberFormat = "@"
    Next cell
End Sub

If you are looking for a solution without programming, the Question should be moved to SuperUser.

How do you monitor network traffic on the iPhone?

You didnt specify the platform you use, so I assume it's a Mac ;-)

What I do is use a proxy. I use SquidMan, a standalone implementation of Squid

I start SquidMan on the Mac, then on the iPhone I enter the Proxy params in the General/Wifi Settings.

Then I can watch the HTTP trafic in the Console App, looking at the squid-access.log

If I need more infos, I switch to tcpdump, but I suppose WireShark should work too.

On postback, how can I check which control cause postback in Page_Init event

Either directly in form parameters or

string controlName = this.Request.Params.Get("__EVENTTARGET");

Edit: To check if a control caused a postback (manually):

// input Image with name="imageName"
if (this.Request["imageName"+".x"] != null) ...;//caused postBack

// Other input with name="name"
if (this.Request["name"] != null) ...;//caused postBack

You could also iterate through all the controls and check if one of them caused a postBack using the above code.

Find column whose name contains a specific string

# select columns containing 'spike'
df.filter(like='spike', axis=1)

You can also select by name, regular expression. Refer to: pandas.DataFrame.filter

How do I check if string contains substring?

I know that best way is str.indexOf(s) !== -1; http://hayageek.com/javascript-string-contains/

I suggest another way(str.replace(s1, "") !== str):

_x000D_
_x000D_
var str = "Hello World!", s1 = "ello", s2 = "elloo";_x000D_
alert(str.replace(s1, "") !== str);_x000D_
alert(str.replace(s2, "") !== str);
_x000D_
_x000D_
_x000D_

Convert from days to milliseconds

The best practice for this, in my opinion is:

TimeUnit.DAYS.toMillis(1);     // 1 day to milliseconds.
TimeUnit.MINUTES.toMillis(23); // 23 minutes to milliseconds.
TimeUnit.HOURS.toMillis(4);    // 4 hours to milliseconds.
TimeUnit.SECONDS.toMillis(96); // 96 seconds to milliseconds.

Select All Rows Using Entity Framework

You can use:

ptx.[tablename].Select( o => true)

How to discover number of *logical* cores on Mac OS X?

The following command gives you all information about your CPU

$ sysctl -a | sort | grep cpu

Eliminating NAs from a ggplot

Additionally, adding na.rm= TRUE to your geom_bar() will work.

ggplot(data = MyData,aes(x= the_variable, fill=the_variable, na.rm = TRUE)) + 
   geom_bar(stat="bin", na.rm = TRUE)

I ran into this issue with a loop in a time series and this fixed it. The missing data is removed and the results are otherwise uneffected.

default select option as blank

Today (2015-02-25)

This is valid HTML5 and sends a blank (not a space) to the server:

<option label=" "></option>

Verified validity on http://validator.w3.org/check

Verified behavior with Win7(IE11 IE10 IE9 IE8 FF35 Safari5.1) Ubuntu14.10(Chrome40, FF35) OSX_Yosemite(Safari8, Chrome40) Android(Samsung-Galaxy-S5)

The following also passes validation today, but passes some sort of space character too the server from most browsers (probably not desirable) and a blank on others (Chrome40/Linux passes a blank):

<option>&#160;</option>

Previously (2013-08-02)

According to my notes, the non-breaking-space entity inside the option tags shown above produced the following error in 2013:

Error: W3C Markup Validaton Service (Public): The first child option element of a select element with a required attribute and without a multiple attribute, and whose size is 1, must have either an empty value attribute, or must have no text content.

At that time, a regular space was valid XHTML4 and sent a blank (not a space) to the server from every browser:

<option> </option>

Future

It would make my heart glad if the spec was updated to explicitly allow a blank option. Preferably using the briefest syntax. Either of the following would be great:

<option />
<option></option>

Test File

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Test</title>
</head>
<body>
  <form action="index.html" method="post">
    <select name="sel">
      <option label=" "></option>
    </select>
  </form>
</body>
</html>

pandas read_csv index_col=None not working with delimiters at the end of each line

Quick Answer

Use index_col=False instead of index_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column.

More Detail

After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created):

index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.

from the documentation shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index.


EDIT 10/20/2014 - More information

I found another valuable entry that is specifically about trailing limiters and how to simply ignore them:

If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...

Ordinarily, you can achieve this behavior using the index_col option.

There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

You can use like the following

string result = null;
object value = cmd.ExecuteScalar();
 if (value != null)
 {
    result = value.ToString();
 }     
 conn.Close();
return result;

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

A function to access the values:

def shape(tensor):
    s = tensor.get_shape()
    return tuple([s[i].value for i in range(0, len(s))])

Example:

batch_size, num_feats = shape(logits)

How do I put double quotes in a string in vba?

I find the easiest way is to double up on the quotes to handle a quote.

Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)" 

Some people like to use CHR(34)*:

Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)" 

*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.

How do I get the current username in Windows PowerShell?

I thought it would be valuable to summarize and compare the given answers.

If you want to access the environment variable:

(easier/shorter/memorable option)

  • [Environment]::UserName -- @ThomasBratt
  • $env:username -- @Eoin
  • whoami -- @galaktor

If you want to access the Windows access token:

(more dependable option)

  • [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -- @MarkSeemann

If you want the name of the logged in user

(rather than the name of the user running the PowerShell instance)

  • $(Get-WMIObject -class Win32_ComputerSystem | select username).username -- @TwonOfAn on this other forum

Comparison

@Kevin Panko's comment on @Mark Seemann's answer deals with choosing one of the categories over the other:

[The Windows access token approach] is the most secure answer, because $env:USERNAME can be altered by the user, but this will not be fooled by doing that.

In short, the environment variable option is more succinct, and the Windows access token option is more dependable.

I've had to use @Mark Seemann's Windows access token approach in a PowerShell script that I was running from a C# application with impersonation.

The C# application is run with my user account, and it runs the PowerShell script as a service account. Because of a limitation of the way I'm running the PowerShell script from C#, the PowerShell instance uses my user account's environment variables, even though it is run as the service account user.

In this setup, the environment variable options return my account name, and the Windows access token option returns the service account name (which is what I wanted), and the logged in user option returns my account name.


Testing

Also, if you want to compare the options yourself, here is a script you can use to run a script as another user. You need to use the Get-Credential cmdlet to get a credential object, and then run this script with the script to run as another user as argument 1, and the credential object as argument 2.

Usage:

$cred = Get-Credential UserTo.RunAs
Run-AsUser.ps1 "whoami; pause" $cred
Run-AsUser.ps1 "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; pause" $cred

Contents of Run-AsUser.ps1 script:

param(
  [Parameter(Mandatory=$true)]
  [string]$script,
  [Parameter(Mandatory=$true)]
  [System.Management.Automation.PsCredential]$cred
)

Start-Process -Credential $cred -FilePath 'powershell.exe' -ArgumentList 'noprofile','-Command',"$script"

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Update for mid 2016:

The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!

Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!

Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!

Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot

  • Webpack
  • NPM as a build tool (no Gulp, Grunt or Bower)
  • React with Redux
  • ESLint
  • the list is long. Go and explore!

Your questions:

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

  • Everything belongs in package.json now

  • Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev (--save-dev updates your package.json by adding an entry to devDependencies)

  • Dependencies required for your application during runtime are in "dependencies" i.e. npm install lodash --save (--save updates your package.json by adding an entry to dependencies)

If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?

Always. Just because of comfort. When you add a flag (--save-dev or --save) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name is npm i -D package-name and shortcut for npm install --save package-name is npm i -S package-name

What's the best practice for primary keys in tables?

I suspect Steven A. Lowe's rolled up newspaper therapy is required for the designer of the original data structure.

As an aside, GUIDs as a primary key can be a performance hog. I wouldn't recommend it.

How to convert an ArrayList containing Integers to primitive int array?

It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.

Just go with Apache Commons

JavaScript: How do I print a message to the error console?

Install Firebug and then you can use console.log(...) and console.debug(...), etc. (see the documentation for more).

TypeError: $ is not a function WordPress

Just add this:

<script>
var $ = jQuery.noConflict();
</script>

to the head tag in header.php . Or in case you want to use the dollar sign in admin area (or somewhere, where header.php is not used), right before the place you want to use the it.

(There might be some conflicts that I'm not aware of, test it and if there are, use the other solutions offered here or at the link bellow.)

Source: http://www.wpdevsolutions.com/use-the-dollar-sign-in-wordpress-instead-of-jquery/

Custom Date/Time formatting in SQL Server

Not answering your question specifically, but isn't that something that should be handled by the presentation layer of your application. Doing it the way you describe creates extra processing on the database end as well as adding extra network traffic (assuming the database exists on a different machine than the application), for something that could be easily computed on the application side, with more rich date processing libraries, as well as being more language agnostic, especially in the case of your first example which contains the abbreviated month name. Anyway the answers others give you should point you in the right direction if you still decide to go this route.

Cannot deserialize the current JSON array (e.g. [1,2,3])


To read more than one json tip (array, attribute) I did the following.


var jVariable = JsonConvert.DeserializeObject<YourCommentaryClass>(jsonVariableContent);

change to

var jVariable = JsonConvert.DeserializeObject <List<YourCommentaryClass>>(jsonVariableContent);

Because you cannot see all the bits in the method used in the foreach loop. Example foreach loop

foreach (jsonDonanimSimple Variable in jVariable)
                {    
                    debugOutput(jVariable.Id.ToString());
                    debugOutput(jVariable.Header.ToString());
                    debugOutput(jVariable.Content.ToString());
                }

I also received an error in this loop and changed it as follows.

foreach (jsonDonanimSimple Variable in jVariable)
                    {    
                        debugOutput(Variable.Id.ToString());
                        debugOutput(Variable.Header.ToString());
                        debugOutput(Variable.Content.ToString());
                    }

how to destroy an object in java?

Short Answer - E

Answer isE given that the rest are plainly wrong, but ..

Long Answer - It isn't that simple; it depends ...

Simple fact is, the garbage collector may never decide to garbage collection every single object that is a viable candidate for collection, not unless memory pressure is extremely high. And then there is the fact that Java is just as susceptible to memory leaks as any other language, they are just harder to cause, and thus harder to find when you do cause them!

The following article has many good details on how memory management works and doesn't work and what gets take up by what. How generational Garbage Collectors work and Thanks for the Memory ( Understanding How the JVM uses Native Memory on Windows and Linux )

If you read the links, I think you will get the idea that memory management in Java isn't as simple as a multiple choice question.

How do I clear all variables in the middle of a Python script?

If you write a function then once you leave it all names inside disappear.

The concept is called namespace and it's so good, it made it into the Zen of Python:

Namespaces are one honking great idea -- let's do more of those!

The namespace of IPython can likewise be reset with the magic command %reset -f. (The -f means "force"; in other words, "don't ask me if I really want to delete all the variables, just do it.")

How to enable production mode?

Go to src/enviroments/enviroments.ts and enable the production mode

export const environment = {
  production: true
};

for Angular 2

Using python map and other functional tools

>>> from itertools import repeat
>>> for foo, bars in zip(foos, repeat(bars)):
...     print foo, bars
... 
1.0 [1, 2, 3]
2.0 [1, 2, 3]
3.0 [1, 2, 3]
4.0 [1, 2, 3]
5.0 [1, 2, 3]

Load image from resources area of project in C#

With and ImageBox named "ImagePreview FormStrings.MyImageNames contains a regular get/set string cast method, which are linked to a scrollbox type list. The images have the same names as the linked names on the list, except for the .bmp endings. All bitmaps are dragged into the resources.resx

Object rm = Properties.Resources.ResourceManager.GetObject(FormStrings.MyImageNames);
Bitmap myImage = (Bitmap)rm;
ImagePreview.Image = myImage;

How to Set JPanel's Width and Height?

please, something went xxx*x, and that's not true at all, check that

JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]

code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )

EDIT: forget setDefaultCloseOperation()

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FrameSize {

    private JFrame frm = new JFrame();
    private JPanel pnl = new JPanel();
    private JButton btn = new JButton("Get ScreenSize for JComponents");

    public FrameSize() {
        btn.setPreferredSize(new Dimension(400, 40));
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("JButton Size - " + btn.getSize());
                System.out.println("JPanel Size - " + pnl.getSize());
                System.out.println("JFrame Size - " + frm.getSize());
            }
        });
        pnl.setPreferredSize(new Dimension(640, 480));
        pnl.add(btn, BorderLayout.SOUTH);
        frm.add(pnl, BorderLayout.CENTER);
        frm.setLocation(150, 100);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
        frm.setResizable(false);
        frm.pack();
        frm.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FrameSize fS = new FrameSize();
            }
        });
    }
}

Where is Java Installed on Mac OS X?

The System Preferences then Java control panel then Java then View will show the exact location of the currently installed default JRE.

How to determine the version of Gradle?

At the root of your project type below in the console:

gradlew --version

You will have gradle version with other information (as a sample):

------------------------------------------------------------          
Gradle 5.1.1 << Here is the version                                                         
------------------------------------------------------------          

Build time:   2019-01-10 23:05:02 UTC                                 
Revision:     3c9abb645fb83932c44e8610642393ad62116807                

Kotlin DSL:   1.1.1                                                   
Kotlin:       1.3.11                                                  
Groovy:       2.5.4                                                   
Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018  
JVM:          10.0.2 ("Oracle Corporation" 10.0.2+13)                 
OS:           Windows 10 10.0 amd64                                   

I think for gradle version it uses gradle/wrapper/gradle-wrapper.properties under the hood.

how to set default main class in java?

As a comment, I had to allow a customer to execute a class in a jar which meant that the manifest file couldn't be modified (they couldn't be expected to do that). Thanks to the post by Anthony and samy-delux's comment, this is what the customer can now run to access the main of the specific class:

java -cp c:\path\to\jar\jarFile.jar com.utils.classpath -e -v textString

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

A filter converting any dates in various ISO-related formats (and who'd use anything else after reading the writings of the Mighty Kuhn?) on standard input to seconds-since-the-epoch time on standard output might serve to illustrate both parts:

martind@whitewater:~$ cat `which isoToEpoch`
#!/usr/bin/perl -w
use strict;
use Time::Piece;
# sudo apt-get install libtime-piece-perl
while (<>) {
  # date --iso=s:
  # 2007-02-15T18:25:42-0800
  # Other matched formats:
  # 2007-02-15 13:50:29 (UTC-0800)
  # 2007-02-15 13:50:29 (UTC-08:00)
  s/(\d{4}-\d{2}-\d{2}([T ])\d{2}:\d{2}:\d{2})(?:\.\d+)? ?(?:\(UTC)?([+\-]\d{2})?:?00\)?/Time::Piece->strptime ($1, "%Y-%m-%d$2%H:%M:%S")->epoch - (defined ($3) ? $3 * 3600 : 0)/eg;
  print;
}
martind@whitewater:~$ 

Regex date validation for yyyy-mm-dd

A simple one would be

\d{4}-\d{2}-\d{2}

Regular expression visualization

Debuggex Demo

but this does not restrict month to 1-12 and days from 1 to 31.

There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.

Cannot download Docker images behind a proxy

The complete solution for Windows, to configure the proxy settings.

< user>:< password>@< proxy-host>:< proxy-port>

You can configure it directly by right-clicking on settings, in the Docker icon, and then Proxies.

There you can configure the proxy address, port, user name, and password.

In this format:

< user>:< password>@< proxy-host>:< proxy-port>

Example:

"geronimous:[email protected]:8080"

Nothing more than this.

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

if you are using visual studio , enable the build property "Prefer 32-bit". see image below.

enter image description here