Programs & Examples On #Freb

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

How can I get selector from jQuery object

Thank you p1nox!

My problem was to put focus back on an ajax call that was modifying part of the form.

$.ajax({  url : "ajax_invite_load.php",
        async : true,
         type : 'POST',
         data : ...
     dataType : 'html',
      success : function(html, statut) {
                    var focus = $(document.activeElement).getSelector();
                    $td_left.html(html);
                    $(focus).focus();
                }
});

I just needed to encapsulate your function in a jQuery plugin:

    !(function ($, undefined) {

    $.fn.getSelector = function () {
      if (!this || !this.length) {
        return ;
      }

      function _getChildSelector(index) {
        if (typeof index === 'undefined') {
          return '';
        }

        index = index + 1;
        return ':nth-child(' + index + ')';
      }

      function _getIdAndClassNames($el) {
        var selector = '';

        // attach id if exists
        var elId = $el.attr('id');
        if(elId){
          selector += '#' + elId;
        }

        // attach class names if exists
        var classNames = $el.attr('class');
        if(classNames){
          selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
        }

        return selector;
      }

      // get all parents siblings index and element's tag name,
      // except html and body elements
      var selector = this.parents(':not(html,body)')
        .map(function() {
          var parentIndex = $(this).index();

          return this.tagName + _getChildSelector(parentIndex);
        })
        .get()
        .reverse()
        .join(' ');

      if (selector) {
        // get node name from the element itself
        selector += ' ' + this[0].nodeName +
          // get child selector from element ifself
          _getChildSelector(this.index());
      }

      selector += _getIdAndClassNames(this);

      return selector;
    }

})(window.jQuery);

Is it possible to change the content HTML5 alert messages?

Thank you guys for the help,

When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:

http://blog.thomaslebrun.net/2011/11/html-5-how-to-customize-the-error-message-for-a-required-field/#.UsNN1BYrh2M

How to rename a class and its corresponding file in Eclipse?

I found the answers above didn't give me the guidance I needed (I too expected to be in the code for the .java file, and right-click on the tab and see a Refactor option). Here's what I did:

  1. Go to the top of the .java module (ctrl+Home)
  2. Double-click on the class name that is the same name as the .java module and the class name should now be highlight
  3. Right-click the highlighted class name | Open Type Hierarchy. The Type Hierarchy should open showing the class name
  4. Right-click the class name in the Type Hierarchy | Refactor | Rename | type the new name in the popup window Rename Type

Defining arrays in Google Scripts

I think that maybe it is because you are declaring a variable that you already declared:

var Name = new Array(6);
//...
var Name[0] = Name_cell.getValue();  //  <-- Here's the issue: 'var'

I think this should be like this:

var Name = new Array(6);
//...
Name[0] = Name_cell.getValue();

Tell me if it works! ;)

How to get user's high resolution profile picture on Twitter?

use this URL : "https://twitter.com/(userName)/profile_image?size=original"

If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient, using TWTRAuthSession.

This is the code snipe for iOS:

if let twitterId = session.userID{
   let twitterClient = TWTRAPIClient(userID: twitterId)
   twitterClient.loadUser(withID: twitterId) {(user, error) in
       if let userName = user?.screenName{
          let url = "https://twitter.com/\(userName)/profile_image?size=original")
       }
   }
}

Remove the last three characters from a string

str= str.Remove(str.Length - 3);

Change package name for Android in React Native

I've used the react-native-rename package.

In terminal run the command to install:

npm install react-native-rename -g

In the root of your React Native project, run the following command:

react-native-rename "NewNameOfApp" -b com.companyname.newnameofapp

Execute SQLite script

You want to feed the create.sql into sqlite3 from the shell, not from inside SQLite itself:

$ sqlite3 auction.db < create.sql

SQLite's version of SQL doesn't understand < for files, your shell does.

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

Computing cross-correlation function?

If you are looking for a rapid, normalized cross correlation in either one or two dimensions I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).

While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.

import numpy
import cv

#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp

#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )

#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv =  cv.fromarray(numpy.float32(resultNp))

#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)

#convert result back to numpy array
resultNp = np.asarray(resultCv)

For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.

Preferred way of getting the selected item of a JComboBox

JComboBox mycombo=new JComboBox(); //Creates mycombo JComboBox.
add(mycombo); //Adds it to the jframe.

mycombo.addItem("Hello Nepal");  //Adds data to the JComboBox.

String s=String.valueOf(mycombo.getSelectedItem());  //Assigns "Hello Nepal" to s.

System.out.println(s);  //Prints "Hello Nepal".

Get the current time in C

Copy-pasted from here:

/* localtime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );
  
  return 0;
}

(just add void to the main() arguments list in order for this to work in C)

Cannot checkout, file is unmerged

In my case, I found that I need the -f option. Such as the following:

git rm -f first_file.txt

to get rid of the "needs merge" error.

How to import RecyclerView for Android L-preview

This works for me:

compile 'com.android.support:recyclerview-v7:21.0.0-rc1'

Android studio, gradle and NDK

We have released a first version of the integration as a preview in 1.3: http://tools.android.com/tech-docs/android-ndk-preview

The integration will stay a preview even after 1.3 becomes final. No current ETA as to when it'll be final (as of 2015/07/10).

More information here: http://tools.android.com/tech-docs/android-ndk-preview

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

Here a code that works with windows office 2010. This script will ask you for input filtered range of cells and then the paste range.

Please, both ranges should have the same number of cells.

Sub Copy_Filtered_Cells()

Dim from As Variant
Dim too As Variant
Dim thing As Variant
Dim cell As Range

'Selection.SpecialCells(xlCellTypeVisible).Select

    'Set from = Selection.SpecialCells(xlCellTypeVisible)
    Set temp = Application.InputBox("Copy Range :", Type:=8)
    Set from = temp.SpecialCells(xlCellTypeVisible)
    Set too = Application.InputBox("Select Paste range selected cells ( Visible cells only)", Type:=8)



    For Each cell In from
        cell.Copy
        For Each thing In too
            If thing.EntireRow.RowHeight > 0 Then
                thing.PasteSpecial
                Set too = thing.Offset(1).Resize(too.Rows.Count)
                Exit For
            End If
        Next
    Next


End Sub

Enjoy!

How do I delete all messages from a single queue using the CLI?

IMPORTANT NOTE: This will delete all users and config.

ALERT !!

ALERT !!

I don't suggest this answer until unless you want to delete data from all of the queues, including users and configs. Just Reset it !!!

rabbitmqctl stop_app
rabbitmqctl reset
rabbitmqctl start_app

How to detect a route change in Angular?

In the component, you might want to try this:

import {NavigationEnd, NavigationStart, Router} from '@angular/router';

constructor(private router: Router) {
router.events.subscribe(
        (event) => {
            if (event instanceof NavigationStart)
                // start loading pages
            if (event instanceof NavigationEnd) {
                // end of loading paegs
            }
        });
}

How do I round a float upwards to the nearest int in C#?

Off the top of my head:

float fl = 0.678;
int rounded_f = (int)(fl+0.5f);

How to get a float result by dividing two integer values using T-SQL?

Because SQL Server performs integer division. Try this:

select 1 * 1.0 / 3

This is helpful when you pass integers as params.

select x * 1.0 / y

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

For me, it was caused before I referred a library (specifically typeORM, using the ormconfig.js file, under the entities key) to the src folder, instead of the dist folder...

   "entities": [
      "src/db/entity/**/*.ts", // Pay attention to "src" and "ts" (this is wrong)
   ],

instead of

   "entities": [
      "dist/db/entity/**/*.js", // Pay attention to "dist" and "js" (this is the correct way)
   ],

printf with std::string?

printf accepts a variable number of arguments. Those can only have Plain Old Data (POD) types. Code that passes anything other than POD to printf only compiles because the compiler assumes you got your format right. %s means that the respective argument is supposed to be a pointer to a char. In your case it is an std::string not const char*. printf does not know it because the argument type goes lost and is supposed to be restored from the format parameter. When turning that std::string argument into const char* the resulting pointer will point to some irrelevant region of memory instead of your desired C string. For that reason your code prints out gibberish.

While printf is an excellent choice for printing out formatted text, (especially if you intend to have padding), it can be dangerous if you haven't enabled compiler warnings. Always enable warnings because then mistakes like this are easily avoidable. There is no reason to use the clumsy std::cout mechanism if the printf family can do the same task in a much faster and prettier way. Just make sure you have enabled all warnings (-Wall -Wextra) and you will be good. In case you use your own custom printf implementation you should declare it with the __attribute__ mechanism that enables the compiler to check the format string against the parameters provided.

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

Open PDF in new browser full window

I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)

Why not just stream down the content with the correct content specifier?

That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.

What is the significance of 1/1/1753 in SQL Server?

Incidentally, Windows no longer knows how to correctly convert UTC to U.S. local time for certain dates in March/April or October/November of past years. UTC-based timestamps from those dates are now somewhat nonsensical. It would be very icky for the OS to simply refuse to handle any timestamps prior to the U.S. government's latest set of DST rules, so it simply handles some of them wrong. SQL Server refuses to process dates before 1753 because lots of extra special logic would be required to handle them correctly and it doesn't want to handle them wrong.

Injecting Mockito mocks into a Spring bean

Since 1.8.3 Mockito has @InjectMocks - this is incredibly useful. My JUnit tests are @RunWith the MockitoJUnitRunner and I build @Mock objects that satisfy all the dependencies for the class being tested, which are all injected when the private member is annotated with @InjectMocks.

I @RunWith the SpringJUnit4Runner for integration tests only now.

I will note that it does not seem to be able to inject List<T> in the same manner as Spring. It looks only for a Mock object that satisfies the List, and will not inject a list of Mock objects. The workaround for me was to use a @Spy against a manually instantiated list, and manually .add the mock object(s) to that list for unit testing. Maybe that was intentional, because it certainly forced me to pay close attention to what was being mocked together.

Docker CE on RHEL - Requires: container-selinux >= 2.9

Just install selinux latest version to fix it:
sudo yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-3.el7.noarch.rpm

More versions at http://mirror.centos.org/centos/7/extras/x86_64/Packages/

Older versions of 2.9: http://ftp.riken.jp/Linux/cern/centos/7/extras/x86_64/Packages/

remove item from array using its name / value

Try this.(IE8+)

