Programs & Examples On #Sharedservicesprovider

How can I see the entire HTTP request that's being sent by my Python application?

A simple method: enable logging in recent versions of Requests (1.x and higher.)

Requests uses the http.client and logging module configuration to control logging verbosity, as described here.

Demonstration

Code excerpted from the linked documentation:

import requests
import logging

# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
http_client.HTTPConnection.debuglevel = 1

# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

requests.get('https://httpbin.org/headers')

Example Output

$ python requests-logging.py 
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org
send: 'GET /headers HTTP/1.1\r\nHost: httpbin.org\r\nAccept-Encoding: gzip, deflate, compress\r\nAccept: */*\r\nUser-Agent: python-requests/1.2.0 CPython/2.7.3 Linux/3.2.0-48-generic\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: application/json
header: Date: Sat, 29 Jun 2013 11:19:34 GMT
header: Server: gunicorn/0.17.4
header: Content-Length: 226
header: Connection: keep-alive
DEBUG:requests.packages.urllib3.connectionpool:"GET /headers HTTP/1.1" 200 226

How to change the background color of Action Bar's Option Menu in Android 4.2?

I'm also struck with this same problem, finally i got simple solution. just added one line to action bar style.

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:textColorPrimary">@color/colorAccent</item>
    <item name="android:colorBackground">@color/colorAppWhite</item>
</style>

"android:colorBackground" is enough to change option menu background

An item with the same key has already been added

I faced similar exception. Check if all columns has header names( from select query in database) with exactly matching property names in model class.

Get request URL in JSP which is forwarded by Servlet

To get the current path from within the JSP file you can simply do one of the following:

<%= request.getContextPath() %>
<%= request.getRequestURI() %>
<%= request.getRequestURL() %>

Pass react component as props

Using this.props.children is the idiomatic way to pass instantiated components to a react component

const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>

When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div or span):

const Label = props => <span>{props.children}</span>
const Button = props => {
    const Inner = props.inner; // Note: variable name _must_ start with a capital letter 
    return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>

If what you want to do is to pass a children-like parameter as a prop, you can do that:

const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />

After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

this works with "NA" not for NA

comments = c("no","yes","NA")
  for (l in 1:length(comments)) {
    #if (!is.na(comments[l])) print(comments[l])
    if (comments[l] != "NA") print(comments[l])
  }

Convert Iterator to ArrayList

use google guava !

Iterable<String> fieldsIterable = ...
List<String> fields = Lists.newArrayList(fieldsIterable);

++

How to disable textbox from editing?

As mentioned above, you can change the property of the textbox "Read Only" to "True" from the properties window.

enter image description here

Swift Error: Editor placeholder in source file

Go to Product > Clean Build Folder

"Least Astonishment" and the Mutable Default Argument

This behavior is easy explained by:

  1. function (class etc.) declaration is executed only once, creating all default value objects
  2. everything is passed by reference

So:

def x(a=0, b=[], c=[], d=0):
    a = a + 1
    b = b + [1]
    c.append(1)
    print a, b, c
  1. a doesn't change - every assignment call creates new int object - new object is printed
  2. b doesn't change - new array is build from default value and printed
  3. c changes - operation is performed on same object - and it is printed

IndentationError: unexpected indent error

While the indentation errors are obvious in the StackOverflow page, they may not be in your editor. You have a mix of different indentation types here, 1, 4 and 8 spaces. You should always use four spaces for indentation, as per PEP8. You should also avoid mixing tabs and spaces.

I also recommend that you try to run your script using the '-tt' command-line option to determine when you accidentally mix tabs and spaces. Of course any decent editor will be able to highlight tabs versus spaces (such as Vim's 'list' option).

setTimeout in React Native

There looks to be an issue when the time of the phone/emulator is different to the one of the server (where react-native packager is running). In my case there was a 1 minute difference between the time of the phone and the computer. After synchronizing them (didn't do anything fancy, the phone was set on manual time, and I just set it to use the network(sim) provided time), everything worked fine. This github issue helped me find the problem.

How can I get the current contents of an element in webdriver

I believe prestomanifesto was on the right track. It depends on what kind of element it is. You would need to use element.get_attribute('value') for input elements and element.text to return the text node of an element.

You could check the WebElement object with element.tag_name to find out what kind of element it is and return the appropriate value.

This should help you figure out:

driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print element
print 'element.text: {0}'.format(element_text)
print 'element.get_attribute(\'value\'): {0}'.format(element_attribute_value)
driver.quit()

what is numeric(18, 0) in sql server 2008 r2

The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place. If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.

And to answer, "can I add (-10) in that column?" - Yes, you can.

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Codified version of all other answers (at the time of writing):

import java.io.*;

/**
 * This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
 * <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
 * of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
 * Also includes comments and observations from others on the same question, and my own experience.
 * <p>
 * <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
 * <p>
 * <b>JVM memory management crash course</b>:
 * Java virtual machine process' heap size is bounded by the maximum memory allowed.
 * The startup and maximum size can be configured by JVM arguments.
 * JVMs don't allocate the maximum memory on startup as the program running may never require that.
 * This is to be a good player and not waste system resources unnecessarily.
 * Instead they allocate some memory and then grow when new allocations require it.
 * The garbage collector will be run at times to clean up unused objects to prevent this growing.
 * Many parameters of this management such as when to grow/shrink or which GC to use
 * can be tuned via advanced configuration parameters on JVM startup.
 *
 * @see <a href="http://stackoverflow.com/a/42567450/253468">
 *     What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
 * @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
 *     Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
 *     Full VM options reference for Windows</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
 *     Full VM options reference for Linux, Mac OS X and Solaris</a>
 * @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
 *     Java HotSpot VM Options quick reference</a>
 */
public class SystemMemory {

    // can be white-box mocked for testing
    private final Runtime runtime = Runtime.getRuntime();

    /**
     * <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
     * <p>
     * <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
     */
    public long getAllocatedTotal() {
        return runtime.totalMemory();
    }

    /**
     * <b>Current allocated free memory</b>: space immediately ready for new objects.
     * <p>
     * <i>Caution</i>: this is not the total free available memory,
     * the JVM may grow the heap for new allocations.
     */
    public long getAllocatedFree() {
        return runtime.freeMemory();
    }

    /**
     * <b>Used memory</b>:
     * Java heap currently used by instantiated objects. 
     * <p>
     * <i>Caution</i>: May include no longer referenced objects, soft references, etc.
     * that will be swept away by the next garbage collection.
     */
    public long getUsed() {
        return getAllocatedTotal() - getAllocatedFree();
    }

    /**
     * <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
     * <p>
     * <i>Caution</i>: This may change over time, do not cache it!
     * There are some JVMs / garbage collectors that can shrink the allocated process memory.
     * <p>
     * <i>Caution</i>: If this is true, the JVM will likely run GC more often.
     */
    public boolean isAtMaximumAllocation() {
        return getAllocatedTotal() == getTotal();
        // = return getUnallocated() == 0;
    }

    /**
     * <b>Unallocated memory</b>: amount of space the process' heap can grow.
     */
    public long getUnallocated() {
        return getTotal() - getAllocatedTotal();
    }

    /**
     * <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
     * <p>
     * <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
     */
    public long getTotal() {
        return runtime.maxMemory();
    }

    /**
     * <b>Total free memory</b>: memory available for new Objects,
     * even at the cost of growing the allocated memory of the process.
     */
    public long getFree() {
        return getTotal() - getUsed();
        // = return getAllocatedFree() + getUnallocated();
    }

    /**
     * <b>Unbounded memory</b>: there is no inherent limit on free memory.
     */
    public boolean isBounded() {
        return getTotal() != Long.MAX_VALUE;
    }

    /**
     * Dump of the current state for debugging or understanding the memory divisions.
     * <p>
     * <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
     */
    public String getCurrentStats() {
        StringWriter backing = new StringWriter();
        PrintWriter out = new PrintWriter(backing, false);
        out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
                getAllocatedTotal(),
                (float)getAllocatedTotal() / (float)getTotal() * 100,
                getTotal(),
                isBounded()? "bounded" : "unbounded",
                isAtMaximumAllocation()? "maxed out" : "can grow",
                getUnallocated()
        );
        out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
                getUsed(),
                (float)getUsed() / (float)getTotal() * 100,
                getTotal(),
                (float)getUsed() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
                getFree(),
                (float)getFree() / (float)getTotal() * 100,
                getTotal(),
                getAllocatedFree(),
                (float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.flush();
        return backing.toString();
    }

    public static void main(String... args) {
        SystemMemory memory = new SystemMemory();
        System.out.println(memory.getCurrentStats());
    }
}

How do I add an "Add to Favorites" button or link on my website?

I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:

jQuery('.bookmarkMeLink').click(function() {
    if (window.sidebar && window.sidebar.addPanel) { 
        // Mozilla Firefox Bookmark
        window.sidebar.addPanel(document.title,window.location.href,'');
    }
    else if(window.sidebar && jQuery.browser.mozilla){
        //for other version of FF add rel="sidebar" to link like this:
        //<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
        jQuery(this).attr('rel', 'sidebar');
    }
    else if(window.external && ('AddFavorite' in window.external)) { 
        // IE Favorite
        window.external.AddFavorite(location.href,document.title); 
    } else if(window.opera && window.print) { 
        // Opera Hotlist
        this.title=document.title;
        return true;
    } else { 
        // webkit - safari/chrome
        alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');

    }
});

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use us jquery function getJson :

$(function(){
    $.getJSON('/api/rest/abc', function(data) {
        console.log(data);
    });
});

How do I associate file types with an iPhone application?

To deal with any type of files for my own APP, I use this configuration for CFBundleDocumentTypes:

    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeName</key>
            <string>IPA</string>
            <key>LSItemContentTypes</key>
            <array>
                <string>public.item</string>
                <string>public.content</string>
                <string>public.data</string>
                <string>public.database</string>
                <string>public.composite-content</string>
                <string>public.contact</string>
                <string>public.archive</string>
                <string>public.url-name</string>
                <string>public.text</string>
                <string>public.plain-text</string>
                <string>public.source-code</string>
                <string>public.executable</string>
                <string>public.script</string>
                <string>public.shell-script</string>
                <string>public.xml</string>
                <string>public.symlink</string>
                <string>org.gnu.gnu-zip-archve</string>
                <string>org.gnu.gnu-tar-archive</string>
                <string>public.image</string>
                <string>public.movie</string>
                <string>public.audiovisual-?content</string>
                <string>public.audio</string>
                <string>public.directory</string>
                <string>public.folder</string>
                <string>com.apple.bundle</string>
                <string>com.apple.package</string>
                <string>com.apple.plugin</string>
                <string>com.apple.application-?bundle</string>
                <string>com.pkware.zip-archive</string>
                <string>public.filename-extension</string>
                <string>public.mime-type</string>
                <string>com.apple.ostype</string>
                <string>com.apple.nspboard-typ</string>
                <string>com.adobe.pdf</string>
                <string>com.adobe.postscript</string>
                <string>com.adobe.encapsulated-?postscript</string>
                <string>com.adobe.photoshop-?image</string>
                <string>com.adobe.illustrator.ai-?image</string>
                <string>com.compuserve.gif</string>
                <string>com.microsoft.word.doc</string>
                <string>com.microsoft.excel.xls</string>
                <string>com.microsoft.powerpoint.?ppt</string>
                <string>com.microsoft.waveform-?audio</string>
                <string>com.microsoft.advanced-?systems-format</string>
                <string>com.microsoft.advanced-?stream-redirector</string>
                <string>com.microsoft.windows-?media-wmv</string>
                <string>com.microsoft.windows-?media-wmp</string>
                <string>com.microsoft.windows-?media-wma</string>
                <string>com.apple.keynote.key</string>
                <string>com.apple.keynote.kth</string>
                <string>com.truevision.tga-image</string>
            </array>
            <key>CFBundleTypeIconFiles</key>
            <array>
                <string>Icon-76@2x</string>
            </array>
        </dict>
    </array>

Is it possible to set an object to null?

"an object" of what type?

You can certainly assign NULL (and nullptr) to objects of pointer types, and it is implementation defined if you can assign NULL to objects of arithmetic types.

If you mean objects of some class type, the answer is NO (excepting classes that have operator= accepting pointer or arithmetic types)

"empty" is more plausible, as many types have both copy assignment and default construction (often implicitly). To see if an existing object is like a default constructed one, you will also need an appropriate bool operator==

Genymotion Android emulator - adb access?

Simply do this, with genymotion device running you can open Virtual Box , and see that there is a VM for you device , then go to network Settings of the VM, NAT and do port forwarding of local 5555 to remote 5555 screen attachedVirtual Box Nat Network Port forwarding

Why does Git say my master branch is "already up to date" even though it is not?

As the other posters say, pull merges changes from upstream into your repository. If you want to replace what is in your repository with what is in upstream, you have several options. Off the cuff, I'd go with

git checkout HEAD^1  # Get off your repo's master.. doesn't matter where you go, so just go back one commit
git branch -d master  # Delete your repo's master branch
git checkout -t upstream/master  # Check out upstream's master into a local tracking branch of the same name

Calling Python in Java?

This gives a pretty good overview over the current options. Some of which are named in other answers. Jython is not usable until they decide to implement Python 3.x and many of the other projects are coming form the python side and want to access java. But there are a few options still, to name something which has not been named yet: gRPC

Is there a portable way to get the current username in Python?

You can probably use:

os.environ.get('USERNAME')

or

os.environ.get('USER')

But it's not going to be safe because environment variables can be changed.

How do you add Boost libraries in CMakeLists.txt?

Additional information to abouve answers for those still having problems.

  1. Last version of Cmake's FindBoost.cmake may not content last version fo Boost. Add it if needed.
  2. Use -DBoost_DEBUG=0 configuration flag to see info on problems.
  3. See for library naming format. Use Boost_COMPILER and Boost_ARCHITECTURE suffix vars if needed.

Apply function to each element of a list

Sometimes you need to apply a function to the members of a list in place. The following code worked for me:

>>> def func(a, i):
...     a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']

Please note, the output of map() is passed to the list constructor to ensure the list is converted in Python 3. The returned list filled with None values should be ignored, since our purpose was to convert list a in place

How can I exit from a javascript function?

You should use return as in:

function refreshGrid(entity) {
  var store = window.localStorage;
  var partitionKey;
  if (exit) {
    return;
  }

Using a PHP variable in a text input value = statement

I have been doing PHP for my project, and I can say that the following code works for me. You should try it.

echo '<input type = "text" value = '.$idtest.'>'; 

Javascript Regex: How to put a variable inside a regular expression?

You can create regular expressions in JS in one of two ways:

  1. Using regular expression literal - /ab{2}/g
  2. Using the regular expression constructor - new RegExp("ab{2}", "g") .

Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is

new RegExp(regularExpressionString, modifiersString)

You can embed variables as part of the regularExpressionString. For example,

var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g") 

This will match any appearance of the pattern cdcdcd.

Accessing dict keys like an attribute?

You can do it using this class I just made. With this class you can use the Map object like another dictionary(including json serialization) or with the dot notation. I hope help you:

class Map(dict):
    """
    Example:
    m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
    """
    def __init__(self, *args, **kwargs):
        super(Map, self).__init__(*args, **kwargs)
        for arg in args:
            if isinstance(arg, dict):
                for k, v in arg.iteritems():
                    self[k] = v

        if kwargs:
            for k, v in kwargs.iteritems():
                self[k] = v

    def __getattr__(self, attr):
        return self.get(attr)

    def __setattr__(self, key, value):
        self.__setitem__(key, value)

    def __setitem__(self, key, value):
        super(Map, self).__setitem__(key, value)
        self.__dict__.update({key: value})

    def __delattr__(self, item):
        self.__delitem__(item)

    def __delitem__(self, key):
        super(Map, self).__delitem__(key)
        del self.__dict__[key]

Usage examples:

m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
# Add new key
m.new_key = 'Hello world!'
print m.new_key
print m['new_key']
# Update values
m.new_key = 'Yay!'
# Or
m['new_key'] = 'Yay!'
# Delete key
del m.new_key
# Or
del m['new_key']

How do you determine what SQL Tables have an identity column programmatically

Another potential way to do this for SQL Server, which has less reliance on the system tables (which are subject to change, version to version) is to use the INFORMATION_SCHEMA views:

select COLUMN_NAME, TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME 

How to change the background colour's opacity in CSS

Use rgba as most of the commonly used browsers supports it..

.social img:hover {
 background-color: rgba(0, 0, 0, .5)
}

how to sort pandas dataframe from one column

This one worked for me:

df=df.sort_values(by=[2])

Whereas:

df=df.sort_values(by=['2']) 

is not working.

Removing index column in pandas when reading a csv

df.reset_index(drop=True, inplace=True)

Returning binary file from controller in ASP.NET Web API

The overload that you're using sets the enumeration of serialization formatters. You need to specify the content type explicitly like:

httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

Merging cells in Excel using Apache POI

syntax is:

sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));

Example:

sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));

