Programs & Examples On #Php mode

Set an environment variable in git bash

A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =:

HOME=c

An environment variable is a regular variable that has been marked for export to the environment.

export HOME
HOME=c

You can combine the assignment with the export statement.

export HOME=c

How to run python script with elevated privilege on windows

Also if your working directory is different than you can use lpDirectory

    procInfo = ShellExecuteEx(nShow=showCmd,
                          lpVerb=lpVerb,
                          lpFile=cmd,
                          lpDirectory= unicode(direc),
                          lpParameters=params)

Will come handy if changing the path is not a desirable option remove unicode for python 3.X

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I know this is old, but since Postgresql 9.3 there is an option to use a keyword "LATERAL" to use RELATED subqueries inside of JOINS, so the query from the question would look like:

SELECT 
    name, author_id, count(*), t.total
FROM
    names as n1
    INNER JOIN LATERAL (
        SELECT 
            count(*) as total
        FROM 
            names as n2
        WHERE 
            n2.id = n1.id
            AND n2.author_id = n1.author_id
    ) as t ON 1=1
GROUP BY 
    n1.name, n1.author_id

What's the best mock framework for Java?

The JMockit project site contains plenty of comparative information for current mocking toolkits.

In particular, check out the feature comparison matrix, which covers EasyMock, jMock, Mockito, Unitils Mock, PowerMock, and of course JMockit. I try to keep it accurate and up-to-date, as much as possible.

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

How to know installed Oracle Client is 32 bit or 64 bit?

Go to %ORACLE_HOME%\inventory\ContentsXML folder and open comps.xml file