//Define function
function removeJsonAttrs(json,attrs){
    return JSON.parse(JSON.stringify(json,function(k,v){
        return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);

Turning off hibernate logging console output

I managed to stop by adding those 2 lines

log4j.logger.org.hibernate.orm.deprecation=error

log4j.logger.org.hibernate=error

Bellow is what my log4j.properties looks like, i just leave some commented lines explaining the log level

# Root logger option
#Level/rules TRACE < DEBUG < INFO < WARN < ERROR < FATAL.
#FATAL: shows messages at a FATAL level only
#ERROR: Shows messages classified as ERROR and FATAL
#WARNING: Shows messages classified as WARNING, ERROR, and FATAL
#INFO: Shows messages classified as INFO, WARNING, ERROR, and FATAL
#DEBUG: Shows messages classified as DEBUG, INFO, WARNING, ERROR, and FATAL
#TRACE : Shows messages classified as TRACE,DEBUG, INFO, WARNING, ERROR, and FATAL
#ALL : Shows messages classified as TRACE,DEBUG, INFO, WARNING, ERROR, and FATAL
#OFF : No log messages display


log4j.rootLogger=INFO, file, console

log4j.logger.main=DEBUG
log4j.logger.org.hibernate.orm.deprecation=error
log4j.logger.org.hibernate=error

#######################################
# Direct log messages to a log file
log4j.appender.file.Threshold=ALL
log4j.appender.file.file=logs/MyProgram.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} - %m%n

# set file size limit
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=50


#############################################
# Direct log messages to System Out
log4j.appender.console.Threshold=INFO
log4j.appender.console.Target=System.out
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{HH:mm:ss} %-5p %c{1} - %m%n

jquery disable form submit on enter

if you just want to disable submit on enter and submit button too use form's onsubmit event

<form onsubmit="return false;">

You can replace "return false" with call to JS function that will do whatever needed and also submit the form as a last step.

Installing Apache Maven Plugin for Eclipse

I found Maven Integration for Eclipse here.

http://download.eclipse.org/technology/m2e/releases

After installing restart eclipse. Worked for me running Eclipse Juno.

How to add soap header in java

I struggled to get this working. That's why I'll add a complete solution here:

My objective is to add this header to the SOAP envelope:

   <soapenv:Header>
      <urn:OTAuthentication>
         <urn:AuthenticationToken>TOKEN</urn:AuthenticationToken>
      </urn:OTAuthentication>
   </soapenv:Header>
  1. First create a SOAPHeaderHandler class.

    import java.util.Set;
    import java.util.TreeSet;
    
    import javax.xml.namespace.QName;
    import javax.xml.soap.SOAPElement;
    import javax.xml.soap.SOAPEnvelope;
    import javax.xml.soap.SOAPFactory;
    import javax.xml.soap.SOAPHeader;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.handler.soap.SOAPHandler;
    import javax.xml.ws.handler.soap.SOAPMessageContext;
    
    public class SOAPHeaderHandler implements SOAPHandler<SOAPMessageContext> {
    
        private final String authenticatedToken;
    
        public SOAPHeaderHandler(String authenticatedToken) {
            this.authenticatedToken = authenticatedToken;
        }
    
        public boolean handleMessage(SOAPMessageContext context) {
            Boolean outboundProperty =
                    (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
            if (outboundProperty.booleanValue()) {
                try {
                    SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
                    SOAPFactory factory = SOAPFactory.newInstance();
                    String prefix = "urn";
                    String uri = "urn:api.ecm.opentext.com";
                    SOAPElement securityElem =
                            factory.createElement("OTAuthentication", prefix, uri);
                    SOAPElement tokenElem =
                            factory.createElement("AuthenticationToken", prefix, uri);
                    tokenElem.addTextNode(authenticatedToken);
                    securityElem.addChildElement(tokenElem);
                    SOAPHeader header = envelope.addHeader();
                    header.addChildElement(securityElem);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // inbound
            }
            return true;
        }
    
        public Set<QName> getHeaders() {
            return new TreeSet();
        }
    
        public boolean handleFault(SOAPMessageContext context) {
            return false;
        }
    
        public void close(MessageContext context) {
            //
        }
    }
    
    1. Add the handler to the proxy. Note that according javax.xml.ws.Binding's documentation: "If the returned chain is modified a call to setHandlerChain is required to configure the binding instance with the new chain."

    Authentication_Service authentication_Service = new Authentication_Service();

    Authentication basicHttpBindingAuthentication = authentication_Service.getBasicHttpBindingAuthentication(); String authenticatedToken = "TOKEN"; List<Handler> handlerChain = ((BindingProvider)basicHttpBindingAuthentication).getBinding().getHandlerChain(); handlerChain.add(new SOAPHeaderHandler(authenticatedToken)); ((BindingProvider)basicHttpBindingAuthentication).getBinding().setHandlerChain(handlerChain);

Using Case/Switch and GetType to determine the object

Depending on what you are doing in the switch statement, the correct answer is polymorphism. Just put a virtual function in the interface/base class and override for each node type.

Creating an empty Pandas DataFrame, then filling it?

If you simply want to create an empty data frame and fill it with some incoming data frames later, try this:

newDF = pd.DataFrame() #creates a new dataframe that's empty
newDF = newDF.append(oldDF, ignore_index = True) # ignoring index is optional
# try printing some data from newDF
print newDF.head() #again optional 

In this example I am using this pandas doc to create a new data frame and then using append to write to the newDF with data from oldDF.

If I have to keep appending new data into this newDF from more than one oldDFs, I just use a for loop to iterate over pandas.DataFrame.append()

How can I select from list of values in Oracle

Hi it is also possible for Strings with XML-Table

SELECT trim(COLUMN_VALUE) str FROM xmltable(('"'||REPLACE('a1, b2, a2, c1', ',', '","')||'"'));

How do I check/uncheck all checkboxes with a button using jQuery?

I know this question is old but, I noticed most people are using a checkbox. The accepted answer uses a button, but cannot work with several buttons (ex. one at top of page one at bottom). So here is a modification that does both.

HTML

<a href="#" class="check-box-machine my-button-style">Check All</a>

jQuery

var ischecked = false;
$(".check-box-machine").click(function(e) {
    e.preventDefault();
    if (ischecked == false) {
        $("input:checkbox").attr("checked","checked");
        $(".check-box-machine").html("Uncheck All");
        ischecked = true;
    } else {
        $("input:checkbox").removeAttr("checked");
        $(".check-box-machine").html("Check All");
        ischecked = false;
    }
});

This will allow you to have as many buttons as you would like with changing text and checkbox values. I included an e.preventDefault() call because this will stop the page from jumping to the top due to the href="#" part.

Generate preview image from Video file?

I recommend php-ffmpeg library.

Extracting image

You can extract a frame at any timecode using the FFMpeg\Media\Video::frame method.

This code returns a FFMpeg\Media\Frame instance corresponding to the second 42. You can pass any FFMpeg\Coordinate\TimeCode as argument, see dedicated documentation below for more information.

$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');

If you want to extract multiple images from the video, you can use the following filter:

$video
    ->filters()
    ->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
    ->synchronize();

$video
    ->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');

By default, this will save the frames as jpg images.

You are able to override this using setFrameFileType to save the frames in another format:

$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);

$video->addFilter($filter);

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I know this is an old post, but a good time to use PrimaryKeyColumn would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.

In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn.

Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.

How to add a spinner icon to button when it's in the Loading state?

Here is a full-fledged css solution inspired by Bulma. Just add

    .button {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      position: relative;
      min-width: 200px;
      max-width: 100%;
      min-height: 40px;
      text-align: center;
      cursor: pointer;
    }

    @-webkit-keyframes spinAround {
      from {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      to {
        -webkit-transform: rotate(359deg);
        transform: rotate(359deg);
      }
    }
    @keyframes spinAround {
      from {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      to {
        -webkit-transform: rotate(359deg);
        transform: rotate(359deg);
      }
    }

    .button.is-loading {
      text-indent: -9999px;
      box-shadow: none;
      font-size: 1rem;
      height: 2.25em;
      line-height: 1.5;
      vertical-align: top;
      padding-bottom: calc(0.375em - 1px);
      padding-left: 0.75em;
      padding-right: 0.75em;
      padding-top: calc(0.375em - 1px);
      white-space: nowrap;
    }

    .button.is-loading::after  {
      -webkit-animation: spinAround 500ms infinite linear;
      animation: spinAround 500ms infinite linear;
      border: 2px solid #dbdbdb;
      border-radius: 290486px;
      border-right-color: transparent;
      border-top-color: transparent;
      content: "";
      display: block;
      height: 1em;
      position: relative;
      width: 1em;
    }

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

No, there is not really any other way : if you have many locations and want to display them on a map, the best solution is to :

  • fetch the latitude+longitude, using the geocoder, when a location is created
  • store those in your database, alongside the address
  • and use those stored latitude+longitude when you want to display the map.

This is, of course, considering that you have a lot less creation/modification of locations than you have consultations of locations.


Yes, it means you'll have to do a bit more work when saving the locations -- but it also means :

  • You'll be able to search by geographical coordinates
    • i.e. "I want a list of points that are near where I'm now"
  • Displaying the map will be a lot faster
    • Even with more than 20 locations on it
  • Oh, and, also (last but not least) : this will work ;-)
    • You will less likely hit the limit of X geocoder calls in N seconds.
    • And you will less likely hit the limit of Y geocoder calls per day.

How to override and extend basic Django admin templates?

Chengs's answer is correct, howewer according to the admin docs not every admin template can be overwritten this way: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#overriding-admin-templates

Templates which may be overridden per app or model

Not every template in contrib/admin/templates/admin may be overridden per app or per model. The following can:

app_index.html
change_form.html
change_list.html
delete_confirmation.html
object_history.html

For those templates that cannot be overridden in this way, you may still override them for your entire project. Just place the new version in your templates/admin directory. This is particularly useful to create custom 404 and 500 pages

I had to overwrite the login.html of the admin and therefore had to put the overwritten template in this folder structure:

your_project
 |-- your_project/
 |-- myapp/
 |-- templates/
      |-- admin/
          |-- login.html  <- do not misspell this

(without the myapp subfolder in the admin) I do not have enough repution for commenting on Cheng's post this is why I had to write this as new answer.

How to install ADB driver for any android device?

UNIVERSAL ADB DRIVER

I have thesame issue before but i solved it easily by just following this steps:

*connect your android phone in a debugging mode (to enable debugging mode goto settings scroll down About Phone scroll down tap seven times Build Number and it will automatically enable developer option turn on developer options and check USB debugging)

download Universal ADB Driver Installer

*choose Adb Driver Installer (Universal)

*install it *it will automatically detect your android device(any kind of brand) *chose the device and install

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I imported the project as general project from git repository.

  • Deleted .settings, .project and .classpath in project's folder
  • Configure -> Convert to Maven Project. Only this solved the problem in my case.

how to configure hibernate config file for sql server

Properties that are database specific are:

  • hibernate.connection.driver_class: JDBC driver class
  • hibernate.connection.url: JDBC URL
  • hibernate.connection.username: database user
  • hibernate.connection.password: database password
  • hibernate.dialect: The class name of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular relational database.

To change the database, you must:

  1. Provide an appropriate JDBC driver for the database on the class path,
  2. Change the JDBC properties (driver, url, user, password)
  3. Change the Dialect used by Hibernate to talk to the database

There are two drivers to connect to SQL Server; the open source jTDS and the Microsoft one. The driver class and the JDBC URL depend on which one you use.

With the jTDS driver

The driver class name is net.sourceforge.jtds.jdbc.Driver.

The URL format for sqlserver is:

 jdbc:jtds:sqlserver://<server>[:<port>][/<database>][;<property>=<value>[;...]]

So the Hibernate configuration would look like (note that you can skip the hibernate. prefix in the properties):

<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
    <property name="connection.url">jdbc:jtds:sqlserver://<server>[:<port>][/<database>]</property>
    <property name="connection.username">sa</property>
    <property name="connection.password">lal</property>

    <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>

    ...
  </session-factory>
</hibernate-configuration>

With Microsoft SQL Server JDBC 3.0:

The driver class name is com.microsoft.sqlserver.jdbc.SQLServerDriver.

The URL format is:

jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]

So the Hibernate configuration would look like:

<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="connection.url">jdbc:sqlserver://[serverName[\instanceName][:portNumber]];databaseName=<databaseName></property>
    <property name="connection.username">sa</property>
    <property name="connection.password">lal</property>

    <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>

    ...
  </session-factory>
</hibernate-configuration>

References

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

This works better, as you can show validationMessage for a specified key:

    ModelState.AddModelError("keyName","Message");

and display it like this:

    @Html.ValidationMessage("keyName")

Setting href attribute at runtime

In jQuery 1.6+ it's better to use:

$(selector).prop('href',"http://www...") to set the value, and

$(selector).prop('href') to get the value

In short, .prop gets and sets values on the DOM object, and .attr gets and sets values in the HTML. This makes .prop a little faster and possibly more reliable in some contexts.

What are the rules about using an underscore in a C++ identifier?

Yes, underscores may be used anywhere in an identifier. I believe the rules are: any of a-z, A-Z, _ in the first character and those +0-9 for the following characters.

Underscore prefixes are common in C code -- a single underscore means "private", and double underscores are usually reserved for use by the compiler.

Text in HTML Field to disappear when clicked?

Simple as this: <input type="text" name="email" value="e-mail..." onFocus="this.value=''">

Difference between java HH:mm and hh:mm on SimpleDateFormat

Actually the last one is not weird. Code is setting the timezone for working instead of working2.

SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).

Fixing this error gives:

24:00:00
00:00:00
01:00:00

Why is printing "B" dramatically slower than printing "#"?

I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8; I used System.nanoTime() for measurements.

Eclipse:

I got the same time on both cases - around 1.564 seconds.

Netbeans:

  • Using "#": 1.536 seconds
  • Using "B": 44.164 seconds

So, it looks like Netbeans has bad performance on print to console.

After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println command), demonstrated by this code:

for (int i = 0; i < 1000; i++) {
    long t1 = System.nanoTime();
    System.out.print("BBB......BBB"); \\<-contain 1000 "B"
    long t2 = System.nanoTime();
    System.out.println(t2-t1);
    System.out.println("");
}

The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):

BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.

And so on..

Summary:

  1. Eclipse works perfectly with "B"
  2. Netbeans has a line-wrapping problem that can be solved (because the problem does not occur in eclipse)(without adding space after B ("B ")).

How to get first item from a java.util.Set?

As, you mentioned pContext.getParent().getPropertyValue return Set. You can convert Set to List to get the first element. Just change your code like:

 Set<String> siteIdSet = (Set<String>) pContext.getParent().getPropertyValue(..);
 List<String> siteIdList=new ArrayList<>(siteIdSet);

 String firstItem=siteIdList.get(0);