Here the cell 0 to cell 5 will be merged of the 4th row.

ImportError: No module named 'google'

I faced the same issue, I was trying to import translate from google.cloud but kept getting same error.

This is what I did

  1. pip install protobuf
  2. pip install google-cloud-translate

and to install storage service from google google-cloud-storageshould be installed separately

Ref - https://cloud.google.com/python/

Can I override and overload static methods in Java?

Static methods can not be overridden because there is nothing to override, as they would be two different methods. For example

static class Class1 {
    public static int Method1(){
          return 0;
    }
}
static class Class2 extends Class1 {
    public static int Method1(){
          return 1;
    }

}
public static class Main {
    public static void main(String[] args){
          //Must explicitly chose Method1 from Class1 or Class2
          Class1.Method1();
          Class2.Method1();
    }
}

And yes static methods can be overloaded just like any other method.

Check if null Boolean is true results in exception

as your variable bool is pointing to a null, you will always get a NullPointerException, you need to initialize the variable first somewhere with a not null value, and then modify it.

App crashing when trying to use RecyclerView on android 5.0

I experienced this crash even though I had the RecyclerView.LayoutManager properly set. I had to move the RecyclerView initialization code into the onViewCreated(...) callback to fix this issue.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_listing, container, false);
    rootView.setTag(TAG);
    return inflater.inflate(R.layout.fragment_listing, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mLayoutManager = new LinearLayoutManager(getActivity());
    mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

    mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new ListingAdapter(mListing);
    mRecyclerView.setAdapter(mAdapter);
}

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

I hope following program will solve your problem

String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);        

Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" +         cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);    

How can I pass command-line arguments to a Perl program?

You can access them directly, by assigning the special variable @ARGV to a list of variables. So, for example:

( $st, $prod, $ar, $file, $chart, $e, $max, $flag ,$id) = @ARGV;

perl tmp.pl 1 2 3 4 5

enter image description here

Difference between \b and \B in regex

\b is used as word boundary

word = "categorical cat"

Find all "cat" in the above word

without \b

re.findall(r'cat',word)
['cat', 'cat']

with \b

re.findall(r'\bcat\b',word)
['cat']

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel with or without the query builder. You can use the following official approach.

Entity::upsert([
    ['name' => 'Pierre Yem Mback', 'city' => 'Eseka', 'salary' => 10000000],
    ['name' => 'Dial rock 360', 'city' => 'Yaounde', 'salary' => 20000000],
    ['name' => 'Ndibou La Menace', 'city' => 'Dakar', 'salary' => 40000000]
], ['name', 'city'], ['salary']);

Right Align button in horizontal LinearLayout

You need to add gravity to the layout not the Button, gravity in button settings is for Text inside the button

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_gravity="right" 
android:layout_height="wrap_content"             
android:orientation="horizontal" 
android:layout_marginTop="35dp">

How to create a link to another PHP page

echo "<a href='index.php'>Index Page</a>";

if you wanna use html tag like anchor tag you have to put in echo

Pad a number with leading zeros in JavaScript

Not a lot of "slick" going on so far:

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

When you initialize an array with a number, it creates an array with the length set to that value so that the array appears to contain that many undefined elements. Though some Array instance methods skip array elements without values, .join() doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a + 1 in there.

Example usage:

pad(10, 4);      // 0010
pad(9, 4);       // 0009
pad(123, 4);     // 0123

pad(10, 4, '-'); // --10

Passing properties by reference in C#

You can't ref a property, but if your functions need both get and set access you can pass around an instance of a class with a property defined:

public class Property<T>
{
    public delegate T Get();
    public delegate void Set(T value);
    private Get get;
    private Set set;
    public T Value {
        get {
            return get();
        }
        set {
            set(value);
        }
    }
    public Property(Get get, Set set) {
        this.get = get;
        this.set = set;
    }
}

Example:

class Client
{
    private string workPhone; // this could still be a public property if desired
    public readonly Property<string> WorkPhone; // this could be created outside Client if using a regular public property
    public int AreaCode { get; set; }
    public Client() {
        WorkPhone = new Property<string>(
            delegate () { return workPhone; },
            delegate (string value) { workPhone = value; });
    }
}
class Usage
{
    public void PrependAreaCode(Property<string> phone, int areaCode) {
        phone.Value = areaCode.ToString() + "-" + phone.Value;
    }
    public void PrepareClientInfo(Client client) {
        PrependAreaCode(client.WorkPhone, client.AreaCode);
    }
}

How to set value in @Html.TextBoxFor in Razor syntax?

It is going to write the value of your property model.Destination

This is by design. You'll want to populate your Destination property with the value you want in your controller before returning your view.