Look for <DEP_LIST> on ~second screen.
If following lines have

  • PLAT="NT_AMD64" then this Oracle Home is 64 bit.
  • PLAT="NT_X86" then - 32 bit.

    You may have both 32-bit and 64-bit Oracle Homes installed.

  • What's the difference between JPA and Hibernate?

    JPA is a specification to standardize ORM-APIs. Hibernate is a vendor of a JPA implementation. So if you use JPA with hibernate, you can use the standard JPA API, hibernate will be under the hood, offering some more non standard functions. See http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html_single/ and http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/

    Transferring files over SSH

    You need to scp something somewhere. You have scp ./styles/, so you're saying secure copy ./styles/, but not where to copy it to.

    Generally, if you want to download, it will go:

    # download: remote -> local
    scp user@remote_host:remote_file local_file 
    

    where local_file might actually be a directory to put the file you're copying in. To upload, it's the opposite:

    # upload: local -> remote
    scp local_file user@remote_host:remote_file
    

    If you want to copy a whole directory, you will need -r. Think of scp as like cp, except you can specify a file with user@remote_host:file as well as just local files.

    Edit: As noted in a comment, if the usernames on the local and remote hosts are the same, then the user can be omitted when specifying a remote file.

    How to read file from res/raw by name

    With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

    getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                                 "raw", getPackageName());
    

    To get it as a InputStream

    InputStream ins = getResources().openRawResource(
                getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                "raw", getPackageName()));
    

    What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

    viewport meta tag on mobile browser,

    The initial-scale property controls the zoom level when the page is first loaded. The maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out.

    HTML: How to center align a form

    The last two lines are important to align in center:

    .f01 {
        background-color: rgb(16, 216, 252);
        padding: 100px;
        text-align: left;
        margin: auto;
        display: table;
    }
    

    How to find length of dictionary values

    Sure. In this case, you'd just do:

    length_key = len(d['key'])  # length of the list stored at `'key'` ...
    

    It's hard to say why you actually want this, but, perhaps it would be useful to create another dict that maps the keys to the length of values:

    length_dict = {key: len(value) for key, value in d.items()}
    length_key = length_dict['key']  # length of the list stored at `'key'` ...
    

    How can I validate google reCAPTCHA v2 using javascript/jQuery?

    Here's how we were able to validate the RECAPTCHA using .NET:

    FRONT-END

    <div id="rcaptcha" class="g-recaptcha" data-sitekey="[YOUR-KEY-GOES-HERE]" data-callback="onFepCaptchaSubmit"></div>
    

    BACK-END:

        public static bool IsCaptchaValid(HttpRequestBase requestBase)
        {
            var recaptchaResponse = requestBase.Form["g-recaptcha-response"];
            if (string.IsNullOrEmpty(recaptchaResponse))
            {
                return false;
            }
    
            string postData = string.Format("secret={0}&response={1}&remoteip={2}", "[YOUR-KEY-GOES-HERE]", recaptchaResponse, requestBase.UserHostAddress);
            byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);
    
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify");
    
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
    
            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
    
            var response = (HttpWebResponse)request.GetResponse();
    
            var responseString = "";
    
            using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
            {
                responseString = sr.ReadToEnd();
            }
    
            return System.Text.RegularExpressions.Regex.IsMatch(responseString, "\"success\"(\\s*?):(\\s*?)true", System.Text.RegularExpressions.RegexOptions.Compiled);
        }
    

    Call the above method within your Controller's POST action.

    Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

    The PropertiesPlaceholderConfigurer bean has an alternative property called "propertiesArray". Use this instead of the "properties" property, and configure it with an <array> of property references.

    Java - How do I make a String array with values?

    Another way to create an array with String apart from

    String[] strings =  { "abc", "def", "hij", "xyz" };
    

    is to use split. I find this more readable if there are lots of Strings.

    String[] strings =  "abc,def,hij,xyz".split(",");
    

    or the following is good if you are parsing lines of strings from another source.

    String[] strings =  ("abc\n" +
                         "def\n" +
                         "hij\n" +
                         "xyz").split("\n");
    

    Check for file exists or not in sql server?

    Create a function like so:

    CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
    RETURNS BIT
    AS
    BEGIN
         DECLARE @result INT
         EXEC master.dbo.xp_fileexist @path, @result OUTPUT
         RETURN cast(@result as bit)
    END;
    GO
    

    Edit your table and add a computed column (IsExists BIT). Set the expression to:

    dbo.fn_FileExists(filepath)
    

    Then just select:

    SELECT * FROM dbo.MyTable where IsExists = 1
    

    Update:

    To use the function outside a computed column:

    select id, filename, dbo.fn_FileExists(filename) as IsExists
    from dbo.MyTable
    

    Update:

    If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.

    And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.

    Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

    DELETE TB1, TB2
        FROM customer_details
            LEFT JOIN customer_booking on TB1.cust_id = TB2.fk_cust_id
        WHERE TB1.cust_id = $id
    

    ORA-01653: unable to extend table by in tablespace ORA-06512

    To resolve this error:

    ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name

    Just run this PL/SQL command for extended tablespace size automatically on-demand:

    alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;
    

    I get this error in import big dump file, just run this command without stopping import routine or restarting the database.

    Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.

    More info: alter_autoextend_on

    jQuery Change event on an <input> element - any way to retain previous value?

    I created these functions based on Joey Guerra's suggestion, thank you for that. I'm elaborating a little bit, perhaps someone can use it. The first function checkDefaults() is called when an input changes, the second is called when the form is submitted using jQuery.post. div.updatesubmit is my submit button, and class 'needsupdate' is an indicator that an update is made but not yet submitted.

    function checkDefaults() {
        var changed = false;
            jQuery('input').each(function(){
                if(this.defaultValue != this.value) {
                    changed = true;
                }
            });
            if(changed === true) {
                jQuery('div.updatesubmit').addClass("needsupdate");
            } else {
                jQuery('div.updatesubmit').removeClass("needsupdate");
            }
    }
    
    function renewDefaults() {
            jQuery('input').each(function(){
                this.defaultValue = this.value;
            });
            jQuery('div.updatesubmit').removeClass("needsupdate");
    }
    

    How can I issue a single command from the command line through sql plus?

    @find /v "@" < %0 | sqlplus -s scott/tiger@orcl & goto :eof
    
    select sysdate from dual;
    

    How do I include a pipe | in my linux find -exec command?

    find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'
    

    How to use a table type in a SELECT FROM statement?

    In SQL you may only use table type which is defined at schema level (not at package or procedure level), and index-by table (associative array) cannot be defined at schema level. So - you have to define nested table like this

    create type exch_row as object (
        currency_cd VARCHAR2(9),
        exch_rt_eur NUMBER,
        exch_rt_usd NUMBER);
    
    create type exch_tbl as table of exch_row;
    

    And then you can use it in SQL with TABLE operator, for example:

    declare
       l_row     exch_row;
       exch_rt   exch_tbl;
    begin
       l_row := exch_row('PLN', 100, 100);
       exch_rt  := exch_tbl(l_row);
    
       for r in (select i.*
                   from item i, TABLE(exch_rt) rt
                  where i.currency = rt.currency_cd) loop
          -- your code here
       end loop;
    end;
    /
    

    Convert hex string to int

    For those of you who need to convert hexadecimal representation of a signed byte from two-character String into byte (which in Java is always signed), there is an example. Parsing a hexadecimal string never gives negative number, which is faulty, because 0xFF is -1 from some point of view (two's complement coding). The principle is to parse the incoming String as int, which is larger than byte, and then wrap around negative numbers. I'm showing only bytes, so that example is short enough.

    String inputTwoCharHex="FE"; //whatever your microcontroller data is
    
    int i=Integer.parseInt(inputTwoCharHex,16);
    //negative numbers is i now look like 128...255
    
    // shortly i>=128
    if (i>=Integer.parseInt("80",16)){
    
        //need to wrap-around negative numbers
        //we know that FF is 255 which is -1
        //and FE is 254 which is -2 and so on
        i=-1-Integer.parseInt("FF",16)+i;
        //shortly i=-256+i;
    }
    byte b=(byte)i;
    //b is now surely between -128 and +127
    

    This can be edited to process longer numbers. Just add more FF's or 00's respectively. For parsing 8 hex-character signed integers, you need to use Long.parseLong, because FFFF-FFFF, which is integer -1, wouldn't fit into Integer when represented as a positive number (gives 4294967295). So you need Long to store it. After conversion to negative number and casting back to Integer, it will fit. There is no 8 character hex string, that wouldn't fit integer in the end.

    How to print a debug log?

    error_log(print_r($variable, TRUE)); 
    

    might be useful

    How can I display a modal dialog in Redux that performs asynchronous actions?

    Update: React 16.0 introduced portals through ReactDOM.createPortal link

    Update: next versions of React (Fiber: probably 16 or 17) will include a method to create portals: ReactDOM.unstable_createPortal() link


    Use portals

    Dan Abramov answer first part is fine, but involves a lot of boilerplate. As he said, you can also use portals. I'll expand a bit on that idea.

    The advantage of a portal is that the popup and the button remain very close into the React tree, with very simple parent/child communication using props: you can easily handle async actions with portals, or let the parent customize the portal.

    What is a portal?

    A portal permits you to render directly inside document.body an element that is deeply nested in your React tree.

    The idea is that for example you render into body the following React tree:

    <div className="layout">
      <div className="outside-portal">
        <Portal>
          <div className="inside-portal">
            PortalContent
          </div>
        </Portal>
      </div>
    </div>
    

    And you get as output:

    <body>
      <div class="layout">
        <div class="outside-portal">
        </div>
      </div>
      <div class="inside-portal">
        PortalContent
      </div>
    </body>
    

    The inside-portal node has been translated inside <body>, instead of its normal, deeply-nested place.

    When to use a portal

    A portal is particularly helpful for displaying elements that should go on top of your existing React components: popups, dropdowns, suggestions, hotspots

    Why use a portal

    No z-index problems anymore: a portal permits you to render to <body>. If you want to display a popup or dropdown, this is a really nice idea if you don't want to have to fight against z-index problems. The portal elements get added do document.body in mount order, which means that unless you play with z-index, the default behavior will be to stack portals on top of each others, in mounting order. In practice, it means that you can safely open a popup from inside another popup, and be sure that the 2nd popup will be displayed on top of the first, without having to even think about z-index.

    In practice

    Most simple: use local React state: if you think, for a simple delete confirmation popup, it's not worth to have the Redux boilerplate, then you can use a portal and it greatly simplifies your code. For such a use case, where the interaction is very local and is actually quite an implementation detail, do you really care about hot-reloading, time-traveling, action logging and all the benefits Redux brings you? Personally, I don't and use local state in this case. The code becomes as simple as:

    class DeleteButton extends React.Component {
      static propTypes = {
        onDelete: PropTypes.func.isRequired,
      };
    
      state = { confirmationPopup: false };
    
      open = () => {
        this.setState({ confirmationPopup: true });
      };
    
      close = () => {
        this.setState({ confirmationPopup: false });
      };
    
      render() {
        return (
          <div className="delete-button">
            <div onClick={() => this.open()}>Delete</div>
            {this.state.confirmationPopup && (
              <Portal>
                <DeleteConfirmationPopup
                  onCancel={() => this.close()}
                  onConfirm={() => {
                    this.close();
                    this.props.onDelete();
                  }}
                />
              </Portal>
            )}
          </div>
        );
      }
    }
    

    Simple: you can still use Redux state: if you really want to, you can still use connect to choose whether or not the DeleteConfirmationPopup is shown or not. As the portal remains deeply nested in your React tree, it is very simple to customize the behavior of this portal because your parent can pass props to the portal. If you don't use portals, you usually have to render your popups at the top of your React tree for z-index reasons, and usually have to think about things like "how do I customize the generic DeleteConfirmationPopup I built according to the use case". And usually you'll find quite hacky solutions to this problem, like dispatching an action that contains nested confirm/cancel actions, a translation bundle key, or even worse, a render function (or something else unserializable). You don't have to do that with portals, and can just pass regular props, since DeleteConfirmationPopup is just a child of the DeleteButton

    Conclusion

    Portals are very useful to simplify your code. I couldn't do without them anymore.

    Note that portal implementations can also help you with other useful features like:

    • Accessibility
    • Espace shortcuts to close the portal
    • Handle outside click (close portal or not)
    • Handle link click (close portal or not)
    • React Context made available in portal tree

    react-portal or react-modal are nice for popups, modals, and overlays that should be full-screen, generally centered in the middle of the screen.

    react-tether is unknown to most React developers, yet it's one of the most useful tools you can find out there. Tether permits you to create portals, but will position automatically the portal, relative to a given target. This is perfect for tooltips, dropdowns, hotspots, helpboxes... If you have ever had any problem with position absolute/relative and z-index, or your dropdown going outside of your viewport, Tether will solve all that for you.

    You can, for example, easily implement onboarding hotspots, that expands to a tooltip once clicked:

    Onboarding hotspot

    Real production code here. Can't be any simpler :)

    <MenuHotspots.contacts>
      <ContactButton/>
    </MenuHotspots.contacts>
    

    Edit: just discovered react-gateway which permits to render portals into the node of your choice (not necessarily body)

    Edit: it seems react-popper can be a decent alternative to react-tether. PopperJS is a library that only computes an appropriate position for an element, without touching the DOM directly, letting the user choose where and when he wants to put the DOM node, while Tether appends directly to the body.

    Edit: there's also react-slot-fill which is interesting and can help solve similar problems by allowing to render an element to a reserved element slot that you put anywhere you want in your tree

    Headers and client library minor version mismatch

    Changing PHP version from 5.6 to 5.5 Fixed it.

    You have to go to control panel > CGI Script and change PHP version there.

    How to grep and replace

    Other solutions mix regex syntaxes. To use perl/PCRE patterns for both search and replace, and only process matching files, this works quite well:

    grep -rlIZPi 'match1' | xargs -0r perl -pi -e 's/match2/replace/gi;'
    

    match1 and match2 are usually identical but match1 can be simplified to remove more advanced features that are only relevant to the substitution, e.g. capturing groups.

    Translation: grep recursively and list matching filenames, each separated by nul to protect any special characters; pipe any filenames to xargs which is expecting a nul-separated list; if any filenames are received, pass them to perl to perform the actual substitutions.

    For case-sensitive matching, drop the i flag from grep and the i pattern modifier from the s/// expression, but not the i flag from perl itself. Remove the I flag from grep to include binary files.

    window.close and self.close do not close the window in Chrome

    Ordinary javascript cannot close windows willy-nilly. This is a security feature, introduced a while ago, to stop various malicious exploits and annoyances.

    From the latest working spec for window.close():

    The close() method on Window objects should, if all the following conditions are met, close the browsing context A:

    • The corresponding browsing context A is script-closable.
    • The browsing context of the incumbent script is familiar with the browsing context A.
    • The browsing context of the incumbent script is allowed to navigate the browsing context A.

    A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a browsing context whose session history contains only one Document.

    This means, with one small exception, javascript must not be allowed to close a window that was not opened by that same javascript.

    Chrome allows that exception -- which it doesn't apply to userscripts -- however Firefox does not. The Firefox implementation flat out states:

    This method is only allowed to be called for windows that were opened by a script using the window.open method.


    If you try to use window.close from a Greasemonkey / Tampermonkey / userscript you will get:
    Firefox: The error message, "Scripts may not close windows that were not opened by script."
    Chrome: just silently fails.



    The long-term solution:

    The best way to deal with this is to make a Chrome extension and/or Firefox add-on instead. These can reliably close the current window.

    However, since the security risks, posed by window.close, are much less for a Greasemonkey/Tampermonkey script; Greasemonkey and Tampermonkey could reasonably provide this functionality in their API (essentially packaging the extension work for you).
    Consider making a feature request.



    The hacky workarounds:

    Chrome is currently was vulnerable to the "self redirection" exploit. So code like this used to work in general:

    open(location, '_self').close();
    

    This is buggy behavior, IMO, and is now (as of roughly April 2015) mostly blocked. It will still work from injected code only if the tab is freshly opened and has no pages in the browsing history. So it's only useful in a very small set of circumstances.

    However, a variation still works on Chrome (v43 & v44) plus Tampermonkey (v3.11 or later). Use an explicit @grant and plain window.close(). EG:

    // ==UserScript==
    // @name        window.close demo
    // @include     http://YOUR_SERVER.COM/YOUR_PATH/*
    // @grant       GM_addStyle
    // ==/UserScript==
    
    setTimeout (window.close, 5000);
    

    Thanks to zanetu for the update. Note that this will not work if there is only one tab open. It only closes additional tabs.


    Firefox is secure against that exploit. So, the only javascript way is to cripple the security settings, one browser at a time.

    You can open up about:config and set
    allow_scripts_to_close_windows to true.

    If your script is for personal use, go ahead and do that. If you ask anyone else to turn that setting on, they would be smart, and justified, to decline with prejudice.

    There currently is no equivalent setting for Chrome.

    How to change the icon of an Android app in Eclipse?

    In your AndroidManifest.xml file

    <application
            android:name="ApplicationClass"
            android:icon="@drawable/ic_launcher"  <--------
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
    

    How do I convert a Python 3 byte-string variable into a regular string?

    UPDATED:

    TO NOT HAVE ANY b and quotes at first and end

    How to convert bytes as seen to strings, even in weird situations.

    As your code may have unrecognizable characters to 'utf-8' encoding, it's better to use just str without any additional parameters:

    some_bad_bytes = b'\x02-\xdfI#)'
    text = str( some_bad_bytes )[2:-1]
    
    print(text)
    
    Output: \x02-\xdfI
    

    if you add 'utf-8' parameter, to these specific bytes, you should receive error.

    As PYTHON 3 standard says, text would be in utf-8 now with no concern.

    How to remove text from a string?

    _x000D_
    _x000D_
    var ret = "data-123".replace('data-','');_x000D_
    console.log(ret);   //prints: 123
    _x000D_
    _x000D_
    _x000D_

    Docs.


    For all occurrences to be discarded use:

    var ret = "data-123".replace(/data-/g,'');
    

    PS: The replace function returns a new string and leaves the original string unchanged, so use the function return value after the replace() call.

    Start new Activity and finish current one in Android?

    You can use finish() method or you can use:

    android:noHistory="true"
    

    And then there is no need to call finish() anymore.

    <activity android:name=".ClassName" android:noHistory="true" ... />
    

    How to calculate combination and permutation in R?

    You can use the combinat package with R 2.13:

    install.packages("combinat")
    require(combinat)
    permn(3)
    combn(3, 2)
    

    If you want to know the number of combination/permutations, then check the size of the result, e.g.:

    length(permn(3))
    dim(combn(3,2))[2]
    

    AngularJs $http.post() does not send data

    I had the same problem with AngularJS and Node.js + Express 4 + Router

    Router expects the data from post's request in body. This body was always empty if i followed the example from Angular Docs

    Notation 1

    $http.post('/someUrl', {msg:'hello word!'})
    

    But if i used it in the data

    Notation 2

    $http({
           withCredentials: false,
           method: 'post',
           url: yourUrl,
           headers: {'Content-Type': 'application/x-www-form-urlencoded'},
           data: postData
     });
    

    Edit 1:

    Otherwise node.js router will expect the data in req.body if used notation 1:

    req.body.msg
    

    Which also sends the information as JSON payload. This is better in some cases where you have arrays in your json and x-www-form-urlencoded will give some problems.

    it worked. Hope it helps.

    Check existence of input argument in a Bash shell script

    If you'd like to check if the argument exists, you can check if the # of arguments is greater than or equal to your target argument number.

    The following script demonstrates how this works

    test.sh

    #!/usr/bin/env bash
    
    if [ $# -ge 3 ]
    then
      echo script has at least 3 arguments
    fi
    

    produces the following output

    $ ./test.sh
    ~
    $ ./test.sh 1
    ~
    $ ./test.sh 1 2
    ~
    $ ./test.sh 1 2 3
    script has at least 3 arguments
    $ ./test.sh 1 2 3 4
    script has at least 3 arguments
    

    How to implement Android Pull-to-Refresh

    Those who are looking to implement pull to refresh functionality for RecyclerView can following my simple tutorial How to implement Pull To Refresh for RecyclerView in Android.

    Libraries To Import

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    

    XML Code

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipe_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
    

    Activity JAVA Code

    import androidx.appcompat.app.AppCompatActivity;
    import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
    import android.os.Bundle;
    import android.os.Handler;
    
    public class MainActivity extends AppCompatActivity {
    
    private SwipeRefreshLayout swipeRefreshLayout;
    
    ...
    
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
           
            ...
            swipeRefreshLayout = findViewById(R.id.swipe_layout);
            initializeRefreshListener();
    }
    
        void initializeRefreshListener() {
    
            swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    // This method gets called when user pull for refresh,
                    // You can make your API call here,
                    // We are using adding a delay for the moment
                    final Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(swipeRefreshLayout.isRefreshing()) {
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        }
                    }, 3000);
                }
            });
        }
    

    Python send POST with header

    Thanks a lot for your link to the requests module. It's just perfect. Below the solution to my problem.

    import requests
    import json
    
    url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
    payload = {
        "Host": "www.mywbsite.fr",
        "Connection": "keep-alive",
        "Content-Length": 129,
        "Origin": "https://www.mywbsite.fr",
        "X-Requested-With": "XMLHttpRequest",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
        "Content-Type": "application/json",
        "Accept": "*/*",
        "Referer": "https://www.mywbsite.fr/data/mult.aspx",
        "Accept-Encoding": "gzip,deflate,sdch",
        "Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
        "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
        "Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
    }
    # Adding empty header as parameters are being sent in payload
    headers = {}
    r = requests.post(url, data=json.dumps(payload), headers=headers)
    print(r.content)
    

    How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

    What is a when you call Ancestors('A',a)? If a['A'] is None, or if a['A'][0] is None, you'd receive that exception.

    PySpark 2.0 The size or shape of a DataFrame

    I think there is not similar function like data.shape in Spark. But I will use len(data.columns) rather than len(data.dtypes)

    Python object.__repr__(self) should be an expression?

    I think the confusion over here roots from the english. I mean __repr__(); short for 'representation' of the value I'm guessing, like @S.Lott said

    "What is the difference between "an actual expression, that can ... recreate the object" and "a rehasing of the actual expression which was used [to create the object]"? Both are an expression that creates the object. There's no practical distinction between these. A repr call could produce either a new expression or the original expression. In many cases, they're the same."

    But in some cases they might be different. E.g; coordinate points, you might want c.coordinate to return: 3,5 but c.__repr__ to return Coordinate(3, 5). Hope that makes more sense...

    What does functools.wraps do?

    I very often use classes, rather than functions, for my decorators. I was having some trouble with this because an object won't have all the same attributes that are expected of a function. For example, an object won't have the attribute __name__. I had a specific issue with this that was pretty hard to trace where Django was reporting the error "object has no attribute '__name__'". Unfortunately, for class-style decorators, I don't believe that @wrap will do the job. I have instead created a base decorator class like so:

    class DecBase(object):
        func = None
    
        def __init__(self, func):
            self.__func = func
    
        def __getattribute__(self, name):
            if name == "func":
                return super(DecBase, self).__getattribute__(name)
    
            return self.func.__getattribute__(name)
    
        def __setattr__(self, name, value):
            if name == "func":
                return super(DecBase, self).__setattr__(name, value)
    
            return self.func.__setattr__(name, value)
    

    This class proxies all the attribute calls over to the function that is being decorated. So, you can now create a simple decorator that checks that 2 arguments are specified like so:

    class process_login(DecBase):
        def __call__(self, *args):
            if len(args) != 2:
                raise Exception("You can only specify two arguments")
    
            return self.func(*args)
    

    How do I check if a file exists in Java?

    Simple example with good coding practices and covering all cases :

     private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
            File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
            if (f.exists()) {
                throw new FileAlreadyExistsException(f.getAbsolutePath());
            } else {
                try {
                    URL u = new URL(url);
                    FileUtils.copyURLToFile(u, f);
                } catch (MalformedURLException ex) {
                    Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    

    Reference and more examples at

    https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations

    Take n rows from a spark dataframe and pass to toPandas()

    You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:

    l = [('Alice', 1),('Jim',2),('Sandra',3)]
    df = sqlContext.createDataFrame(l, ['name', 'age'])
    
    df_pandas = pd.DataFrame(df.head(3), columns=df.columns)
    
    In [4]: df_pandas
    Out[4]: 
         name  age
    0   Alice    1
    1     Jim    2
    2  Sandra    3
    

    c++ string array initialization

    With support for C++11 initializer lists it is very easy:

    #include <iostream>
    #include <vector>
    #include <string>
    using namespace std;
    
    using Strings = vector<string>;
    
    void foo( Strings const& strings )
    {
        for( string const& s : strings ) { cout << s << endl; }
    }
    
    auto main() -> int
    {
        foo( Strings{ "hi", "there" } ); 
    }
    

    Lacking that (e.g. for Visual C++ 10.0) you can do things like this:

    #include <iostream>
    #include <vector>
    #include <string>
    using namespace std;
    
    typedef vector<string> Strings;
    
    void foo( Strings const& strings )
    {
        for( auto it = begin( strings );  it != end( strings );  ++it )
        {
            cout << *it << endl;
        }
    }
    
    template< class Elem >
    vector<Elem>& r( vector<Elem>&& o ) { return o; }
    
    template< class Elem, class Arg >
    vector<Elem>& operator<<( vector<Elem>& v, Arg const& a )
    {
        v.push_back( a );
        return v;
    }
    
    int main()
    {
        foo( r( Strings() ) << "hi" << "there" ); 
    }
    

    Regex: Remove lines containing "help", etc

    You can do this using sed: sed '/help/ d' < inputFile > outputFile

    JSON: why are forward slashes escaped?

    PHP escapes forward slashes by default which is probably why this appears so commonly. I'm not sure why, but possibly because embedding the string "</script>" inside a <script> tag is considered unsafe.

    This functionality can be disabled by passing in the JSON_UNESCAPED_SLASHES flag but most developers will not use this since the original result is already valid JSON.

    Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

    Another solution:

    if (view == null) {
        view = inflater.inflate(R.layout.nearbyplaces, container, false);
    }
    

    That's it, if not null you don't need to reinitialize it removing from parent is unnecessary step.

    How to install all required PHP extensions for Laravel?

    Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

    You can run the following command in Ubuntu to make sure the extensions are installed.

    sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
    

    PHP version specific installation (if PHP 7.4 installed)

    sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
    

    You may need other PHP extensions for your composer packages. Find from links below.

    PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

    PHP extensions for Ubuntu 18.04 LTS (Bionic)

    PHP extensions for Ubuntu 16.04 LTS (Xenial)

    Order by descending date - month, day and year

    If you restructured your date format into YYYY/MM/DD then you can use this simple string ordering to achieve the formating you need.

    Alternatively, using the SUBSTR(store_name,start,length) command you should be able to restructure the sorting term into the above format

    perhaps using the following

    SELECT     *
    FROM         vw_view
    ORDER BY SUBSTR(EventDate,6,4) + SUBSTR(EventDate, 0, 5) DESC
    

    Error in strings.xml file in Android

    1. for error: unescaped apostrophe in string

    what I found is that AAPT2 tool points to wrong row in xml, sometimes. So you should correct whole strings.xml file

    In Android Studio, in problem file use :

    Edit->find->replace

    Then write in first field \' (or \&,>,\<,\")
    in second put '(or &,>,<,")
    then replace each if needed.(or "reptlace all" in case with ')
    Then in first field again put '(or &,>,<,")
    and in second write \'
    then replace each if needed.(or "replace all" in case with ')

    2. for other problematic symbols
    I use to comment each next half part +rebuild until i won't find the wrong sign.

    E.g. an escaped word "\update" unexpectedly drops such error :)

    Explode string by one or more spaces or tabs

    Explode string by one or more spaces or tabs in php example as follow: 
    
       <?php 
           $str = "test1 test2   test3        test4"; 
           $result = preg_split('/[\s]+/', $str);
           var_dump($result);  
        ?>
    
       /** To seperate by spaces alone: **/
        <?php
          $string = "p q r s t";   
          $res = preg_split('/ +/', $string);
          var_dump($res);
        ?>
    

    TypeScript error TS1005: ';' expected (II)

    The issue was in my code.

    In large code base, issue was not clear.

    A simplified code is below:

    Bad:

     collection.insertMany(
        [[],
        function (err, result) {
        });
    

    Good:

    collection.insertMany(
        [],
        function (err, result) {
        });
    

    That is, the first one has [[], instead of normal array []

    TS error was not clear enough, and it showed error in the last line with });

    Hope this helps.

    Why do I get "MismatchSenderId" from GCM server side?

    Use sender ID & API Key generated here: http://developers.google.com instead (browse for Google Cloud Messaging first and follow the instruction).

    Visual C++: How to disable specific linker warnings?

    Update 2018-10-16

    Reportedly, as of VS 2013, this warning can be disabled. See the comment by @Mark Ransom.

    Original Answer

    You can't disable that specific warning.

    According to Geoff Chappell the 4099 warning is treated as though it's too important to ignore, even by using in conjunction with /wx (which would treat warnings as errors and ignore the specified warning in other situations)

    Here is the relevant text from the link:

    Not Quite Unignorable Warnings

    For some warning numbers, specification in a /ignore option is accepted but not necessarily acted upon. Should the warning occur while the /wx option is not active, then the warning message is still displayed, but if the /wx option is active, then the warning is ignored. It is as if the warning is thought important enough to override an attempt at ignoring it, but not if the user has put too high a price on unignored warnings.

    The following warning numbers are affected:

    4200, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4219, 4231 and 4237
    

    How to cast a double to an int in Java by rounding it down?

    Math.floor(n)
    

    where n is a double. This'll actually return a double, it seems, so make sure that you typecast it after.

    Using onBlur with JSX and React

    There are a few problems here.

    1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

    2: you need a place to render the error.

    3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

    handleBlur: function () {
      this.setState({validating: true});
    },
    render: function () {
      return <div>
        ...
        <input
            type="password"
            placeholder="Password (confirm)"
            valueLink={this.linkState('password2')}
            onBlur={this.handleBlur}
         />
        ...
        {this.renderPasswordConfirmError()}
      </div>
    },
    renderPasswordConfirmError: function() {
      if (this.state.validating && this.state.password !== this.state.password2) {
        return (
          <div>
            <label className="error">Please enter the same password again.</label>
          </div>
        );
      }  
      return null;
    },
    

    How can I view the shared preferences file using Android Studio?

    Another simple way would be using a root explorer app on your phone.

    Then go to /data/data/package name/shared preferences folder/name of your preferences.xml, you can use ES File explorer, and go to the root of your device, not sd card.

    How do I configure Maven for offline development?

    You can run maven in offline mode mvn -o install. Of course any artifacts not available in your local repository will fail. Maven is not predicated on distributed repositories, but they certainly make things more seamless. Its for this reason that many shops use internal mirrors that are incrementally synced with the central repos.

    In addition, the mvn dependency:go-offline can be used to ensure you have all of your dependencies installed locally before you begin to work offline.

    How to convert an int to a hex string?

    I wanted a random integer converted into a six-digit hex string with a # at the beginning. To get this I used

    "#%6x" % random.randint(0xFFFFFF)
    

    How do I download a file from the internet to my linux server with Bash

    You can use the command wget to download from command line. Specifically, you could use

    wget http://download.oracle.com/otn-pub/java/jdk/7u10-b18/jdk-7u10-linux-x64.tar.gz
    

    However because Oracle requires you to accept a license agreement this may not work (and I am currently unable to test it).

    OOP vs Functional Programming vs Procedural

    In order to answer your question, we need two elements:

    1. Understanding of the characteristics of different architecture styles/patterns.
    2. Understanding of the characteristics of different programming paradigms.

    A list of software architecture styles/pattern is shown on the software architecture article on Wikipeida. And you can research on them easily on the web.

    In short and general, Procedural is good for a model that follows a procedure, OOP is good for design, and Functional is good for high level programming.

    I think you should try reading the history on each paradigm and see why people create it and you can understand them easily.

    After understanding them both, you can link the items of architecture styles/patterns to programming paradigms.

    MySQL timezone change?

    This works fine

    <?php
          $con=mysqli_connect("localhost","my_user","my_password","my_db");
          $con->query("SET GLOBAL time_zone = 'Asia/Calcutta'");
          $con->query("SET time_zone = '+05:30'");
          $con->query("SET @@session.time_zone = '+05:30'");
    ?>
    

    How to unzip a list of tuples into individual lists?

    Use zip(*list):

    >>> l = [(1,2), (3,4), (8,9)]
    >>> list(zip(*l))
    [(1, 3, 8), (2, 4, 9)]
    

    The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

    zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

    map(list, zip(*l))          # keep it a generator
    [list(t) for t in zip(*l)]  # consume the zip generator into a list of lists
    

    How to pass multiple values to single parameter in stored procedure

    Either use a User Defined Table

    Or you can use CSV by defining your own CSV function as per This Post.

    I'd probably recommend the second method, as your stored proc is already written in the correct format and you'll find it handy later on if you need to do this down the road.

    Cheers!

    Get the value in an input text box

    You can only select a value with the following two ways:

    // First way to get a value
    value = $("#txt_name").val(); 
    
    // Second way to get a value
    value = $("#txt_name").attr('value');
    

    If you want to use straight JavaScript to get the value, here is how:

    document.getElementById('txt_name').value 
    

    Sort a Custom Class List<T>

    You are correct that your cTag class must implement IComparable<T> interface. Then you can just call Sort() on your list.

    To implement IComparable<T> interface, you must implement CompareTo(T other) method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.

    public class cTag:IComparable<cTag> {
        public int id { get; set; }
        public int regnumber { get; set; }
        public string date { get; set; }
        public int CompareTo(cTag other) {
            return date.CompareTo(other.date);
        }
    }
    

    However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:

    public class cTag:IComparable<cTag> {
        public int id { get; set; }
        public int regnumber { get; set; }
        public DateTime date { get; set; }
        public int CompareTo(cTag other) {
            return date.CompareTo(other.date);
        }
    }
    

    Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String) method.

    Choice between vector::resize() and vector::reserve()

    reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.

    Is there any better choice in this kind of scenario?

    it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.

    fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?

    How can I quickly and easily convert spreadsheet data to JSON?

    Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

    1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

      Rory Gallagher      Guitar
      Gerry McAvoy        Bass
      Rod de'Ath          Drums
      Lou Martin          Keyboards
      Donkey Kong Sioux   Self-Appointed Semi-official Stomper
      

      Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

    2. Save the file as a CSV file.

    3. Copy the contents of the CSV file to the clipboard

    4. Go to http://www.convertcsv.com/csv-to-json.htm

    5. Verify that the "First row is column names" checkbox is checked

    6. Paste the CSV data into the content area

    7. Mash the "Convert CSV to JSON" button

      With the data shown above, you will now have:

      [
        {
          "MUSICIAN":"Rory Gallagher",
          "INSTRUMENT":"Guitar"
        },
        {
          "MUSICIAN":"Gerry McAvoy",
          "INSTRUMENT":"Bass"
        },
        {
          "MUSICIAN":"Rod D'Ath",
          "INSTRUMENT":"Drums"
        },
        {
          "MUSICIAN":"Lou Martin",
          "INSTRUMENT":"Keyboards"
        }
        {
          "MUSICIAN":"Donkey Kong Sioux",
          "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
        }
      ]
      

      With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

    8. Go here: http://jsonlint.com/

    9. Paste the JSON into the content area

    10. Pres the "Validate" button.

    If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

    Monad in plain English? (For the OOP programmer with no FP background)

    I'll try to make the shortest definition I can manage using OOP terms:

    A generic class CMonadic<T> is a monad if it defines at least the following methods:

    class CMonadic<T> { 
        static CMonadic<T> create(T t);  // a.k.a., "return" in Haskell
        public CMonadic<U> flatMap<U>(Func<T, CMonadic<U>> f); // a.k.a. "bind" in Haskell
    }
    

    and if the following laws apply for all types T and their possible values t

    left identity:

    CMonadic<T>.create(t).flatMap(f) == f(t)
    

    right identity

    instance.flatMap(CMonadic<T>.create) == instance
    

    associativity:

    instance.flatMap(f).flatMap(g) == instance.flatMap(t => f(t).flatMap(g))
    

    Examples:

    A List monad may have:

    List<int>.create(1) --> [1]
    

    And flatMap on the list [1,2,3] could work like so:

    intList.flatMap(x => List<int>.makeFromTwoItems(x, x*10)) --> [1,10,2,20,3,30]
    

    Iterables and Observables can also be made monadic, as well as Promises and Tasks.

    Commentary:

    Monads are not that complicated. The flatMap function is a lot like the more commonly encountered map. It receives a function argument (also known as delegate), which it may call (immediately or later, zero or more times) with a value coming from the generic class. It expects that passed function to also wrap its return value in the same kind of generic class. To help with that, it provides create, a constructor that can create an instance of that generic class from a value. The return result of flatMap is also a generic class of the same type, often packing the same values that were contained in the return results of one or more applications of flatMap to the previously contained values. This allows you to chain flatMap as much as you want:

    intList.flatMap(x => List<int>.makeFromTwo(x, x*10))
           .flatMap(x => x % 3 == 0 
                       ? List<string>.create("x = " + x.toString()) 
                       : List<string>.empty())
    

    It just so happens that this kind of generic class is useful as a base model for a huge number of things. This (together with the category theory jargonisms) is the reason why Monads seem so hard to understand or explain. They're a very abstract thing and only become obviously useful once they're specialized.

    For example, you can model exceptions using monadic containers. Each container will either contain the result of the operation or the error that has occured. The next function (delegate) in the chain of flatMap callbacks will only be called if the previous one packed a value in the container. Otherwise if an error was packed, the error will continue to propagate through the chained containers until a container is found that has an error handler function attached via a method called .orElse() (such a method would be an allowed extension)

    Notes: Functional languages allow you to write functions that can operate on any kind of a monadic generic class. For this to work, one would have to write a generic interface for monads. I don't know if its possible to write such an interface in C#, but as far as I know it isn't:

    interface IMonad<T> { 
        static IMonad<T> create(T t); // not allowed
        public IMonad<U> flatMap<U>(Func<T, IMonad<U>> f); // not specific enough,
        // because the function must return the same kind of monad, not just any monad
    }
    

    Responsively change div size keeping aspect ratio

    <style>
    #aspectRatio
    {
      position:fixed;
      left:0px;
      top:0px;
      width:60vw;
      height:40vw;
      border:1px solid;
      font-size:10vw;
    }
    </style>
    <body>
    <div id="aspectRatio">Aspect Ratio?</div>
    </body>
    

    The key thing to note here is vw = viewport width, and vh = viewport height

    How do I set <table> border width with CSS?

    Doing borders on tables with css is a bit more complicated (but not as much, see this jsfiddle as example):

    _x000D_
    _x000D_
    table {_x000D_
      border-collapse: collapse;_x000D_
      border: 1px solid black;_x000D_
    }_x000D_
    _x000D_
    table td {_x000D_
      border: 1px solid black;_x000D_
    }
    _x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>test</td>_x000D_
        <td>test</td>_x000D_
      </tr>_x000D_
    </table>
    _x000D_
    _x000D_
    _x000D_

    Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

    You probably haven't added a reference to Microsoft XML (any version) for Dim objHTTP As New MSXML2.XMLHTTP in the VBA window's Tools/References... dialog.

    Also, it's a good idea to avoid using late binding (CreateObject...); better to use early binding (Dim objHTTP As New MSXML2.XMLHTTP), as early binding allows you to use Intellisense to list the members and do all sorts of design-time validation.

    Escaping HTML strings with jQuery

    escape() and unescape() are intended to encode / decode strings for URLs, not HTML.

    Actually, I use the following snippet to do the trick that doesn't require any framework:

    var escapedHtml = html.replace(/&/g, '&amp;')
                          .replace(/>/g, '&gt;')
                          .replace(/</g, '&lt;')
                          .replace(/"/g, '&quot;')
                          .replace(/'/g, '&apos;');
    

    Android 6.0 Marshmallow. Cannot write to SD Card

    Maybe you cannot use manifest class from generated code in your project. So, you can use manifest class from android sdk "android.Manifest.permission.WRITE_EXTERNAL_STORAGE". But in Marsmallow version have 2 permission must grant are WRITE and READ EXTERNAL STORAGE in storage category. See my program, my program will request permission until user choose yes and do something after permissions is granted.

                if (Build.VERSION.SDK_INT >= 23) {
                    if (ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(LoginActivity.this,
                                new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
                                1);
                    } else {
                        //do something
                    }
                } else {
                        //do something
                }
    

    How to create an integer-for-loop in Ruby?

    Try Below Simple Ruby Magics :)

    (1..x).each { |n| puts n }
    x.times { |n| puts n }
    1.upto(x) { |n| print n }
    

    How to get the version of ionic framework?

    That is the version number of the Ionic CLI, which is different from the version number of Ionic's library. Here are a couple easy ways to check the version.

    In the browser console, you can run ionic.version and it will print to the console what version it is.

    Screenshot of Chrome Dev Tools console

    You can also look at the bower.json file in your app, and it will show the version number like you see here. https://github.com/ionic-in-action/chapter5/blob/master/bower.json#L5

    How do I list the symbols in a .so file

    For shared libraries libNAME.so the -D switch was necessary to see symbols in my Linux

    nm -D libNAME.so
    

    and for static library as reported by others

    nm -g libNAME.a
    

    How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

    I am using mysql 8.0.12 and updating the mysql connector to mysql-connector-java-8.0.12 resolved the issue for me.

    Hope it helps somebody.

    Spring REST Service: how to configure to remove null objects in json response

    Since Jackson is being used, you have to configure that as a Jackson property. In the case of Spring Boot REST services, you have to configure it in application.properties or application.yml:

    spring.jackson.default-property-inclusion = NON_NULL
    

    source

    What's the difference between SortedList and SortedDictionary?

    Check out the MSDN page for SortedList:

    From Remarks section:

    The SortedList<(Of <(TKey, TValue>)>) generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this, it is similar to the SortedDictionary<(Of <(TKey, TValue>)>) generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:

    • SortedList<(Of <(TKey, TValue>)>) uses less memory than SortedDictionary<(Of <(TKey, TValue>)>).
    • SortedDictionary<(Of <(TKey, TValue>)>) has faster insertion and removal operations for unsorted data, O(log n) as opposed to O(n) for SortedList<(Of <(TKey, TValue>)>).

    • If the list is populated all at once from sorted data, SortedList<(Of <(TKey, TValue>)>) is faster than SortedDictionary<(Of <(TKey, TValue>)>).

    how to remove "," from a string in javascript

    If U want to delete more than one characters, say comma and dots you can write

    <script type="text/javascript">
      var mystring = "It,is,a,test.string,of.mine" 
      mystring = mystring.replace(/[,.]/g , ''); 
      alert( mystring);
    </script>
    

    Generate random colors (RGB)

    You could also use Hex Color Code,

    Name    Hex Color Code  RGB Color Code
    Red     #FF0000         rgb(255, 0, 0)
    Maroon  #800000         rgb(128, 0, 0)
    Yellow  #FFFF00         rgb(255, 255, 0)
    Olive   #808000         rgb(128, 128, 0)
    

    For example

    import matplotlib.pyplot as plt
    import random
    
    number_of_colors = 8
    
    color = ["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])
                 for i in range(number_of_colors)]
    print(color)
    

    ['#C7980A', '#F4651F', '#82D8A7', '#CC3A05', '#575E76', '#156943', '#0BD055', '#ACD338']

    Lets try plotting them in a scatter plot

    for i in range(number_of_colors):
        plt.scatter(random.randint(0, 10), random.randint(0,10), c=color[i], s=200)
    
    plt.show()
    

    enter image description here

    In PHP how can you clear a WSDL cache?

    I recommend using a cache-buster in the wsdl url.

    In our apps we use a SVN Revision id in the wsdl url so the client immediately knows of changing structures. This works on our app because, everytime we change the server-side, we also need to adjust the client accordingly.

    $client = new SoapClient('http://somewhere.com/?wsdl&rev=$Revision$');
    

    This requires svn to be configured properly. Not on all repositories this is enabled by default.

    In case you are not responsible for both components (server,client) or you don't use SVN you may find another indicator which can be utilised as a cache-buster in your wsdl url.

    Enable/Disable a dropdownbox in jquery

    Here is one way that I hope is easy to understand:

    http://jsfiddle.net/tft4t/

    $(document).ready(function() {
     $("#chkdwn2").click(function() {
       if ($(this).is(":checked")) {
          $("#dropdown").prop("disabled", true);
       } else {
          $("#dropdown").prop("disabled", false);  
       }
     });
    });
    

    JavaScript equivalent to printf/String.Format

    With sprintf.js in place - one can make a nifty little format-thingy

    String.prototype.format = function(){
        var _args = arguments 
        Array.prototype.unshift.apply(_args,[this])
        return sprintf.apply(undefined,_args)
    }   
    // this gives you:
    "{%1$s}{%2$s}".format("1", "0")
    // {1}{0}
    

    How can I see the current value of my $PATH variable on OS X?

    By entering $PATH on its own at the command prompt, you're trying to run it. This isn't like Windows where you can get your path output by simply typing path.

    If you want to see what the path is, simply echo it:

    echo $PATH
    

    Returning multiple objects in an R function

    Is something along these lines what you are looking for?

    x1 = function(x){
      mu = mean(x)
      l1 = list(s1=table(x),std=sd(x))
      return(list(l1,mu))
    }
    
    library(Ecdat)
    data(Fair)
    x1(Fair$age)
    

    Permission denied error on Github Push

    I had this problem too but managed to solve it, the error is that ur computer has saved a git username and password so if you shift to another account the error 403 will appear. Below is the solution For Windows you can find the keys here:

    control panel > user accounts > credential manager > Windows credentials > Generic credentials

    Next remove the Github keys.

    Copying a HashMap in Java

    Since Java 10 it is possible to use

    Map.copyOf
    

    for creating a shallow copy, which is also immutable. (Here is its Javadoc). For a deep copy, as mentioned in this answer you, need some kind of value mapper to make a safe copy of values. You don't need to copy keys though, since they must be immutable.

    How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

    I had the same issue and I have tried many answers but nothing worked.

    I tried the following and it worked successfully :

    <input type=text  data-date-format='yy-mm-dd'  > 
    

    How to create enum like type in TypeScript?

    This is now part of the language. See TypeScriptLang.org > Basic Types > enum for the documentation on this. An excerpt from the documentation on how to use these enums:

    enum Color {Red, Green, Blue};
    var c: Color = Color.Green;
    

    Or with manual backing numbers:

    enum Color {Red = 1, Green = 2, Blue = 4};
    var c: Color = Color.Green;
    

    You can also go back to the enum name by using for example Color[2].

    Here's an example of how this all goes together:

    module myModule {
        export enum Color {Red, Green, Blue};
    
        export class MyClass {
            myColor: Color;
    
            constructor() {
                console.log(this.myColor);
                this.myColor = Color.Blue;
                console.log(this.myColor);
                console.log(Color[this.myColor]);
            }
        }
    }
    
    var foo = new myModule.MyClass();
    

    This will log:

    undefined  
    2  
    Blue
    

    Because, at the time of writing this, the Typescript Playground will generate this code:

    var myModule;
    (function (myModule) {
        (function (Color) {
            Color[Color["Red"] = 0] = "Red";
            Color[Color["Green"] = 1] = "Green";
            Color[Color["Blue"] = 2] = "Blue";
        })(myModule.Color || (myModule.Color = {}));
        var Color = myModule.Color;
        ;
        var MyClass = (function () {
            function MyClass() {
                console.log(this.myColor);
                this.myColor = Color.Blue;
                console.log(this.myColor);
                console.log(Color[this.myColor]);
            }
            return MyClass;
        })();
        myModule.MyClass = MyClass;
    })(myModule || (myModule = {}));
    var foo = new myModule.MyClass();
    

    How do I install the ext-curl extension with PHP 7?

    Well I was able to install it by :

    sudo apt-get install php-curl
    

    on my system. This will install a dependency package, which depends on the default php version.

    After that restart apache

    sudo service apache2 restart
    

    Perform Button click event when user press Enter key in Textbox

    In the aspx page load event, add an onkeypress to the box.

    this.TextBox1.Attributes.Add(
        "onkeypress", "button_click(this,'" + this.Button1.ClientID + "')");
    

    Then add this javascript to evaluate the key press, and if it is "enter," click the right button.

    <script>
        function button_click(objTextBox,objBtnID)
        {
            if(window.event.keyCode==13)
            {
                document.getElementById(objBtnID).focus();
                document.getElementById(objBtnID).click();
            }
        }
    </script>
    

    Get first element of Series without knowing the index

    Use iloc to access by position (rather than label):

    In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
    
    In [12]: df
    Out[12]: 
       A  B
    a  1  2
    b  3  4
    
    In [13]: df.iloc[0]  # first row in a DataFrame
    Out[13]: 
    A    1
    B    2
    Name: a, dtype: int64
    
    In [14]: df['A'].iloc[0]  # first item in a Series (Column)
    Out[14]: 1
    

    Parsing Json rest api response in C#

    Create a C# class that maps to your Json and use Newsoft JsonConvert to Deserialise it.

    For example:

    public Class MyResponse
    {
        public Meta Meta { get; set; }
        public Response Response { get; set; }
    }
    

    How to run .NET Core console app from the command line

    You can very easily create an EXE (for Windows) without using any cryptic build commands. You can do it right in Visual Studio.

    1. Right click the Console App Project and select Publish.
    2. A new page will open up (screen shot below)
    3. Hit Configure...
    4. Then change Deployment Mode to Self-contained or Framework dependent. .NET Core 3.0 introduces a Single file deployment which is a single executable.
    5. Use "framework dependent" if you know the target machine has a .NET Core runtime as it will produce fewer files to install.
    6. If you now view the bin folder in explorer, you will find the .exe file.
    7. You will have to deploy the exe along with any supporting config and dll files.

    Console App Publish

    How to read a file and write into a text file?

        An example of reading a file:
    Dim sFileText as String
    Dim iFileNo as Integer
    iFileNo = FreeFile
    'open the file for reading
    Open "C:\Test.txt" For Input As #iFileNo
    'change this filename to an existing file! (or run the example below first)
    
    'read the file until we reach the end
    Do While Not EOF(iFileNo)
    Input #iFileNo, sFileText
    'show the text (you will probably want to replace this line as appropriate to your program!)
    MsgBox sFileText
    Loop
    
    'close the file (if you dont do this, you wont be able to open it again!)
    Close #iFileNo
    (note: an alternative to Input # is Line Input # , which reads whole lines).
    
    
    An example of writing a file:
    Dim sFileText as String
    Dim iFileNo as Integer
    iFileNo = FreeFile
    'open the file for writing
    Open "C:\Test.txt" For Output As #iFileNo
    'please note, if this file already exists it will be overwritten!
    
    'write some example text to the file
    Print #iFileNo, "first line of text"
    Print #iFileNo, " second line of text"
    Print #iFileNo, "" 'blank line
    Print #iFileNo, "some more text!"
    
    'close the file (if you dont do this, you wont be able to open it again!)
    Close #iFileNo
    

    From Here

    How to send 100,000 emails weekly?

    Short answer: While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to outsource this to one of the companies that specialize in it (I did say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).

    Long answer: If you decide that you absolutely want to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:

    • e-mail content that is not spam (otherwise you'll run into additional major roadblocks on every step, even legal repercussions)
    • in addition, your content should be easy to distinguish from spam - that may be a bit hard to do in some cases (I heard that a certain pharmaceutical company had to all but abandon e-mail, as their brand names are quite common in spams)
    • a configurable SMTP server of your own, one which won't buckle when you dump 100k e-mails onto it (your ISP's upstream server won't be sufficient here and you'll make the ISP violently unhappy; we used two dedicated boxes)
    • some mail wrapper (e.g. PhpMailer if PHP's your poison of choice; using PHP's mail() is horrible enough by itself)
    • your own sender function to run in a loop, create the mails and pass them to the wrapper (note that you may run into PHP's memory limits if your app has a memory leak; you may need to recycle the sending process periodically, or even better, decouple the "creating e-mails" and "sending e-mails" altogether)

    Surprisingly, that was the easy part. The hard part is actually sending it:

    • some servers will ban you when you send too many mails close together, so you need to shuffle and watch your queue (e.g. send one mail to [email protected], then three to other domains, only then another to [email protected])
    • you need to have correct PTR, SPF, DKIM records
    • handling remote server timeouts, misconfigured DNS records and other network pleasantries
    • handling invalid e-mails (and no, regex is the wrong tool for that)
    • handling unsubscriptions (many legitimate newsletters have been reclassified as spam due to many frustrated users who couldn't unsubscribe in one step and instead chose to "mark as spam" - the spam filters do learn, esp. with large e-mail providers)
    • handling bounces and rejects ("no such mailbox [email protected]","mailbox [email protected] full")
    • handling blacklisting and removal from blacklists (Sure, you're not sending spam. Some recipients won't be so sure - with such large list, it will happen sometimes, no matter what precautions you take. Some people (e.g. your not-so-scrupulous competitors) might even go as far to falsely report your mailings as spam - it does happen. On average, it takes weeks to get yourself removed from a blacklist.)

    And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).

    I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:

    • the remote SMTP servers don't want to talk to your SMTP server
    • your mails are getting marked as spam (<blink> is not your friend here, nor is <font color=...>)
    • your mails are delivered days, even weeks late (contrary to popular opinion, SMTP is designed to make a best effort to deliver the message sometime in the future - not to deliver it now)
    • your mails are not delivered at all (already sent from e-mail server on hop #4, not sent yet from server on hop #5, the server that currently holds the message crashes, data is lost)
    • your mails are mangled by some braindead server en route (this one is somewhat solvable with base64 encoding, but then the size goes up and the e-mail looks more suspicious)
    • your mails are delivered and the recipients seem not to want them ("I'm sure I didn't sign up for this, I remember exactly what I did a year ago" (of course you do, sir))
    • users with various versions of Microsoft Outlook and its special handling of Internet mail
    • wizard's apprentice mode (a self-reinforcing positive feedback loop - in other words, automated e-mails as replies to automated e-mails as replies to...; you really don't want to be the one to set this off, as you'd anger half the internet at yourself)

    and it'll be your job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.

    If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.

    Trigger change event of dropdown

    Try this:

    $('#id').change();

    Works for me.

    On one line together with setting the value: $('#id').val(16).change();

    In Android, how do I set margins in dp programmatically?

    layout_margin is a constraint that a view child tell to its parent. However it is the parent's role to choose whether to allow margin or not. Basically by setting android:layout_margin="10dp", the child is pleading the parent view group to allocate space that is 10dp bigger than its actual size. (padding="10dp", on the other hand, means the child view will make its own content 10dp smaller.)

    Consequently, not all ViewGroups respect margin. The most notorious example would be listview, where the margins of items are ignored. Before you call setMargin() to a LayoutParam, you should always make sure that the current view is living in a ViewGroup that supports margin (e.g. LinearLayouot or RelativeLayout), and cast the result of getLayoutParams() to the specific LayoutParams you want. (ViewGroup.LayoutParams does not even have setMargins() method!)

    The function below should do the trick. However make sure you substitute RelativeLayout to the type of the parent view.

    private void setMargin(int marginInPx) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) getLayoutParams();
        lp.setMargins(marginInPx,marginInPx, marginInPx, marginInPx);
        setLayoutParams(lp);
    }
    

    "Debug certificate expired" error in Eclipse Android plugins

    In Windows 7 it is at the path

    C:\Users\[username]\.android
    
    • goto this path and remove debug.keystore
    • clean and build your project.

    How to move certain commits to be based on another branch in git?

    The simplest thing you can do is cherry picking a range. It does the same as the rebase --onto but is easier for the eyes :)

    git cherry-pick quickfix1..quickfix2
    

    How to handle authentication popup with Selenium WebDriver using Java

    This should work for Firefox by using AutoAuth plugin:

    FirefoxProfile firefoxProfile = new ProfilesIni().getProfile("default");
    File ffPluginAutoAuth = new File("D:\\autoauth-2.1-fx+fn.xpi");
    firefoxProfile.addExtension(ffPluginAutoAuth);
    driver = new FirefoxDriver(firefoxProfile);
    

    Call a function on click event in Angular 2

    Exact transfer to Angular2+ is as below:

    <button (click)="myFunc()"></button>
    

    also in your component file:

    import { Component, OnInit } from "@angular/core";
    
    @Component({
      templateUrl:"button.html" //this is the component which has the above button html
    })
    
    export class App implements OnInit{
      constructor(){}
    
      ngOnInit(){
    
      }
    
      myFunc(){
        console.log("function called");
      }
    }
    

    Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

    I agree with BMSAndroidDroid and Flo-Scheild-Bobby. I was doing a tutorial called DailyQuote and had used the Cordova library. I then changed my OS from Windows to Ubuntu and tried to import projects into Eclipse, (I'm using Eclipse Juno 64-bit, on Ubuntu 12.04 64-bit, Oracle JDK 7. I also installed the Ubuntu 32-bit libs- so no issues with 64 and 32bit), and got the same issue.

    As suggested by Flo-Scheild-Bobby, open configure build path and add the jar(s) again that you added before. Then remove the old jar link(s) and thats it.

    How to Sign an Already Compiled Apk

    fastest way is by signing with the debug keystore:

    jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ~/.android/debug.keystore app.apk androiddebugkey -storepass android
    

    or on Windows:

    jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore %USERPROFILE%/.android/debug.keystore test.apk androiddebugkey -storepass android
    

    Remove row lines in twitter bootstrap

    In Bootstrap 3 I've added a table-no-border class

    .table-no-border>thead>tr>th, 
    .table-no-border>tbody>tr>th, 
    .table-no-border>tfoot>tr>th, 
    .table-no-border>thead>tr>td, 
    .table-no-border>tbody>tr>td, 
    .table-no-border>tfoot>tr>td {
      border-top: none; 
    }
    

    How to get the separate digits of an int number?

    Integer.toString(1100) gives you the integer as a string. Integer.toString(1100).getBytes() to get an array of bytes of the individual digits.

    Edit:

    You can convert the character digits into numeric digits, thus:

      String string = Integer.toString(1234);
      int[] digits = new int[string.length()];
    
      for(int i = 0; i<string.length(); ++i){
        digits[i] = Integer.parseInt(string.substring(i, i+1));
      }
      System.out.println("digits:" + Arrays.toString(digits));
    

    How to get a user's client IP address in ASP.NET?

    As others have said you can't do what you are asking. If you describe the problem you are trying to solve maybe someone can help?

    E.g.

    • are you trying to uniquely identify your users?
    • Could you use a cookie, or the session ID perhaps instead of the IP address?

    Edit The address you see on the server shouldn't be the ISP's address, as you say that would be a huge range. The address for a home user on broadband will be the address at their router, so every device inside the house will appear on the outside to be the same, but the router uses NAT to ensure that traffic is routed to each device correctly. For users accessing from an office environment the address may well be the same for all users. Sites that use IP address for ID run the risk of getting it very wrong - the examples you give are good ones and they often fail. For example my office is in the UK, the breakout point (where I "appear" to be on the internet) is in another country where our main IT facility is, so from my office my IP address appears to be not in the UK. For this reason I can't access UK only web content, such as the BBC iPlayer). At any given time there would be hundreds, or even thousands, of people at my company who appear to be accessing the web from the same IP address.

    When you are writing server code you can never be sure what the IP address you see is referring to. Some users like it this way. Some people deliberately use a proxy or VPN to further confound you.

    When you say your machine address is different to the IP address shown on StackOverflow, how are you finding out your machine address? If you are just looking locally using ipconfig or something like that I would expect it to be different for the reasons I outlined above. If you want to double check what the outside world thinks have a look at whatismyipaddress.com/.

    This Wikipedia link on NAT will provide you some background on this.

    Storing image in database directly or as base64 data?

    I recommend looking at modern databases like NoSQL and also I agree with user1252434's post. For instance I am storing a few < 500kb PNGs as base64 on my Mongo db with binary set to true with no performance hit at all. Mongo can be used to store large files like 10MB videos and that can offer huge time saving advantages in metadata searches for those videos, see storing large objects and files in mongodb.

    How do I copy a range of formula values and paste them to a specific range in another sheet?

    How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

    Which concurrent Queue implementation should I use in Java?

    Your question title mentions Blocking Queues. However, ConcurrentLinkedQueue is not a blocking queue.

    The BlockingQueues are ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, and SynchronousQueue.

    Some of these are clearly not fit for your purpose (DelayQueue, PriorityBlockingQueue, and SynchronousQueue). LinkedBlockingQueue and LinkedBlockingDeque are identical, except that the latter is a double-ended Queue (it implements the Deque interface).

    Since ArrayBlockingQueue is only useful if you want to limit the number of elements, I'd stick to LinkedBlockingQueue.

    Password encryption at client side

    You've tagged this question with the tag, and SSL is the answer. Curious.

    Bootstrap navbar Active State not working

    As someone who doesn't know javascript, here's a PHP method that works for me and is easy to understand. My whole navbar is in a PHP function that is in a file of common components I include from my pages. So for example in my 'index.php' page I have... `

    <?php
       $calling_file = basename(__FILE__);
       include 'my_common_includes.php';    // Going to use my navbar function "my_navbar"
       my_navbar($calling_file);    // Call the navbar function
     ?>
    

    Then in the 'my_common_includes.php' I have...

    <?php
       function my_navbar($calling_file)
       {
          // All your usual nabvbar code here up to the menu items
          if ($calling_file=="index.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
        echo '<a class="nav-link" href="index.php">Home</a>
    </li>';
          if ($calling_file=="about.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
        echo '<a class="nav-link" href="about.php">About</a>
    </li>';
          if ($calling_file=="galleries.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
        echo '<a class="nav-link" href="galleries.php">Galleries</a>
    </li>';
           // etc for the rest of the menu items and closing out the navbar
         }
      ?>
    

    Regex: Specify "space or start of string" and "space or end of string"

    \b matches at word boundaries (without actually matching any characters), so the following should do what you want:

    \bstackoverflow\b
    

    How do I force a vertical scrollbar to appear?

    Give your body tag an overflow: scroll;

    body {
        overflow: scroll;
    }
    

    or if you only want a vertical scrollbar use overflow-y

    body {
        overflow-y: scroll;
    }
    

    MongoDB: How to find out if an array field contains an element?

    I am trying to explain by putting problem statement and solution to it. I hope it will help

    Problem Statement:

    Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-

    Solution:

    Below are the conditions that need to be taken care of

    1. Product price should be less than 15
    2. Product name should be either ABC Product or PQR Product
    3. Product should be in published state.

    Below is the statement that applies above criterion to create query and fetch data.

    $elements = $collection->find(
                 Array(
                    [price] => Array( [$lt] => 15 ),
                    [$or] => Array(
                                [0]=>Array(
                                        [product_name]=>Array(
                                           [$in]=>Array(
                                                [0] => ABC Product,
                                                [1]=> PQR Product
                                                )
                                            )
                                        )
                                    ),
                    [state]=>Published
                    )
                );
    

    Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

    In case you can't upgrade to Ruby on Rails 2.3.11 (and to expand on douglasr's answer), thread must be required at the top of boot.rb. For example:

    require 'thread'
    
    # Don't change this file!
    # Configure your app in config/environment.rb and config/environments/*.rb
    ...
    

    Difference between "this" and"super" keywords in Java

    this is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example.

    super allows access to non-private methods and fields in the super-class, and to access constructors from within the class' constructors only.

    How to use Javascript to read local text file and read line by line?

    Without jQuery:

    document.getElementById('file').onchange = function(){
    
      var file = this.files[0];
    
      var reader = new FileReader();
      reader.onload = function(progressEvent){
        // Entire file
        console.log(this.result);
    
        // By lines
        var lines = this.result.split('\n');
        for(var line = 0; line < lines.length; line++){
          console.log(lines[line]);
        }
      };
      reader.readAsText(file);
    };
    

    HTML:

    <input type="file" name="file" id="file">
    

    Remember to put your javascript code after the file field is rendered.

    Dynamically Dimensioning A VBA Array?

    You can also look into using the Collection Object. This usually works better than an array for custom objects, since it dynamically sizes and has methods for:

    • Add
    • Count
    • Remove
    • Item(index)

    Plus its normally easier to loop through a collection too since you can use the for...each structure very easily with a collection.

    Converting a pointer into an integer

    'size_t' and 'ptrdiff_t' are required to match your architecture (whatever it is). Therefore, I think rather than using 'int', you should be able to use 'size_t', which on a 64 bit system should be a 64 bit type.

    This discussion unsigned int vs size_t goes into a bit more detail.

    Testing whether a value is odd or even

    if (i % 2) {
    return odd numbers
    }
    
    if (i % 2 - 1) {
    return even numbers
    }
    

    How to return part of string before a certain character?

    Another method could be to split the string by ":" and then pop off the end. var newString = string.split(":").pop();

    What is the difference between explicit and implicit cursors in Oracle?

    In answer to the first question. Straight from the Oracle documentation

    A cursor is a pointer to a private SQL area that stores information about processing a specific SELECT or DML statement.

    How to develop Android app completely using python?

    There are two primary contenders for python apps on Android

    Chaquopy

    https://chaquo.com/chaquopy/

    This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."

    Beeware (Toga widget toolkit)

    https://pybee.org/

    This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.

    Which One?

    Both are active projects and their github accounts shows a fair amount of recent activity.

    Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.

    On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.

    Programmatically add new column to DataGridView

    Here's a sample method that adds two extra columns programmatically to the grid view:

        private void AddColumnsProgrammatically()
        {
            // I created these columns at function scope but if you want to access 
            // easily from other parts of your class, just move them to class scope.
            // E.g. Declare them outside of the function...
            var col3 = new DataGridViewTextBoxColumn();
            var col4 = new DataGridViewCheckBoxColumn();
    
            col3.HeaderText = "Column3";
            col3.Name = "Column3";
    
            col4.HeaderText = "Column4";
            col4.Name = "Column4";
    
            dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
        }
    

    A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)

    For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:

    // Note that this info scattered throughout the designer but can easily collected.
    
            System.Windows.Forms.DataGridViewTextBoxColumn Column1;
            System.Windows.Forms.DataGridViewCheckBoxColumn Column2;
    
            this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
    
            this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.Column1,
            this.Column2});
    
            this.Column1.HeaderText = "Column1";
            this.Column1.Name = "Column1";
    
            this.Column2.HeaderText = "Column2";
            this.Column2.Name = "Column2";
    

    Axios handling errors

    I tried using the try{}catch{} method but it did not work for me. However, when I switched to using .then(...).catch(...), the AxiosError is caught correctly that I can play around with. When I try the former when putting a breakpoint, it does not allow me to see the AxiosError and instead, says to me that the caught error is undefined, which is also what eventually gets displayed in the UI.

    Not sure why this happens I find it very trivial. Either way due to this, I suggest using the conventional .then(...).catch(...) method mentioned above to avoid throwing undefined errors to the user.

    php execute a background process

    I'd just like to add a very simple example for testing this functionality on Windows:

    Create the following two files and save them to a web directory:

    foreground.php:

    <?php
    
    ini_set("display_errors",1);
    error_reporting(E_ALL);
    
    echo "<pre>loading page</pre>";
    
    function run_background_process()
    {
        file_put_contents("testprocesses.php","foreground start time = " . time() . "\n");
        echo "<pre>  foreground start time = " . time() . "</pre>";
    
        // output from the command must be redirected to a file or another output stream 
        // http://ca.php.net/manual/en/function.exec.php
    
        exec("php background.php > testoutput.php 2>&1 & echo $!", $output);
    
        echo "<pre>  foreground end time = " . time() . "</pre>";
        file_put_contents("testprocesses.php","foreground end time = " . time() . "\n", FILE_APPEND);
        return $output;
    }
    
    echo "<pre>calling run_background_process</pre>";
    
    $output = run_background_process();
    
    echo "<pre>output = "; print_r($output); echo "</pre>";
    echo "<pre>end of page</pre>";
    ?>
    

    background.php:

    <?
    file_put_contents("testprocesses.php","background start time = " . time() . "\n", FILE_APPEND);
    sleep(10);
    file_put_contents("testprocesses.php","background end time = " . time() . "\n", FILE_APPEND);
    ?>
    

    Give IUSR permission to write to the directory in which you created the above files

    Give IUSR permission to READ and EXECUTE C:\Windows\System32\cmd.exe

    Hit foreground.php from a web browser

    The following should be rendered to the browser w/the current timestamps and local resource # in the output array:

    loading page
    calling run_background_process
      foreground start time = 1266003600
      foreground end time = 1266003600
    output = Array
    (
        [0] => 15010
    )
    end of page
    

    You should see testoutput.php in the same directory as the above files were saved, and it should be empty

    You should see testprocesses.php in the same directory as the above files were saved, and it should contain the following text w/the current timestamps:

    foreground start time = 1266003600
    foreground end time = 1266003600
    background start time = 1266003600
    background end time = 1266003610
    

    Extracting a parameter from a URL in WordPress

    In the call back function, use the $request parameter

    $parameters = $request->get_params();
    echo $parameters['ppc'];
    

    How to parse the AndroidManifest.xml file inside an .apk package

    apkanalyzer will be helpful

    @echo off
    
    ::##############################################################################
    ::##
    ::##  apkanalyzer start up script for Windows
    ::##
    ::##  converted by ewwink
    ::##
    ::##############################################################################
    
    ::Attempt to set APP_HOME
    
    SET SAVED=%cd%
    SET APP_HOME=C:\android\sdk\tools
    SET APP_NAME="apkanalyzer"
    
    ::Add default JVM options here. You can also use JAVA_OPTS and APKANALYZER_OPTS to pass JVM options to this script.
    SET DEFAULT_JVM_OPTS=-Dcom.android.sdklib.toolsdir=%APP_HOME%
    
    SET CLASSPATH=%APP_HOME%\lib\dvlib-26.0.0-dev.jar;%APP_HOME%\lib\util-2.2.1.jar;%APP_HOME%\lib\jimfs-1.1.jar;%APP_HOME%\lib\annotations-13.0.jar;%APP_HOME%\lib\ddmlib-26.0.0-dev.jar;%APP_HOME%\lib\repository-26.0.0-dev.jar;%APP_HOME%\lib\sdk-common-26.0.0-dev.jar;%APP_HOME%\lib\kotlin-stdlib-1.1.3-2.jar;%APP_HOME%\lib\protobuf-java-3.0.0.jar;%APP_HOME%\lib\apkanalyzer-cli.jar;%APP_HOME%\lib\gson-2.3.jar;%APP_HOME%\lib\httpcore-4.2.5.jar;%APP_HOME%\lib\dexlib2-2.2.1.jar;%APP_HOME%\lib\commons-compress-1.12.jar;%APP_HOME%\lib\generator.jar;%APP_HOME%\lib\error_prone_annotations-2.0.18.jar;%APP_HOME%\lib\commons-codec-1.6.jar;%APP_HOME%\lib\kxml2-2.3.0.jar;%APP_HOME%\lib\httpmime-4.1.jar;%APP_HOME%\lib\annotations-12.0.jar;%APP_HOME%\lib\bcpkix-jdk15on-1.56.jar;%APP_HOME%\lib\jsr305-3.0.0.jar;%APP_HOME%\lib\explainer.jar;%APP_HOME%\lib\builder-model-3.0.0-dev.jar;%APP_HOME%\lib\baksmali-2.2.1.jar;%APP_HOME%\lib\j2objc-annotations-1.1.jar;%APP_HOME%\lib\layoutlib-api-26.0.0-dev.jar;%APP_HOME%\lib\jcommander-1.64.jar;%APP_HOME%\lib\commons-logging-1.1.1.jar;%APP_HOME%\lib\annotations-26.0.0-dev.jar;%APP_HOME%\lib\builder-test-api-3.0.0-dev.jar;%APP_HOME%\lib\animal-sniffer-annotations-1.14.jar;%APP_HOME%\lib\bcprov-jdk15on-1.56.jar;%APP_HOME%\lib\httpclient-4.2.6.jar;%APP_HOME%\lib\common-26.0.0-dev.jar;%APP_HOME%\lib\jopt-simple-4.9.jar;%APP_HOME%\lib\sdklib-26.0.0-dev.jar;%APP_HOME%\lib\apkanalyzer.jar;%APP_HOME%\lib\shared.jar;%APP_HOME%\lib\binary-resources.jar;%APP_HOME%\lib\guava-22.0.jar
    
    SET APP_ARGS=%*
    ::Collect all arguments for the java command, following the shell quoting and substitution rules
    SET APKANALYZER_OPTS=%DEFAULT_JVM_OPTS% -classpath %CLASSPATH% com.android.tools.apk.analyzer.ApkAnalyzerCli %APP_ARGS%
    
    ::Determine the Java command to use to start the JVM.
    SET JAVACMD="java"
    where %JAVACMD% >nul 2>nul
    if %errorlevel%==1 (
      echo ERROR: 'java' command could be found in your PATH.
      echo Please set the 'java' variable in your environment to match the
      echo location of your Java installation.
      echo.
      exit /b 0
    )
    
    :: execute apkanalyzer
    
    %JAVACMD% %APKANALYZER_OPTS%
    

    original post https://stackoverflow.com/a/51905063/1383521

    Java Class.cast() vs. cast operator

    Class.cast() is rarely ever used in Java code. If it is used then usually with types that are only known at runtime (i.e. via their respective Class objects and by some type parameter). It is only really useful in code that uses generics (that's also the reason it wasn't introduced earlier).

    It is not similar to reinterpret_cast, because it will not allow you to break the type system at runtime any more than a normal cast does (i.e. you can break generic type parameters, but can't break "real" types).

    The evils of the C-style cast operator generally don't apply to Java. The Java code that looks like a C-style cast is most similar to a dynamic_cast<>() with a reference type in Java (remember: Java has runtime type information).

    Generally comparing the C++ casting operators with Java casting is pretty hard since in Java you can only ever cast reference and no conversion ever happens to objects (only primitive values can be converted using this syntax).

    Download and install an ipa from self hosted url on iOS

    Answer for Enterprise account with Xcode8

    1. Export the .ipa by checking the "with manifest plist checkbox" and provide the links requested.

    2. Upload the .ipa file and .plist file to the same location of the server (which you provided when exporting .ipa/ which mentioned in the .plist file).

    3. Create the Download Link as given below. url should link to your .plist file location.

      itms-services://?action=download-manifest&url=https://yourdomainname.com/app.plist

    4. Copy this link and paste it in safari browser in your iphone. It will ask to install :D

    Create a html button using this full url

    append option to select menu?

    You can also use insertAdjacentHTML function:

    const select = document.querySelector('select')
    const value = 'bmw'
    const label = 'BMW'
    
    select.insertAdjacentHTML('beforeend', `
      <option value="${value}">${label}</option>
    `)
    

    Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

    Make sure you have all dependencies solved

    I run into this problem in my first attempt at AOP, following a spring tutorial. My problem was not having spring-aop.jar in my classpath. The tutorial listed all other dependencies I had to add, namely:

    • aspectjrt.jar
    • aspectjweaver.jar
    • aspectj.jar
    • aopalliance.jar

    But the one was missing. Just one more problem that can contribute to that symptom in the original question.

    I am using Eclipse (neon), Java SE 8, beans 3.0, spring AOP 3.0, Spring 4.3.4. The problem showed in the Java view --not JEE--, and while trying to just run the application with Right button menu -> Run As -> Java Application.

    Oracle copy data to another table

    insert into EXCEPTION_CODES (CODE, MESSAGE)
    select CODE, MESSAGE from Exception_code_tmp
    

    How do I check out a specific version of a submodule using 'git submodule'?

    Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.

    $ cd submodule
    $ git checkout v2.0
    Previous HEAD position was 5c1277e... bumped version to 2.0.5
    HEAD is now at f0a0036... version 2.0
    

    git-status on the parent repository will now report a dirty tree:

    # On branch dev [...]
    #
    #   modified:   submodule (new commits)
    

    Add the submodule directory and commit to store the new pointer.

    Key value pairs using JSON

    JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.

    Since Javascripts objects consists of key/value pairs its very easy to use and access JSON that way.

    So if we have an object:

    var myObj = {
        foo:   'bar',
        base:  'ball',
        deep:  {
           java:  'script'
        }
    };
    

    We can convert that into a string by calling window.JSON.stringify(myObj); with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}".

    The other way around, we would call window.JSON.parse("a json string like the above");.

    JSON.parse() returns a javascript object/array on success.

    alert(myObj.deep.java);  // 'script'
    

    window.JSON is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.

    Undoing accidental git stash pop

    If your merge was not too complicated another option would be to:

    1. Move all the changes including the merge changes back to stash using "git stash"
    2. Run the merge again and commit your changes (without the changes from the dropped stash)
    3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

    After that you are left with only the changes from the stash you dropped too early.

    What is the difference between ELF files and bin files?

    A Bin file is a pure binary file with no memory fix-ups or relocations, more than likely it has explicit instructions to be loaded at a specific memory address. Whereas....

    ELF files are Executable Linkable Format which consists of a symbol look-ups and relocatable table, that is, it can be loaded at any memory address by the kernel and automatically, all symbols used, are adjusted to the offset from that memory address where it was loaded into. Usually ELF files have a number of sections, such as 'data', 'text', 'bss', to name but a few...it is within those sections where the run-time can calculate where to adjust the symbol's memory references dynamically at run-time.

    Can Json.NET serialize / deserialize to / from a stream?

    I arrived at this question looking for a way to stream an open ended list of objects onto a System.IO.Stream and read them off the other end, without buffering the entire list before sending. (Specifically I'm streaming persisted objects from MongoDB over Web API.)

    @Paul Tyng and @Rivers did an excellent job answering the original question, and I used their answers to build a proof of concept for my problem. I decided to post my test console app here in case anyone else is facing the same issue.

    using System;
    using System.Diagnostics;
    using System.IO;
    using System.IO.Pipes;
    using System.Threading;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    
    namespace TestJsonStream {
        class Program {
            static void Main(string[] args) {
                using(var writeStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.None)) {
                    string pipeHandle = writeStream.GetClientHandleAsString();
                    var writeTask = Task.Run(() => {
                        using(var sw = new StreamWriter(writeStream))
                        using(var writer = new JsonTextWriter(sw)) {
                            var ser = new JsonSerializer();
                            writer.WriteStartArray();
                            for(int i = 0; i < 25; i++) {
                                ser.Serialize(writer, new DataItem { Item = i });
                                writer.Flush();
                                Thread.Sleep(500);
                            }
                            writer.WriteEnd();
                            writer.Flush();
                        }
                    });
                    var readTask = Task.Run(() => {
                        var sw = new Stopwatch();
                        sw.Start();
                        using(var readStream = new AnonymousPipeClientStream(pipeHandle))
                        using(var sr = new StreamReader(readStream))
                        using(var reader = new JsonTextReader(sr)) {
                            var ser = new JsonSerializer();
                            if(!reader.Read() || reader.TokenType != JsonToken.StartArray) {
                                throw new Exception("Expected start of array");
                            }
                            while(reader.Read()) {
                                if(reader.TokenType == JsonToken.EndArray) break;
                                var item = ser.Deserialize<DataItem>(reader);
                                Console.WriteLine("[{0}] Received item: {1}", sw.Elapsed, item);
                            }
                        }
                    });
                    Task.WaitAll(writeTask, readTask);
                    writeStream.DisposeLocalCopyOfClientHandle();
                }
            }
    
            class DataItem {
                public int Item { get; set; }
                public override string ToString() {
                    return string.Format("{{ Item = {0} }}", Item);
                }
            }
        }
    }
    

    Note that you may receive an exception when the AnonymousPipeServerStream is disposed, I ignored this as it isn't relevant to the problem at hand.

    C++ string to double conversion

    You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.

    With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)

    #include <stdlib.h>
    
    int main()
    {
        string word;  
        openfile >> word;
        double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
                                         previously (the function requires it)*/
        return 0;
    }
    

    What is the difference between i++ and ++i?

    Oddly it looks like the other two answers don't spell it out, and it's definitely worth saying:


    i++ means 'tell me the value of i, then increment'

    ++i means 'increment i, then tell me the value'


    They are Pre-increment, post-increment operators. In both cases the variable is incremented, but if you were to take the value of both expressions in exactly the same cases, the result will differ.

    PHP regular expression - filter number only

    This is the right answer

    preg_match("/^[0-9]+$/", $yourstr);
    

    This function return TRUE(1) if it matches or FALSE(0) if it doesn't

    Quick Explanation :

    '^' : means that it should begin with the following ( in our case is a range of digital numbers [0-9] ) ( to avoid cases like ("abdjdf125") )

    '+' : means there should be at least one digit

    '$' : means after our pattern the string should end ( to avoid cases like ("125abdjdf") )

    Assign multiple values to array in C

    You can use:

    GLfloat coordinates[8] = {1.0f, ..., 0.0f};
    

    but this is a compile-time initialisation - you can't use that method in the current standard to re-initialise (although I think there are ways to do it in the upcoming standard, which may not immediately help you).

    The other two ways that spring to mind are to blat the contents if they're fixed:

    GLfloat base_coordinates[8] = {1.0f, ..., 0.0f};
    GLfloat coordinates[8];
    :
    memcpy (coordinates, base_coordinates, sizeof (coordinates));
    

    or provide a function that looks like your initialisation code anyway:

    void setCoords (float *p0, float p1, ..., float p8) {
        p0[0] = p1; p0[1] = p2; p0[2] = p3; p0[3] = p4;
        p0[4] = p5; p0[5] = p6; p0[6] = p7; p0[7] = p8;
    }
    :
    setCoords (coordinates, 1.0f, ..., 0.0f);
    

    keeping in mind those ellipses (...) are placeholders, not things to literally insert in the code.

    How to read line by line or a whole text file at once?

    Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:

    #include<cstdio>
    #include<iostream>
    
    using namespace std;
    
    int main(){
       freopen("path to file", "rb", stdin);
       string line;
       while(getline(cin, line))
           cout << line << endl;
       return 0;
    }
    

    How to extract the year from a Python datetime object?

    It's in fact almost the same in Python.. :-)

    import datetime
    year = datetime.date.today().year
    

    Of course, date doesn't have a time associated, so if you care about that too, you can do the same with a complete datetime object:

    import datetime
    year = datetime.datetime.today().year
    

    (Obviously no different, but you can store datetime.datetime.today() in a variable before you grab the year, of course).

    One key thing to note is that the time components can differ between 32-bit and 64-bit pythons in some python versions (2.5.x tree I think). So you will find things like hour/min/sec on some 64-bit platforms, while you get hour/minute/second on 32-bit.

    How to get a parent element to appear above child

    Some of these answers do work, but setting position: absolute; and z-index: 10; seemed pretty strong just to achieve the required effect. I found the following was all that was required, though unfortunately, I've not been able to reduce it any further.

    HTML:

    <div class="wrapper">
        <div class="parent">
            <div class="child">
                ...
            </div>
        </div>
    </div>
    

    CSS:

    .wrapper {
        position: relative;
        z-index: 0;
    }
    
    .child {
        position: relative;
        z-index: -1;
    }
    

    I used this technique to achieve a bordered hover effect for image links. There's a bit more code here but it uses the concept above to show the border over the top of the image.

    http://jsfiddle.net/g7nP5/

    HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

    If you're still facing the issue even after replacing doGet() with doPost() and changing the form method="post". Try clearing the cache of the browser or hit the URL in another browser or incognito/private mode. It may works!

    For best practices, please follow this link. https://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html

    Pass form data to another page with php

    The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

    index.php

    <html>
    <body>
    
    <form action="site2.php" method="post">
    Name: <input type="text" name="name">
    Email: <input type="text" name="email">
    <input type="submit">
    </form>
    
    </body>
    </html> 
    

    site2.php

     <html>
     <body>
    
     Hello <?php echo $_POST["name"]; ?>!<br>
     Your mail is <?php echo $_POST["mail"]; ?>.
    
     </body>
     </html> 
    

    output

    Hello "name" !

    Your email is "[email protected]" .

    Can jQuery get all CSS styles associated with an element?

    I had tried many different solutions. This was the only one that worked for me in that it was able to pick up on styles applied at class level and at style as directly attributed on the element. So a font set at css file level and one as a style attribute; it returned the correct font.

    It is simple! (Sorry, can't find where I originally found it)

    //-- html object
    var element = htmlObject; //e.g document.getElementById
    //-- or jquery object
    var element = htmlObject[0]; //e.g $(selector)
    
    var stylearray = document.defaultView.getComputedStyle(element, null);
    var font = stylearray["font-family"]
    

    Alternatively you can list all the style by cycling through the array

    for (var key in stylearray) {
    console.log(key + ': ' + stylearray[key];
    }
    

    How to remove the last character from a string?

    u can do i hereString = hereString.replace(hereString.chatAt(hereString.length() - 1) ,' whitespeace');

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

    This does what you want, and will work in nearly all cases:

    >>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
    True
    

    The expression 'a','b' in ['b', 'a', 'foo', 'bar'] doesn't work as expected because Python interprets it as a tuple:

    >>> 'a', 'b'
    ('a', 'b')
    >>> 'a', 5 + 2
    ('a', 7)
    >>> 'a', 'x' in 'xerxes'
    ('a', True)
    

    Other Options

    There are other ways to execute this test, but they won't work for as many different kinds of inputs. As Kabie points out, you can solve this problem using sets...

    >>> set(['a', 'b']).issubset(set(['a', 'b', 'foo', 'bar']))
    True
    >>> {'a', 'b'} <= {'a', 'b', 'foo', 'bar'}
    True
    

    ...sometimes:

    >>> {'a', ['b']} <= {'a', ['b'], 'foo', 'bar'}
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    

    Sets can only be created with hashable elements. But the generator expression all(x in container for x in items) can handle almost any container type. The only requirement is that container be re-iterable (i.e. not a generator). items can be any iterable at all.

    >>> container = [['b'], 'a', 'foo', 'bar']
    >>> items = (i for i in ('a', ['b']))
    >>> all(x in [['b'], 'a', 'foo', 'bar'] for x in items)
    True
    

    Speed Tests

    In many cases, the subset test will be faster than all, but the difference isn't shocking -- except when the question is irrelevant because sets aren't an option. Converting lists to sets just for the purpose of a test like this won't always be worth the trouble. And converting generators to sets can sometimes be incredibly wasteful, slowing programs down by many orders of magnitude.

    Here are a few benchmarks for illustration. The biggest difference comes when both container and items are relatively small. In that case, the subset approach is about an order of magnitude faster:

    >>> smallset = set(range(10))
    >>> smallsubset = set(range(5))
    >>> %timeit smallset >= smallsubset
    110 ns ± 0.702 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
    >>> %timeit all(x in smallset for x in smallsubset)
    951 ns ± 11.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    

    This looks like a big difference. But as long as container is a set, all is still perfectly usable at vastly larger scales:

    >>> bigset = set(range(100000))
    >>> bigsubset = set(range(50000))
    >>> %timeit bigset >= bigsubset
    1.14 ms ± 13.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    >>> %timeit all(x in bigset for x in bigsubset)
    5.96 ms ± 37 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    Using subset testing is still faster, but only by about 5x at this scale. The speed boost is due to Python's fast c-backed implementation of set, but the fundamental algorithm is the same in both cases.

    If your items are already stored in a list for other reasons, then you'll have to convert them to a set before using the subset test approach. Then the speedup drops to about 2.5x:

    >>> %timeit bigset >= set(bigsubseq)
    2.1 ms ± 49.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    And if your container is a sequence, and needs to be converted first, then the speedup is even smaller:

    >>> %timeit set(bigseq) >= set(bigsubseq)
    4.36 ms ± 31.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    The only time we get disastrously slow results is when we leave container as a sequence:

    >>> %timeit all(x in bigseq for x in bigsubseq)
    184 ms ± 994 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
    

    And of course, we'll only do that if we must. If all the items in bigseq are hashable, then we'll do this instead:

    >>> %timeit bigset = set(bigseq); all(x in bigset for x in bigsubseq)
    7.24 ms ± 78 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    That's just 1.66x faster than the alternative (set(bigseq) >= set(bigsubseq), timed above at 4.36).

    So subset testing is generally faster, but not by an incredible margin. On the other hand, let's look at when all is faster. What if items is ten-million values long, and is likely to have values that aren't in container?

    >>> %timeit hugeiter = (x * 10 for bss in [bigsubseq] * 2000 for x in bss); set(bigset) >= set(hugeiter)
    13.1 s ± 167 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    >>> %timeit hugeiter = (x * 10 for bss in [bigsubseq] * 2000 for x in bss); all(x in bigset for x in hugeiter)
    2.33 ms ± 65.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    Converting the generator into a set turns out to be incredibly wasteful in this case. The set constructor has to consume the entire generator. But the short-circuiting behavior of all ensures that only a small portion of the generator needs to be consumed, so it's faster than a subset test by four orders of magnitude.

    This is an extreme example, admittedly. But as it shows, you can't assume that one approach or the other will be faster in all cases.

    The Upshot

    Most of the time, converting container to a set is worth it, at least if all its elements are hashable. That's because in for sets is O(1), while in for sequences is O(n).

    On the other hand, using subset testing is probably only worth it sometimes. Definitely do it if your test items are already stored in a set. Otherwise, all is only a little slower, and doesn't require any additional storage. It can also be used with large generators of items, and sometimes provides a massive speedup in that case.

    Android: Align button to bottom-right of screen using FrameLayout?

    Actually it's possible, despite what's being said in other answers. If you have a FrameLayout, and want to position a child item to the bottom, you can use android:layout_gravity="bottom" and that is going to align that child to the bottom of the FrameLayout.

    I know it works because I'm using it. I know is late, but it might come handy to others since this ranks in the top positions on google

    IIS sc-win32-status codes

    Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
    http://msdn.microsoft.com/en-us/library/ms681381.aspx

    You can also use command line utility net to find information about a Win32 error code. The syntax would be:
    net helpmsg Win32_Status_Code

    What does Ruby have that Python doesn't, and vice versa?

    Syntax is not a minor thing, it has a direct impact on how we think. It also has a direct effect on the rules we create for the systems we use. As an example we have the order of operations because of the way we write mathematical equations or sentences. The standard notation for mathematics allows people to read it more than one way and arrive at different answers given the same equation. If we had used prefix or postfix notation we would have created rules to distinguish what the numbers to be manipulated were rather than only having rules for the order in which to compute values.

    The standard notation makes it plain what numbers we are talking about while making the order in which to compute them ambiguous. Prefix and postfix notation make the order in which to compute plain while making the numbers ambiguous. Python would already have multiline lambdas if it were not for the difficulties caused by the syntactic whitespace. (Proposals do exist for pulling this kind of thing off without necessarily adding explicit block delimiters.)

    I find it easier to write conditions where I want something to occur if a condition is false much easier to write with the unless statement in Ruby than the semantically equivalent "if-not" construction in Ruby or other languages for example. If most of the languages that people are using today are equal in power, how can the syntax of each language be considered a trivial thing? After specific features like blocks and inheritance mechanisms etc. syntax is the most important part of a language,hardly a superficial thing.

    What is superficial are the aesthetic qualities of beauty that we ascribe to syntax. Aesthetics have nothing to do with how our cognition works, syntax does.

    How to run .APK file on emulator

    You need to install the APK on the emulator. You can do this with the adb command line tool that is included in the Android SDK.

    adb -e install -r yourapp.apk
    

    Once you've done that you should be able to run the app.

    The -e and -r flags might not be necessary. They just specify that you are using an emulator (if you also have a device connected) and that you want to replace the app if it already exists.

    Align items in a stack panel?

    Maybe not what you want if you need to avoid hard-coding size values, but sometimes I use a "shim" (Separator) for this:

    <Separator Width="42"></Separator>
    

    XSLT getting last element

    You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

    (//element[@name='D'])[last()]
    

    Get average color of image via Javascript

    Javascript does not have access to an image's individual pixel color data. At least, not maybe until html5 ... at which point it stands to reason that you'll be able to draw an image to a canvas, and then inspect the canvas (maybe, I've never done it myself).

    How to execute a query in ms-access in VBA code?

    Take a look at this tutorial for how to use SQL inside VBA:

    http://www.ehow.com/how_7148832_access-vba-query-results.html

    For a query that won't return results, use (reference here):

    DoCmd.RunSQL
    

    For one that will, use (reference here):

    Dim dBase As Database
    dBase.OpenRecordset
    

    How to use makefiles in Visual Studio?

    I actually use a makefile to build any dependencies needed before invoking devenv to build a particular project as in the following:

    debug: coratools_debug
        devenv coralib.vcproj /build debug
    
    coratools_debug: nothing
        cd ../coratools
        nmake debug
        cd $(MAKEDIR)
    

    You can also use the msbuild tool to do the same thing:

    debug: coratools_debug
        msbuild coralib.vcxproj /p:Configuration=debug
    
    coratools_debug: nothing
        cd ../coratools
        nmake debug
        cd $(MAKEDIR)
    

    In my opinion, this is much easier than trying to figure out the overly complicated visual studio project management scheme.

    HTTP Get with 204 No Content: Is that normal

    204 No Content

    The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

    According to the RFC part for the status code 204, it seems to me a valid choice for a GET request.

    A 404 Not Found, 200 OK with empty body and 204 No Content have completely different meaning, sometimes we can't use proper status code but bend the rules and they will come back to bite you one day or later. So, if you can use proper status code, use it!

    I think the choice of GET or POST is very personal as both of them will do the work but I would recommend you to keep a POST instead of a GET, for two reasons:

    • You want the other part (the servlet if I understand correctly) to perform an action not retrieve some data from it.
    • By default GET requests are cacheable if there are no parameters present in the URL, a POST is not.

    Python3 project remove __pycache__ folders and .pyc files

    macOS & Linux

    BSD's find implementation on macOS is different from GNU find - this is compatible with both BSD and GNU find. Start with a globbing implementation, using -name and the -o for or - Put this function in your .bashrc file:

    pyclean () {
        find . -type f -name '*.py[co]' -delete -o -type d -name __pycache__ -delete
    }
    

    Then cd to the directory you want to recursively clean, and type pyclean.

    GNU find-only

    This is a GNU find, only (i.e. Linux) solution, but I feel it's a little nicer with the regex:

    pyclean () {
        find . -regex '^.*\(__pycache__\|\.py[co]\)$' -delete
    }
    

    Any platform, using Python 3

    On Windows, you probably don't even have find. You do, however, probably have Python 3, which starting in 3.4 has the convenient pathlib module:

    python3 -Bc "import pathlib; [p.unlink() for p in pathlib.Path('.').rglob('*.py[co]')]"
    python3 -Bc "import pathlib; [p.rmdir() for p in pathlib.Path('.').rglob('__pycache__')]"
    

    The -B flag tells Python not to write .pyc files. (See also the PYTHONDONTWRITEBYTECODE environment variable.)

    The above abuses list comprehensions for looping, but when using python -c, style is rather a secondary concern. Alternatively we could abuse (for example) __import__:

    python3 -Bc "for p in __import__('pathlib').Path('.').rglob('*.py[co]'): p.unlink()"
    python3 -Bc "for p in __import__('pathlib').Path('.').rglob('__pycache__'): p.rmdir()"
    

    Critique of an answer

    The top answer used to say:

    find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf
    

    This would seem to be less efficient because it uses three processes. find takes a regular expression, so we don't need a separate invocation of grep. Similarly, it has -delete, so we don't need a separate invocation of rm —and contrary to a comment here, it will delete non-empty directories so long as they get emptied by virtue of the regular expression match.

    From the xargs man page:

    find /tmp -depth -name core -type f -delete
    

    Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process).

    Missing visible-** and hidden-** in Bootstrap v4

    Bootstrap 4 to hide whole content use this class '.d-none' it will be hide everything regardless of breakpoints same like previous bootstrap version class '.hidden'

    symfony 2 No route found for "GET /"

    I have also tried that error , I got it right by just adding /hello/any name because it is path that there must be an hello/name

    example : instead of just putting http://localhost/app_dev.php

    put it like this way http://localhost/name_of_your_project/web/app_dev.php/hello/ai

    it will display Hello Ai . I hope I answer your question.

    Spring Boot Adding Http Request Interceptors

    I had the same issue of WebMvcConfigurerAdapter being deprecated. When I searched for examples, I hardly found any implemented code. Here is a piece of working code.

    create a class that extends HandlerInterceptorAdapter

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    import me.rajnarayanan.datatest.DataTestApplication;
    @Component
    public class EmployeeInterceptor extends HandlerInterceptorAdapter {
        private static final Logger logger = LoggerFactory.getLogger(DataTestApplication.class);
        @Override
        public boolean preHandle(HttpServletRequest request, 
                HttpServletResponse response, Object handler) throws Exception {
    
                String x = request.getMethod();
                logger.info(x + "intercepted");
            return true;
        }
    
    }
    

    then Implement WebMvcConfigurer interface

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    import me.rajnarayanan.datatest.interceptor.EmployeeInterceptor;
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
        @Autowired
        EmployeeInterceptor employeeInterceptor ;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry){
            registry.addInterceptor(employeeInterceptor).addPathPatterns("/employee");
        }
    }
    

    Why do we need middleware for async flow in Redux?

    There are synchronous action creators and then there are asynchronous action creators.

    A synchronous action creator is one that when we call it, it immediately returns an Action object with all the relevant data attached to that object and its ready to be processed by our reducers.

    Asynchronous action creators is one in which it will require a little bit of time before it is ready to eventually dispatch an action.

    By definition, anytime you have an action creator that makes a network request, it is always going to qualify as an async action creator.

    If you want to have asynchronous action creators inside of a Redux application you have to install something called a middleware that is going to allow you to deal with those asynchronous action creators.

    You can verify this in the error message that tells us use custom middleware for async actions.

    So what is a middleware and why do we need it for async flow in Redux?

    In the context of redux middleware such as redux-thunk, a middleware helps us deal with asynchronous action creators as that is something that Redux cannot handle out of the box.

    With a middleware integrated into the Redux cycle, we are still calling action creators, that is going to return an action that will be dispatched but now when we dispatch an action, rather than sending it directly off to all of our reducers, we are going to say that an action will be sent through all the different middleware inside the application.

    Inside of a single Redux app, we can have as many or as few middleware as we want. For the most part, in the projects we work on we will have one or two middleware hooked up to our Redux store.

    A middleware is a plain JavaScript function that will be called with every single action that we dispatch. Inside of that function a middleware has the opportunity to stop an action from being dispatched to any of the reducers, it can modify an action or just mess around with an action in any way you which for example, we could create a middleware that console logs every action you dispatch just for your viewing pleasure.

    There are a tremendous number of open source middleware you can install as dependencies into your project.

    You are not limited to only making use of open source middleware or installing them as dependencies. You can write your own custom middleware and use it inside of your Redux store.

    One of the more popular uses of middleware (and getting to your answer) is for dealing with asynchronous action creators, probably the most popular middleware out there is redux-thunk and it is about helping you deal with asynchronous action creators.

    There are many other types of middleware that also help you in dealing with asynchronous action creators.

    Unable to use Intellij with a generated sources folder

    i ran mvn generate-resources and then marked the /target/generated-resources folder as "sources" (Project Structure -> Project Settings -> Modules -> Select /target/generated-resources -> Click on blue "Sources" icon.

    jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

    Check this find code for Database use:

    function numonly(root){
        >>var reet = root.value;
        var arr1 = reet.length;
        var ruut = reet.charAt(arr1-1);
        >>>if (reet.length > 0){
            var regex = /[0-9]|\./;
            if (!ruut.match(regex)){
                var reet = reet.slice(0, -1);
                $(root).val(reet);
            >>>>}
        }
    }
    //Then use the even handler onkeyup='numonly(this)'
    

    PHP convert date format dd/mm/yyyy => yyyy-mm-dd

    Try Using DateTime::createFromFormat

    $date = DateTime::createFromFormat('d/m/Y', "24/04/2012");
    echo $date->format('Y-m-d');
    

    Output

    2012-04-24
    

    EDIT:

    If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.

    $old_date = explode('/', '5/4/2010'); 
    $new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];
    

    OUTPUT:

    2010-4-5
    

    How do you tell if a string contains another string in POSIX sh?

    Here is a link to various solutions of your issue.

    This is my favorite as it makes the most human readable sense:

    The Star Wildcard Method

    if [[ "$string" == *"$substring"* ]]; then
        return 1
    fi
    return 0
    

    Bootstrap 3 dropdown select

    I found a better library which transform the normal <select> <option> to bootsrap button dropdown format.

    https://developer.snapappointments.com/bootstrap-select/

    Make first letter of a string upper case (with maximum performance)

    Since I happened to be working on this also, and was looking around for any ideas, this is the solution I came to. It uses LINQ, and will be able to capitalize the first letter of a string, even if the first occurrence isn't a letter. Here's the extension method I ended up making.

    public static string CaptalizeFirstLetter(this string data)
    {
        var chars = data.ToCharArray();
    
        // Find the Index of the first letter
        var charac = data.First(char.IsLetter);
        var i = data.IndexOf(charac);
    
        // capitalize that letter
        chars[i] = char.ToUpper(chars[i]);
    
        return new string(chars);
    }
    

    I'm sure there's a way to optimize or clean this up a little bit.

    Angular 4/5/6 Global Variables

    You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.

    How to check if a string array contains one string in JavaScript?

    Create this function prototype:

    Array.prototype.contains = function ( needle ) {
       for (i in this) {
          if (this[i] == needle) return true;
       }
       return false;
    }
    

    and then you can use following code to search in array x

    if (x.contains('searchedString')) {
        // do a
    }
    else
    {
          // do b
    }
    

    What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

    In short,

    Struts is for Front-end development of website

    Hibernate is for back-end development of website

    Spring is for full stack development of website in which Spring MVC(Model-View-Controller) is for Front-end. ORM, JDBC for Data Access / Integration(backend). etc

    Pass value to iframe from a window

    Here's another solution, usable if the frames are from different domains.

    var frame = /*the iframe DOM object*/;
    frame.contentWindow.postMessage({call:'sendValue', value: /*value*/}, /*frame domain url or '*'*/);
    

    And in the frame itself:

    window.addEventListener('message', function(event) {
        var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
        if (origin !== /*the container's domain url*/)
            return;
        if (typeof event.data == 'object' && event.data.call=='sendValue') {
            // Do something with event.data.value;
        }
    }, false);
    

    Don't know which browsers support this, though.

    Create a List that contain each Line of a File

    I am not sure about Python but most languages have push/append function for arrays.

    How do I check form validity with angularjs?

    You can also use myform.$invalid

    E.g.

    if($scope.myform.$invalid){return;}
    

    How to install .MSI using PowerShell

    In powershell 5.1 you can actually use install-package, but it can't take extra msi arguments.

    install-package .\file.msi
    

    Otherwise with start-process and waiting:

    start -wait file.msi ALLUSERS=1,INSTALLDIR=C:\FILE
    

    Adding an arbitrary line to a matplotlib plot in ipython notebook

    You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments):

    plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)

    (of course you can choose the color, line width, line style, etc.)

    From your example:

    import numpy as np
    import matplotlib.pyplot as plt
    
    np.random.seed(5)
    x = np.arange(1, 101)
    y = 20 + 3 * x + np.random.normal(0, 60, 100)
    plt.plot(x, y, "o")
    
    
    # draw vertical line from (70,100) to (70, 250)
    plt.plot([70, 70], [100, 250], 'k-', lw=2)
    
    # draw diagonal line from (70, 90) to (90, 200)
    plt.plot([70, 90], [90, 200], 'k-')
    
    plt.show()
    

    new chart

    How to iterate through a String

    Java Strings aren't character Iterable. You'll need:

    for (int i = 0; i < examplestring.length(); i++) {
      char c = examplestring.charAt(i);
      ...
    }
    

    Awkward I know.

    Apply CSS styles to an element depending on its child elements

    In my case, I had to change the cell padding of an element that contained an input checkbox for a table that's being dynamically rendered with DataTables:

    <td class="dt-center">
        <input class="a" name="constCheck" type="checkbox" checked="">
    </td>
    

    After implementing the following line code within the initComplete function I was able to produce the correct padding, which fixed the rows from being displayed with an abnormally large height

     $('tbody td:has(input.a)').css('padding', '0px');
    

    Now, you can see that the correct styles are being applied to the parent element:

    <td class=" dt-center" style="padding: 0px;">
        <input class="a" name="constCheck" type="checkbox" checked="">
    </td>
    

    Essentially, this answer is an extension of @KP's answer, but the more collaboration of implementing this the better. In summation, I hope this helps someone else because it works! Lastly, thank you so much @KP for leading me in the right direction!

    What's in an Eclipse .classpath/.project file?

    This eclipse documentation has details on the markups in .project file: The project description file

    It describes the .project file as:

    When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"

    How can I remove "\r\n" from a string in C#? Can I use a regular expression?

    Here is the perfect method:

    Please note that Environment.NewLine works on on Microsoft platforms.

    In addition to the above, you need to add \r and \n in a separate function!

    Here is the code which will support whether you type on Linux, Windows, or Mac:

    var stringTest = "\r Test\nThe Quick\r\n brown fox";
    
    Console.WriteLine("Original is:");
    Console.WriteLine(stringTest);
    Console.WriteLine("-------------");
    
    stringTest = stringTest.Trim().Replace("\r", string.Empty);
    stringTest = stringTest.Trim().Replace("\n", string.Empty);
    stringTest = stringTest.Replace(Environment.NewLine, string.Empty);
    
    Console.WriteLine("Output is : ");
    Console.WriteLine(stringTest);
    Console.ReadLine();
    

    The preferred way of creating a new element with jQuery

    I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.

    How do I kill the process currently using a port on localhost in Windows?

    Result for Windows Command Prompt

    In my case, 8080 is the port I want to kill
    And 18264 is the PID listening on port 8080
    So the task you have to kill is the PID for that particular port

    C:\Users\Niroshan>netstat -ano|findstr "PID :8080"
    
    Proto Local Address Foreign Address State PID
    TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 18264
    
    taskkill /PID 18264 /f
    
    

    jQuery bind/unbind 'scroll' event on $(window)

    You need to:

    unbind('scroll')
    

    At the moment you are not specifying the event to unbind.

    How do I trim a file extension from a String in Java?

    I would do like this:

    String title_part = "title part1.txt";
    int i;
    for(i=title_part.length()-1 ; i>=0 && title_part.charAt(i)!='.' ; i--);
    title_part = title_part.substring(0,i);
    

    Starting to the end till the '.' then call substring.

    Edit: Might not be a golf but it's effective :)

    How to find out the MySQL root password

    You cannot find it. It is stored in a database, which you need the root password to access, and even if you did get access somehow, it is hashed with a one-way hash. You can reset it: http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html

    Automatic vertical scroll bar in WPF TextBlock?

    <ScrollViewer MaxHeight="50"  
                  Width="Auto" 
                  HorizontalScrollBarVisibility="Disabled"
                  VerticalScrollBarVisibility="Auto">
         <TextBlock Text="{Binding Path=}" 
                    Style="{StaticResource TextStyle_Data}" 
                    TextWrapping="Wrap" />
    </ScrollViewer>
    

    I am doing this in another way by putting MaxHeight in ScrollViewer.

    Just Adjust the MaxHeight to show more or fewer lines of text. Easy.

    How to use su command over adb shell?

    By default CM10 only allows root access from Apps not ADB. Go to Settings -> Developer options -> Root access, and change option to "Apps and ADB".

    JavaScript OOP in NodeJS: how?

    If you are working on your own, and you want the closest thing to OOP as you would find in Java or C# or C++, see the javascript library, CrxOop. CrxOop provides syntax somewhat familiar to Java developers.

    Just be careful, Java's OOP is not the same as that found in Javascript. To get the same behavior as in Java, use CrxOop's classes, not CrxOop's structures, and make sure all your methods are virtual. An example of the syntax is,

    crx_registerClass("ExampleClass", 
    { 
        "VERBOSE": 1, 
    
        "public var publicVar": 5, 
        "private var privateVar": 7, 
    
        "public virtual function publicVirtualFunction": function(x) 
        { 
            this.publicVar1 = x;
            console.log("publicVirtualFunction"); 
        }, 
    
        "private virtual function privatePureVirtualFunction": 0, 
    
        "protected virtual final function protectedVirtualFinalFunction": function() 
        { 
            console.log("protectedVirtualFinalFunction"); 
        }
    }); 
    
    crx_registerClass("ExampleSubClass", 
    { 
        VERBOSE: 1, 
        EXTENDS: "ExampleClass", 
    
        "public var publicVar": 2, 
    
        "private virtual function privatePureVirtualFunction": function(x) 
        { 
            this.PARENT.CONSTRUCT(pA);
            console.log("ExampleSubClass::privatePureVirtualFunction"); 
        } 
    }); 
    
    var gExampleSubClass = crx_new("ExampleSubClass", 4);
    
    console.log(gExampleSubClass.publicVar);
    console.log(gExampleSubClass.CAST("ExampleClass").publicVar);
    

    The code is pure javascript, no transpiling. The example is taken from a number of examples from the official documentation.

    Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

    I used to have the same problem.

    Your config use security="none" so cannot generate _csrf:

    <http pattern="/login.jsp" security="none"/>
    

    you can set access="IS_AUTHENTICATED_ANONYMOUSLY" for page /login.jsp replace above config:

    <http>
        <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern="/**" access="ROLE_USER"/>
        <form-login login-page="/login.jsp"
                authentication-failure-url="/login.jsp?error=1"
                default-target-url="/index.jsp"/>
        <logout/>
        <csrf />
    </http>