How to add "Maven Managed Dependencies" library in build path eclipse?

I could figure out the problem. I was getting following warning on startup of eclipse.

The Maven Integration requires that Eclipse be running in a JDK, because a number of Maven core plugins are using jars from the JDk.

Please make sure the -vm option in eclipse.ini is pointing to a JDK and verify that
Installed JRE's are also using JDK installs

I changed eclipse.ini file and added following and restarted eclipse

-vm
C:/Program Files/java/jdk1.6.0_21/bin/javaw.exe

Now I can see "Maven Dependency" library included automatically in java build path.

How to wrap text using CSS?

This will work everywhere.

<body>
  <table style="table-layout:fixed;">
  <tr>
    <td><div style="word-wrap: break-word; width: 100px" > gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div></td>
  </tr>
  </table>
 </body>

PHP: Calling another class' method

If they are separate classes you can do something like the following:

class A
{
    private $name;

    public function __construct()
    {
        $this->name = 'Some Name';
    }

    public function getName()
    {
        return $this->name;
    }
}

class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    function getNameOfA()
    {
        return $this->a->getName();
    }
}

$a = new A();
$b = new B($a);

$b->getNameOfA();

What I have done in this example is first create a new instance of the A class. And after that I have created a new instance of the B class to which I pass the instance of A into the constructor. Now B can access all the public members of the A class using $this->a.

Also note that I don't instantiate the A class inside the B class because that would mean I tighly couple the two classes. This makes it hard to:

  1. unit test your B class
  2. swap out the A class for another class

jQuery lose focus event

Use blur event to call your function when element loses focus :

$('#filter').blur(function() {
  $('#options').hide();
});

Detect if a page has a vertical scrollbar?

$(document).ready(function() {
    // Check if body height is higher than window height :)
    if ($("body").height() > $(window).height()) {
        alert("Vertical Scrollbar! D:");
    }

    // Check if body width is higher than window width :)
    if ($("body").width() > $(window).width()) {
        alert("Horizontal Scrollbar! D:<");
    }
});

WPF MVVM: How to close a window

You can do it without code behind. Create command, in Execute method call "Save" method on viewmodel and after that call close method on edit window, which you can pass to the command by parameter:

public void Execute(object parameter)
{
    _mainViewModel.SaveSomething();
    var editWindow = parameter as MyEditWindow;
    editWindow?.Close();
}

Save&Close button XAML:

<Button Content"Save&Close" Command="{Binding SaveCmd}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"  IsDefault="True" />

How to write trycatch in R

R uses functions for implementing try-catch block:

The syntax somewhat looks like this:

result = tryCatch({
    expr
}, warning = function(warning_condition) {
    warning-handler-code
}, error = function(error_condition) {
    error-handler-code
}, finally={
    cleanup-code
})

In tryCatch() there are two ‘conditions’ that can be handled: ‘warnings’ and ‘errors’. The important thing to understand when writing each block of code is the state of execution and the scope. @source

Truncating a table in a stored procedure

All DDL statements in Oracle PL/SQL should use Execute Immediate before the statement. Hence you should use:

execute immediate 'truncate table schema.tablename';

Is there a "between" function in C#?

So far, it looks like none of the answers have considered the likely possibility that dynamically, you don't know which value is the lower and upper bound. For the general case, you could create your own IsBetween method that would probably go something like:

    public bool IsBetween(double testValue, double bound1, double bound2)
    {
        return (testValue >= Math.Min(bound1,bound2) && testValue <= Math.Max(bound1,bound2));
    }

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Execute ssh with password authentication via windows command prompt

PowerShell solution

Using Posh-SSH:

New-SSHSession -ComputerName 0.0.0.0 -Credential $cred | Out-Null
Invoke-SSHCommand -SessionId 1 -Command "nohup sleep 5 >> abs.log &" | Out-Null

How to create a signed APK file using Cordova command line interface?

##Generated signed apk from commandline
#variables
APP_NAME=THE_APP_NAME
APK_LOCATION=./
APP_HOME=/path/to/THE_APP
APP_KEY=/path/to/Android_key
APP_KEY_ALIAS=the_alias
APP_KEY_PASSWORD=123456789
zipalign=$ANDROID_HOME/build-tools/28.0.3/zipalign

#the logic
cd $APP_HOME
cordova build --release android
cd platforms/android/app/build/outputs/apk/release
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore $APP_KEY ./app-release-unsigned.apk $APP_KEY_ALIAS <<< $APP_KEY_PASSWORD
rm -rf "$APK_LOCATION/$APP_NAME.apk"
$zipalign -v 4 ./app-release-unsigned.apk "$APK_LOCATION/$APP_NAME.apk"
open $APK_LOCATION
#the end

Why is quicksort better than mergesort?

Quicksort is NOT better than mergesort. With O(n^2) (worst case that rarely happens), quicksort is potentially far slower than the O(nlogn) of the merge sort. Quicksort has less overhead, so with small n and slow computers, it is better. But computers are so fast today that the additional overhead of a mergesort is negligible, and the risk of a very slow quicksort far outweighs the insignificant overhead of a mergesort in most cases.

In addition, a mergesort leaves items with identical keys in their original order, a useful attribute.

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

In my case, I tried everything above, nothing worked. I am pretty sure, my database looks like below.

mysql  Ver 14.14 Distrib 5.7.17, for Linux (x86_64) using  EditLine wrapper

Connection id:      12
Current database:   xxx
Current user:       yo@localhost
SSL:            Not in use
Current pager:      stdout
Using outfile:      ''
Using delimiter:    ;
Server version:     5.7.17-0ubuntu0.16.04.1 (Ubuntu)
Protocol version:   10
Connection:     Localhost via UNIX socket
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:        /var/run/mysqld/mysqld.sock
Uptime:         42 min 49 sec

Threads: 1  Questions: 372  Slow queries: 0  Opens: 166  Flush tables: 1  Open tables: 30  Queries per second avg: 0.144

so, I look up the column charset in every table

show create table company;

It turns out the column charset is latin. That's why, I can not insert Chinese into database.

 ALTER TABLE company CONVERT TO CHARACTER SET utf8;

That might help you. :)

MySQL: Check if the user exists and drop it

This worked for me:

GRANT USAGE ON *.* TO 'username'@'localhost';
DROP USER 'username'@'localhost';

This creates the user if it doesn't already exist (and grants it a harmless privilege), then deletes it either way. Found solution here: http://bugs.mysql.com/bug.php?id=19166

Updates: @Hao recommends adding IDENTIFIED BY; @andreb (in comments) suggests disabling NO_AUTO_CREATE_USER.

ArrayList filter

Iterate through the list and check if contains your string "How" and if it does then remove. You can use following code:

// need to construct a new ArrayList otherwise remove operation will not be supported
List<String> list = new ArrayList<String>(Arrays.asList(new String[] 
                                  {"How are you?", "How you doing?","Joe", "Mike"}));
System.out.println("List Before: " + list);
for (Iterator<String> it=list.iterator(); it.hasNext();) {
    if (!it.next().contains("How"))
        it.remove(); // NOTE: Iterator's remove method, not ArrayList's, is used.
}
System.out.println("List After: " + list);

OUTPUT:

List Before: [How are you?, How you doing?, Joe, Mike]
List After: [How are you?, How you doing?]

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Converting xml to string using C#

As Chris suggests, you can do it like this:

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

Or like this:

public string GetXMLAsString(XmlDocument myxml)
    {

        StringWriter sw = new StringWriter();
        XmlTextWriter tx = new XmlTextWriter(sw);
        myxml.WriteTo(tx);

        string str = sw.ToString();// 
        return str;
    }

and if you really want to create a new XmlDocument then do this

XmlDocument newxmlDoc= myxml

How to copy directories with spaces in the name

robocopy "C:\Users\Angie\My Documents" "C:\test-backup\My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Music" "C:\test-backup\My Music" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Pictures" "C:\test-backup\My Pictures" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"

how to call a method in another Activity from Activity

If you need to call the same method from both Activities why not then use a third object?

public class FirstActivity extends Activity 
{  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

    }      

    // Utility.method() used somewhere in FirstActivity
}

public class Utility {

    public static void method()
    {

    }  

}

public class SecondActivity extends Activity 
{  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

        Utility.method();

    }
}

Of course making it static depends on the use case.

Execute a shell script in current shell with sudo permission

Easiest method is to type:

sudo /bin/sh example.sh

What is the difference between 'java', 'javaw', and 'javaws'?

I have checked that the output redirection works with javaw:

javaw -cp ... mypath.MyClass ... arguments 1>log.txt 2>err.txt

It means, if the Java application prints out anything via System.out or System.err, it is written to those files, as also with using java (without w). Especially on starting java, the JRE may write starting errors (class not found) on the error output pipe. In this respect, it is essential to know about errors. I suggest to use the console redirection in any case if javaw is invoked.

In opposite if you use

start java .... 1>log.txt 2>err.txt

With the Windows console start command, the console output redirection does not work with java nor with javaw.

Explanation why it is so: I think that javaw opens an internal process in the OS (adequate using the java.lang.Process class), and transfers a known output redirection to this process. If no redirection is given on the command line, nothing is redirected and the internal started process for javaw doesn't have any console outputs. The behavior for java.lang.Process is similar. The virtual machine may use this internal feature for javaw too.

If you use 'start', the Windows console creates a new process for Windows to execute the command after start, but this mechanism does not use a given redirection for the started sub process, unfortunately.

Method has the same erasure as another method in type

The problem is that Set<Integer> and Set<String> are actually treated as a Set from the JVM. Selecting a type for the Set (String or Integer in your case) is only syntactic sugar used by the compiler. The JVM can't distinguish between Set<String> and Set<Integer>.

vagrant login as root by default

Adding this to the Vagrantfile worked for me. These lines are the equivalent of you entering sudo su - every time you login. Please notice that this requires reprovisioning the VM.

config.vm.provision "shell", inline: <<-SHELL
    echo "sudo su -" >> .bashrc
SHELL

How can I make my flexbox layout take 100% vertical space?

You should set height of html, body, .wrapper to 100% (in order to inherit full height) and then just set a flex value greater than 1 to .row3 and not on the others.