Revert to Eclipse default settings

Just delete your .metadata folder in your workspace and start eclipse....:)

Determine Whether Two Date Ranges Overlap

(StartA <= EndB) and (EndA >= StartB)

Proof:
Let ConditionA Mean that DateRange A Completely After DateRange B

_                        |---- DateRange A ------|
|---Date Range B -----|                          _

(True if StartA > EndB)

Let ConditionB Mean that DateRange A is Completely Before DateRange B

|---- DateRange A -----|                        _ 
_                          |---Date Range B ----|

(True if EndA < StartB)

Then Overlap exists if Neither A Nor B is true -
(If one range is neither completely after the other,
nor completely before the other, then they must overlap.)

Now one of De Morgan's laws says that:

Not (A Or B) <=> Not A And Not B

Which translates to: (StartA <= EndB) and (EndA >= StartB)


NOTE: This includes conditions where the edges overlap exactly. If you wish to exclude that,
change the >= operators to >, and <= to <


NOTE2. Thanks to @Baodad, see this blog, the actual overlap is least of:
{ endA-startA, endA - startB, endB-startA, endB - startB }

(StartA <= EndB) and (EndA >= StartB) (StartA <= EndB) and (StartB <= EndA)


NOTE3. Thanks to @tomosius, a shorter version reads:
DateRangesOverlap = max(start1, start2) < min(end1, end2)
This is actually a syntactical shortcut for what is a longer implementation, which includes extra checks to verify that the start dates are on or before the endDates. Deriving this from above:

If start and end dates can be out of order, i.e., if it is possible that startA > endA or startB > endB, then you also have to check that they are in order, so that means you have to add two additional validity rules:
(StartA <= EndB) and (StartB <= EndA) and (StartA <= EndA) and (StartB <= EndB) or:
(StartA <= EndB) and (StartA <= EndA) and (StartB <= EndA) and (StartB <= EndB) or,
(StartA <= Min(EndA, EndB) and (StartB <= Min(EndA, EndB)) or:
(Max(StartA, StartB) <= Min(EndA, EndB)

But to implement Min() and Max(), you have to code, (using C ternary for terseness),:
(StartA > StartB? Start A: StartB) <= (EndA < EndB? EndA: EndB)

How can you zip or unzip from the script using ONLY Windows' built-in capabilities?

Tar

Windows 10 includes tar.exe:

# example 1
tar.exe -a -c -f out.zip in.txt
# example 2
tar.exe -x -f out.zip

https://techcommunity.microsoft.com/t5/containers/-/ba-p/382409

If you have older Windows, you can still download it:

https://github.com/libarchive/libarchive/releases

PowerShell

# example 1
Compress-Archive in.txt out.zip
# example 2
Expand-Archive out.zip

https://docs.microsoft.com/powershell/module/microsoft.powershell.archive

Directory

For both tools, you can use a file or directory for the input.

LINQ to Entities does not recognize the method

I got the same error in this code:

 var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

this was the exactly error:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'

I solved this way:

var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated

NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory

How to get HttpClient returning status code and response body?

BasicResponseHandler throws if the status is not 2xx. See its javadoc.

Here is how I would do it:

HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream

Or you can also write a ResponseHandler starting from BasicResponseHandler source that don't throw when the status is not 2xx.

How to write a multiline command?

If you came here looking for an answer to this question but not exactly the way the OP meant, ie how do you get multi-line CMD to work in a single line, I have a sort of dangerous answer for you.

Trying to use this with things that actually use piping, like say findstr is quite problematic. The same goes for dealing with elses. But if you just want a multi-line conditional command to execute directly from CMD and not via a batch file, this should do work well.

Let's say you have something like this in a batch that you want to run directly in command prompt:

@echo off
for /r %%T IN (*.*) DO (
    if /i "%%~xT"==".sln" (
        echo "%%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file
        echo Dumping SLN file contents
        type "%%~T"
    )
)

Now, you could use the line-continuation carat (^) and manually type it out like this, but warning, it's tedious and if you mess up you can learn the joy of typing it all out again.

Well, it won't work with just ^ thanks to escaping mechanisms inside of parentheses shrug At least not as-written. You actually would need to double up the carats like so:

@echo off ^
More? for /r %T IN (*.sln) DO (^^
More? if /i "%~xT"==".sln" (^^
More? echo "%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file^^
More? echo Dumping SLN file contents^^
More? type "%~T"))

Instead, you can be a dirty sneaky scripter from the wrong side of the tracks that don't need no carats by swapping them out for a single pipe (|) per continuation of a loop/expression:

@echo off
for /r %T IN (*.sln) DO if /i "%~xT"==".sln" echo "%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file | echo Dumping SLN file contents | type "%~T"

Android Studio - Auto complete and other features not working

In my case, when I switch keyboard language to English, the auto complete works again.

Cannot push to Git repository on Bitbucket

Just need config file under ~/.ssh directory
ref : https://confluence.atlassian.com/bitbucket/set-up-ssh-for-git-728138079.html
add bellow configuration in config file

Host bitbucket.org
 IdentityFile ~/.ssh/<privatekeyfile>

How to check if a variable is null or empty string or all whitespace in JavaScript?

isEmptyOrSpaces(str){
    return !str || str.trim() === '';
}

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

Some old gradle tools cannot copy .so files into build folder by somehow, manually copying these files into build folder as below can solve the problem:

build/intermediates/rs/{build config}/{support architecture}/

build config: beta/production/sit/uat

support architecture: armeabi/armeabi-v7a/mips/x86

creating an array of structs in c++

You can't use an initialization-list for a struct after it's been initialized. You've already default-initialized the two Customer structs when you declared the array customerRecords. Therefore you're going to have either use member-access syntax to set the value of the non-static data members, initialize the structs using a list of initialization lists when you declare the array itself, or you can create a constructor for your struct and use the default operator= member function to initialize the array members.

So either of the following could work:

Customer customerRecords[2];
customerRecords[0].uid = 25;
customerRecords[0].name = "Bob Jones";
customerRecords[1].uid = 25;
customerRecords[1].namem = "Jim Smith";

Or if you defined a constructor for your struct like:

Customer::Customer(int id, string input_name): uid(id), name(input_name) {}

You could then do:

Customer customerRecords[2];
customerRecords[0] = Customer(25, "Bob Jones");
customerRecords[1] = Customer(26, "Jim Smith");

Or you could do the sequence of initialization lists that Tuomas used in his answer. The reason his initialization-list syntax works is because you're actually initializing the Customer structs at the time of the declaration of the array, rather than allowing the structs to be default-initialized which takes place whenever you declare an aggregate data-structure like an array.

Create a unique number with javascript time

let now = new Date();
let timestamp = now.getFullYear().toString();
let month = now.getMonth() + 1;
timestamp += (month < 10 ? '0' : '') + month.toString();
timestamp += (now.getDate() < 10 ? '0' : '') + now.getDate().toString();
timestamp += (now.getHours() < 10 ? '0' : '') + now.getHours().toString();
timestamp += (now.getMinutes() < 10 ? '0' : '') + now.getMinutes().toString();
timestamp += (now.getSeconds() < 10 ? '0' : '') + now.getSeconds().toString();
timestamp += (now.getMilliseconds() < 100 ? '0' : '') + now.getMilliseconds().toString();

remove script tag from HTML content

$html = <<<HTML
...
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$tags_to_remove = array('script','style','iframe','link');
foreach($tags_to_remove as $tag){
    $element = $dom->getElementsByTagName($tag);
    foreach($element  as $item){
        $item->parentNode->removeChild($item);
    }
}
$html = $dom->saveHTML();

MySQL my.cnf file - Found option without preceding group

What worked for me:

  • Open my.ini with Notepad++
  • Encoding --> convert to ANSI
  • save

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

It is possible to do everything you want. Aaron's answer was not quite complete.

His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.

The following code snippet grabs the first line of a file and inserts it into the table @Lines:

declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);

declare @Lines table (
    line varchar(8000)
);

declare @sql varchar(8000) = ' 
    create table #tmp (
        line varchar(8000)
    );

    bulk insert #tmp
        from '''+@filename+'''
        with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');

    select * from #tmp';

insert into @Lines
    exec(@sql);

select * from @lines

Force browser to refresh css, javascript, etc

<script src="foo.js?<?php echo date('YmdHis',filemtime('foo.js'));?>"></script>

It will refresh if modify.

How do ports work with IPv6?

The protocols used in IPv6 are the same as the protocols in IPv4. The only thing that changed between the two versions is the addressing scheme, DHCP [DHCPv6] and ICMP [ICMPv6]. So basically, anything TCP/UDP related, including the port range (0-65535) remains unchanged.

Edit: Port 0 is a reserved port in TCP but it does exist. See RFC793

How can I create an object and add attributes to it?

There are a few ways to reach this goal. Basically you need an object which is extendable.

obj.a = type('Test', (object,), {})  
obj.a.b = 'fun'  

obj.b = lambda:None

class Test:
  pass
obj.c = Test()

Open page in new window without popup blocking

A browser will only open a tab/popup without the popup blocker warning if the command to open the tab/popup comes from a trusted event. That means the user has to actively click somewhere to open a popup.

In your case, the user performs a click so you have the trusted event. You do lose that trusted context, however, by performing the Ajax request. Your success handler does not have that event anymore. The only way to circumvent this is to perform a synchronous Ajax request which will block your browser while it runs, but will preserve the event context.

In jQuery this should do the trick:

$.ajax({
 url: 'http://yourserver/',
 data: 'your image',
 success: function(){window.open(someUrl);},
 async: false
});

Here is your answer: Open new tab without popup blocker after ajax call on user click

Bootstrap modal appearing under background

For me the easiest solution was to put my modal in a wrapper with absolute position and z-index higher than .modal-backdrop. Since modal-backdrop (at least in my case) has z-index 1050:

_x000D_
_x000D_
.my-modal-wrapper {_x000D_
  position: absolute;_x000D_
  z-index: 1060;_x000D_
}
_x000D_
<div class="my-modal-wrapper"></div>
_x000D_
_x000D_
_x000D_

How does a Java HashMap handle different objects with the same hash code?

Here is a rough description of HashMap's mechanism, for Java 8 version, (it might be slightly different from Java 6).


Data structures

  • Hash table
    Hash value is calculated via hash() on key, and it decide which bucket of the hashtable to use for a given key.
  • Linked list (singly)
    When count of elements in a bucket is small, a singly linked list is used.
  • Red-Black tree
    When count of elements in a bucket is large, a red-black tree is used.

Classes (internal)

  • Map.Entry
    Represent a single entity in map, the key/value entity.
  • HashMap.Node
    Linked list version of node.

    It could represent:

    • A hash bucket.
      Because it has a hash property.
    • A node in singly linked list, (thus also head of linkedlist).
  • HashMap.TreeNode
    Tree version of node.

Fields (internal)

  • Node[] table
    The bucket table, (head of the linked lists).
    If a bucket don't contains elements, then it's null, thus only take space of a reference.
  • Set<Map.Entry> entrySet Set of entities.
  • int size
    Number of entities.
  • float loadFactor
    Indicate how full the hash table is allowed, before resizing.
  • int threshold
    The next size at which to resize.
    Formula: threshold = capacity * loadFactor

Methods (internal)

  • int hash(key)
    Calculate hash by key.
  • How to map hash to bucket?
    Use following logic:

    static int hashToBucket(int tableSize, int hash) {
        return (tableSize - 1) & hash;
    }
    

About capacity

In hash table, capacity means the bucket count, it could be get from table.length.
Also could be calculated via threshold and loadFactor, thus no need to be defined as a class field.

Could get the effective capacity via: capacity()


Operations

  • Find entity by key.
    First find the bucket by hash value, then loop linked list or search sorted tree.
  • Add entity with key.
    First find the bucket according to hash value of key.
    Then try find the value:
    • If found, replace the value.
    • Otherwise, add a new node at beginning of linked list, or insert into sorted tree.
  • Resize
    When threshold reached, will double hashtable's capacity(table.length), then perform a re-hash on all elements to rebuild the table.
    This could be an expensive operation.

Performance

  • get & put
    Time complexity is O(1), because:
    • Bucket is accessed via array index, thus O(1).
    • Linked list in each bucket is of small length, thus could view as O(1).
    • Tree size is also limited, because will extend capacity & re-hash when element count increase, so could view it as O(1), not O(log N).

Section vs Article HTML5

A section is basically a wrapper for h1 (or other h tags) and the content that corresponds to this. An article is essentially a document within your document that is repeated or paginated...like each blog post on your document can be an article, or each comment on your document can be an article.

Is quitting an application frowned upon?

If you specify API >= 16, Activity#finishAffinity() meets your needs.

Reduce git repository size

git gc --aggressive is one way to force the prune process to take place (to be sure: git gc --aggressive --prune=now). You have other commands to clean the repo too. Don't forget though, sometimes git gc alone can increase the size of the repo!

It can be also used after a filter-branch, to mark some directories to be removed from the history (with a further gain of space); see here. But that means nobody is pulling from your public repo. filter-branch can keep backup refs in .git/refs/original, so that directory can be cleaned too.

Finally, as mentioned in this comment and this question; cleaning the reflog can help:

git reflog expire --all --expire=now
git gc --prune=now --aggressive

An even more complete, and possibly dangerous, solution is to remove unused objects from a git repository


Update Feb. 2021, eleven years later: the new git maintenance command (man page) should supersede git gc, and can be scheduled.

Datagridview full row selection but get single cell value

Simplest code is DataGridView1.SelectedCells(column_index).Value

As an example, for the first selected cell:

DataGridView1.SelectedCells(0).Value

Why is the time complexity of both DFS and BFS O( V + E )

An intuitive explanation to this is by simply analysing a single loop:

  1. visit a vertex -> O(1)
  2. a for loop on all the incident edges -> O(e) where e is a number of edges incident on a given vertex v.

So the total time for a single loop is O(1)+O(e). Now sum it for each vertex as each vertex is visited once. This gives

For every V
=> 

    O(1)
    +

    O(e)

=> O(V) + O(E)

Multipart forms from C# client

In the version of .NET I am using you also have to do this:

System.Net.ServicePointManager.Expect100Continue = false;

If you don't, the HttpWebRequest class will automatically add the Expect:100-continue request header which fouls everything up.

Also I learned the hard way that you have to have the right number of dashes. whatever you say is the "boundary" in the Content-Type header has to be preceded by two dashes

--THEBOUNDARY

and at the end

--THEBOUNDARY--

exactly as it does in the example code. If your boundary is a lot of dashes followed by a number then this mistake won't be obvious by looking at the http request in a proxy server

What's the difference between next() and nextLine() methods from Scanner class?

From javadocs

next() Returns the next token if it matches the pattern constructed from the specified string. nextLine() Advances this scanner past the current line and returns the input that was skipped.

Which one you choose depends which suits your needs best. If it were me reading a whole file I would go for nextLine until I had all the file.

Where to download visual studio express 2005?

As of late April 2009, Microsoft has discontinued all previous versions of Visual Studio Express, including 2005. It is no longer possible to obtain these previous versions from the Microsoft website.

From Here

Asynchronously load images with jQuery

use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:

$("#img_id").error(function(){
  //$(this).hide();
  //alert("img not loaded");
  //some action you whant here
});

careful - .error() event will not trigger when the src attribute is empty for an image.

How to get the caller class in Java

This is the most efficient way to get just the callers class. Other approaches take an entire stack dump and only give you the class name.

However, this class in under sun.* which is really for internal use. This means that it may not work on other Java platforms or even other Java versions. You have to decide whether this is a problem or not.

Visual Studio: LINK : fatal error LNK1181: cannot open input file

In Linker, general, additional library directories, add the directory to the .dll or .libs you have included in Linker, Input. It does not work if you put this in VC++ Directories, Library Directories.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

This bug still exists in 0.8+/1.10

With Jackson

compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.2.2'

I had to include as well as the above suggestion before it would compile

exclude 'META-INF/services/com.fasterxml.jackson.core.JsonFactory'

Find a value in DataTable

AFAIK, there is nothing built in for searching all columns. You can use Find only against the primary key. Select needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.

PowerShell array initialization

Here's another idea. You have to remember, that it's .NET underneath:

$arr = [System.Array]::CreateInstance([System.Object], 5)
$arr.GetType()
$arr.Length

$arr = [Object[]]::new(5)
$arr.GetType()
$arr.Length

Result:

IsPublic IsSerial Name                                     BaseType                                                                                               
-------- -------- ----                                     --------                                                                                               
True     True     Object[]                                 System.Array                                                                                           
5
True     True     Object[]                                 System.Array                                                                                           
5

Using new() has one distinct advantage: when you're programming in ISE and want to create an object, ISE will give you hint with all paramer combinations and their types. You don't have that with New-Object, where you have to remember the types and order of arguments.

ISE IntelliSense for new object

how to open Jupyter notebook in chrome on windows

See response on this thread that has worked for me:

https://stackoverflow.com/a/62275293/11141700

NOTE - Additional STEP 3 that has made the difference for me compared to similar approaches suggested here

In short:

Step 1 - Generate config for Jupyter Notebook:

jupyter notebook --generate-config

Step 2 - Edit the config file using "nano" or other editor

The config fileshould be under your home directory under ".jupyter" folder:

~/.jupyter/jupyter_notebook_config.py

Step 3 - Disable launching browser by redirecting file

First comment out the line, then change True to False:

c.NotebookApp.use_redirect_file = False

Step 4 - add a line to your .bashrc file to set the BROWSER path

export BROWSER='/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'

For me it was Chrome under my Windows Program File. Otherwise any linux installation under WSL doesn't have a native browser to launch, so need to set it to the Windows executable.

Step 5 - restart .bashrc

source .bashrc

SQL: How To Select Earliest Row

Simply use min()

SELECT company, workflow, MIN(date) 
FROM workflowTable 
GROUP BY company, workflow

Javascript Equivalent to PHP Explode()

I used slice, split and join You can just write one line of code

      let arrys = (str.split(":").slice(1)).join(":");

How to use refs in React with Typescript

Just to add a different approach - you can simply cast your ref, something like:

let myInputElement: Element = this.refs["myInput"] as Element

Calling a JavaScript function returned from an Ajax response

PHP side code Name of file class.sendCode.php

<?php
class  sendCode{ 

function __construct($dateini,$datefin) {

            echo $this->printCode($dateini,$datefin);
        }

    function printCode($dateini,$datefin){

        $code =" alert ('code Coming from AJAX {$this->dateini} and {$this->datefin}');";
//Insert all the code you want to execute, 
//only javascript or Jquery code , dont incluce <script> tags
            return $code ;
    }
}
new sendCode($_POST['dateini'],$_POST['datefin']);

Now from your Html page you must trigger the ajax function to send the data.

....  <script src="http://code.jquery.com/jquery-1.9.1.js"></script> ....
Date begin: <input type="text" id="startdate"><br>
Date end : <input type="text" id="enddate"><br>
<input type="button" value="validate'" onclick="triggerAjax()"/>

Now at our local script.js we will define the ajax

function triggerAjax() {
    $.ajax({
            type: "POST",
            url: 'class.sendCode.php',
            dataType: "HTML",
            data : {

                dateini : $('#startdate').val(),
                datefin : $('#enddate').val()},

                  success: function(data){
                      $.globalEval(data);
// here is where the magic is made by executing the data that comes from
// the php class.  That is our javascript code to be executed
                  }


        });
}

Pandas: Return Hour from Datetime Column Directly

Now we can use:

sales['time_hour'] = sales['timestamp'].apply(lambda x: x.hour)

set option "selected" attribute from dynamic created option

You could search all the option values until it finds the correct one.

var defaultVal = "Country";
$("#select").find("option").each(function () {

    if ($(this).val() == defaultVal) {

        $(this).prop("selected", "selected");
    }
});

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

How to find children of nodes using BeautifulSoup

Perhaps you want to do

soup.find("li", { "class" : "test" }).find('a')

Access to ES6 array element index inside for-of loop

Also you can use JavaScript to solve your problem

_x000D_
_x000D_
iterate(item, index) {
    console.log(`${item} has index ${index}`);
    //Do what you want...
}

readJsonList() {    
    jsonList.forEach(this.iterate);
    //it could be any array list.
}   
_x000D_
_x000D_
_x000D_

Make a td fixed size (width,height) while rest of td's can expand

just set the width of the td/column you want to be fixed and the rest will expand.

<td width="200"></td>

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

Convert java.util.Date to String

Let's try this

public static void main(String args[]) {

    Calendar cal = GregorianCalendar.getInstance();
    Date today = cal.getTime();
    DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {           
        String str7 = df7.format(today);
        System.out.println("String in yyyy-MM-dd format is: " + str7);          
    } catch (Exception ex) {
      ex.printStackTrace();
    }
}

Or a utility function