_x000D_
_x000D_
.wrapper, html, body {
    height: 100%;
    margin: 0;
}
.wrapper {
    display: flex;
    flex-direction: column;
}
#row1 {
    background-color: red;
}
#row2 {
    background-color: blue;
}
#row3 {
    background-color: green;
    flex:2;
    display: flex;
}
#col1 {
    background-color: yellow;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col2 {
    background-color: orange;
    flex: 1 1;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col3 {
    background-color: purple;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
_x000D_
<div class="wrapper">
    <div id="row1">this is the header</div>
    <div id="row2">this is the second line</div>
    <div id="row3">
        <div id="col1">col1</div>
        <div id="col2">col2</div>
        <div id="col3">col3</div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

DEMO

document.all vs. document.getElementById

document.all is a proprietary Microsoft extension to the W3C standard.

getElementById() is standard - use that.

However, consider if using a js library like jQuery would come in handy. For example, $("#id") is the jQuery equivalent for getElementById(). Plus, you can use more than just CSS3 selectors.

How to make execution pause, sleep, wait for X seconds in R?

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
{
  print(i)
  date_time<-Sys.time()
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}

Better way to cast object to int

You can first cast object to string and then cast the string to int; for example:

string str_myobject = myobject.ToString();
int int_myobject = int.Parse(str_myobject);

this worked for me.

How to convert Double to int directly?

double myDb = 12.3;
int myInt = (int) myDb;

Result is: myInt = 12

How to check if a list is empty in Python?

if not myList:
  print "Nothing here"

Is floating point math broken?

Did you try the duct tape solution?

Try to determine when errors occur and fix them with short if statements, it's not pretty but for some problems it is the only solution and this is one of them.

 if( (n * 0.1) < 100.0 ) { return n * 0.1 - 0.000000000000001 ;}
                    else { return n * 0.1 + 0.000000000000001 ;}    

I had the same problem in a scientific simulation project in c#, and I can tell you that if you ignore the butterfly effect it's gonna turn to a big fat dragon and bite you in the a**

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

Also you can use LINQ. For example for clear Textbox text do something like:

this.Controls.OfType<TextBox>().ToList().ForEach(t => t.Text = string.Empty);

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Oracle will try to recompile invalid objects as they are referred to. Here the trigger is invalid, and every time you try to insert a row it will try to recompile the trigger, and fail, which leads to the ORA-04098 error.

You can select * from user_errors where type = 'TRIGGER' and name = 'NEWALERT' to see what error(s) the trigger actually gets and why it won't compile. In this case it appears you're missing a semicolon at the end of the insert line:

INSERT INTO Users (userID, firstName, lastName, password)
VALUES ('how', 'im', 'testing', 'this trigger')

So make it:

CREATE OR REPLACE TRIGGER newAlert
AFTER INSERT OR UPDATE ON Alerts
  BEGIN
        INSERT INTO Users (userID, firstName, lastName, password)
        VALUES ('how', 'im', 'testing', 'this trigger');
  END;           
/

If you get a compilation warning when you do that you can do show errors if you're in SQL*Plus or SQL Developer, or query user_errors again.

Of course, this assumes your Users tables does have those column names, and they are all varchar2... but presumably you'll be doing something more interesting with the trigger really.

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

Python variables as keys to dict

Not the most elegant solution, and only works 90% of the time:

def vardict(*args):
    ns = inspect.stack()[1][0].f_locals
    retval = {}
    for a in args:
        found = False
        for k, v in ns.items():
            if a is v:
                retval[k] = v
                if found:
                    raise ValueError("Value found in more than one local variable: " + str(a))
                found = True
        if found:
            continue
        if 'self' in ns:
            for k, v in ns['self'].__dict__.items():
                if a is v:
                    retval[k] = v
                    if found:
                        raise ValueError("Value found in more than one instance attribute: " + str(a))
                    found = True
        if found:
            continue
        for k, v in globals().items():
            if a is v:
                retval[k] = v
                if found:
                    raise ValueError("Value found in more than one global variable: " + str(a))
                found = True
        assert found, "Couldn't find one of the parameters."
    return retval

You'll run into problems if you store the same reference in multiple variables, but also if multiple variables store the same small int, since these get interned.

Disable Pinch Zoom on Mobile Web

IE has its own way: A css property, -ms-content-zooming. Setting it to none on the body or something should disable it.

Disable pinch to zoom in IE10

http://msdn.microsoft.com/en-us/library/ie/hh771891(v=vs.85).aspx

Remove all whitespace from C# string with regex

Using REGEX you can remove the spaces in a string.

The following namespace is mandatory.

using System.Text.RegularExpressions;

Syntax:

Regex.Replace(text, @"\s", "")

How to write log file in c#?

create a class create a object globally and call this

using System.IO;
using System.Reflection;


   public class LogWriter
{
    private string m_exePath = string.Empty;
    public LogWriter(string logMessage)
    {
        LogWrite(logMessage);
    }
    public void LogWrite(string logMessage)
    {
        m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        try
        {
            using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
            {
                Log(logMessage, w);
            }
        }
        catch (Exception ex)
        {
        }
    }

    public void Log(string logMessage, TextWriter txtWriter)
    {
        try
        {
            txtWriter.Write("\r\nLog Entry : ");
            txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            txtWriter.WriteLine("  :");
            txtWriter.WriteLine("  :{0}", logMessage);
            txtWriter.WriteLine("-------------------------------");
        }
        catch (Exception ex)
        {
        }
    }
}

assign headers based on existing row in dataframe in R

A new answer that uses dplyr and tidyr:

Extracts the desired column names and converts to a list

library(tidyverse)

col_names <- raw_dta %>% 
  slice(2) %>%
  pivot_longer(
    cols = "X2":"X10", # until last named column
    names_to = "old_names",
    values_to = "new_names") %>% 
  pull(new_names)

Removes the incorrect rows and adds the correct column names

dta <- raw_dta %>% 
  slice(-1, -2) %>% # Removes the rows containing new and original names
  set_names(., nm = col_names)

append option to select menu?

HTML

<select id="mySelect">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select>

JavaScript

 var mySelect = document.getElementById('mySelect'),
    newOption = document.createElement('option');

newOption.value = 'bmw';

// Not all browsers support textContent (W3C-compliant)
// When available, textContent is faster (see http://stackoverflow.com/a/1359822/139010)
if (typeof newOption.textContent === 'undefined')
{
    newOption.innerText = 'BMW';
}
else
{
    newOption.textContent = 'BMW';
}

mySelect.appendChild(newOption);

Demo →

Javascript to export html table to Excel

For UTF 8 Conversion and Currency Symbol Export Use this:

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
      if (!table.nodeType) table = document.getElementById(table)
      var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

Django ChoiceField

New method in Django 3

you can use Field.choices Enumeration Types new update in django3 like this :

from django.db import models

class Status(models.TextChoices):
    UNPUBLISHED = 'UN', 'Unpublished'
    PUBLISHED = 'PB', 'Published'


class Book(models.Model):
    status = models.CharField(
        max_length=2,
        choices=Status.choices,
        default=Status.UNPUBLISHED,
    )

django docs

C#: what is the easiest way to subtract time?

Hi if you are going to subtract only Integer value from DateTime then you have to write code like this

DateTime.Now.AddHours(-2)

Here I am subtracting 2 hours from the current date and time

How to increment an iterator by 2?

The very simple answer:

++++iter

The long answer:

You really should get used to writing ++iter instead of iter++. The latter must return (a copy of) the old value, which is different from the new value; this takes time and space.

Note that prefix increment (++iter) takes an lvalue and returns an lvalue, whereas postfix increment (iter++) takes an lvalue and returns an rvalue.

How to store token in Local or Session Storage in Angular 2?

Adding onto Bojan Kogoj's answer:

In your app.module.ts, add a new provider for storage.

@NgModule({
   providers: [
      { provide: Storage, useValue: localStorage }
   ],
   imports:[],
   declarations:[]
})

And then you can use DI to get it wherever you need it.

 @Injectable({
    providedIn:'root'
 })
 export class StateService {
    constructor(private storage: Storage) { }
 }

How to get the position of a character in Python?

There are two string methods for this, find() and index(). The difference between the two is what happens when the search string isn't found. find() returns -1 and index() raises ValueError.

Using find()

>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1

Using index()

>>> myString = 'Position of a character'
>>> myString.index('s')
2
>>> myString.index('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

From the Python manual

string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

And:

string.index(s, sub[, start[, end]])
Like find() but raise ValueError when the substring is not found.

Image Greyscale with CSS & re-color on mouse-over?

You can use a sprite which has both version—the colored and the monochrome—stored into it.

Create a custom View by inflating a layout?

Use the LayoutInflater as I shown below.

    public View myView() {
        View v; // Creating an instance for View Object
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.myview, null);

        TextView text1 = v.findViewById(R.id.dolphinTitle);
        Button btn1 = v.findViewById(R.id.dolphinMinusButton);
        TextView text2 = v.findViewById(R.id.dolphinValue);
        Button btn2 = v.findViewById(R.id.dolphinPlusButton);

        return v;
    }

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

How to Navigate from one View Controller to another using Swift

SWIFT 3.01

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)

What is a regular expression for a MAC Address?

I don't think that the main RegEx is correct as it also classifies

'3D-F2-C9:A6-B3:4F' 

as a valid MAC Address, even though it is not correct. The correct one would be:

((([a-zA-z0-9]{2}[-:]){5}([a-zA-z0-9]{2}))|(([a-zA-z0-9]{2}:){5}([a-zA-z0-9]{2})))

So that every time you can choose ':' or '-' for the whole MAC address.

Why doesn't TFS get latest get the latest?

Every time this happens to me (so far) is because I have local edits pending on the .csproj project file. That file seems to keep a list of all the files included in the project. Any new files added by somebody else are "not downloaded" because they are not in my locally edited (now stale) project file. To get all the files I first have to undo pending changes to the .csproj file first then "get all". I do not have to undo other changes I have made, but I may have to go back and include my new files again (and then the next guy gets the same problem when he tries to "get all"...)

It seems to me there is some fundamental kludginess when multiple people are adding new files at the same time.

(this is in .Net Framework projects, maybe the other frameworks like Core behave differently)

Will using 'var' affect performance?

It's depends of situation, if you try use, this code bellow.

The expression is converted to "OBJECT" and decrease so much the performance, but it's a isolated problem.

CODE:

public class Fruta
{
    dynamic _instance;

    public Fruta(dynamic obj)
    {
        _instance = obj;
    }

    public dynamic GetInstance()
    {
        return _instance;
    }
}

public class Manga
{
    public int MyProperty { get; set; }
    public int MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }
    public int MyProperty3 { get; set; }
}

public class Pera
{
    public int MyProperty { get; set; }
    public int MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }
}

public class Executa
{
    public string Exec(int count, int value)
    {
        int x = 0;
        Random random = new Random();
        Stopwatch time = new Stopwatch();
        time.Start();

        while (x < count)
        {
            if (value == 0)
            {
                var obj = new Pera();
            }
            else if (value == 1)
            {
                Pera obj = new Pera();
            }
            else if (value == 2)
            {
                var obj = new Banana();
            }
            else if (value == 3)
            {
                var obj = (0 == random.Next(0, 1) ? new Fruta(new Manga()).GetInstance() : new Fruta(new Pera()).GetInstance());
            }
            else
            {
                Banana obj = new Banana();
            }

            x++;
        }

        time.Stop();
        return time.Elapsed.ToString();
    }

    public void ExecManga()
    {
        var obj = new Fruta(new Manga()).GetInstance();
        Manga obj2 = obj;
    }

    public void ExecPera()
    {
        var obj = new Fruta(new Pera()).GetInstance();
        Pera obj2 = obj;
    }
}

Above results with ILSPY.

public string Exec(int count, int value)
{
    int x = 0;
    Random random = new Random();
    Stopwatch time = new Stopwatch();
    time.Start();

    for (; x < count; x++)
    {
        switch (value)
        {
            case 0:
                {
                    Pera obj5 = new Pera();
                    break;
                }
            case 1:
                {
                    Pera obj4 = new Pera();
                    break;
                }
            case 2:
                {
                    Banana obj3 = default(Banana);
                    break;
                }
            case 3:
                {
                    object obj2 = (random.Next(0, 1) == 0) ? new Fruta(new Manga()).GetInstance() : new Fruta(new Pera()).GetInstance();
                    break;
                }
            default:
                {
                    Banana obj = default(Banana);
                    break;
                }
        }
    }
time.Stop();
return time.Elapsed.ToString();
}

If you wish execute this code use the code bellow, and get the difference of times.

        static void Main(string[] args)
    {
        Executa exec = new Executa();            
        int x = 0;
        int times = 4;
        int count = 100000000;
        int[] intanceType = new int[4] { 0, 1, 2, 3 };

        while(x < times)
        {                
            Parallel.For(0, intanceType.Length, (i) => {
                Console.WriteLine($"Tentativa:{x} Tipo de Instancia: {intanceType[i]} Tempo Execução: {exec.Exec(count, intanceType[i])}");
            });
            x++;
        }

        Console.ReadLine();
    }

Regards

Looping through list items with jquery

   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
   <script>
      $(document).ready(function() {
      $("form").submit(function(e){
          e.preventDefault();
       var name = $("#name").val();
       var amount =$("#number").val();
       var gst=(amount)*(0.18);
           gst=Math.round(gst);

       var total=parseInt(amount)+parseInt(gst);
       $(".myTable tbody").append("<tr><td></td><td>"+name+"</td><td>"+amount+"</td><td>"+gst+"</td><td>"+total+"</td></tr>");
       $("#name").val('');
       $("#number").val('');

       $(".myTable").find("tbody").find("tr").each(function(i){
       $(this).closest('tr').find('td:first-child').text(i+1);

       });

       $("#formdata").on('submit', '.myTable', function () {

                   var sum = 0;

          $(".myTable tbody tr").each(function () {
                    var getvalue = $(this).val();
                    if ($.isNumeric(getvalue))
                     {
                        sum += parseFloat(getvalue);
                     }                  
                     });

                     $(".total").text(sum);
        });

    });
   });

   </script>

     <style>
           #formdata{
                      float:left;
                      width:400px;
                    }

     </style>
  </head>


  <body>  

       <form id="formdata">  

                           <span>Product Name</span>
                           <input type="text" id="name">
                            <br>

                           <span>Product Amount</span>
                           <input type="text" id="number">
                           <br>
                           <br>
                           <center><button type="submit" class="adddata">Add</button></center>
       </form>
       <br>
       <br>

      <table class="myTable" border="1px" width="300px">
      <thead><th>s.no</th><th>Name</th><th>Amount</th><th>Gst</th><th>NetTotal</th></thead>

      <tbody></tbody>

      <tfoot>
             <tr>
                 <td></td>
                 <td></td>
                 <td></td>
                 <td class="total"></td>
                 <td class="total"></td>
             </tr>

      </tfoot>
      </table>

   </body>

html cellpadding the left side of a cell