public String convertDateToString(Date date, String format) {
    String dateStr = null;
    DateFormat df = new SimpleDateFormat(format);

    try {
        dateStr = df.format(date);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return dateStr;
}

From Convert Date to String in Java

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

gem uninstall -aIx

and

bundle install

worked for me.

How can I transition height: 0; to height: auto; using CSS?

There seems to be no proper solution. max-height approach is quite good but doesn't work well for the hide phase - there will be a noticeable delay unless you know the height of the content.

I think the best way is to use max-height but only for the show phase. And not to use any animation on hiding. For most cases it shouldn't be crucial.

max-height should be set to a quite huge value to ensure any content fits. Animation speed can be controlled using transition duration (speed = max-height / duration). Speed does not depend on the size of the content. The time it takes to show the whole content will depend on its size.

_x000D_
_x000D_
document.querySelector("button").addEventListener(_x000D_
  "click", _x000D_
  function(){_x000D_
    document.querySelector("div").classList.toggle("hide");_x000D_
  }_x000D_
)
_x000D_
div {    _x000D_
    max-height: 20000px;_x000D_
    transition: max-height 3000ms;_x000D_
    overflow-y: hidden;_x000D_
}_x000D_
_x000D_
.hide {_x000D_
    max-height: 0;_x000D_
    transition: none;_x000D_
}
_x000D_
<button>Toggle</button>_x000D_
<div class="hide">Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. _x000D_
</div>
_x000D_
_x000D_
_x000D_

Finding Android SDK on Mac and adding to PATH

If Android Studio shows you the path /Users/<name>/Library/Android/sdk but you can not find it in your folder, just right-click and select "Show View Option". There you will be able to select "Show Library Folder"; select it and you can access the SDK.

How to prevent buttons from submitting forms

Just add e.preventDefault(); in your method should prevent your page from submitting forms.

function myFunc(e){
       e.preventDefault();
}

According to the MDN Web Docs

The preventDefault () method of the Event interface tells the user agent that if the event is not explicitly processed, its default action should not be taken into account as it would normally be. The event continues to propagate as usual, unless one of its listeners calls stopPropagation () or stopImmediatePropagation (), either of which terminates the propagation.

SQL Server Text type vs. varchar data type

In SQL server 2005 new datatypes were introduced: varchar(max) and nvarchar(max) They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar and nvarchar. Among these advantages are the ability to use string manipulation functions such as substring().

Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.

In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.

As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.

Linux shell sort file according to the second column?

FWIW, here is a sort method for showing which processes are using the most virt memory.

memstat | sort -k 1 -t':' -g -r | less

Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In addition to @chanafdo answer, you can use route name

when working with laravel blade

<a href="{{route('login')}}">login here</a> with parameter in route name

when go to url like URI: profile/{id} <a href="{{route('profile', ['id' => 1])}}">login here</a>

without blade

<a href="<?php echo route('login')?>">login here</a>

with parameter in route name

when go to url like URI: profile/{id} <a href="<?php echo route('profile', ['id' => 1])?>">login here</a>

As of laravel 5.2 you can use @php @endphp to create as <?php ?> in laravel blade. Using blade your personal opinion but I suggest to use it. Learn it. It has many wonderful features as template inheritance, Components & Slots,subviews etc...

How to sort a data frame by date

Assuming your data frame is named d,

d[order(as.Date(d$V3, format="%d/%m/%Y")),]

Read my blog post, Sorting a data frame by the contents of a column, if that doesn't make sense.

Count the frequency that a value occurs in a dataframe column

In 0.18.1 groupby together with count does not give the frequency of unique values:

>>> df
   a
0  a
1  b
2  s
3  s
4  b
5  a
6  b

>>> df.groupby('a').count()
Empty DataFrame
Columns: []
Index: [a, b, s]

However, the unique values and their frequencies are easily determined using size:

>>> df.groupby('a').size()
a
a    2
b    3
s    2

With df.a.value_counts() sorted values (in descending order, i.e. largest value first) are returned by default.

How to uncheck a checkbox in pure JavaScript?

You will need to assign an ID to the checkbox:

<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">

and then in JavaScript:

document.getElementById("checkboxId").checked = false;

Countdown timer using Moment js

Here are some other solutions. No need to use additional plugins.

Snippets down below uses .subtract API and requires moment 2.1.0+

Snippets are also available in here https://jsfiddle.net/traBolic/ku5cyrev/

Formatting with the .format API:

_x000D_
_x000D_
const duration = moment.duration(9, 's');

const intervalId = setInterval(() => {
  duration.subtract(1, "s");

  const inMilliseconds = duration.asMilliseconds();

  // "mm:ss:SS" will include milliseconds
  console.log(moment.utc(inMilliseconds).format("HH[h]:mm[m]:ss[s]"));

  if (inMilliseconds !== 0) return;

  clearInterval(intervalId);
  console.warn("Times up!");
}, 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Manuel formatting by .hours, .minutes and .seconds API in a template string

_x000D_
_x000D_
const duration = moment.duration(9, 's');

const intervalId = setInterval(() => {
  duration.subtract(1, "s");

  console.log(`${duration.hours()}h:${duration.minutes()}m:${duration.seconds()}s`);
  // `:${duration.milliseconds()}` to add milliseconds

  if (duration.asMilliseconds() !== 0) return;

  clearInterval(intervalId);
  console.warn("Times up!");
}, 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Latex Multiple Linebreaks

Insert some vertical space

blah blah blah \\
\vspace{1cm}

to scale to the font, use ex (the height of a lowercase "x") as the unit, and there are various predefined lengths related to the line spacing available, you might be particularly interested in baselineskip.

How to import classes defined in __init__.py

If lib/__init__.py defines the Helper class then in settings.py you can use:

from . import Helper

This works because . is the current directory, and acts as a synonym for the lib package from the point of view of the settings module. Note that it is not necessary to export Helper via __all__.

(Confirmed with python 2.7.10, running on Windows.)

How to return a boolean method in java?

You can also do this, for readability's sake

boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());

if(!passwordVerified ){
    txtaError.setEditable(true);
    txtaError.setText("*Password didn't match!");
    txtaError.setForeground(Color.red);
    txtaError.setEditable(false);
}else{
    addNewUser();
}
return passwordVerified;

How to hide keyboard in swift on pressing return key?

The return true part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder(), like so:

// Called on 'Return' pressed. Return false to ignore.

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    textField.resignFirstResponder()
    return true
}

What's the difference between RANK() and DENSE_RANK() functions in oracle?

The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).

For example, consider the set {25, 25, 50, 75, 75, 100}. For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.

how to print a string to console in c++

yes it's possible to print a string to the console.

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string strMytestString("hello world");
    cout << strMytestString;
    return 0;
}

stdafx.h isn't pertinent to the solution, everything else is.

How to close a web page on a button click, a hyperlink or a link button click?

Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.

Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close

    private void myNewButton_Click(object sender, EventArgs e) {
        this.Close();
    }

And that should be it.

The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.

How can I get the count of line in a file in an efficient way?

Try the unix "wc" command. I don't mean use it, I mean download the source and see how they do it. It's probably in c, but you can easily port the behavior to java. The problem with making your own is to account for the ending cr/lf problem.

Disable/Enable Submit Button until all forms have been filled

I think this will be much simpler for beginners in JavaScript

    //The function checks if the password and confirm password match
    // Then disables the submit button for mismatch but enables if they match
            function checkPass()
            {
                //Store the password field objects into variables ...
                var pass1 = document.getElementById("register-password");
                var pass2 = document.getElementById("confirm-password");
                //Store the Confimation Message Object ...
                var message = document.getElementById('confirmMessage');
                //Set the colors we will be using ...
                var goodColor = "#66cc66";
                var badColor = "#ff6666";
                //Compare the values in the password field 
                //and the confirmation field
                if(pass1.value == pass2.value){
                    //The passwords match. 
                    //Set the color to the good color and inform
                    //the user that they have entered the correct password 
                    pass2.style.backgroundColor = goodColor;
                    message.style.color = goodColor;
                    message.innerHTML = "Passwords Match!"
 //Enables the submit button when there's no mismatch                   
                    var tabPom = document.getElementById("btnSignUp");
                    $(tabPom ).prop('disabled', false);
                }else{
                    //The passwords do not match.
                    //Set the color to the bad color and
                    //notify the user.
                    pass2.style.backgroundColor = badColor;
                    message.style.color = badColor;
                    message.innerHTML = "Passwords Do Not Match!"
 //Disables the submit button when there's mismatch       
                    var tabPom = document.getElementById("btnSignUp");
                    $(tabPom ).prop('disabled', true);
                }
            } 

Python: Convert timedelta to int in a dataframe

You could do this, where td is your series of timedeltas. The division converts the nanosecond deltas into day deltas, and the conversion to int drops to whole days.

import numpy as np

(td / np.timedelta64(1, 'D')).astype(int)

How to efficiently use try...catch blocks in PHP

Important note

The following discussion assumes that we are talking about code structured as in the example above: no matter which alternative is chosen, an exception will cause the method to logically stop doing whatever it was in the middle of.


As long as you intend to do the same thing no matter which statement in the try block throws an exception, then it's certainly better to use a single try/catch. For example:

function createCar()
{
    try {
      install_engine();
      install_brakes();
    } catch (Exception $e) {
        die("I could not create a car");
    }
}

Multiple try/catch blocks are useful if you can and intend to handle the failure in a manner specific to what exactly caused it.

function makeCocktail()
{
    try {
        pour_ingredients();
        stir();
    } catch (Exception $e) {
        die("I could not make you a cocktail");
    }

    try {
        put_decorative_umbrella();
    } catch (Exception $e) {
        echo "We 're out of umbrellas, but the drink itself is fine"
    }
}

Setting default value for TypeScript object passed as argument

No, TypeScript doesn't have a natural way of setting defaults for properties of an object defined like that where one has a default and the other does not. You could define a richer structure:

class Name {
    constructor(public first : string, 
        public last: string = "Smith") {

    }
}

And use that in place of the inline type definition.

function sayName(name: Name) {
    alert(name.first + " " + name.last);
}

You can't do something like this unfortunately:

function sayName(name : { first: string; last?:string } 
       /* and then assign a default object matching the signature */  
       = { first: null, last: 'Smith' }) {

} 

As it would only set the default if name was undefined.

python convert list to dictionary

Using the usual grouper recipe, you could do:

Python 2:

d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))

Python 3:

d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))

Get all LI elements in array

If you want all the li tags in an array even when they are in different ul tags then you can simply do

var lis = document.getElementByTagName('li'); 

and if you want to get particular div tag li's then:

var lis = document.getElementById('divID').getElementByTagName('li'); 

else if you want to search a ul first and then its li tags then you can do:

var uls = document.getElementsByTagName('ul');
for(var i=0;i<uls.length;i++){
    var lis=uls[i].getElementsByTagName('li');
    for(var j=0;j<lis.length;j++){
        console.log(lis[j].innerHTML);
    }
}

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Ya its possible to do without support of javascript..
We can use html5 auto focus attribute
For Example:

<input type="text" name="name" autofocus="autofocus" id="xax" />

If use it (autofocus="autofocus") in text field means that text field get focused when page gets loaded.. For more details:
http://www.hscripts.com/tutorials/html5/autofocus-attribute.html

In-memory size of a Python structure

I've been happily using pympler for such tasks. It's compatible with many versions of Python -- the asizeof module in particular goes back to 2.2!