I use inline css all the time BECAUSE.... I want absolute control of the design and place different things aligned differently from cell to cell.

It is not hard to understand...

Anyway, I just put something like this inside my tag:

style='padding:5px 10px 5px 5px'

Where the order represents top, right, bottom and left.

How do I tell a Python script to use a particular version

put at the start of my programs its use full for work with python

import sys

if sys.version_info[0] < 3:
    raise Exception("Python 3 or a more recent version is required.")

This code will help full for the progress

Stored Procedure error ORA-06550

create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS)  from PLAYERREGULARSEASON  where TEAM    = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)

LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;

END;
/

how to call javascript function in html.actionlink in asp.net mvc?

@Html.ActionLink("Edit","ActionName",new{id=item.id},new{onclick="functionname();"})

Why maven settings.xml file is not there?

As per the maven's documentation, there are two possible settings.xml locations

One is the global maven's repo (Your initial download and subsequent unzipped files from apache maven) $M2_HOME/conf/settings.xml

And the second is the user created one (Your local copy) ${user.home}/.m2/settings.xml

The local copy takes precedence over the global copy in terms of settings information. But it is said that they both get merged during "runtime". If you need to have your local copy of the settings.xml, simply copy from the global copy and paste in your .m2 folder and adjust the details as needed

Is it possible to refresh a single UITableViewCell in a UITableView?

Once you have the indexPath of your cell, you can do something like:

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates]; 

In Xcode 4.6 and higher:

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPathOfYourCell] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates]; 

You can set whatever your like as animation effect, of course.

Using GregorianCalendar with SimpleDateFormat

tl;dr

LocalDate.parse(
    "23-Mar-2017" ,
    DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) 
)

Avoid legacy date-time classes

The Question and other Answers are now outdated, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Using java.time

You seem to be dealing with date-only values. So do not use a date-time class. Instead use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Parse a string.

String input = "23-Mar-2017" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f );

Generate a string.

String output = ld.format( f );

If you were given numbers rather than text for the year, month, and day-of-month, use LocalDate.of.

LocalDate ld = LocalDate.of( 2017 , 3 , 23 );  // ( year , month 1-12 , day-of-month )

See this code run live at IdeOne.com.

input: 23-Mar-2017

ld.toString(): 2017-03-23

output: 23-Mar-2017


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Calculate difference between 2 date / times in Oracle SQL

declare
strTime1 varchar2(50) := '02/08/2013 01:09:42 PM';
strTime2 varchar2(50) := '02/08/2013 11:09:00 PM';
v_date1 date := to_date(strTime1,'DD/MM/YYYY HH:MI:SS PM');
v_date2 date := to_date(strTime2,'DD/MM/YYYY HH:MI:SS PM');
difrence_In_Hours number;
difrence_In_minutes number;
difrence_In_seconds number;
begin
    difrence_In_Hours   := (v_date2 - v_date1) * 24;
    difrence_In_minutes := difrence_In_Hours * 60;
    difrence_In_seconds := difrence_In_minutes * 60;

    dbms_output.put_line(strTime1);        
    dbms_output.put_line(strTime2);
    dbms_output.put_line('*******');
    dbms_output.put_line('difrence_In_Hours  : ' || difrence_In_Hours);
    dbms_output.put_line('difrence_In_minutes: ' || difrence_In_minutes);
    dbms_output.put_line('difrence_In_seconds: ' || difrence_In_seconds);        
end ;

Hope this helps.

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

=ROUND((TODAY()-A1)/365,0) will provide number of years between date in cell A1 and today's date

How to define hash tables in Bash?

I agree with @lhunath and others that the associative array are the way to go with Bash 4. If you are stuck to Bash 3 (OSX, old distros that you cannot update) you can use also expr, which should be everywhere, a string and regular expressions. I like it especially when the dictionary is not too big.

  1. Choose 2 separators that you will not use in keys and values (e.g. ',' and ':' )
  2. Write your map as a string (note the separator ',' also at beginning and end)

    animals=",moo:cow,woof:dog,"
    
  3. Use a regex to extract the values

    get_animal {
        echo "$(expr "$animals" : ".*,$1:\([^,]*\),.*")"
    }
    
  4. Split the string to list the items

    get_animal_items {
        arr=$(echo "${animals:1:${#animals}-2}" | tr "," "\n")
        for i in $arr
        do
            value="${i##*:}"
            key="${i%%:*}"
            echo "${value} likes to $key"
        done
    }
    

Now you can use it:

$ animal = get_animal "moo"
cow
$ get_animal_items
cow likes to moo
dog likes to woof

iPhone system font

Swift

Specific font

Setting a specific font in Swift is done like this:

let myFont = UIFont(name: "Helvetica", size: 17)

If you don't know the name, you can get a list of the available font names like this:

print(UIFont.familyNames())

Or an even more detailed list like this:

for familyName in UIFont.familyNames() {
    print(UIFont.fontNamesForFamilyName(familyName))
}

But the system font changes from version to version of iOS. So it would be better to get the system font dynamically.

System font

let myFont = UIFont.systemFontOfSize(17)

But we have the size hard-coded in. What if the user's eyes are bad and they want to make the font larger? Of course, you could make a setting in your app for the user to change the font size, but this would be annoying if the user had to do this separately for every single app on their phone. It would be easier to just make one change in the general settings...

Dynamic font

let myFont = UIFont.preferredFont(forTextStyle: .body)

Ah, now we have the system font at the user's chosen size for the Text Style we are working with. This is the recommended way of setting the font. See Supporting Dynamic Type for more info on this.

Related

How to check if String value is Boolean type in Java?

The methods you're calling on the Boolean class don't check whether the string contains a valid boolean value, but they return the boolean value that represents the contents of the string: put "true" in string, they return true, put "false" in string, they return false.

You can surely use these methods, however, to check for valid boolean values, as I'd expect them to throw an exception if the string contains "hello" or something not boolean.

Wrap that in a Method ContainsBoolString and you're go.

EDIT
By the way, in C# there are methods like bool Int32.TryParse(string x, out int i) that perform the check whether the content can be parsed and then return the parsed result.

int i;
if (Int32.TryParse("Hello", out i))
  // Hello is an int and its value is in i
else
  // Hello is not an int

Benchmarks indicate they are way faster than the following:

int i;
try
{
   i = Int32.Parse("Hello");
   // Hello is an int and its value is in i
}
catch
{
   // Hello is not an int
}

Maybe there are similar methods in Java? It's been a while since I've used Java...

Tooltip with HTML content without JavaScript

Using the title attribute:

_x000D_
_x000D_
<a href="#" title="Tooltip here">Link</a>
_x000D_
_x000D_
_x000D_

How to display HTML in TextView?

May I suggest a somewhat hacky but still genius solution! I got the idea from this article and adapted it for Android. Basically you use a WebView and insert the HTML you want to show and edit in an editable div tag. This way when the user taps the WebView the keyboard appears and allows editing. They you just add some JavaScript to get back the edited HTML and voila!

Here is the code:

public class HtmlTextEditor extends WebView {

    class JsObject {
        // This field always keeps the latest edited text
        public String text;
        @JavascriptInterface
        public void textDidChange(String newText) {
            text = newText.replace("\n", "");
        }
    }

    private JsObject mJsObject;

    public HtmlTextEditor(Context context, AttributeSet attrs) {
        super(context, attrs);

        getSettings().setJavaScriptEnabled(true);
        mJsObject = new JsObject();
        addJavascriptInterface(mJsObject, "injectedObject");
        setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadUrl(
                        "javascript:(function() { " +
                            "    var editor = document.getElementById(\"editor\");" +
                            "    editor.addEventListener(\"input\", function() {" +
                            "        injectedObject.textDidChange(editor.innerHTML);" +
                            "    }, false)" +
                            "})()");
            }
        });
    }

    public void setText(String text) {
        if (text == null) { text = ""; }

        String editableHtmlTemplate = "<!DOCTYPE html>" + "<html>" + "<head>" + "<meta name=\"viewport\" content=\"initial-scale=1.0\" />" + "</head>" + "<body>" + "<div id=\"editor\" contenteditable=\"true\">___REPLACE___</div>" + "</body>" + "</html>";
        String editableHtml = editableHtmlTemplate.replace("___REPLACE___", text);
        loadData(editableHtml, "text/html; charset=utf-8", "UTF-8");
        // Init the text field in case it's read without editing the text before
        mJsObject.text = text;
    }

    public String getText() {
        return mJsObject.text;
    }
}

And here is the component as a Gist.

Note: I didn't need the height change callback from the original solution so that's missing here but you can easily add it if needed.

Get a random item from a JavaScript array

Here's yet another way:

function rand(items) {
    // "~~" for a closest "int"
    return items[~~(items.length * Math.random())];
}

Or as recommended below by @1248177:

function rand(items) {
    // "|" for a kinda "int div"
    return items[items.length * Math.random() | 0];
}

Is there a limit on an Excel worksheet's name length?

The file format would permit up to 255-character worksheet names, but if the Excel UI doesn't want you exceeding 31 characters, don't try to go beyond 31. App's full of weird undocumented limits and quirks, and feeding it files that are within spec but not within the range of things the testers would have tested usually causes REALLY strange behavior. (Personal favorite example: using the Excel 4.0 bytecode for an if() function, in a file with an Excel 97-style stringtable, disabled the toolbar button for bold in Excel 97.)

PHP Checking if the current date is before or after a set date

if(strtotime($db_date) > time()) {
  echo $db_date;
} else {
  echo 'go ahead';
}

Java : How to determine the correct charset encoding of a stream

You can certainly validate the file for a particular charset by decoding it with a CharsetDecoder and watching out for "malformed-input" or "unmappable-character" errors. Of course, this only tells you if a charset is wrong; it doesn't tell you if it is correct. For that, you need a basis of comparison to evaluate the decoded results, e.g. do you know beforehand if the characters are restricted to some subset, or whether the text adheres to some strict format? The bottom line is that charset detection is guesswork without any guarantees.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

Oracle SQL Server Insert Multiple Rows

In a multitable insert, you insert computed rows derived from the rows returned from the evaluation of a subquery into one or more tables.

Unconditional INSERT ALL:- To add multiple rows to a table at once, you use the following form of the INSERT statement:

INSERT ALL
   INTO table_name (column_list) VALUES (value_list_1)
   INTO table_name (column_list) VALUES (value_list_2)
   INTO table_name (column_list) VALUES (value_list_3)
   ...
   INTO table_name (column_list) VALUES (value_list_n)
SELECT 1 FROM DUAL; -- SubQuery

Specify ALL followed by multiple insert_into_clauses to perform an unconditional multitable insert. Oracle Database executes each insert_into_clause once for each row returned by the subquery.

MySQL Server Insert Multiple Rows

INSERT INTO table_name (column_list)
VALUES
    (value_list_1),
    (value_list_2),
    ...
    (value_list_n);

Single Row insert Query

INSERT INTO table_name (col1,col2) VALUES(val1,val2);

Callback when DOM is loaded in react.js

I applied componentDidUpdate to table to have all columns same height. it works same as on $(window).load() in jquery.

eg:

componentDidUpdate: function() {
        $(".tbl-tr").height($(".tbl-tr ").height());
    }

Is it possible to force row level locking in SQL Server?

Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:

ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);

HTML5 Video autoplay on iPhone

I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.

  1. Using dangerouslySetInnerHtml to embed the <video> code. For example:
<div dangerouslySetInnerHTML={{ __html: `
    <video class="video-js" playsinline autoplay loop muted>
        <source src="../video_path.mp4" type="video/mp4"/>
    </video>`}}
/>
  1. Resizing the video weight. I noticed my iPhone does not autoplay videos over 3 megabytes. So I used an online compressor tool (https://www.mp4compress.com/) to go from 4mb to less than 500kb

Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

Check if one date is between two dates

Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below

var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";

var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11
var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);

console.log(check > from && check < to)

How to show an empty view with a RecyclerView?

Use AdapterDataObserver in custom RecyclerView

Kotlin:

RecyclerViewEnum.kt

enum class RecyclerViewEnum {
    LOADING,
    NORMAL,
    EMPTY_STATE
}

RecyclerViewEmptyLoadingSupport.kt

class RecyclerViewEmptyLoadingSupport : RecyclerView {

    var stateView: RecyclerViewEnum? = RecyclerViewEnum.LOADING
        set(value) {
            field = value
            setState()
        }
    var emptyStateView: View? = null
    var loadingStateView: View? = null


    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {}


    private val dataObserver = object : AdapterDataObserver() {
        override fun onChanged() {
            onChangeState()
        }

        override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
            super.onItemRangeRemoved(positionStart, itemCount)
            onChangeState()
        }

        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            super.onItemRangeInserted(positionStart, itemCount)
            onChangeState()
        }
    }


    override fun setAdapter(adapter: RecyclerView.Adapter<*>?) {
        super.setAdapter(adapter)
        adapter?.registerAdapterDataObserver(dataObserver)
        dataObserver.onChanged()
    }


    fun onChangeState() {
        if (adapter?.itemCount == 0) {
            emptyStateView?.visibility = View.VISIBLE
            loadingStateView?.visibility = View.GONE
            [email protected] = View.GONE
        } else {
            emptyStateView?.visibility = View.GONE
            loadingStateView?.visibility = View.GONE
            [email protected] = View.VISIBLE
        }
    }

    private fun setState() {

        when (this.stateView) {
            RecyclerViewEnum.LOADING -> {
                loadingStateView?.visibility = View.VISIBLE
                [email protected] = View.GONE
                emptyStateView?.visibility = View.GONE
            }

            RecyclerViewEnum.NORMAL -> {
                loadingStateView?.visibility = View.GONE
                [email protected] = View.VISIBLE
                emptyStateView?.visibility = View.GONE
            }
            RecyclerViewEnum.EMPTY_STATE -> {
                loadingStateView?.visibility = View.GONE
                [email protected] = View.GONE
                emptyStateView?.visibility = View.VISIBLE
            }
        }
    }
}

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/emptyView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/emptyLabelTv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="empty" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/loadingView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:gravity="center"
        android:orientation="vertical">

        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_gravity="center"
            android:indeterminate="true"
            android:theme="@style/progressBarBlue" />
    </LinearLayout>

    <com.peeyade.components.recyclerView.RecyclerViewEmptyLoadingSupport
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

in activity use this way:

recyclerView?.apply {
        layoutManager = GridLayoutManager(context, 2)
        emptyStateView = emptyView
        loadingStateView = loadingView
        adapter = adapterGrid
    }

    // you can set LoadingView or emptyView manual
    recyclerView.stateView = RecyclerViewEnum.EMPTY_STATE
    recyclerView.stateView = RecyclerViewEnum.LOADING

How to call a function, PostgreSQL

We can have two ways of calling the functions written in pgadmin for postgre sql database.

Suppose we have defined the function as below:

CREATE OR REPLACE FUNCTION helloWorld(name text) RETURNS void AS $helloWorld$
DECLARE
BEGIN
    RAISE LOG 'Hello, %', name;
END;
$helloWorld$ LANGUAGE plpgsql;

We can call the function helloworld in one of the following way:

SELECT "helloworld"('myname');

SELECT public.helloworld('myname')

How to determine CPU and memory consumption from inside a process?

Linux

A portable way of reading memory and load numbers is the sysinfo call

Usage

   #include <sys/sysinfo.h>

   int sysinfo(struct sysinfo *info);

DESCRIPTION

   Until Linux 2.3.16, sysinfo() used to return information in the
   following structure:

       struct sysinfo {
           long uptime;             /* Seconds since boot */
           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
           unsigned long totalram;  /* Total usable main memory size */
           unsigned long freeram;   /* Available memory size */
           unsigned long sharedram; /* Amount of shared memory */
           unsigned long bufferram; /* Memory used by buffers */
           unsigned long totalswap; /* Total swap space size */
           unsigned long freeswap;  /* swap space still available */
           unsigned short procs;    /* Number of current processes */
           char _f[22];             /* Pads structure to 64 bytes */
       };

   and the sizes were given in bytes.

   Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure
   is:

       struct sysinfo {
           long uptime;             /* Seconds since boot */
           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
           unsigned long totalram;  /* Total usable main memory size */
           unsigned long freeram;   /* Available memory size */
           unsigned long sharedram; /* Amount of shared memory */
           unsigned long bufferram; /* Memory used by buffers */
           unsigned long totalswap; /* Total swap space size */
           unsigned long freeswap;  /* swap space still available */
           unsigned short procs;    /* Number of current processes */
           unsigned long totalhigh; /* Total high memory size */
           unsigned long freehigh;  /* Available high memory size */
           unsigned int mem_unit;   /* Memory unit size in bytes */
           char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */
       };

   and the sizes are given as multiples of mem_unit bytes.

How does the Java 'for each' loop work?

The Java for each loop (aka enhanced for loop) is a simplified version of a for loop. The advantage is that there is less code to write and less variables to manage. The downside is that you have no control over the step value and no access to the loop index inside the loop body.

They are best used when the step value is a simple increment of 1 and when you only need access to the current loop element. For example, if you need to loop over every element in an array or Collection without peeking ahead or behind the current element.

There is no loop initialization, no boolean condition and the step value is implicit and is a simple increment. This is why they are considered so much simpler than regular for loops.

Enhanced for loops follow this order of execution:

1) loop body

2) repeat from step 1 until entire array or collection has been traversed

Example – Integer Array

int [] intArray = {1, 3, 5, 7, 9};
for(int currentValue : intArray) {
  System.out.println(currentValue);
}

The currentValue variable holds the current value being looped over in the intArray array. Notice there’s no explicit step value – it’s always an increment by 1.

The colon can be thought of to mean “in”. So the enhanced for loop declaration states: loop over intArray and store the current array int value in the currentValue variable.

Output:

1
3
5
7
9

Example – String Array

We can use the for-each loop to iterate over an array of strings. The loop declaration states: loop over myStrings String array and store the current String value in the currentString variable.

String [] myStrings  = {
  "alpha",
  "beta",
  "gamma",
  "delta"
};

for(String currentString : myStrings) {
  System.out.println(currentString);
}

Output:

alpha
beta
gamma
delta

Example – List

The enhanced for loop can also be used to iterate over a java.util.List as follows:

List<String> myList = new ArrayList<String>();
myList.add("alpha");
myList.add("beta");
myList.add("gamma");
myList.add("delta");

for(String currentItem : myList) {
  System.out.println(currentItem);
}

The loop declaration states: loop over myList List of Strings and store the current List value in the currentItem variable.

Output:

alpha
beta
gamma
delta

Example – Set

The enhanced for loop can also be used to iterate over a java.util.Set as follows:

Set<String> mySet = new HashSet<String>();
mySet.add("alpha");
mySet.add("alpha");
mySet.add("beta");
mySet.add("gamma");
mySet.add("gamma");
mySet.add("delta");

for(String currentItem : mySet) {
  System.out.println(currentItem);
}

The loop declaration states: loop over mySet Set of Strings and store the current Set value in the currentItem variable. Notice that since this is a Set, duplicate String values are not stored.

Output:

alpha
delta
beta
gamma

Source: Loops in Java – Ultimate Guide

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

Also you can use AppCompatActivity instead of Activity.
Then getSupportFragmentManager() will work.
And also not forget to make your App theme extend AppCompat theme in this case

How to automatically update an application without ClickOnce?

A Lay men's way is

on Main() rename the executing assembly file .exe to some thing else check date and time of created. and the updated file date time and copy to the application folder.

//Rename he executing file
System.IO.FileInfo file = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);

System.IO.File.Move(file.FullName, file.DirectoryName + "\\" + file.Name.Replace(file.Extension,"") + "-1" + file.Extension);

then do the logic check and copy the new file to executing folder

How can I set size of a button?

This is how I did it.

            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("SAP Multiple Entries");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel(new GridLayout(10,10,10,10));
            frame.setLayout(new FlowLayout());
            frame.setSize(512, 512);
            JButton button = new JButton("Select File");
            button.setPreferredSize(new Dimension(256, 256));
            panel.add(button);

            button.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent ae) {
                    JFileChooser fileChooser = new JFileChooser();
                    int returnValue = fileChooser.showOpenDialog(null);
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();

                        keep = selectedFile.getAbsolutePath();


                       // System.out.println(keep);
                        //out.println(file.flag); 
                       if(file.flag==true) {
                           JOptionPane.showMessageDialog(null, "It is done! \nLocation: " + file.path , "Success Message", JOptionPane.INFORMATION_MESSAGE);
                       }
                       else{
                           JOptionPane.showMessageDialog(null, "failure", "not okay", JOptionPane.INFORMATION_MESSAGE);
                       }
                    }
                }
            });
            frame.add(button);
            frame.pack();
            frame.setVisible(true);

How can I disable the default console handler, while using the java logging API?

You must instruct your logger not to send its messages on up to its parent logger:

...
import java.util.logging.*;
...
Logger logger = Logger.getLogger(this.getClass().getName());
logger.setUseParentHandlers(false);
...

However, this should be done before adding any more handlers to logger.

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

Prevents the background from scrolling without any fuss.

Also prevents page jumping around from missing scrollbars

body.modal-open {
        position: fixed;
        overflow-y: scroll;
    }

Custom Authentication in ASP.Net-Core