For example, using hughdbrown's example but with from pympler import asizeof at the start and print asizeof.asizeof(v) at the end, I see (system Python 2.5 on MacOSX 10.5):

$ python pymp.py 
set 120
unicode 32
tuple 32
int 16
decimal 152
float 16
list 40
object 0
dict 144
str 32

Clearly there is some approximation here, but I've found it very useful for footprint analysis and tuning.

How to identify server IP address in PHP

You may have to use $HTTP_SERVER_VARS['server_ADDR'] if you are not getting anything from above answers and if you are using older version of PHP

What exactly is nullptr?

Here's the LLVM header.

// -*- C++ -*-
//===--------------------------- __nullptr --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#ifndef _LIBCPP_NULLPTR
#define _LIBCPP_NULLPTR

#include <__config>

#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif

#ifdef _LIBCPP_HAS_NO_NULLPTR

_LIBCPP_BEGIN_NAMESPACE_STD

struct _LIBCPP_TEMPLATE_VIS nullptr_t
{
    void* __lx;

    struct __nat {int __for_bool_;};

    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t() : __lx(0) {}
    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t(int __nat::*) : __lx(0) {}

    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR operator int __nat::*() const {return 0;}

    template <class _Tp>
        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
        operator _Tp* () const {return 0;}

    template <class _Tp, class _Up>
        _LIBCPP_INLINE_VISIBILITY
        operator _Tp _Up::* () const {return 0;}

    friend _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR bool operator==(nullptr_t, nullptr_t) {return true;}
    friend _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR bool operator!=(nullptr_t, nullptr_t) {return false;}
};

inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t __get_nullptr_t() {return nullptr_t(0);}

#define nullptr _VSTD::__get_nullptr_t()

_LIBCPP_END_NAMESPACE_STD

#else  // _LIBCPP_HAS_NO_NULLPTR

namespace std
{
    typedef decltype(nullptr) nullptr_t;
}

#endif  // _LIBCPP_HAS_NO_NULLPTR

#endif  // _LIBCPP_NULLPTR