Creating custom authentication in ASP.NET Core can be done in a variety of ways. If you want to build off existing components (but don't want to use identity), checkout the "Security" category of docs on docs.asp.net. https://docs.asp.net/en/latest/security/index.html

Some articles you might find helpful:

Using Cookie Middleware without ASP.NET Identity

Custom Policy-Based Authorization

And of course, if that fails or docs aren't clear enough, the source code is at https://github.com/dotnet/aspnetcore/tree/master/src/Security which includes some samples.

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

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

How to store a command in a variable in a shell script?

Its is not necessary to store commands in variables even as you need to use it later. just execute it as per normal. If you store in variable, you would need some kind of eval statement or invoke some unnecessary shell process to "execute your variable".

Given an RGB value, how do I create a tint (or shade)?

Among several options for shading and tinting:

  • For shades, multiply each component by 1/4, 1/2, 3/4, etc., of its previous value. The smaller the factor, the darker the shade.

  • For tints, calculate (255 - previous value), multiply that by 1/4, 1/2, 3/4, etc. (the greater the factor, the lighter the tint), and add that to the previous value (assuming each.component is a 8-bit integer).

Note that color manipulations (such as tints and other shading) should be done in linear RGB. However, RGB colors specified in documents or encoded in images and video are not likely to be in linear RGB, in which case a so-called inverse transfer function needs to be applied to each of the RGB color's components. This function varies with the RGB color space. For example, in the sRGB color space (which can be assumed if the RGB color space is unknown), this function is roughly equivalent to raising each sRGB color component (ranging from 0 through 1) to a power of 2.2. (Note that "linear RGB" is not an RGB color space.)

See also Violet Giraffe's comment about "gamma correction".

How can I use external JARs in an Android project?

in android studio if using gradle

add this to build.gradle

compile fileTree(dir: 'libs', include: ['*.jar'])

and add the jar file to libs folder

How to send image to PHP file using Ajax?

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('#abc').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            url: 'post.php',
            method:'POST',
            data: new FormData(this),
            contentType: false,
            cache:false,
            processData:false,
            success: function (data) {
              alert(data);
              location.reload();
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form enctype= "multipart/form-data" id="abc">
      <input name="fname" ><br>
      <input name="lname"><br>
      <input type="file" name="file" required=""><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

Extract XML Value in bash script

I agree with Charles Duffy that a proper XML parser is the right way to go.

But as to what's wrong with your sed command (or did you do it on purpose?).

  • $data was not quoted, so $data is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.

So given your specific XML structure, this modified sed command should work

title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")

Basically for the line that contains title, extract the text between the tags, then quit (so you don't extract the 2nd <title>)

Cross-reference (named anchor) in markdown

For anyone who is looking for a solution to this problem in GitBook. This is how I made it work (in GitBook). You need to tag your header explicitly, like this:

# My Anchored Heading {#my-anchor}

Then link to this anchor like this

[link to my anchored heading](#my-anchor)

Solution, and additional examples, may be found here: https://seadude.gitbooks.io/learn-gitbook/

Example to use shared_ptr?

Learning to use smart pointers is in my opinion one of the most important steps to become a competent C++ programmer. As you know whenever you new an object at some point you want to delete it.

One issue that arise is that with exceptions it can be very hard to make sure a object is always released just once in all possible execution paths.

This is the reason for RAII: http://en.wikipedia.org/wiki/RAII

Making a helper class with purpose of making sure that an object always deleted once in all execution paths.

Example of a class like this is: std::auto_ptr

But sometimes you like to share objects with other. It should only be deleted when none uses it anymore.

In order to help with that reference counting strategies have been developed but you still need to remember addref and release ref manually. In essence this is the same problem as new/delete.

That's why boost has developed boost::shared_ptr, it's reference counting smart pointer so you can share objects and not leak memory unintentionally.

With the addition of C++ tr1 this is now added to the c++ standard as well but its named std::tr1::shared_ptr<>.

I recommend using the standard shared pointer if possible. ptr_list, ptr_dequeue and so are IIRC specialized containers for pointer types. I ignore them for now.

So we can start from your example:

std::vector<gate*> G; 
G.push_back(new ANDgate);  
G.push_back(new ORgate); 
for(unsigned i=0;i<G.size();++i) 
{ 
  G[i]->Run(); 
} 

The problem here is now that whenever G goes out scope we leak the 2 objects added to G. Let's rewrite it to use std::tr1::shared_ptr

// Remember to include <memory> for shared_ptr
// First do an alias for std::tr1::shared_ptr<gate> so we don't have to 
// type that in every place. Call it gate_ptr. This is what typedef does.
typedef std::tr1::shared_ptr<gate> gate_ptr;    
// gate_ptr is now our "smart" pointer. So let's make a vector out of it.
std::vector<gate_ptr> G; 
// these smart_ptrs can't be implicitly created from gate* we have to be explicit about it
// gate_ptr (new ANDgate), it's a good thing:
G.push_back(gate_ptr (new ANDgate));  
G.push_back(gate_ptr (new ORgate)); 
for(unsigned i=0;i<G.size();++i) 
{ 
   G[i]->Run(); 
} 

When G goes out of scope the memory is automatically reclaimed.

As an exercise which I plagued newcomers in my team with is asking them to write their own smart pointer class. Then after you are done discard the class immedietly and never use it again. Hopefully you acquired crucial knowledge on how a smart pointer works under the hood. There's no magic really.

Get file name from URI string in C#

using System.IO;

private String GetFileName(String hrefLink)
{
    return Path.GetFileName(hrefLink.Replace("/", "\\"));
}

THis assumes, of course, that you've parsed out the file name.

EDIT #2:

using System.IO;

private String GetFileName(String hrefLink)
{
    return Path.GetFileName(Uri.UnescapeDataString(hrefLink).Replace("/", "\\"));
}

This should handle spaces and the like in the file name.

What's the difference between ViewData and ViewBag?

Although you might not have a technical advantage to choosing one format over the other, you should be aware of some important differences between the two syntaxes. One obvious difference is that ViewBag works only when the key you’re accessing is a valid C# identifi er. For example, if you place a value in ViewData["Key With Spaces"], you can’t access that value using ViewBag because the code won’t compile. Another key issue to consider is that you cannot pass in dynamic values as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order to choose the correct extension method. If any parameter is dynamic, compilation will fail. For example, this code will always fail: @Html.TextBox("name", ViewBag.Name). To work around this, either use ViewData["Name"] or cast the va

ImportError: DLL load failed: The specified module could not be found

For Windows 10 x64 and Python:

Open a Visual Studio x64 command prompt, and use dumpbin:

dumpbin /dependents [Python Module DLL or PYD file]

If you do not have Visual Studio installed, it is possible to download dumpbin elsewhere, or use another utility such as Dependency Walker.

Note that all other answers (to date) are simply random stabs in the dark, whereas this method is closer to a sniper rifle with night vision.

Case study 1

  1. I switched on Address Sanitizer for a Python module that I wrote using C++ using MSVC and CMake.

  2. It was giving this error: ImportError: DLL load failed: The specified module could not be found

  3. Opened a Visual Studio x64 command prompt.

  4. Under Windows, a .pyd file is a .dll file in disguise, so we want to run dumpbin on this file.

  5. cd MyLibrary\build\lib.win-amd64-3.7\Debug

  6. dumpbin /dependents MyLibrary.cp37-win_amd64.pyd which prints this:

    Microsoft (R) COFF/PE Dumper Version 14.27.29112.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    
    Dump of file MyLibrary.cp37-win_amd64.pyd
    
    File Type: DLL
    
      Image has the following dependencies:
    
        clang_rt.asan_dbg_dynamic-x86_64.dll
        gtestd.dll
        tbb_debug.dll
        python37.dll
        KERNEL32.dll
        MSVCP140D.dll
        VCOMP140D.DLL
        VCRUNTIME140D.dll
        VCRUNTIME140_1D.dll
        ucrtbased.dll
    
      Summary
    
         1000 .00cfg
        D6000 .data
         7000 .idata
        46000 .pdata
       341000 .rdata
        23000 .reloc
         1000 .rsrc
       856000 .text
    
  7. Searched for clang_rt.asan_dbg_dynamic-x86_64.dll, copied it into the same directory, problem solved.

  8. Alternatively, could update the environment variable PATH to point to the directory with the missing .dll.

Please feel free to add your own case studies here! I've made it a community wiki answer.

jQuery - Sticky header that shrinks when scrolling down

This should be what you are looking for using jQuery.

$(function(){
  $('#header_nav').data('size','big');
});

$(window).scroll(function(){
  if($(document).scrollTop() > 0)
{
    if($('#header_nav').data('size') == 'big')
    {
        $('#header_nav').data('size','small');
        $('#header_nav').stop().animate({
            height:'40px'
        },600);
    }
}
else
  {
    if($('#header_nav').data('size') == 'small')
      {
        $('#header_nav').data('size','big');
        $('#header_nav').stop().animate({
            height:'100px'
        },600);
      }  
  }
});

Demonstration: http://jsfiddle.net/jezzipin/JJ8Jc/

How to remove new line characters from a string?

I know this is an old post, however I thought I'd share the method I use to remove new line characters.

s.Replace(Environment.NewLine, "");

References:

MSDN String.Replace Method and MSDN Environment.NewLine Property

Failed to serialize the response in Web API with Json

When it comes to returning data back to the consumer from Web Api (or any other web service for that matter), I highly recommend not passing back entities that come from a database. It is much more reliable and maintainable to use Models in which you have control of what the data looks like and not the database. That way you don't have to mess around with the formatters so much in the WebApiConfig. You can just create a UserModel that has child Models as properties and get rid of the reference loops in the return objects. That makes the serializer much happier.

Also, it isn't necessary to remove formatters or supported media types typically if you are just specifying the "Accepts" header in the request. Playing around with that stuff can sometimes make things more confusing.

Example:

public class UserModel {
    public string Name {get;set;}
    public string Age {get;set;}
    // Other properties here that do not reference another UserModel class.
}

Is a view faster than a simple query?

My understanding is that a while back, a view would be faster because SQL Server could store an execution plan and then just use it instead of trying to figure one out on the fly. I think the performance gains nowadays is probably not as great as it once was, but I would have to guess there would be some marginal improvement to use the view.

Where Sticky Notes are saved in Windows 10 1607

If at all you can't find .snt folder and above mentioned answers don't work for you. you can simply take plum.sqlite file and read it online or sqlite editor.

for online you can refer to http://inloop.github.io/sqlite-viewer/ link and browse the url as C:\Users\YOURUSERNAME\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState

and pick sql lite file and execute it. Post executing select Note and you will find all rows corresponding to each sticky notes you have lost. Select the Text column and copy content, you will find all your data there.

ENJOY !!!! enter image description here

Java Replace Character At Specific Position Of String?

Kay!

First of all, when dealing with strings you have to refer to their positions in 0 base convention. This means that if you have a string like this:

String str = "hi";
//str length is equal 2 but the character
//'h' is in the position 0 and character 'i' is in the postion 1


With that in mind, the best way to tackle this problem is creating a method to replace a character at a given position in a string like this:

Method:

public String changeCharInPosition(int position, char ch, String str){
    char[] charArray = str.toCharArray();
    charArray[position] = ch;
    return new String(charArray);
}

Then you should call the method 'changeCharInPosition' in this way:

String str = "hi";
str = changeCharInPosition(1, 'k', str);
System.out.print(str); //this will return "hk"

If you have any questions, don't hesitate, post something!

Java properties UTF-8 encoding in Eclipse

If the properties are for XML or HTML, it's safest to use XML entities. They're uglier to read, but it means that the properties file can be treated as straight ASCII, so nothing will get mangled.

Note that HTML has entities that XML doesn't, so I keep it safe by using straight XML: http://www.w3.org/TR/html4/sgml/entities.html

Deleting Objects in JavaScript

I stumbled across this article in my search for this same answer. What I ended up doing is just popping out obj.pop() all the stored values/objects in my object so I could reuse the object. Not sure if this is bad practice or not. This technique came in handy for me testing my code in Chrome Dev tools or FireFox Web Console.

How can I update my ADT in Eclipse?

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help

  2. Install New Software ---> Add

  3. inside Add Repository write the Name: ADT (or whatever you want)

  4. Location: https://dl-ssl.google.com/android/eclipse/

  5. after loading you should get Developer Tools and NDK Plugins

  6. check both if you want to use the Native Developer Kit (NDK) in the future or check

  7. Developer Tool only

  8. click Next

  9. Finish

"’" showing on page instead of " ' "

You must have copy/paste text from Word Document. Word document use Smart Quotes. You can replace it with Special Character (&rsquo;) or simply type in your HTML editor (').

I'm sure this will solve your problem.

How can I create persistent cookies in ASP.NET?

Here's how you can do that.

Writing the persistent cookie.

//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");

//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);

Reading the persistent cookie.

//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
    //No cookie found or cookie expired.
    //Handle the situation here, Redirect the user or simply return;
}

//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
    string userId = myCookie.Values["userid"].ToString();
    //Yes userId is found. Mission accomplished.
}

Inline CSS styles in React: how to implement a:hover?

In regards to styled-components and react-router v4 you can do this:

import {NavLink} from 'react-router-dom'

const Link = styled(NavLink)`     
  background: blue;

  &:hover {
    color: white;
  }
`

...
<Clickable><Link to="/somewhere">somewhere</Link></Clickable>

Replace all particular values in a data frame

Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:

> df[df=="" | df==12] <- NA
> df
     A    B
1  <NA> <NA>
2  xyz  <NA>
3  jkl  100

For factors, zxzak's code already yields factors:

> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame':   3 obs. of  2 variables:
 $ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
 $ B: Factor w/ 3 levels "","100","12": 3 1 2

If in trouble, I'd suggest to temporarily drop the factors.

df[] <- lapply(df, as.character)

Convert URL to File or Blob for FileReader.readAsDataURL

Try this I learned this from @nmaier when I was mucking around with converting to ico: Well i dont really understand what array buffer is but it does what we need:

function previewFile(file) {

  var reader  = new FileReader();

  reader.onloadend = function () {
    console.log(reader.result); //this is an ArrayBuffer
  }
  reader.readAsArrayBuffer(file);
}

notice how i just changed your readAsDataURL to readAsArrayBuffer.

Here is the example @nmaier gave me: https://stackoverflow.com/a/24253997/1828637

it has a fiddle

if you want to take this and make a file out of it i would think you would use file-output-stream in the onloadend

Get class name of object as string in Swift

Swift 5

Here is the extension to get the typeName as a variable (work with both value type or reference type).

protocol NameDescribable {
    var typeName: String { get }
    static var typeName: String { get }
}

extension NameDescribable {
    var typeName: String {
        return String(describing: type(of: self))
    }

    static var typeName: String {
        return String(describing: self)
    }
}

How to use:

// Extend with class/struct/enum...
extension NSObject: NameDescribable {}
extension Array: NameDescribable {}
extension UIBarStyle: NameDescribable { }

print(UITabBarController().typeName)
print(UINavigationController.typeName)
print([Int]().typeName)
print(UIBarStyle.typeName)

// Out put:
UITabBarController
UINavigationController
Array<Int>
UIBarStyle

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

I have this problem when update android studio from 3.2 to 3.3 and test every answers that i none of them was working. at the end i enabled Maven repository and its work.

enter image description here

Twitter bootstrap scrollable table

CSS

.achievements-wrapper { height: 300px; overflow: auto; }

HTML

<div class="span3 achievements-wrapper">
    <h2>Achievements left</h2>
    <table class="table table-striped">
    ...
    </table>
</div>

How to get URI from an asset File?

Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.

@Throws(IOException::class)
    fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
            .also {
               if (!it.exists()) {
                it.outputStream().use { cache ->
                    context.assets.open(fileName).use { inputStream ->
                            inputStream.copyTo(cache)
                    }
                  }
                }
            }

Get the path to the file like:

val filePath =  getFileFromAssets(context, "fileName.extension").absolutePath

Cancel a UIView animation?

Simplest way to stop all animations on a particular view, immediately, is this:

Link the project to QuartzCore.framework. At the start of your code:

#import <QuartzCore/QuartzCore.h>

Now, when you want to stop all animations on a view dead in their tracks, say this:

[CATransaction begin];
[theView.layer removeAllAnimations];
[CATransaction commit];

The middle line would work all by itself, but there's a delay until the runloop finishes (the "redraw moment"). To prevent that delay, wrap the command in an explicit transaction block as shown. This works provided no other changes have been performed on this layer in the current runloop.

How to grep a string in a directory and all its subdirectories?

grep -r -e string directory

-r is for recursive; -e is optional but its argument specifies the regex to search for. Interestingly, POSIX grep is not required to support -r (or -R), but I'm practically certain that System V grep did, so in practice they (almost) all do. Some versions of grep support -R as well as (or conceivably instead of) -r; AFAICT, it means the same thing.

Multiple Image Upload PHP form with one input

extract($_POST);
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name) {
    $file_name=$_FILES["files"]["name"][$key];
    $file_tmp=$_FILES["files"]["tmp_name"][$key];
    $ext=pathinfo($file_name,PATHINFO_EXTENSION);

    if(in_array($ext,$extension)) {
        if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name)) {
            move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
        }
        else {
            $filename=basename($file_name,$ext);
            $newFileName=$filename.time().".".$ext;
            move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
        }
    }
    else {
        array_push($error,"$file_name, ");
    }
}