(a great deal can be uncovered with a quick grep -r /usr/include/*`)

One thing that jumps out is the operator * overload (returning 0 is a lot friendlier than segfaulting...). Another thing is it doesn't look compatible with storing an address at all. Which, compared to how it goes slinging void*'s and passing NULL results to normal pointers as sentinel values, would obviously reduce the "never forget, it might be a bomb" factor.

Retrieve CPU usage and memory usage of a single process on Linux?

You can get the results by the name of the process using

ps -C chrome -o %cpu,%mem,cmd

the -C option allows you to use process name without knowing it's pid.

Inserting line breaks into PDF

The solution I've found was:

$text = 'Line one\n\nLine two');
$text = explode('\n', $text);

foreach ($text as $txt){
    $pdf->Write($txt);
    $pdf->Ln();
}

So this way, you may have any number of \n in any position, if you're getting this text dinamically from the database, it will break lines correctrly.

How to pass command-line arguments to a PowerShell ps1 file

You may not get "xuxu p1 p2 p3 p4" as it seems. But when you are in PowerShell and you set

PS > set-executionpolicy Unrestricted -scope currentuser

You can run those scripts like this:

./xuxu p1 p2 p3 p4

or

.\xuxu p1 p2 p3 p4

or

./xuxu.ps1 p1 p2 p3 p4

I hope that makes you a bit more comfortable with PowerShell.

Android Layout Weight

weight values 0-1 share distribution of available space (after setting layout_width="0px") in proportion to the weight value. View elements with weight not specified (no weight entry) get weight 0 which means they get no expansion.

A simple alternative with no weight entries needed is to attach marquee to a view with text which tells it to expand from minimum needed for the text (wrap_content) to space available EditText: android:layout_width="wrap_content" android:ellipsize="marquee"

Why do Twitter Bootstrap tables always have 100% width?

I was having the same issue, I made the table fixed and then specified my td width. If you have th you can do those as well.

<style>
table {
table-layout: fixed;
word-wrap: break-word;
}
</style>

<td width="10%" /td>

I didn't have any luck with .table-nonfluid.

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t in a string marks an escape sequence for a tab character. For a literal \, use \\.

Getting absolute URLs using ASP.NET Core

If you just want to convert a relative path with optional parameters I created an extension method for IHttpContextAccessor

public static string AbsoluteUrl(this IHttpContextAccessor httpContextAccessor, string relativeUrl, object parameters = null)
{
    var request = httpContextAccessor.HttpContext.Request;

    var url = new Uri(new Uri($"{request.Scheme}://{request.Host.Value}"), relativeUrl).ToString();

    if (parameters != null)
    {
        url = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(url, ToDictionary(parameters));
    }

    return url;
}


private static Dictionary<string, string> ToDictionary(object obj)
{
    var json = JsonConvert.SerializeObject(obj);
    return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}

You can then call the method from your service/view using the injected IHttpContextAccessor

var callbackUrl = _httpContextAccessor.AbsoluteUrl("/Identity/Account/ConfirmEmail", new { userId = applicationUser.Id, code });

Get local href value from anchor (a) tag

document.getElementById("link").getAttribute("href"); If you have more than one <a> tag, for example:

_x000D_
_x000D_
<ul>_x000D_
  <li>_x000D_
    <a href="1"></a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="2"></a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="3"></a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

You can do it like this: document.getElementById("link")[0].getAttribute("href"); to access the first array of <a> tags, or depends on the condition you make.

Is it possible to clone html element objects in JavaScript / JQuery?

It's actually very easy in jQuery:

$("#ddl_1").clone().attr("id",newId).appendTo("body");

Change .appendTo() of course...

svn: E155004: ..(path of resource).. is already locked

Inside the folder

TortoiseSVN -> Clean up...

Get current NSDate in timestamp format

If you'd like to call this method directly on an NSDate object and get the timestamp as a string in milliseconds without any decimal places, define this method as a category:

@implementation NSDate (MyExtensions)
- (NSString *)unixTimestampInMilliseconds
{
     return [NSString stringWithFormat:@"%.0f", [self timeIntervalSince1970] * 1000];
}

Class Not Found: Empty Test Suite in IntelliJ

I had a similar problem after starting a new IntelliJ project. I found that the "module compile output path" for my module was not properly specified. When I assigned the path in the module's "compile output path" to the proper location, the problem was solved. The compile output path is assigned in the Project settings. Under Modules, select the module involved and select the Paths tab...

Paths tab in the Project Settings | Modules dialog

screenshot

...I sent the compiler output to a folder named "output" that is present in the parent Project folder.

Google Maps API v3: How do I dynamically change the marker icon?

You can try this code

    <script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>

<script>

    function initialize()
    {
        var map;
        var bounds = new google.maps.LatLngBounds();
        var mapOptions = {
                            zoom: 10,
                            mapTypeId: google.maps.MapTypeId.ROADMAP    
                         };
        map = new google.maps.Map(document.getElementById("mapDiv"), mapOptions);
        var markers = [
            ['title-1', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.120850, '<p> Hello - 1 </p>'],
            ['title-2', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.420850, '<p> Hello - 2 </p>'],
            ['title-3', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.720850, '<p> Hello - 3 </p>'],
            ['title-4', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -1.020850, '<p> Hello - 4 </p>'],
            ['title-5', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -1.320850, '<p> Hello - 5 </p>']
        ];

        var infoWindow = new google.maps.InfoWindow(), marker, i;
        var testMarker = [];
        var status = [];
        for( i = 0; i < markers.length; i++ ) 
        {
            var title = markers[i][0];
            var loan = markers[i][1];
            var lat = markers[i][2];
            var long = markers[i][3];
            var add = markers[i][4];


            var iconGreen = 'img/greenMarker.png'; //green marker
            var iconRed = 'img/redMarker.png';     //red marker

            var infoWindowContent = loan + "\n" + placeId + add;

            var position = new google.maps.LatLng(lat, long);
            bounds.extend(position);

            marker = new google.maps.Marker({
                map: map,
                title: title,
                position: position,
                icon: iconGreen
            });
            testMarker[i] = marker;
            status[i] = 1;
            google.maps.event.addListener(marker, 'click', ( function toggleBounce( i,status,testMarker) 
            {
                return function() 
                {
                    infoWindow.setContent(markers[i][1]+markers[i][4]);
                    if( status[i] === 1 )
                    {
                        testMarker[i].setIcon(iconRed);
                        status[i] = 0;

                    }
                    for( var k = 0; k <  markers.length ; k++ )
                    {
                        if(k != i)
                        {
                            testMarker[k].setIcon(iconGreen);
                            status[i] = 1;

                        }
                    }
                    infoWindow.open(map, testMarker[i]);
                }
            })( i,status,testMarker));
            map.fitBounds(bounds);
        }
        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event)
        {
            this.setZoom(8);
            google.maps.event.removeListener(boundsListener);
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);

</script>

<div id="mapDiv" style="width:820px; height:300px"></div>

How to change time in DateTime?

Use Date.Add and add a New TimeSpan with the new time you want to add

DateTime dt = DateTime.Now
dt.Date.Add(new TimeSpan(12,15,00))

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

If anyone experiences the error for the same reason why I experience it, here's my solution:

if you had Html.AntiForgeryToken();

change it to @Html.AntiForgeryToken()

Domain Account keeping locking out with correct password every few minutes

I have seen this problem when the user had set up a scheduled task to run under his account. He forgot to update the password on the task after he changed his account password. The scheduled task was trying to logon with the old password and kept locking out his account.

Why does ENOENT mean "No such file or directory"?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

This error occurs when versions of NodeJS and Node Sass are not matched.

you can resolve your issue by doing as below:

- Step 1: Remove Nodejs from your computer

- Step 2: Reinstall Nodejs version 14.15.1.

- Step 3: Uninstall Node sass by run the command npm uninstall node-sass

- Step 4: Reinstall Node sass version 4.14.1 by run the command npm install [email protected]

After all steps, you can run command ng serve -o to run your application.

Node sass version 5.0.0 is incompatible with ^4.0.0.

Convert string to int if string is a number

To put it on one line:

currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

You are allowed to use IDs that start with a digit in your HTML5 documents:

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

But querySelector method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Use a value like b22 for the ID attribute and your code will work.

Since you want to select an element by ID you can also use .getElementById method:

document.getElementById('22')

JPA eager fetch does not join

The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.

If you set fetchType=EAGER This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.

If you set fetchType=LAZY the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.

You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.

For the second part of the question - how to get hibernate to generate optimised SQL?

Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.

PHP - SSL certificate error: unable to get local issuer certificate

Thanks @Mladen Janjetovic,

Your suggestion worked for me in mac with ampps installed.

Copied: http://curl.haxx.se/ca/cacert.pem

To: /Applications/AMPPS/extra/etc/openssl/certs/cacert.pem

And updated php.ini with that path and restarted Apache:

[curl]
; A default value for the CURLOPT_CAINFO option. This is required to be an
; absolute path.
curl.cainfo="/Applications/AMPPS/extra/etc/openssl/certs/cacert.pem"
openssl.cafile="/Applications/AMPPS/extra/etc/openssl/certs/cacert.pem"

And applied same setting in windows AMPPS installation and it worked perfectly in it too.

[curl]
; A default value for the CURLOPT_CAINFO option. This is required to be an
; absolute path.
curl.cainfo="C:/Ampps/php/extras/ssl/cacert.pem"
openssl.cafile="C:/Ampps/php/extras/ssl/cacert.pem"

: Same for wamp.

[curl]
; A default value for the CURLOPT_CAINFO option. This is required to be an
; absolute path.
curl.cainfo="C:/wamp/bin/php/php5.6.16/extras/ssl/cacert.pem"
openssl.cafile="C:/wamp/bin/php/php5.6.16/extras/ssl/cacert.pem"

If you are looking for generating new SSL certificate using SAN for localhost, steps on this post worked for me on Centos 7 / Vagrant / Chrome Browser.

How to download PDF automatically using js?

Use the download attribute.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

Difference between webdriver.Dispose(), .Close() and .Quit()

quit(): Quits this driver, closing every associated window that was open.

close() : Close the current window, quitting the browser if it's the last window currently open.

When do you use Java's @Override annotation and why?

I use it everywhere. On the topic of the effort for marking methods, I let Eclipse do it for me so, it's no additional effort.

I'm religious about continuous refactoring.... so, I'll use every little thing to make it go more smoothly.

Codeigniter - no input file specified

My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:

<IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On

    # If your website begins from a folder e.g localhost/my_project then 
    # you have to change it to: RewriteBase /my_project/
    # If your site begins from the root e.g. example.local/ then
    # let it as it is
    RewriteBase /

    # Protect application and system files from being viewed when the index.php is missing
    RewriteCond $1 ^(application|system|private|logs)

    # Rewrite to index.php/access_denied/URL
    RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

    # Allow these directories and files to be displayed directly:
    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)

    # No rewriting
    RewriteRule ^(.*)$ - [PT,L]

    # Rewrite to index.php/URL
    RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>

Add tooltip to font awesome icon

Simply use title in tag like

<i class="fa fa-edit" title="Edit Mode"></i>

This will show 'Edit Mode' when hover that icon.

How to change sender name (not email address) when using the linux mail command for autosending mail?

It depends on what sender address you are talking about. The sender address visble in the recipients mailprogramm is extracted from the "From:" Header. which can probably easily be set from your program.

If you are talking about the SMTP envelope sender address, you can pass the -f argument to the sendmail binary. Depending on the server configuration you may not be allowed to do that with the apache user.

from the sendmail manpage :

   -f <address>
                 This  option  sets  the  address  of the envelope sender of a
                 locally-generated message (also known as  the  return  path).
                 The  option  can normally be used only by a trusted user, but
                 untrusted_set_sender can be set to allow untrusted  users  to
                 use it. [...]

How to avoid precompiled headers

You can always disable the use of pre-compiled headers in the project settings.

Instructions for VS 2010 (should be similar for other versions of VS):

Select your project, use the "Project -> Properties" menu and go to the "Configuration Properties -> C/C++ -> Precompiled Headers" section, then change the "Precompiled Header" setting to "Not Using Precompiled Headers" option.


If you are only trying to setup a minimal Visual Studio project for simple C++ command-line programs (such as those developed in introductory C++ programming classes), you can create an empty C++ project.

Convert a Unicode string to a string in Python (containing extra symbols)

Here is an example code

import unicodedata    
raw_text = u"here $%6757 dfgdfg"
convert_text = unicodedata.normalize('NFKD', raw_text).encode('ascii','ignore')

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

HTML checkbox - allow to check only one checkbox

The unique name identifier applies to radio buttons:

<input type="radio" />

change your checkboxes to radio and everything should be working

HTTP Headers for File Downloads

You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:

<?php

$filename = $_GET['file'];

// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
  ini_set('zlib.output_compression', 'Off');

// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));

if( $filename == "" ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
  exit;
} elseif ( ! file_exists( $filename ) ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
  exit;
};
switch( $file_extension )
{
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "doc": $ctype="application/msword"; break;
  case "xls": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();

Android Studio suddenly cannot resolve symbols

None of these solutions worked for me. I had to uninstall Android Studio all together, then remove all Android Studio related files (user files), then reinstall it again.

How can I install Visual Studio Code extensions offline?

Adding to t3chb0t's excellent answer - Use these PowerShell commands to install all VSCode extensions in a folder:

cd C:\PathToFolderWithManyDownloadedExtensionFiles
Get-ChildItem . -Filter *.vsix | ForEach-Object { code --install-extension $_.FullName }

Then, reload VSCode to complete the installation.

Running multiple AsyncTasks at the same time -- not possible?

It is posible. My android device version is 4.0.4 and android.os.Build.VERSION.SDK_INT is 15

I have 3 spinners

Spinner c_fruit=(Spinner) findViewById(R.id.fruits);
Spinner c_vegetable=(Spinner) findViewById(R.id.vegetables);
Spinner c_beverage=(Spinner) findViewById(R.id.beverages);

And also I have a Async-Tack class.

Here is my spinner loading code

RequestSend reqs_fruit = new RequestSend(this);
reqs_fruit.where="Get_fruit_List";
reqs_fruit.title="Loading fruit";
reqs_fruit.execute();

RequestSend reqs_vegetable = new RequestSend(this);
reqs_vegetable.where="Get_vegetable_List";
reqs_vegetable.title="Loading vegetable";
reqs_vegetable.execute();

RequestSend reqs_beverage = new RequestSend(this);
reqs_beverage.where="Get_beverage_List";
reqs_beverage.title="Loading beverage";
reqs_beverage.execute();

This is working perfectly. One by one my spinners loaded. I didn't user executeOnExecutor.

Here is my Async-task class

public class RequestSend  extends AsyncTask<String, String, String > {

    private ProgressDialog dialog = null;
    public Spinner spin;
    public String where;
    public String title;
    Context con;
    Activity activity;      
    String[] items;

    public RequestSend(Context activityContext) {
        con = activityContext;
        dialog = new ProgressDialog(activityContext);
        this.activity = activityContext;
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            ArrayAdapter<String> adapter = new ArrayAdapter<String> (activity, android.R.layout.simple_spinner_item, items);       
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spin.setAdapter(adapter);
        } catch (NullPointerException e) {
            Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (Exception e)  {
            Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        super.onPostExecute(result);

        if (dialog != null)
            dialog.dismiss();   
    }

    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setTitle(title);
        dialog.setMessage("Wait...");
        dialog.setCancelable(false); 
        dialog.show();
    }

    @Override
    protected String doInBackground(String... Strings) {
        try {
            Send_Request();
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        return null;
    }

    public void Send_Request() throws JSONException {

        try {
            String DataSendingTo = "http://www.example.com/AppRequest/" + where;
            //HttpClient
            HttpClient httpClient = new DefaultHttpClient();
            //Post header
            HttpPost httpPost = new HttpPost(DataSendingTo);
            //Adding data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

            nameValuePairs.add(new BasicNameValuePair("authorized","001"));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);

            BufferedReader reader;
            try {
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    builder.append(line) ;
                }

                JSONTokener tokener = new JSONTokener(builder.toString());
                JSONArray finalResult = new JSONArray(tokener);
                items = new String[finalResult.length()]; 
                // looping through All details and store in public String array
                for(int i = 0; i < finalResult.length(); i++) {
                    JSONObject c = finalResult.getJSONObject(i);
                    items[i]=c.getString("data_name");
                }

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to split a delimited string into an array in awk?

I know this is kind of old question, but I thought maybe someone like my trick. Especially since this solution not limited to a specific number of items.

# Convert to an array
_ITEMS=($(echo "12|23|11" | tr '|' '\n'))

# Output array items
for _ITEM in "${_ITEMS[@]}"; do
  echo "Item: ${_ITEM}"
done

The output will be:

Item: 12
Item: 23
Item: 11

How to send and receive JSON data from a restful webservice using Jersey API

Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.

@Path("/hello")
public class Hello {

  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {

    String input = (String) inputJsonObj.get("input");
    String output = "The input you sent is :" + input;
    JSONObject outputJsonObj = new JSONObject();
    outputJsonObj.put("output", output);

    return outputJsonObj;
  }
}

And, your client code should look like this:

  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  client.addFilter(new LoggingFilter());
  WebResource service = client.resource(getBaseURI());
  JSONObject inputJsonObj = new JSONObject();
  inputJsonObj.put("input", "Value");
  System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

FWIW the removal of Apache library was foreshadowed a while ago. Our good friend Jesse Wilson gave us a clue back in 2011: http://android-developers.blogspot.com/2011/09/androids-http-clients.html

Google stopped working on ApacheHTTPClient a while ago, so any library that is still relying upon that should be put onto the list of deprecated libraries unless the maintainers update their code.

<rant> I can't tell you how many technical arguments I've had with people who insisted on sticking with Apache HTTP client. There are some major apps that are going to break because management at my not-to-be-named previous employers didn't listen to their top engineers or knew what they were talking about when they ignored the warning ... but, water under the bridge.

I win.

</rant>

Allow a div to cover the whole page instead of the area within the container

Try this

#dimScreen {
    width: 100%;
    height: 100%;
    background:rgba(255,255,255,0.5);
    position: fixed;
    top: 0;
    left: 0;
}

jquery dialog save cancel button styling

after looking at some other threads I came up with this solution to add icons to the buttons in a confirm dialog, which seems to work well in version 1.8.1 and can be modified to do other styling:

$("#confirmBox").dialog({
    modal:true,
    autoOpen:false,        
    buttons: { 
        "Save": function() { ... },                
        "Cancel": function() { ... }
        }
});

var buttons = $('.ui-dialog-buttonpane').children('button');
buttons.removeClass('ui-button-text-only').addClass('ui-button-text-icon');

$(buttons[0]).append("<span class='ui-icon ui-icon-check'></span>");
$(buttons[1]).append("<span class='ui-icon ui-icon-close'></span>");

I'd be interested in seeing if there was a better way to do it, but this seems pretty efficient.

filemtime "warning stat failed for"

in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().

$filedate = date_create(date("Y-m-d", filectime($file)));

becomes

$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));

that worked for me.

Complete snippet for deleting files by number of days:

$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
    $extension      = substr($file, -3, 3); 
    if ($extension == 'jpg') // in case you only want specific files deleted
    {
        $stat = stat($directory.$file);
        $filedate = date_create(date("Y-m-d", $stat['ctime']));
        $today = date_create(date("Y-m-d"));
        $days = date_diff($filedate, $today, true);
        if ($days->days > 1) 
        { 
            unlink($directory.$file);
        }
    } 
}

HashMaps and Null values?

You can keep note of below possibilities:

1. Values entered in a map can be null.

However with multiple null keys and values it will only take a null key value pair once.

Map<String, String> codes = new HashMap<String, String>();

codes.put(null, null);
codes.put(null,null);
codes.put("C1", "Acathan");

for(String key:codes.keySet()){
    System.out.println(key);
    System.out.println(codes.get(key));
}

output will be :

null //key  of the 1st entry
null //value of 1st entry
C1
Acathan

2. your code will execute null only once

options.put(null, null);  
Person person = sample.searchPerson(null);   

It depends on the implementation of your searchPerson method if you want multiple values to be null, you can implement accordingly

Map<String, String> codes = new HashMap<String, String>();

    codes.put(null, null);
    codes.put("X1",null);
    codes.put("C1", "Acathan");
    codes.put("S1",null);


    for(String key:codes.keySet()){
        System.out.println(key);
        System.out.println(codes.get(key));
    }

output:

null
null

X1
null
S1
null
C1
Acathan

How to get Linux console window width in Python

Starting at Python 3.3 it is straight forward: https://docs.python.org/3/library/os.html#querying-the-size-of-a-terminal

>>> import os
>>> ts = os.get_terminal_size()
>>> ts.lines
24
>>> ts.columns
80

How to pass text in a textbox to JavaScript function?

This is what I have done. (Adapt from all of your answers)

<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />

It works. Thanks to all of you. :)

Rails: Check output of path helper from console

For Rails 5.2.4.1, I had to

app.extend app._routes.named_routes.path_helpers_module
app.whatever_path

Download file through an ajax call php

I have accomplished this with a hidden iframe. I use perl, not php, so will just give concept, not code solution.

Client sends Ajax request to server, causing the file content to be generated. This is saved as a temp file on the server, and the filename is returned to the client.

Client (javascript) receives filename, and sets the iframe src to some url that will deliver the file, like:

$('iframe_dl').src="/app?download=1&filename=" + the_filename

Server slurps the file, unlinks it, and sends the stream to the client, with these headers:

Content-Type:'application/force-download'
Content-Disposition:'attachment; filename=the_filename'

Works like a charm.

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Just another way of doing it.

[somearray, anotherarray].flatten
=> ["some", "thing", "another", "thing"]

How do I convert a javascript object array to a string array of the object attribute I want?

You can do this to only monitor own properties of the object:

var arr = [];

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        arr.push(p[key]);
    }
}

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

How to use sed to replace only the first occurrence in a file?

A sed script that will only replace the first occurrence of "Apple" by "Banana"

Example

     Input:      Output:

     Apple       Banana
     Apple       Apple
     Orange      Orange
     Apple       Apple

This is the simple script: Editor's note: works with GNU sed only.

sed '0,/Apple/{s/Apple/Banana/}' input_filename

The first two parameters 0 and /Apple/ are the range specifier. The s/Apple/Banana/ is what is executed within that range. So in this case "within the range of the beginning (0) up to the first instance of Apple, replace Apple with Banana. Only the first Apple will be replaced.

Background: In traditional sed the range specifier is also "begin here" and "end here" (inclusive). However the lowest "begin" is the first line (line 1), and if the "end here" is a regex, then it is only attempted to match against on the next line after "begin", so the earliest possible end is line 2. So since range is inclusive, smallest possible range is "2 lines" and smallest starting range is both lines 1 and 2 (i.e. if there's an occurrence on line 1, occurrences on line 2 will also be changed, not desired in this case). GNU sed adds its own extension of allowing specifying start as the "pseudo" line 0 so that the end of the range can be line 1, allowing it a range of "only the first line" if the regex matches the first line.

Or a simplified version (an empty RE like // means to re-use the one specified before it, so this is equivalent):

sed '0,/Apple/{s//Banana/}' input_filename

And the curly braces are optional for the s command, so this is also equivalent:

sed '0,/Apple/s//Banana/' input_filename

All of these work on GNU sed only.

You can also install GNU sed on OS X using homebrew brew install gnu-sed.

Change div height on button click

Do this:

function changeHeight() {
document.getElementById('chartdiv').style.height = "200px"
}
<button type="button" onClick="changeHeight();"> Click Me!</button>

Referencing system.management.automation.dll in Visual Studio

A copy of System.Management.Automation.dll is installed when you install the windows SDK (a suitable, recent version of it, anyway). It should be in C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\

How do I use a file grep comparison inside a bash if/else statement?

From grep --help, but also see man grep:

Exit status is 0 if any line was selected, 1 otherwise; if any error occurs and -q was not given, the exit status is 2.

if grep --quiet MYSQL_ROLE=master /etc/aws/hosts.conf; then
  echo exists
else
  echo not found
fi

You may want to use a more specific regex, such as ^MYSQL_ROLE=master$, to avoid that string in comments, names that merely start with "master", etc.

This works because the if takes a command and runs it, and uses the return value of that command to decide how to proceed, with zero meaning true and non-zero meaning false—the same as how other return codes are interpreted by the shell, and the opposite of a language like C.

How can I remove file extension from a website address?

For those who are still looking for a simple answer to this; You can remove your file extension by using .htaccessbut this solution is just saving the day maybe even not. Because when user copies the URL from address bar or tries to reload or even coming back from history, your standart Apache Router will not be able to realize what are you looking for and throw you a 404 Error. You need a dedicated Router for this purpose to make your app understand what does the URL actually means by saying something Server and File System has no idea about.

I leave here my solution for this. This is tested and used many times for my clients and for my projects too. It supports multi language and language detection too. Read Readme file is recommended. It also provides you a good structure to have a tidy project with differenciated language files (you can even have different designs for each language) and separated css,js and phpfiles even more like images or whatever you have.

Cr8Router - Simple PHP Router

How to create a function in a cshtml template?

You can use the @helper Razor directive:

@helper WelcomeMessage(string username)
{
    <p>Welcome, @username.</p>
}

Then you invoke it like this:

@WelcomeMessage("John Smith")

Reading file input from a multipart/form-data POST

I have implemented MultipartReader NuGet package for ASP.NET 4 for reading multipart form data. It is based on Multipart Form Data Parser, but it supports more than one file.

Combine a list of data frames into one data frame by row

An updated visual for those wanting to compare some of the recent answers (I wanted to compare the purrr to dplyr solution). Basically I combined answers from @TheVTM and @rmf.

enter image description here

Code:

library(microbenchmark)
library(data.table)
library(tidyverse)

dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
  dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
                            c=rep(LETTERS,10),d=rep(LETTERS,10))
}


mb <- microbenchmark(
  dplyr::bind_rows(dflist),
  data.table::rbindlist(dflist),
  purrr::map_df(dflist, bind_rows),
  do.call("rbind",dflist),
  times=500)

ggplot2::autoplot(mb)

Session Info:

sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Package Versions:

> packageVersion("tidyverse")
[1] ‘1.1.1’
> packageVersion("data.table")
[1] ‘1.10.0’

MySQL error 1449: The user specified as a definer does not exist

you can create user with name web2vi and grant all privilage

How to get the current branch name in Git?

You can do this with a single grep instruction, using Perl mode and \K to reset the match buffer, so you get only the branch name.

$ git branch | grep -oP "^\*\s+\K\S+$"
master

PHP Warning Permission denied (13) on session_start()

You don't appear to have write permission to the /tmp directory on your server. This is a bit weird, but you can work around it. Before the call to session_start() put in a call to session_save_path() and give it the name of a directory writable by the server. Details are here.

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

In my case I was missing new inside the type definition.

some-js-component.d.ts file:

import * as React from "react";

export default class SomeJSXComponent extends React.Component<any, any> {
    new (props: any, context?: any)
}

and inside the tsx file where I was trying to import the untyped component:

import SomeJSXComponent from 'some-js-component'

const NewComp = ({ asdf }: NewProps) => <SomeJSXComponent withProps={asdf} />

Downgrade npm to an older version

Before doing that Download Node Js 8.11.3 from the URL: download

Open command prompt and run this:

npm install -g [email protected]

use this version this is the stable version which works along with cordova 7.1.0

for installing cordova use : • npm install -g [email protected]

• Run command

• Cordova platform remove android (if you have old android code or code is having some issue)

• Cordova platform add android : for building android app in cordova Running: Corodva run android

How to get the public IP address of a user in C#

lblmessage.Text =Request.ServerVariables["REMOTE_HOST"].ToString();

How do I exit the results of 'git diff' in Git Bash on windows?

None of the above solutions worked for me on Windows 8

But the following command works fine

SHIFT + Q

Regular Expression for alphanumeric and underscores

For those of you looking for unicode alphanumeric matching, you might want to do something like:

^[\p{L} \p{Nd}_]+$

Further reading at http://unicode.org/reports/tr18/ and at http://www.regular-expressions.info/unicode.html

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

ASP.NET MVC - Set custom IIdentity or IPrincipal

As an addition to LukeP code for Web Forms users (not MVC) if you want to simplify the access in the code behind of your pages, just add the code below to a base page and derive the base page in all your pages:

Public Overridable Shadows ReadOnly Property User() As CustomPrincipal
    Get
        Return DirectCast(MyBase.User, CustomPrincipal)
    End Get
End Property

So in your code behind you can simply access:

User.FirstName or User.LastName

What I'm missing in a Web Form scenario, is how to obtain the same behaviour in code not tied to the page, for example in httpmodules should I always add a cast in each class or is there a smarter way to obtain this?

Thanks for your answers and thank to LukeP since I used your examples as a base for my custom user (which now has User.Roles, User.Tasks, User.HasPath(int) , User.Settings.Timeout and many other nice things)

How to append data to div using JavaScript?

Using appendChild:

var theDiv = document.getElementById("<ID_OF_THE_DIV>");
var content = document.createTextNode("<YOUR_CONTENT>");
theDiv.appendChild(content);

Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by @BiAiB. So use caution if you are planning to use this version.

var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.innerHTML += "<YOUR_CONTENT>"; 

Using Font Awesome icon for bullet points, with a single list item element

My solution using standard <ul> and <i> inside <li>

  <ul>
    <li><i class="fab fa-cc-paypal"></i> <div>Paypal</div></li>
    <li><i class="fab fa-cc-apple-pay"></i> <div>Apple Pay</div></li>
    <li><i class="fab fa-cc-stripe"></i> <div>Stripe</div></li>
    <li><i class="fab fa-cc-visa"></i> <div>VISA</div></li>
  </ul>

enter image description here

DEMO HERE

Converting a JS object to an array using jQuery

ES8 way made easy:

The official documentation

_x000D_
_x000D_
    const obj = { x: 'xxx', y: 1 };_x000D_
    let arr = Object.values(obj); // ['xxx', 1]_x000D_
    console.log(arr);
_x000D_
_x000D_
_x000D_