and you must check your HTML code

<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
    <table width="100%">
        <tr>
            <td>Select Photo (one or multiple):</td>
            <td><input type="file" name="files[]" multiple/></td>
        </tr>
        <tr>
            <td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
        </tr>
    </table>
</form>

Using awk to print all columns from the nth to the last

awk '{out=$2; for(i=3;i<=NF;i++){out=out" "$i}; print out}'

My answer is based on the one of VeeArr, but I noticed it started with a white space before it would print the second column (and the rest). As I only have 1 reputation point, I can't comment on it, so here it goes as a new answer:

start with "out" as the second column and then add all the other columns (if they exist). This goes well as long as there is a second column.

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

If you are using a non default MySQL port number then do the following:

  1. Stop your xampp/wamp/etc session
  2. Set port number used by MySQL in config.inc.php under the phpMyAdmin folder.
  3. For example if your MySQL port number is 33747 then paste the following
    $cfg['Servers'][$i]['port'] = 33747;
    
    under the
    /* Authentication type and info */
    
    section.
  4. Restart Apache and MySQL servers.

What does '?' do in C++?

It's the conditional operator.

a ? b : c

It's a shortcut for IF/THEN/ELSE.

means: if a is true, return b, else return c. In this case, if f==r, return 1, else return 0.

dll missing in JDBC

Set java.library.path to a directory containing this DLL which Java uses to find native libraries. Specify -D switch on the command line

java -Djava.library.path=C:\Java\native\libs YourProgram

C:\Java\native\libs should contain sqljdbc_auth.dll

Look at this SO post if you are using Eclipse or at this blog if you want to set programatically.

How do I check my gcc C++ compiler version for my Eclipse?

gcc -dumpversion

-dumpversion Print the compiler version (for example, 3.0) — and don't do anything else.

The same works for following compilers/aliases:

cc -dumpversion
g++ -dumpversion
clang -dumpversion
tcc -dumpversion

Be careful with automate parsing the GCC output:

  • Output of --version might be localized (e.g. to Russian, Chinese, etc.)
  • GCC might be built with option --with-gcc-major-version-only. And some distros (e.g. Fedora) are already using that
  • GCC might be built with option --with-pkgversion. And --version output will contain something like Android (5220042 based on r346389c) clang version 8.0.7 (it's real version string)

using lodash .groupBy. how to add your own keys for grouped output?

You can do it like this in Lodash 4.x

_x000D_
_x000D_
var data = [{_x000D_
  "name": "jim",_x000D_
  "color": "blue",_x000D_
  "age": "22"_x000D_
}, {_x000D_
  "name": "Sam",_x000D_
  "color": "blue",_x000D_
  "age": "33"_x000D_
}, {_x000D_
  "name": "eddie",_x000D_
  "color": "green",_x000D_
  "age": "77"_x000D_
}];_x000D_
_x000D_
console.log(_x000D_
  _.chain(data)_x000D_
    // Group the elements of Array based on `color` property_x000D_
    .groupBy("color")_x000D_
    // `key` is group's name (color), `value` is the array of objects_x000D_
    .map((value, key) => ({ color: key, users: value }))_x000D_
    .value()_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_


Original Answer

var result = _.chain(data)
    .groupBy("color")
    .pairs()
    .map(function(currentItem) {
        return _.object(_.zip(["color", "users"], currentItem));
    })
    .value();
console.log(result);

Online Demo

Note: Lodash 4.0 onwards, the .pairs function has been renamed to _.toPairs()

Can an Option in a Select tag carry multiple values?

If you're goal is to write this information to the database, then why do you need to have a primary value and 'related' values in the value attribute? Why not just send the primary value to the database and let the relational nature of the database take care of the rest.

If you need to have multiple values in your OPTIONs, try a delimiter that isn't very common:

<OPTION VALUE="1|2010">One</OPTION>

...

or add an object literal (JSON format):

<OPTION VALUE="{'primary':'1','secondary':'2010'}">One</OPTION>

...

It really depends on what you're trying to do.

Javascript Object push() function

push() is for arrays, not objects, so use the right data structure.

var data = [];
// ...
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
// ...
var tempData = [];
for ( var index=0; index<data.length; index++ ) {
    if ( data[index].Status == "Valid" ) {
        tempData.push( data );
    }
}
data = tempData;

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

Your code can simplified a lot to

$('img', resp).attr('src', function(idx, urlRelative ) {
    return self.config.proxy_server + self.config.location_images + urlRelative;
});

moving changed files to another branch for check-in

A soft git reset will put committed changes back into your index. Next, checkout the branch you had intended to commit on. Then git commit with a new commit message.

  1. git reset --soft <commit>

  2. git checkout <branch>

  3. git commit -m "Commit message goes here"

From git docs:

git reset [<mode>] [<commit>] This form resets the current branch head to and possibly updates the index (resetting it to the tree of ) and the working tree depending on . If is omitted, defaults to --mixed. The must be one of the following:

--soft Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

Figure out size of UILabel based on String in Swift

Swift 5:

If you have UILabel and someway boundingRect isn't working for you (I faced this problem. It always returned 1 line height.) there is an extension to easily calculate label size.

extension UILabel {
    func getSize(constrainedWidth: CGFloat) -> CGSize {
        return systemLayoutSizeFitting(CGSize(width: constrainedWidth, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
    }
}

You can use it like this:

let label = UILabel()
label.text = "My text\nIs\nAwesome"
let labelSize = label.getSize(constrainedWidth:200.0)

Works for me

Jquery button click() function is not working

You need to use the event delegation syntax of .on() here. Change:

$("#add").click(function() {

to

$("#buildyourform").on('click', '#add', function () {

jsFiddle example

npm not working - "read ECONNRESET"

This is what worked for me:

proxy = http://1.1.1.1:3128/
https_proxy = http://1.1.1.1:3128/
strict-ssl = false
ca = null
registry = http://registry.npmjs.org/

Answer found here: https://fak3r.com/2015/07/31/howto-use-npm-behind-a-corporate-proxy/

Android Camera : data intent returns null

Kotlin code that works for me:

 private fun takePhotoFromCamera() {
          val intent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA)
      }

And get Result :

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
 if (requestCode == PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA) {
         if (resultCode == Activity.RESULT_OK) {
           val photo: Bitmap? =  MediaStore.Images.Media.getBitmap(this.contentResolver, Uri.parse( data!!.dataString)   )
            // Do something here : set image to an ImageView or save it ..   
              imgV_pic.imageBitmap = photo 
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "Camera  , RESULT_CANCELED ")
        }

    }

}

and don't forget to declare request code:

companion object {
 const val PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA = 300
  }

Running Selenium WebDriver python bindings in chrome

Mac OSX only

An easier way to get going (assuming you already have homebrew installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command:

brew install chromedriver

That should put the chromedriver in your path and you should be all set.

How to use not contains() in xpath?

You can use not(expression) function

not() is a function in xpath (as opposed to an operator)

Example:

//a[not(contains(@id, 'xx'))]

OR

expression != true()

How do I set vertical space between list items?

Add a margin to your li tags. That will create space between the li and you can use line-height to set the spacing to the text within the li tags.

How to Use Content-disposition for force a file to download to the hard drive?

With recent browsers you can use the HTML5 download attribute as well:

<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>

It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):

(function (){

    addEvent(window, "load", function (){
        if (isInternetExplorer())
            polyfillDataUriDownload();
    });

    function polyfillDataUriDownload(){
        var links = document.querySelectorAll('a[download], area[download]');
        for (var index = 0, length = links.length; index<length; ++index) {
            (function (link){
                var dataUri = link.getAttribute("href");
                var fileName = link.getAttribute("download");
                if (dataUri.slice(0,5) != "data:")
                    throw new Error("The XHR part is not implemented here.");
                addEvent(link, "click", function (event){
                    cancelEvent(event);
                    try {
                        var dataBlob = dataUriToBlob(dataUri);
                        forceBlobDownload(dataBlob, fileName);
                    } catch (e) {
                        alert(e)
                    }
                });
            })(links[index]);
        }
    }

    function forceBlobDownload(dataBlob, fileName){
        window.navigator.msSaveBlob(dataBlob, fileName);
    }

    function dataUriToBlob(dataUri) {
        if  (!(/base64/).test(dataUri))
            throw new Error("Supports only base64 encoding.");
        var parts = dataUri.split(/[:;,]/),
            type = parts[1],
            binData = atob(parts.pop()),
            mx = binData.length,
            uiArr = new Uint8Array(mx);
        for(var i = 0; i<mx; ++i)
            uiArr[i] = binData.charCodeAt(i);
        return new Blob([uiArr], {type: type});
    }

    function addEvent(subject, type, listener){
        if (window.addEventListener)
            subject.addEventListener(type, listener, false);
        else if (window.attachEvent)
            subject.attachEvent("on" + type, listener);
    }

    function cancelEvent(event){
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    }

    function isInternetExplorer(){
        return /*@cc_on!@*/false || !!document.documentMode;
    }
    
})();

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

What's the difference between "super()" and "super(props)" in React when using es6 classes?

Here we won't get this in the constructor so it will return undefined, but we will be able to fetch this outside the constructor function

class MyComponent extends React.Component {
  constructor() {
    console.log(this); // Reference Error i.e return undefined
  }

  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

If we are using super(), then we can fetch the "this" variable inside the constructor as well

class MyComponent extends React.Component {
  constructor() {
    super();
    console.log(this); // this logged to console
  }

  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

So when we are using super(); we will be able to fetch this but this.props will be undefined in the constructor. But other than constructor, this.props will not return undefined.

If we use super(props), then we can use this.props value inside the constructor as well

Sophie Alpert's Answer

If you want to use this.props in the constructor, you need to pass props to super. Otherwise, it doesn’t matter because React sets .props on the instance from the outside immediately after calling the constructor.

What characters are forbidden in Windows and Linux directory names?

I had the same need and was looking for recommendation or standard references and came across this thread. My current blacklist of characters that should be avoided in file and directory names are:

$CharactersInvalidForFileName = {
    "pound" -> "#",
    "left angle bracket" -> "<",
    "dollar sign" -> "$",
    "plus sign" -> "+",
    "percent" -> "%",
    "right angle bracket" -> ">",
    "exclamation point" -> "!",
    "backtick" -> "`",
    "ampersand" -> "&",
    "asterisk" -> "*",
    "single quotes" -> "“",
    "pipe" -> "|",
    "left bracket" -> "{",
    "question mark" -> "?",
    "double quotes" -> "”",
    "equal sign" -> "=",
    "right bracket" -> "}",
    "forward slash" -> "/",
    "colon" -> ":",
    "back slash" -> "\\",
    "lank spaces" -> "b",
    "at sign" -> "@"
};

C# Creating and using Functions

This code gives you an error because your Add function needs to be static:

static public int Add(int x, int y)

In C# there is a distinction between functions that operate on instances (non-static) and functions that do not operate on instances (static). Instance functions can call other instance functions and static functions because they have an implicit reference to the instance. In contrast, static functions can call only static functions, or else they must explicitly provide an instance on which to call a non-static function.

Since public static void Main(string[] args) is static, all functions that it calls need to be static as well.

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

I had the same error because of character '@' in my resources/application.properties. All I did was replacing the '@' for its unicode value: eureka.client.serviceUrl.defaultZone=http://discUser:discPassword\u0040localhost:8082/eureka/ and it worked like charm. I know the '@' is a perfectly valid character in .properties files and the file was in UTF-8 encoding and it makes me question my career till today but it's worth a shot if you delete content of your resource files to see if you can get pass this error.