Programs & Examples On #Wiimote

The Wii Remote, also known as the Wiimote, is the primary controller for Nintendo's Wii console.

Confirm Password with jQuery Validate

Remove the required: true rule.

Demo: Fiddle

jQuery('.validatedForm').validate({
            rules : {
                password : {
                    minlength : 5
                },
                password_confirm : {
                    minlength : 5,
                    equalTo : "#password"
                }
            }

Windows Forms - Enter keypress activates submit button?

private void textBox_KeyDown(object sender, KeyEventArgs e) 
{
    if (e.KeyCode == Keys.Enter)
        button.PerformClick();
}

Javascript/jQuery: Set Values (Selection) in a multiple Select

var groups = ["Test", "Prof","Off"];

    $('#fruits option').filter(function() {
      return groups.indexOf($(this).text()) > -1; //Options text exists in array
    }).prop('selected', true); //Set selected

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

If you are building a windows app try to build as x64 instead of Any CPU. It should work fine.

What is tempuri.org?

Webservices require unique namespaces so they don't confuse each others schemas and whatever with each other. A URL (domain, subdomain, subsubdomain, etc) is a clever identifier as it's "guaranteed" to be unique, and in most circumstances you've already got one.

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

This is the best way to get a simple date string :

 @DateTime.Parse(Html.DisplayFor(Model => Model.AuditDate).ToString()).ToShortDateString()

Is there a way to list all resources in AWS

EDIT: This answer is deprecated. Check the other answers.

No,
There is no way to get all resources within your account in one go. Each region is independent and for some services like IAM concept of a region does not exist at all. Although there are API calls available to list down resources and services.
For example:

  • To get list of all available regions for your account:

    output, err := client.DescribeRegions(&ec2.DescribeRegionsInput{})
    

  • To get list of IAM users, roles or group you can use:

    client.GetAccountAuthorizationDetails(&iam.GetAccountAuthorizationDetailsInput{})

    You can find more detail about API calls and their use at: https://docs.aws.amazon.com/sdk-for-go/api/service/iam/

    Above link is only for IAM. Similarly, you can find API for all other resources and services.

  • How to check postgres user and password?

    You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.

    Usually, you can login as the postgres user:

    Open a Terminal and do sudo su postgres. Now, after entering your admin password, you are able to launch psql and do

    CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';
    

    This creates a new admin user. If you want to list the existing users, you could also do

    \du
    

    to list all users and then

    ALTER USER yourusername WITH PASSWORD 'yournewpass';
    

    CSS Calc Viewport Units Workaround?

    <div>It's working fine.....</div>
    
    div
    {
         height: calc(100vh - 8vw);
        background: #000;
        overflow:visible;
        color: red;
    }
    

    Check here this css code right now support All browser without Opera

    just check this

    Live

    see Live preview by jsfiddle

    See Live preview by codepen.io

    java.lang.UnsupportedClassVersionError: Bad version number in .class file?

    Also check any jar files in your project that have been compiled for a higher version of Java. If these are your own libraries, you can fix this by changing the target version attribute to javac

    <javac destdir="${classes.dir}"
                debug="on" classpathref="project.classpath" target="1.6">
    

    How to calculate a Mod b in Casio fx-991ES calculator

    type normal division first and then type shift + S->d

    What's "tools:context" in Android layout files?

    According to the Android Tools Project Site:

    tools:context

    This attribute is typically set on the root element in a layout XML file, and records which activity the layout is associated with (at designtime, since obviously a layout can be used by more than one layout). This will for example be used by the layout editor to guess a default theme, since themes are defined in the Manifest and are associated with activities, not layouts. You can use the same dot prefix as in manifests to just specify the activity class without the full application package name as a prefix.

    <android.support.v7.widget.GridLayout
        xmlns:android="http://schemas.android.com/apk/res/android"    
        xmlns:tools="http://schemas.android.com/tools"
        tools:context=".MainActivity">  
    

    Used by: Layout editors in Studio & Eclipse, Lint

    Best way to display data via JSON using jQuery

    Perfect! Thank you Jay, below is my HTML:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
    <link rel="stylesheet" href="../css/screen.css" type="text/css" media="screen, projection" />
    <link rel="stylesheet" href="../css/print.css" type="text/css" media="print" />
    <!--[if IE]><link rel="stylesheet" href="../css/ie.css" type="text/css" media="screen, projection"><![endif]-->
    <link href="../css/highlight.css" rel="stylesheet" type="text/css" media="screen" />
    <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
    /* <![CDATA[ */
    $(document).ready(function(){
        $.getJSON("readJSON.php",function(data){
            $.each(data.post, function(i,post){
                content += '<p>' + post.post_author + '</p>';
                content += '<p>' + post.post_content + '</p>';
                content += '<p' + post.date + '</p>';
                content += '<br/>';
                $(content).appendTo("#posts");
            });
        });   
    });
    /* ]]> */
    </script>
    </head>
    <body>
            <div class="container">
                    <div class="span-24">
                           <h2>Check out the following posts:</h2>
                            <div id="posts">
                            </di>
                    </div>
            </div>
    </body>
    </html>
    

    And my JSON outputs:

    { posts: [{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"This is a post","author":"Ryan Coughlin"}]}
    

    I get this error, when I run my code:

    object is undefined
    http://localhost:8888/rks/post/js/jquery.js
    Line 19
    

    Raising a number to a power in Java

    Your calculation is likely the culprit. Try using:

    bmi = weight / Math.pow(height / 100.0, 2.0);
    

    Because both height and 100 are integers, you were likely getting the wrong answer when dividing. However, 100.0 is a double. I suggest you make weight a double as well. Also, the ^ operator is not for powers. Use the Math.pow() method instead.

    How do I replace text in a selection?

    1) Ctrl + F (or Cmd + F on a Mac);
    2) Enter the string you want to find on the input at the bottom of the window.
    3) Press "Find All";

    All of the appearances are now selected. Do whatever you want.

    Aside

    There are a bunch of options at the left of the input that opens on Ctrl + F. There's one that says something like "Find in selected text". Select a bunch of text, check that option and repeat the same steps above starting from 2). Now, only matches belonging to that selection are selected.

    Android studio: emulator is running but not showing up in Run App "choose a running device"

    I am using Idea based Android Studio (some people are talking about eclipse one here)

    When I launch the app in the emulator (using the Run App button of Android Studio) AVD shows up but the app does not launch or run.

    However when I connect my mobile and launch the app on my mobile the App works (this itself took some time, enabling developer options on mobile and doing the right configuration)

    • Because My app is launching on connected mobile, I can say nothing wrong with App.
    • There is some problem with AVD integration which I could not figure out so As of now I am working around my problem following way.

    1 - I installed the app manually by dragging the APK file on AVD. (APK file is app\build\outputs\apk\debug folder)

    2 - Then my AVD was not showing the installed APP list. 3 - I searched my APP using Google bar on AVD and dragged the APP icon on the home screen of AVD.

    4 - I can now launch the APP using my APP icon on the home screen of AVD.

    That's how I am working around my problem. I will try to debug more on why it does not get installed and launched directly.

    I have verified that Run App Icon does install the Application. Installation, not launching, appears to be the problem for me.

    SQL Update Multiple Fields FROM via a SELECT Statement

    you can use update from...

    something like:

    update shipment set.... from shipment inner join ProfilerTest.dbo.BookingDetails on ...

    How to open a link in new tab (chrome) using Selenium WebDriver?

    for clicking on the link which expected to be opened from new tab use this

    WebDriver driver = new ChromeDriver(); 
    driver.get("https://www.yourSite.com"); 
    WebElement link=driver.findElement(By.xpath("path_to_link")); 
    
    Actions actions = new Actions(driver); 
    actions.keyDown(Keys.LEFT_CONTROL) 
           .click(element) 
           .keyUp(Keys.LEFT_CONTROL) 
           .build() 
           .perform(); 
    
    ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles()); 
    driver.switchTo().window(tab.get(1));
    

    How to do a for loop in windows command line?

    This may help you find what you're looking for... Batch script loop

    My answer is as follows:

    @echo off
    :start
    set /a var+=1
    if %var% EQU 100 goto end
    :: Code you want to run goes here
    goto start
    
    :end
    echo var has reached %var%.
    pause
    exit
    

    The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.

    SQL providerName in web.config

    System.Data.SqlClient is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.

    I don't know where providerName=SqlServer comes from. Could you be getting this confused with the provider keyword in your connection string? (I know I was :) )

    In the web.config you should have the System.Data.SqlClient as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.

    <connectionStrings>
       <add 
          name="LocalSqlServer" 
          connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
          providerName="System.Data.SqlClient"
       />
    </connectionStrings>
    

    See http://msdn.microsoft.com/en-US/library/htw9h4z3(v=VS.80).aspx

    MySQL Where DateTime is greater than today

    Remove the date() part

    SELECT name, datum 
    FROM tasks 
    WHERE datum >= NOW()
    

    and if you use a specific date, don't forget the quotes around it and use the proper format with :

    SELECT name, datum 
    FROM tasks 
    WHERE datum >= '2014-05-18 15:00:00'
    

    Setting PATH environment variable in OSX permanently

    You can open any of the following files:

    /etc/profile
    ~/.bash_profile
    ~/.bash_login   (if .bash_profile does not exist)
    ~/.profile      (if .bash_login does not exist)
    

    And add:

    export PATH="$PATH:your/new/path/here"
    

    Testing Spring's @RequestBody using Spring MockMVC

    the following works for me,

      mockMvc.perform(
                MockMvcRequestBuilders.post("/api/test/url")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(asJsonString(createItemForm)))
                .andExpect(status().isCreated());
    
      public static String asJsonString(final Object obj) {
        try {
            return new ObjectMapper().writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    

    A simple jQuery form validation script

    you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

    <script type="text/javascript">
    $(document).ready(function(){
        $("#formID").validate({
        rules :{
            "data[User][name]" : {
                required : true
            }
        },
        messages :{
            "data[User][name]" : {
                required : 'Enter username'
            }
        }
        });
    });
    </script>
    

    You can see required : true same there is many more property like for email you can define email : true for number number : true

    Pass row number as variable in excel sheet

    An alternative is to use OFFSET:

    Assuming the column value is stored in B1, you can use the following

    C1 = OFFSET(A1, 0, B1 - 1)
    

    This works by:

    a) taking a base cell (A1)
    b) adding 0 to the row (keeping it as A)
    c) adding (A5 - 1) to the column

    You can also use another value instead of 0 if you want to change the row value too.

    Tomcat base URL redirection

    What i did:

    I added the following line inside of ROOT/index.jsp

     <meta http-equiv="refresh" content="0;url=/somethingelse/index.jsp"/>
    

    What is the meaning of polyfills in HTML5?

    First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.

    The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "

    Source and example of polyfill here:

    http://www.programmerinterview.com/index.php/html5/html5-polyfill/

    Some dates recognized as dates, some dates not recognized. Why?

    Right-click on the column header and select Format Cells, the chose Date and select the desired date format. Those that are not recognized are ambiguous, and as such not interpreted as anything but that is resolved after applying formatting to the column. Note that for me, in Excel 2002 SP3, the dates given above are automatically and correctly interpreted as dates when pasting.

    Convert unsigned int to signed int C

    I know it's an old question, but it's a good one, so how about this?

    unsigned short int x = 65529U;
    short int y = *(short int*)&x;
    
    printf("%d\n", y);
    

    Mockito - difference between doReturn() and when()

    Continuing this answer, There is another difference that if you want your method to return different values for example when it is first time called, second time called etc then you can pass values so for example...

    PowerMockito.doReturn(false, false, true).when(SomeClass.class, "SomeMethod", Matchers.any(SomeClass.class));
    

    So it will return false when the method is called in same test case and then it will return false again and lastly true.

    Java ArrayList clear() function

    ArrayList.clear(From Java Doc):

    Removes all of the elements from this list. The list will be empty after this call returns

    How to get the insert ID in JDBC?

    In my case ->

    ConnectionClass objConnectionClass=new ConnectionClass();
    con=objConnectionClass.getDataBaseConnection();
    pstmtGetAdd=con.prepareStatement(SQL_INSERT_ADDRESS_QUERY,Statement.RETURN_GENERATED_KEYS);
    pstmtGetAdd.setString(1, objRegisterVO.getAddress());
    pstmtGetAdd.setInt(2, Integer.parseInt(objRegisterVO.getCityId()));
    int addId=pstmtGetAdd.executeUpdate();              
    if(addId>0)
    {
        ResultSet rsVal=pstmtGetAdd.getGeneratedKeys();
        rsVal.next();
        addId=rsVal.getInt(1);
    }
    

    How to remove list elements in a for loop in Python?

    You are not permitted to remove elements from the list while iterating over it using a for loop.

    The best way to rewrite the code depends on what it is you're trying to do.

    For example, your code is equivalent to:

    for item in a:
      print item
    a[:] = []
    

    Alternatively, you could use a while loop:

    while a:
      print a.pop(0)
    

    I'm trying to remove items if they match a condition. Then I go to next item.

    You could copy every element that doesn't match the condition into a second list:

    result = []
    for item in a:
      if condition is False:
        result.append(item)
    a = result
    

    Alternatively, you could use filter or a list comprehension and assign the result back to a:

    a = filter(lambda item:... , a)
    

    or

    a = [item for item in a if ...]
    

    where ... stands for the condition that you need to check.

    How to implement a FSM - Finite State Machine in Java

    Consider the easy, lightweight Java library EasyFlow. From their docs:

    With EasyFlow you can:

    • implement complex logic but keep your code simple and clean
    • handle asynchronous calls with ease and elegance
    • avoid concurrency by using event-driven programming approach
    • avoid StackOverflow error by avoiding recursion
    • simplify design, programming and testing of complex java applications

    GROUP BY and COUNT in PostgreSQL

    I think you just need COUNT(DISTINCT post_id) FROM votes.

    See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.

    EDIT: Corrected my careless mistake per Erwin's comment.

    ImportError: No module named model_selection

    do you have sklearn? if not, do the following:

    sudo pip install sklearn
    

    After installing sklearn

    from sklearn.model_selection import train_test_split
    

    works fine

    how to get param in method post spring mvc?

    It also works if you change the content type

        <form method="POST"
        action="http://localhost:8080/cms/customer/create_customer"
        id="frmRegister" name="frmRegister"
        enctype="application/x-www-form-urlencoded">
    

    In the controller also add the header value as follows:

        @RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")
    

    Javascript equivalent of php's strtotime()?

    I found this article and tried the tutorial. Basically, you can use the date constructor to parse a date, then write get the seconds from the getTime() method

    var d=new Date("October 13, 1975 11:13:00");
    document.write(d.getTime() + " milliseconds since 1970/01/01");
    

    Does this work?

    Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

    tl;dr

    The answer is NEVER! (unless you really know what you're doing)

    9/10 times the solution can be resolved with a proper understanding of encoding/decoding.

    1/10 people have an incorrectly defined locale or environment and need to set:

    PYTHONIOENCODING="UTF-8"  
    

    in their environment to fix console printing problems.

    What does it do?

    sys.setdefaultencoding("utf-8") (struck through to avoid re-use) changes the default encoding/decoding used whenever Python 2.x needs to convert a Unicode() to a str() (and vice-versa) and the encoding is not given. I.e:

    str(u"\u20AC")
    unicode("€")
    "{}".format(u"\u20AC") 
    

    In Python 2.x, the default encoding is set to ASCII and the above examples will fail with:

    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
    

    (My console is configured as UTF-8, so "€" = '\xe2\x82\xac', hence exception on \xe2)

    or

    UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
    

    sys.setdefaultencoding("utf-8") will allow these to work for me, but won't necessarily work for people who don't use UTF-8. The default of ASCII ensures that assumptions of encoding are not baked into code

    Console

    sys.setdefaultencoding("utf-8") also has a side effect of appearing to fix sys.stdout.encoding, used when printing characters to the console. Python uses the user's locale (Linux/OS X/Un*x) or codepage (Windows) to set this. Occasionally, a user's locale is broken and just requires PYTHONIOENCODING to fix the console encoding.

    Example:

    $ export LANG=en_GB.gibberish
    $ python
    >>> import sys
    >>> sys.stdout.encoding
    'ANSI_X3.4-1968'
    >>> print u"\u20AC"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
    >>> exit()
    
    $ PYTHONIOENCODING=UTF-8 python
    >>> import sys
    >>> sys.stdout.encoding
    'UTF-8'
    >>> print u"\u20AC"
    €
    

    What's so bad with sys.setdefaultencoding("utf-8")?

    People have been developing against Python 2.x for 16 years on the understanding that the default encoding is ASCII. UnicodeError exception handling methods have been written to handle string to Unicode conversions on strings that are found to contain non-ASCII.

    From https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/

    def welcome_message(byte_string):
        try:
            return u"%s runs your business" % byte_string
        except UnicodeError:
            return u"%s runs your business" % unicode(byte_string,
                encoding=detect_encoding(byte_string))
    
    print(welcome_message(u"Angstrom (Å®)".encode("latin-1"))
    

    Previous to setting defaultencoding this code would be unable to decode the “Å” in the ascii encoding and then would enter the exception handler to guess the encoding and properly turn it into unicode. Printing: Angstrom (Å®) runs your business. Once you’ve set the defaultencoding to utf-8 the code will find that the byte_string can be interpreted as utf-8 and so it will mangle the data and return this instead: Angstrom (U) runs your business.

    Changing what should be a constant will have dramatic effects on modules you depend upon. It's better to just fix the data coming in and out of your code.

    Example problem

    While the setting of defaultencoding to UTF-8 isn't the root cause in the following example, it shows how problems are masked and how, when the input encoding changes, the code breaks in an unobvious way: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte

    What is the difference/usage of homebrew, macports or other package installation tools?

    Homebrew and macports both solve the same problem - that is the installation of common libraries and utilities that are not bundled with osx.

    Typically these are development related libraries and the most common use of these tools is for developers working on osx.

    They both need the xcode command line tools installed (which you can download separately from https://developer.apple.com/), and for some specific packages you will need the entire xcode IDE installed.

    xcode can be installed from the mac app store, its a free download but it takes a while since its around 5GB (if I remember correctly).

    macports is an osx version of the port utility from BSD (as osx is derived from BSD, this was a natural choice). For anyone familiar with any of the BSD distributions, macports will feel right at home.

    One major difference between homebrew and macports; and the reason I prefer homebrew is that it will not overwrite things that should be installed "natively" in osx. This means that if there is a native package available, homebrew will notify you instead of overwriting it and causing problems further down the line. It also installs libraries in the user space (thus, you don't need to use "sudo" to install things). This helps when getting rid of libraries as well since everything is in a path accessible to you.

    homebrew also enjoys a more active user community and its packages (called formulas) are updated quite often.


    macports does not overwrite native OSX packages - it supplies its own version - This is the main reason I prefer macports over home-brew, you need to be certain of what you are using and Apple's change at different times to the ports and have been know to be years behind updates in some projects

    Can you give a reference showing that macports overwrites native OS X packages? As far as I can tell, all macports installation happens in /opt/local

    Perhaps I should clarify - I did not say anywhere in my answer that macports overwrites OSX native packages. They both install items separately.

    Homebrew will warn you when you should install things "natively" (using the library/tool's preferred installer) for better compatibility. This is what I meant. It will also use as many of the local libraries that are available in OS X. From the wiki:

    We really don’t like dupes in Homebrew/homebrew

    However, we do like dupes in the tap!

    Stuff that comes with OS X or is a library that is provided by RubyGems, CPAN or PyPi should not be duped. There are good reasons for this:

    • Duplicate libraries regularly break builds
    • Subtle bugs emerge with duplicate libraries, and to a lesser extent, duplicate tools
    • We want you to try harder to make your formula work with what OS X comes with

    You can optionally overwrite the macosx supplied versions of utilities with homebrew.

    How to calculate number of days between two given dates?

    everyone has answered excellently using the date, let me try to answer it using pandas

    dt = pd.to_datetime('2008/08/18', format='%Y/%m/%d')
    dt1 = pd.to_datetime('2008/09/26', format='%Y/%m/%d')
    
    (dt1-dt).days
    

    This will give the answer. In case one of the input is dataframe column. simply use dt.days in place of days

    (dt1-dt).dt.days
    

    JavaScript Extending Class

    For Autodidacts:

    function BaseClass(toBePrivate){
        var morePrivates;
        this.isNotPrivate = 'I know';
        // add your stuff
    }
    var o = BaseClass.prototype;
    // add your prototype stuff
    o.stuff_is_never_private = 'whatever_except_getter_and_setter';
    
    
    // MiddleClass extends BaseClass
    function MiddleClass(toBePrivate){
        BaseClass.call(this);
        // add your stuff
        var morePrivates;
        this.isNotPrivate = 'I know';
    }
    var o = MiddleClass.prototype = Object.create(BaseClass.prototype);
    MiddleClass.prototype.constructor = MiddleClass;
    // add your prototype stuff
    o.stuff_is_never_private = 'whatever_except_getter_and_setter';
    
    
    
    // TopClass extends MiddleClass
    function TopClass(toBePrivate){
        MiddleClass.call(this);
        // add your stuff
        var morePrivates;
        this.isNotPrivate = 'I know';
    }
    var o = TopClass.prototype = Object.create(MiddleClass.prototype);
    TopClass.prototype.constructor = TopClass;
    // add your prototype stuff
    o.stuff_is_never_private = 'whatever_except_getter_and_setter';
    
    
    // to be continued...
    

    Create "instance" with getter and setter:

    function doNotExtendMe(toBePrivate){
        var morePrivates;
        return {
            // add getters, setters and any stuff you want
        }
    }
    

    Allow scroll but hide scrollbar

    It's better, if you use two div containers in HTML .

    As Shown Below:

    HTML:

    <div id="container1">
        <div id="container2">
            // Content here
        </div>
    </div>
    

    CSS:

     #container1{
        height: 100%;
        width: 100%;
        overflow: hidden;
    }
    
     #container2{
        height: 100%;
        width: 100%;
        overflow: auto;
        padding-right: 20px;
    }
    

    What are the differences between a clustered and a non-clustered index?

    Pros:

    Clustered indexes work great for ranges (e.g. select * from my_table where my_key between @min and @max)

    In some conditions, the DBMS will not have to do work to sort if you use an orderby statement.

    Cons:

    Clustered indexes are can slow down inserts because the physical layouts of the records have to be modified as records are put in if the new keys are not in sequential order.

    How to avoid Sql Query Timeout

    My team were experiencing these issues intermittently with long running SSIS packages. This has been happening since Windows server patching.

    Our SSIS and SQL servers are on separate VM servers.

    Working with our Wintel Servers team we rebooted both servers and for the moment, the problem appears to have gone away.

    The engineer has said that they're unsure if the issue is the patches or new VMTools that they updated at the same time. We'll monitor for now and if the timeout problems recur, they'll try rolling back the VMXNET3 driver, first, then if that doesn't work, take off the June Rollup patches.

    So for us the issue is nothing to do with our SQL Queries (we're loading billions of new rows so it has to be long running).

    C# List of objects, how do I get the sum of a property

    Here is example code you could run to make such test:

    var f = 10000000;
    var p = new int[f];
    
    for(int i = 0; i < f; ++i)
    {
        p[i] = i % 2;
    }
    
    var time = DateTime.Now;
    p.Sum();
    Console.WriteLine(DateTime.Now - time);
    
    int x = 0;
    time = DateTime.Now;
    foreach(var item in p){
       x += item;
    }
    Console.WriteLine(DateTime.Now - time);
    
    x = 0;
    time = DateTime.Now;
    for(int i = 0, j = f; i < j; ++i){
       x += p[i];
    }
    Console.WriteLine(DateTime.Now - time);
    

    The same example for complex object is:

    void Main()
    {
        var f = 10000000;
        var p = new Test[f];
    
        for(int i = 0; i < f; ++i)
        {
            p[i] = new Test();
            p[i].Property = i % 2;
        }
    
        var time = DateTime.Now;
        p.Sum(k => k.Property);
        Console.WriteLine(DateTime.Now - time);
    
        int x = 0;
        time = DateTime.Now;
        foreach(var item in p){
            x += item.Property;
        }
        Console.WriteLine(DateTime.Now - time);
    
        x = 0;
        time = DateTime.Now;
        for(int i = 0, j = f; i < j; ++i){
            x += p[i].Property;
        }
        Console.WriteLine(DateTime.Now - time);
    }
    
    class Test
    {
        public int Property { get; set; }
    }
    

    My results with compiler optimizations off are:

    00:00:00.0570370 : Sum()
    00:00:00.0250180 : Foreach()
    00:00:00.0430272 : For(...)
    

    and for second test are:

    00:00:00.1450955 : Sum()
    00:00:00.0650430 : Foreach()
    00:00:00.0690510 : For()
    

    it looks like LINQ is generally slower than foreach(...) but what is weird for me is that foreach(...) appears to be faster than for loop.

    What characters do I need to escape in XML documents?

    According to the specifications of the World Wide Web Consortium (w3C), there are 5 characters that must not appear in their literal form in an XML document, except when used as markup delimiters or within a comment, a processing instruction, or a CDATA section. In all the other cases, these characters must be replaced either using the corresponding entity or the numeric reference according to the following table:

    Original CharacterXML entity replacementXML numeric replacement
    <                              &lt;                                    &#60;                                    
    >                              &gt;                                   &#62;                                    
    "                               &quot;                               &#34;                                    
    &                              &amp;                               &#38;                                    
    '                               &apos;                               &#39;                                    

    Notice that the aforementioned entities can be used also in HTML, with the exception of &apos;, that was introduced with XHTML 1.0 and is not declared in HTML 4. For this reason, and to ensure retro-compatibility, the XHTML specification recommends the use of &#39; instead.

    Using std::max_element on a vector<double>

    min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

    cLower = *min_element(C.begin(), C.end());
    

    Python - converting a string of numbers into a list of int

    Try this :

    import re
    [int(s) for s in re.split('[\s,]+',example_string)]
    

    Making a cURL call in C#

    Late response but this is what I ended up doing. If you want to run your curl commands very similarly as you run them on linux and you have windows 10 or latter do this:

        public static string ExecuteCurl(string curlCommand, int timeoutInSeconds=60)
        {
            if (string.IsNullOrEmpty(curlCommand))
                return "";
    
            curlCommand = curlCommand.Trim();
    
            // remove the curl keworkd
            if (curlCommand.StartsWith("curl"))
            {
                curlCommand = curlCommand.Substring("curl".Length).Trim();
            }
    
            // this code only works on windows 10 or higher
            {
    
                curlCommand = curlCommand.Replace("--compressed", "");
    
                // windows 10 should contain this file
                var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, "curl.exe");
    
                if (System.IO.File.Exists(fullPath) == false)
                {
                    if (Debugger.IsAttached) { Debugger.Break(); }
                    throw new Exception("Windows 10 or higher is required to run this application");
                }
    
                // on windows ' are not supported. For example: curl 'http://ublux.com' does not work and it needs to be replaced to curl "http://ublux.com"
                List<string> parameters = new List<string>();
    
    
                // separate parameters to escape quotes
                try
                {
                    Queue<char> q = new Queue<char>();
    
                    foreach (var c in curlCommand.ToCharArray())
                    {
                        q.Enqueue(c);
                    }
    
                    StringBuilder currentParameter = new StringBuilder();
    
                    void insertParameter()
                    {
                        var temp = currentParameter.ToString().Trim();
                        if (string.IsNullOrEmpty(temp) == false)
                        {
                            parameters.Add(temp);
                        }
    
                        currentParameter.Clear();
                    }
    
                    while (true)
                    {
                        if (q.Count == 0)
                        {
                            insertParameter();
                            break;
                        }
    
                        char x = q.Dequeue();
    
                        if (x == '\'')
                        {
                            insertParameter();
    
                            // add until we find last '
                            while (true)
                            {
                                x = q.Dequeue();
    
                                // if next 2 characetrs are \' 
                                if (x == '\\' && q.Count > 0 && q.Peek() == '\'')
                                {
                                    currentParameter.Append('\'');
                                    q.Dequeue();
                                    continue;
                                }
    
                                if (x == '\'')
                                {
                                    insertParameter();
                                    break;
                                }
    
                                currentParameter.Append(x);
                            }
                        }
                        else if (x == '"')
                        {
                            insertParameter();
    
                            // add until we find last "
                            while (true)
                            {
                                x = q.Dequeue();
    
                                // if next 2 characetrs are \"
                                if (x == '\\' && q.Count > 0 && q.Peek() == '"')
                                {
                                    currentParameter.Append('"');
                                    q.Dequeue();
                                    continue;
                                }
    
                                if (x == '"')
                                {
                                    insertParameter();
                                    break;
                                }
    
                                currentParameter.Append(x);
                            }
                        }
                        else
                        {
                            currentParameter.Append(x);
                        }
                    }
                }
                catch
                {
                    if (Debugger.IsAttached) { Debugger.Break(); }
                    throw new Exception("Invalid curl command");
                }
    
                StringBuilder finalCommand = new StringBuilder();
    
                foreach (var p in parameters)
                {
                    if (p.StartsWith("-"))
                    {
                        finalCommand.Append(p);
                        finalCommand.Append(" ");
                        continue;
                    }
    
                    var temp = p;
    
                    if (temp.Contains("\""))
                    {
                        temp = temp.Replace("\"", "\\\"");
                    }
                    if (temp.Contains("'"))
                    {
                        temp = temp.Replace("'", "\\'");
                    }
    
                    finalCommand.Append($"\"{temp}\"");
                    finalCommand.Append(" ");
                }
    
    
                using (var proc = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "curl.exe",
                        Arguments = finalCommand.ToString(),
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true,
                        WorkingDirectory = Environment.SystemDirectory
                    }
                })
                {
                    proc.Start();
    
                    proc.WaitForExit(timeoutInSeconds*1000);
    
                    return proc.StandardOutput.ReadToEnd();
                }
            }
        }
    

    The reason why the code is a little bit long is because windows will give you an error if you execute a single quote. In other words, the command curl 'https://google.com' will work on linux and it will not work on windows. Thanks to that method I created you can use single quotes and run your curl commands exactly as you run them on linux. This code also checks for escaping characters such as \' and \".

    For example use this code as

    var output = ExecuteCurl(@"curl 'https://google.com' -H 'Accept: application/json, text/javascript, */*; q=0.01'");

    If you where to run that same string agains C:\Windows\System32\curl.exe it will not work because for some reason windows does not like single quotes.

    gcc makefile error: "No rule to make target ..."

    This error occurred for me inside Travis when I forgot to add new files to my git repository. Silly mistake, but I can see it being quite common.

    Fixed positioned div within a relative parent div

    Gavin,

    The issue you are having is a misunderstanding of positioning. If you want it to be "fixed" relative to the parent, then you really want your #fixed to be position:absolute which will update its position relative to the parent.

    This question fully describes positioning types and how to use them effectively.

    In summary, your CSS should be

    #wrap{ 
        position:relative;
    }
    #fixed{ 
        position:absolute;
        top:30px;
        left:40px;
    }
    

    Complexities of binary tree traversals

    T(n) = 2T(n/2)+ c

    T(n/2) = 2T(n/4) + c => T(n) = 4T(n/4) + 2c + c

    similarly T(n) = 8T(n/8) + 4c+ 2c + c

    ....

    ....

    last step ... T(n) = nT(1) + c(sum of powers of 2 from 0 to h(height of tree))

    so Complexity is O(2^(h+1) -1)

    but h = log(n)

    so, O(2n - 1) = O(n)

    How to install bcmath module?

    The following worked for me on Centos 7.4 with PHP 7.1 using remi repository.

    First find out which PHP version I have:

    [kiat@reporting ~]$ php --version
    PHP 7.1.33 (cli) (built: Oct 23 2019 07:28:45) ( NTS )
    Copyright (c) 1997-2018 The PHP Group
    Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
        with Zend OPcache v7.1.33, Copyright (c) 1999-2018, by Zend Technologies
    

    Then search for bcmath extension in remi-php71 repository:

    [kiat@reporting ~]$ yum search php71 | grep bcmath
    php71-php-bcmath.x86_64 : A module for PHP applications for using the bcmath
    php71u-bcmath.x86_64 : A module for PHP applications for using the bcmath
    

    Now install the first matching extension:

    [kiat@reporting ~]$ sudo yum --enablerepo=remi-php71 install php-bcmath
    Loaded plugins: fastestmirror, langpacks
    base                                                     | 3.6 kB     00:00
    .
    .
    .
    

    Finally, restart php and nginx:

    [kiat@reporting ~]$ sudo systemctl restart php-fpm nginx
    

    Best way to test if a row exists in a MySQL table

    I'd go with COUNT(1). It is faster than COUNT(*) because COUNT(*) tests to see if at least one column in that row is != NULL. You don't need that, especially because you already have a condition in place (the WHERE clause). COUNT(1) instead tests the validity of 1, which is always valid and takes a lot less time to test.

    How to remove trailing whitespaces with sed?

    In the specific case of sed, the -i option that others have already mentioned is far and away the simplest and sanest one.

    In the more general case, sponge, from the moreutils collection, does exactly what you want: it lets you replace a file with the result of processing it, in a way specifically designed to keep the processing step from tripping over itself by overwriting the very file it's working on. To quote the sponge man page:

    sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before writing the output file. This allows constructing pipelines that read from and write to the same file.

    https://joeyh.name/code/moreutils/

    Can't load IA 32-bit .dll on a AMD 64-bit platform

    For your Native library location, use X64 over X86. At least this fixed problem I had.

    How to use ADB in Android Studio to view an SQLite DB

    What it mentions as you type adb?

    step1. >adb shell
    step2. >cd data/data
    step3. >ls -l|grep "your app package here"
    step4. >cd "your app package here"
    step5. >sqlite3 xx.db
    

    Get Image Height and Width as integer values?

    getimagesize('image.jpg') function works only if allow_url_fopen is set to 1 or On inside php.ini file on the server, if it is not enabled, one should use ini_set('allow_url_fopen',1); on top of the file where getimagesize() function is used.

    Remove all newlines from inside a string

    strip only removes characters from the beginning and end of a string. You want to use replace:

    str2 = str.replace("\n", "")
    re.sub('\s{2,}', ' ', str) # To remove more than one space 
    

    How do I increase the capacity of the Eclipse output console?

    On the MAC OS X 10.9.5 and Eclipse Luna Service Release 1 (4.4.1), its not found under the Window menu, but instead under: Eclipse > Preferences > Run/Debug > Console.

    Drop Down Menu/Text Field in one

    You can use the <datalist> tag instead of the <select> tag.

    <input list="browsers" name="browser" id="browser">
    <datalist id="browsers">
      <option value="Edge">
      <option value="Firefox">
      <option value="Chrome">
      <option value="Opera">
      <option value="Safari">
    </datalist>
    

    identifier "string" undefined?

    You forgot the namespace you're referring to. Add

    using namespace std;

    to avoid std::string all the time.

    phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

    You have to go into your mySQL settings and change the settings to Legacy authentication. I use mysql community installer and it allows you to go back and reconfigure the settings. Create a new user, and choose standard authentication, choose a password, thats it. Its that simple!!!

    manage.py runserver

    Just in case any Windows users are having trouble, I thought I'd add my own experience. When running python manage.py runserver 0.0.0.0:8000, I could view urls using localhost:8000, but not my ip address 192.168.1.3:8000.

    I ended up disabling ipv6 on my wireless adapter, and running ipconfig /renew. After this everything worked as expected.

    add new row in gridview after binding C#, ASP.net

    You can run this example directly.

    aspx page:

    <asp:GridView ID="grd" runat="server" DataKeyNames="PayScale" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Pay Scale">
                <ItemTemplate>
                    <asp:TextBox ID="txtPayScale" runat="server" Text='<%# Eval("PayScale") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Increment Amount">
                <ItemTemplate>
                    <asp:TextBox ID="txtIncrementAmount" runat="server" Text='<%# Eval("IncrementAmount") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Period">
                <ItemTemplate>
                    <asp:TextBox ID="txtPeriod" runat="server" Text='<%# Eval("Period") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />
    

    C# code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            grd.DataSource = GetTableWithInitialData(); // get first initial data
            grd.DataBind();
        }
    }
    
    public DataTable GetTableWithInitialData() // this might be your sp for select
    {
        DataTable table = new DataTable();
        table.Columns.Add("PayScale", typeof(string));
        table.Columns.Add("IncrementAmount", typeof(string));
        table.Columns.Add("Period", typeof(string));
    
        table.Rows.Add(1, "David", "1");
        table.Rows.Add(2, "Sam", "2");
        table.Rows.Add(3, "Christoff", "1.5");
        return table;
    }
    
    protected void btnAddRow_Click(object sender, EventArgs e)
    {
        DataTable dt = GetTableWithNoData(); // get select column header only records not required
        DataRow dr;
    
        foreach (GridViewRow gvr in grd.Rows)
        {
            dr = dt.NewRow();
    
            TextBox txtPayScale = gvr.FindControl("txtPayScale") as TextBox;
            TextBox txtIncrementAmount = gvr.FindControl("txtIncrementAmount") as TextBox;
            TextBox txtPeriod = gvr.FindControl("txtPeriod") as TextBox;
    
            dr[0] = txtPayScale.Text;
            dr[1] = txtIncrementAmount.Text;
            dr[2] = txtPeriod.Text;
    
            dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
        }
    
        dr = dt.NewRow(); // add last empty row
        dt.Rows.Add(dr);
    
        grd.DataSource = dt; // bind new datatable to grid
        grd.DataBind();
    }
    
    public DataTable GetTableWithNoData() // returns only structure if the select columns
    {
        DataTable table = new DataTable();
        table.Columns.Add("PayScale", typeof(string));
        table.Columns.Add("IncrementAmount", typeof(string));
        table.Columns.Add("Period", typeof(string));
        return table;
    }
    

    How to center buttons in Twitter Bootstrap 3?

    <div class="row">
      <div class="col-sm-12">
        <div class="text-center">
          <button class="btn btn-primary" id="singlebutton"> Next Step!</button>
        </div>
      </div>
    </div>
    

    Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

    Following the unobtrusive principle, it's not quite required for "_myPartial" to inject content directly into scripts section. You could add those partial view scripts into separate .js file and reference them into @scripts section from parent view.

    JSON: why are forward slashes escaped?

    I asked the same question some time ago and had to answer it myself. Here's what I came up with:

    It seems, my first thought [that it comes from its JavaScript roots] was correct.

    '\/' === '/' in JavaScript, and JSON is valid JavaScript. However, why are the other ignored escapes (like \z) not allowed in JSON?

    The key for this was reading http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML.

    Should I use encodeURI or encodeURIComponent for encoding URLs?

    xkr.us has a great discussion, with examples. To quote their summary:

    The escape() method does not encode the + character which is interpreted as a space on the server side as well as generated by forms with spaces in their fields. Due to this shortcoming and the fact that this function fails to handle non-ASCII characters correctly, you should avoid use of escape() whenever possible. The best alternative is usually encodeURIComponent().

    escape() will not encode: @*/+

    Use of the encodeURI() method is a bit more specialized than escape() in that it encodes for URIs as opposed to the querystring, which is part of a URL. Use this method when you need to encode a string to be used for any resource that uses URIs and needs certain characters to remain un-encoded. Note that this method does not encode the ' character, as it is a valid character within URIs.

    encodeURI() will not encode: ~!@#$&*()=:/,;?+'

    Lastly, the encodeURIComponent() method should be used in most cases when encoding a single component of a URI. This method will encode certain chars that would normally be recognized as special chars for URIs so that many components may be included. Note that this method does not encode the ' character, as it is a valid character within URIs.

    encodeURIComponent() will not encode: ~!*()'

    use Lodash to sort array of object by value

    This method orderBy does not change the input array, you have to assign the result to your array :

    var chars = this.state.characters;
    
    chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'
    
     this.setState({characters: chars})
    

    Get only the date in timestamp in mysql

    $date= new DateTime($row['your_date']) ;  
    echo $date->format('Y-m-d');
    

    Why am I getting AttributeError: Object has no attribute

    Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName.

    change html text from link with jquery

    The method you are looking for is jQuery's .text() and you can used it in the following fashion:

    $('#a_tbnotesverbergen').text('text here');
    

    Vertically align text to top within a UILabel

    Instead of using sizeToFit, you could manually change the label's height;

    CGSize size = [descLabel.text sizeWithFont:descLabel.font constrainedToSize:CGSizeMake(labelWidth, labelHeight)];
    CGRect frame = descLabel.frame;
    frame.size.height = size.height;    
    [yourLabel setFrame:frame];
    

    The size returned will be the best fit for the content of your label. If the label's height is fitted to its content, you wouldn't have problems with the content being positioned on the center of the label.

    The following classes could not be instantiated: - android.support.v7.widget.Toolbar

    Another mistake that can have the same effect can be the wrong theme in the preview. For some reason I had selected some other theme here. After choosing my AppTheme it worked fine again:

    layout options

    How to change the name of an iOS app?

    From Xcode 4.2 and onwards, you can use one more option. Just click once on .proj file name at the top in left navigation pane and it will be available for renaming.Rename it and the whole project will get renamed and not only the target.

    Get value of Span Text

    The accepted answer is close... but no cigar!

    Use textContent instead of innerHTML if you strictly want a string to be returned to you.

    innerHTML can have the side effect of giving you a node element if there's other dom elements in there. textContent will guard against this possibility.

    Hiding axis text in matplotlib plots

    If you are like me and don't always retrieve the axes, ax, when plotting the figure, then a simple solution would be to do

    plt.xticks([])
    plt.yticks([])
    

    How do I use System.getProperty("line.separator").toString()?

    Try BufferedReader.readLine() instead of all this complication. It will recognize all possible line terminators.

    Protecting cells in Excel but allow these to be modified by VBA script

    I selected the cells I wanted locked out in sheet1 and place the suggested code in the open_workbook() function and worked like a charm.

    ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
    UserInterfaceOnly:=True
    

    how to apply click event listener to image in android

    ImageView img = (ImageView) findViewById(R.id.myImageId);
    img.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
           // your code here
        }
    });
    

    How to call a method daily, at specific time, in C#?

    Try to use Windows Task Scheduler. Create an exe which is not prompting for any user inputs.

    https://docs.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-start-page

    How do I negate a test with regular expressions in a bash script?

    the safest way is to put the ! for the regex negation within the [[ ]] like this:

    if [[ ! ${STR} =~ YOUR_REGEX ]]; then
    

    otherwise it might fail on certain systems.

    MVC3 DropDownListFor - a simple example?

    You should do like this:

    @Html.DropDownListFor(m => m.ContribType, 
                    new SelectList(Model.ContribTypeOptions, 
                                   "ContribId", "Value"))
    

    Where:

    m => m.ContribType
    

    is a property where the result value will be.

    What is an attribute in Java?

    ¦ What is an attribute?

    – A variable that belongs to an object.Attributes is same term used alternatively for properties or fields or data members or class members

    ¦ How else can it be called?

    – field or instance variable

    ¦ How do you create one? What is the syntax?

    – You need to declare attributes at the beginning of the class definition, outside of any method. The syntax is the following: ;

    Having Django serve downloadable files

    You should use sendfile apis given by popular servers like apache or nginx in production. Many years i was using sendfile api of these servers for protecting files. Then created a simple middleware based django app for this purpose suitable for both development & production purpose.You can access the source code here.
    UPDATE: in new version python provider uses django FileResponse if available and also adds support for many server implementations from lighthttp, caddy to hiawatha

    Usage

    pip install django-fileprovider
    
    • add fileprovider app to INSTALLED_APPS settings,
    • add fileprovider.middleware.FileProviderMiddleware to MIDDLEWARE_CLASSES settings
    • set FILEPROVIDER_NAME settings to nginx or apache in production, by default it is python for development purpose.

    in your classbased or function views set response header X-File value to absolute path to the file. For example,

    def hello(request):  
       // code to check or protect the file from unauthorized access
       response = HttpResponse()  
       response['X-File'] = '/absolute/path/to/file'  
       return response  
    

    django-fileprovider impemented in a way that your code will need only minimum modification.

    Nginx configuration

    To protect file from direct access you can set the configuration as

     location /files/ {
      internal;
      root   /home/sideffect0/secret_files/;
     }
    

    Here nginx sets a location url /files/ only access internaly, if you are using above configuration you can set X-File as,

    response['X-File'] = '/files/filename.extension' 
    

    By doing this with nginx configuration, the file will be protected & also you can control the file from django views

    Button Width Match Parent

    The size attribute can be provided using ButtonTheme with minWidth: double.infinity

    ButtonTheme(
      minWidth: double.infinity,
      child: MaterialButton(
        onPressed: () {},
        child: Text('Raised Button'),
      ),
    ),
    

    or after https://github.com/flutter/flutter/pull/19416 landed

    MaterialButton(
      onPressed: () {},
      child: SizedBox.expand(
        width: double.infinity, 
        child: Text('Raised Button'),
      ),
    ),
    

    How to get all child inputs of a div element (jQuery)

    here is my approach:

    You can use it in other event.

    _x000D_
    _x000D_
    var id;_x000D_
    $("#panel :input").each(function(e){ _x000D_
      id = this.id;_x000D_
      // show id _x000D_
      console.log("#"+id);_x000D_
      // show input value _x000D_
      console.log(this.value);_x000D_
      // disable input if you want_x000D_
      //$("#"+id).prop('disabled', true);_x000D_
    });
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
    <div id="panel">_x000D_
      <table>_x000D_
        <tr>_x000D_
           <td><input id="Search_NazovProjektu" type="text" value="Naz Val" /></td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
           <td><input id="Search_Popis" type="text" value="Po Val" /></td>_x000D_
        </tr>_x000D_
      </table>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How to remove the last character from a string?

    public String removeLastChar(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        return s.substring(0, s.length()-1);
    }
    

    Adding value labels on a matplotlib bar chart

    If you only want to add Datapoints above the bars, you could easily do it with:

     for i in range(len(frequencies)): # your number of bars
        plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument 
        y = y_values[i]+1, #takes your y values as vertical positioning argument 
        s = data_labels[i], # the labels you want to add to the data
        size = 9) # font size of datalabels
    

    Any way to generate ant build.xml file automatically from Eclipse?

    I've had the same problem, our work environment is based on Eclipse Java projects, and we needed to build automatically an ANT file so that we could use a continuous integration server (Jenkins, in our case).

    We rolled out our own Eclipse Java to Ant tool, which is now available on GitHub:

    ant-build-for-java

    To use it, call:

    java -jar ant-build-for-java.jar <folder with repositories> [<.userlibraries file>]
    

    The first argument is the folder with the repositories. It will search the folder recursively for any .project file. The tool will create a build.xml in the given folder.

    Optionally, the second argument can be an exported .userlibraries file, from Eclipse, needed when any of the projects use Eclipse user libraries. The tool was tested only with user libraries using relative paths, it's how we use them in our repo. This implies that JARs and other archives needed by projects are inside an Eclipse project, and referenced from there.

    The tool only supports dependencies from other Eclipse projects and from Eclipse user libraries.

    Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

    I encountered the same problem and finally found out that the <tx:annotaion-driven /> was not defined within the [dispatcher]-servlet.xml where component-scan element enabled @service annotated class.

    Simply put <tx:annotaion-driven /> with component-scan element together, the problem disappeared.

    How to get setuptools and easy_install?

    please try to install the dependencie with pip, run this command:

    sudo pip install -U setuptools
    

    How can I make a menubar fixed on the top while scrolling

    The postition:absolute; tag positions the element relative to it's immediate parent. I noticed that even in the examples, there isn't room for scrolling, and when i tried it out, it didn't work. Therefore, to pull off the facebook floating menu, the position:fixed; tag should be used instead. It displaces/keeps the element at the given/specified location, and the rest of the page can scroll smoothly - even with the responsive ones.

    Please see CSS postion attribute documentation when you can :)

    sqlalchemy IS NOT NULL select

    In case anyone else is wondering, you can use is_ to generate foo IS NULL:

    >>> from sqlalchemy.sql import column
    >>> print column('foo').is_(None)
    foo IS NULL
    >>> print column('foo').isnot(None)
    foo IS NOT NULL
    

    Passing a variable from node.js to html

    I figured it out I was able to pass a variable like this

    <script>var name = "<%= name %>";</script>
    console.log(name);
    

    Is Ruby pass by reference or by value?

    It should be noted that you do not have to even use the "replace" method to change the value original value. If you assign one of the hash values for a hash, you are changing the original value.

    def my_foo(a_hash)
      a_hash["test"]="reference"
    end;
    
    hash = {"test"=>"value"}
    my_foo(hash)
    puts "Ruby is pass-by-#{hash["test"]}"
    

    How do you tell if a checkbox is selected in Selenium for Java?

    public boolean getcheckboxvalue(String element)
        {   
            WebElement webElement=driver.findElement(By.xpath(element));
            return webElement.isSelected();
        }
    

    PHP Fatal error: Cannot access empty property

    Interesting:

    1. You declared an array var $my_value = array();
    2. Pushed value into it $a->my_value[] = 'b';
    3. Assigned a string to variable. (so it is no more array) $a->set_value ('c');
    4. Tried to push a value into array, that does not exist anymore. (it's string) $a->my_class('d');

    And your foreach wont work anymore.

    How to convert SQL Server's timestamp column to datetime format

    Some of them actually does covert to a date-time from SQL Server 2008 onwards.

    Try the following SQL query and you will see for yourself:

    SELECT CAST (0x00009CEF00A25634 AS datetime)
    

    The above will result in 2009-12-30 09:51:03:000 but I have encountered ones that actually don't map to a date-time.

    C#: calling a button event handler method without actually clicking the button

    It's just a method on your form, you can call it just like any other method. You just have to create an EventArgs object to pass to it, (and pass it the handle of the button as sender)

    What is the difference between single-quoted and double-quoted strings in PHP?

    Example of single, double, heredoc, and nowdoc quotes

    <?php
    
        $fname = "David";
    
        // Single quotes
        echo 'My name is $fname.'; // My name is $fname.
    
        // Double quotes
        echo "My name is $fname."; // My name is David.
    
        // Curly braces to isolate the name of the variable
        echo "My name is {$fname}."; // My name is David.
    
        // Example of heredoc
        echo $foo = <<<abc
        My name is {$fname}
        abc;
    
            // Example of nowdoc
            echo <<< 'abc'
            My name is "$name".
            Now, I am printing some
        abc;
    
    ?>
    

    What is the difference between '@' and '=' in directive scope in AngularJS?

    Simply we can use:-

    1. @ :- for String values for one way Data binding. in one way data binding you can only pass scope value to directive

    2. = :- for object value for two way data binding. in two way data binding you can change the scope value in directive as well as in html also.

    3. & :- for methods and functions.

    EDIT

    In our Component definition for Angular version 1.5 And above
    there are four different type of bindings:

    1. = Two-way data binding :- if we change the value,it automatically update
    2. < one way binding :- when we just want to read a parameter from a parent scope and not update it.

    3. @ this is for String Parameters

    4. & this is for Callbacks in case your component needs to output something to its parent scope

    Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

    The behavior depends on which version your repository has. Subversion 1.5 allows 4 types of merge:

    1. merge sourceURL1[@N] sourceURL2[@M] [WCPATH]
    2. merge sourceWCPATH1@N sourceWCPATH2@M [WCPATH]
    3. merge [-c M[,N...] | -r N:M ...] SOURCE[@REV] [WCPATH]
    4. merge --reintegrate SOURCE[@REV] [WCPATH]

    Subversion before 1.5 only allowed the first 2 formats.

    Technically you can perform all merges with the first two methods, but the last two enable subversion 1.5's merge tracking.

    TortoiseSVN's options merge a range or revisions maps to method 3 when your repository is 1.5+ or to method one when your repository is older.

    When merging features over to a release/maintenance branch you should use the 'Merge a range of revisions' command.

    Only when you want to merge all features of a branch back to a parent branch (commonly trunk) you should look into using 'Reintegrate a branch'.

    And the last command -Merge two different trees- is only usefull when you want to step outside the normal branching behavior. (E.g. Comparing different releases and then merging the differenct to yet another branch)

    Reading string by char till end of line C/C++

    The answer to your original question

    How to read a string one char at the time, and stop when you reach end of line?

    is, in C++, very simply, namely: use getline. The link shows a simple example:

    #include <iostream>
    #include <string>
    int main () {
      std::string name;
      std::cout << "Please, enter your full name: ";
      std::getline (std::cin,name);
      std::cout << "Hello, " << name << "!\n";
      return 0;
    }
    

    Do you really want to do this in C? I wouldn't! The thing is, in C, you have to allocate the memory in which to place the characters you read in? How many characters? You don't know ahead of time. If you allocate too few characters, you will have to allocate a new buffer every time to realize you reading more characters than you made room for. If you over-allocate, you are wasting space.

    C is a language for low-level programming. If you are new to programming and writing simple applications for reading files line-by-line, just use C++. It does all that memory allocation for you.

    Your later questions regarding "\0" and end-of-lines in general were answered by others and do apply to C as well as C++. But if you are using C, please remember that it's not just the end-of-line that matters, but memory allocation as well. And you will have to be careful not to overrun your buffer.

    SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

    I had wrong entry in hosts file under C:\Windows\System32\drivers\etc

    [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.
    

    Make sure to have entry like below

    127.0.0.1   localhost
    127.0.0.1   localhost   servername
    

    WARNING: Can't verify CSRF token authenticity rails

    For those of you that do need a non jQuery answer you can simple add the following:

    xmlhttp.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
    

    A very simple example can be sen here:

    xmlhttp.open("POST","example.html",true);
    xmlhttp.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
    xmlhttp.send();
    

    Does Spring Data JPA have any way to count entites using method name resolving?

    If anyone wants to get the count with based on multiple conditions than here is a sample custom query

    @Query("select count(sl) from SlUrl sl where sl.user =?1 And sl.creationDate between ?2 And ?3")
        long countUrlsBetweenDates(User user, Date date1, Date date2);
    

    Using IS NULL or IS NOT NULL on join conditions - Theory question

    Actually NULL filter is not being ignored. Thing is this is how joining two tables work.

    I will try to walk down with the steps performed by database server to make it understand. For example when you execute the query which you said is ignoring the NULL condition. SELECT * FROM shipments s LEFT OUTER JOIN returns r
    ON s.id = r.id AND r.id is null WHERE s.day >= CURDATE() - INTERVAL 10 DAY

    1st thing happened is all the rows from table SHIPMENTS get selected

    on next step database server will start selecting one by one record from 2nd(RETURNS) table.

    on third step the record from RETURNS table will be qualified against the join conditions you have provided in the query which in this case is (s.id = r.id and r.id is NULL)

    note that this qualification applied on third step only decides if server should accept or reject the current record of RETURNS table to append with the selected row of SHIPMENT table. It can in no way effect the selection of record from SHIPMENT table.

    And once server is done with joining two tables which contains all the rows of SHIPMENT table and selected rows of RETURNS table it applies the where clause on the intermediate result. so when you put (r.id is NULL) condition in where clause than all the records from the intermediate result with r.id = null gets filtered out.

    JavaScript: Parsing a string Boolean value?

    You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:

    function test (input) {
        try {
            return !!$.parseJSON(input.toLowerCase());
        } catch (e) { }
    }
    

    How to generate serial version UID in Intellij

    Easiest method: Alt+Enter on

    private static final long serialVersionUID = ;
    

    IntelliJ will underline the space after the =. put your cursor on it and hit alt+Enter (Option+Enter on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.

    How do I change the UUID of a virtual disk?

    The following worked for me:

    1. run VBoxManage internalcommands sethduuid "VDI/VMDK file" twice (the first time is just to conveniently generate an UUID, you could use any other UUID generation method instead)

    2. open the .vbox file in a text editor

    3. replace the UUID found in Machine uuid="{...}" with the UUID you got when you ran sethduuid the first time

    4. replace the UUID found in HardDisk uuid="{...}" and in Image uuid="{}" (towards the end) with the UUID you got when you ran sethduuid the second time

    javascript date to string

    I like Daniel Cerecedo's answer using toJSON() and regex. An even simpler form would be:

    var now = new Date();
    var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/;
    var token_array = regex.exec(now.toJSON());
    // [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ]
    var myFormat = token_array.slice(1).join('');
    // "20171031022445"
    

    Typescript ReferenceError: exports is not defined

    For some ASP.NET projects import and export may not be used at all in your Typescripts.

    The question's error showed up when I attempted to do so and I only discovered later that I just needed to add the generated JS script to the View like so:

    <script src="~/scripts/js/[GENERATED_FILE].Index.js" asp-append-version="true"></script>
    

    Get nodes where child node contains an attribute

    //book[title[@lang='it']]
    

    is actually equivalent to

     //book[title/@lang = 'it']
    

    I tried it using vtd-xml, both expressions spit out the same result... what xpath processing engine did you use? I guess it has conformance issue Below is the code

    import com.ximpleware.*;
    public class test1 {
      public static void main(String[] s) throws Exception{
          VTDGen vg = new VTDGen();
          if (vg.parseFile("c:/books.xml", true)){
              VTDNav vn = vg.getNav();
              AutoPilot ap = new AutoPilot(vn);
              ap.selectXPath("//book[title[@lang='it']]");
                      //ap.selectXPath("//book[title/@lang='it']");
    
              int i;
              while((i=ap.evalXPath())!=-1){
                  System.out.println("index ==>"+i);
              }
              /*if (vn.endsWith(i, "< test")){
                 System.out.println(" good ");  
              }else
                  System.out.println(" bad ");*/
    
          }
      }
    }
    

    #include errors detected in vscode

    For Windows:

    1. Please add this directory to your environment variable(Path):

    C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin\

    1. For Include errors detected, mention the path of your include folder into

    "includePath": [ "C:/mingw-w64/x86_64-8.1.0-win32-seh-rt_v6-rev0/mingw64/include/" ]

    , as this is the path from where the compiler fetches the library to be included in your program.

    If statement with String comparison fails

    If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.

    How to retrieve form values from HTTPPOST, dictionary or?

    Simply, you can use FormCollection like:

    [HttpPost] 
    public ActionResult SubmitAction(FormCollection collection)
    {
         // Get Post Params Here
     string var1 = collection["var1"];
    }
    

    You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:

    //Defined in another file
    class MyForm
    {
      public string var1 { get; set; }
    }
    
    [HttpPost]
    public ActionResult SubmitAction(MyForm form)
    {      
      string var1 = form1.Var1;
    }
    

    ng: command not found while creating new project using angular-cli

    Make sure that the npm directory is in your "Path" variable.

    If the module is installed properly, it may work if you start it out of your global node module directory, but your command line tool doesn't know where to find the ng command when you are not in this directory.

    For Win system variable add something like:

    %USERPROFILE%\AppData\Roaming\npm
    

    And if you use a unix-like terminal (emulator):

    PATH=$PATH:[path_to_your_user_profile]/path-to-npm
    

    Best practices for SQL varchar column length

    Always check with your business domain expert. If that's you, look for an industry standard. If, for example, the domain in question is a natural person's family name (surname) then for a UK business I'd go to the UK Govtalk data standards catalogue for person information and discover that a family name will be between 1 and 35 characters.

    How to increase maximum execution time in php

    You can try to set_time_limit(n). However, if your PHP setup is running in safe mode, you can only change it from the php.ini file.

    How to set headers in http get request?

    Go's net/http package has many functions that deal with headers. Among them are Add, Del, Get and Set methods. The way to use Set is:

    func yourHandler(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("header_name", "header_value")
    }
    

    JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

    - First to me Iterating and Looping are 2 different things.

    Eg: Increment a variable till 5 is Looping.

        int count = 0;
    
        for (int i=0 ; i<5 ; i++){
    
            count = count + 1;
    
       }
    

    Eg: Iterate over the Array to print out its values, is about Iteration

        int[] arr = {5,10,15,20,25};
    
        for (int i=0 ; i<arr.length ; i++){
    
            System.out.println(arr[i]);
    
       }
    

    Now about all the Loops:

    - Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...

    For Loop :

    int sum = 0; 
    
    for (int i = 1; i <= 100; i++) {
    
      sum += i; 
    
    }
    
     System.out.println("The sum is " + sum);
    

    The Difference between While and Do-While is as Follows :

    - While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.

    - Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.

    While Loop :

    int sum = 0; 
    int i = 0;       // i is 0 Here
    
        while (i<100) {
    
          sum += i; 
          i++;
    
        }
    
      System.out.println("The sum is " + sum);
    

    do-While :

    int sum = 0; 
    int i = 0;      // i is 0 Here
    
        do{ 
    
          sum += i; 
           i++
        }while(i < 100; );
    
         System.out.println("The sum is " + sum);
    

    From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.

    ArrayList<String> arr = new ArrayList<String>();
    
    arr.add("Vivek");
    arr.add("Is");
    arr.add("Good");
    arr.add("Boy");
    
    for (String str : arr){         // str represents the value in each index of arr
    
        System.out.println(str);     
    
     }
    

    How do I enable php to work with postgresql?

    You need to install the pgsql module for php. In debian/ubuntu is something like this:

    sudo apt-get install php5-pgsql
    

    Or if the package is installed, you need to enable de module in php.ini

    extension=php_pgsql.dll (windows)
    extension=php_pgsql.so (linux)
    

    Greatings.

    How do I compare two variables containing strings in JavaScript?

    You can use javascript dedicate string compare method string1.localeCompare(string2). it will five you -1 if the string not equals, 0 for strings equal and 1 if string1 is sorted after string2.

    <script>
        var to_check=$(this).val();
        var cur_string=$("#0").text();
        var to_chk = "that";
        var cur_str= "that";
        if(to_chk.localeCompare(cur_str) == 0){
            alert("both are equal");
            $("#0").attr("class","correct");    
        } else {
            alert("both are not equal");
            $("#0").attr("class","incorrect");
        }
    </script>
    

    Best way to create enum of strings?

    If you do not want to use constructors, and you want to have a special name for the method, try it this:

    public enum MyType {
      ONE {
          public String getDescription() {
              return "this is one";
          }
      },    
      TWO {
          public String getDescription() {
              return "this is two";
          }
      };
    
      public abstract String getDescription();
    }
    

    I suspect that this is the quickest solution. There is no need to use variables final.

    jQuery UI Dialog Box - does not open after being closed

    I had the same problem with jquery-ui overlay dialog box - it would work only once and then stop unless i reload the page. I found the answer in one of their examples -
    Multiple overlays on a same page
    flowplayer_tools_multiple_open_close
    - who would have though, right?? :-) -

    the important setting appeared to be

    oneInstance: false
    

    so, now i have it like this -

    $(document).ready(function() {
    
     var overlays = null;
    
     overlays = jQuery("a[rel]");
    
     for (var n = 0; n < overlays.length; n++) {
    
        $(overlays[n]).overlay({
            oneInstance: false, 
            mask: '#669966',
            effect: 'apple',
            onBeforeLoad: function() {
                overlay_before_load(this);
            }
        });
    
      }
    
    }
    

    and everything works just fine

    hope this helps somebody

    O.

    How can I change Eclipse theme?

    In the eclipse Version: 2019-09 R (4.13.0) on windows Go to Window > preferences > Appearance Select the required theme for dark theme to choose Dark and click on Ok. enter image description here

    How to restrict user to type 10 digit numbers in input element?

    simply include parsley.js file in your document and in input element of mobile number enter this

    data-parsley-type= "number" data-parsley-length="[10,10]" data-parsley-length-message= "Enter a Mobile Number"

    you can change the message according to your requirement you also need to initialize parsley.js file in your document by writing

     <script type="text/javascript">
    
            $(document).ready(function() {
                $('form').parsley();
            });
        </script>   
    

    ---above code in your document.***

    How can I make a TextArea 100% width without overflowing when padding is present in CSS?

    The answer to many CSS formatting problems seems to be "add another <div>!"

    So, in that spirit, have you tried adding a wrapper div to which the border/padding are applied and then putting the 100% width textarea inside of that? Something like (untested):

    _x000D_
    _x000D_
    textarea_x000D_
    {_x000D_
      width:100%;_x000D_
    }_x000D_
    .textwrapper_x000D_
    {_x000D_
      border:1px solid #999999;_x000D_
      margin:5px 0;_x000D_
      padding:3px;_x000D_
    }
    _x000D_
    <div style="display: block;" id="rulesformitem" class="formitem">_x000D_
      <label for="rules" id="ruleslabel">Rules:</label>_x000D_
      <div class="textwrapper"><textarea cols="2" rows="10" id="rules"/></div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How to convert DataSet to DataTable

    DataSet is collection of DataTables.... you can get the datatable from DataSet as below.

    //here ds is dataset
    DatTable dt = ds.Table[0]; /// table of dataset
    

    how to convert current date to YYYY-MM-DD format with angular 2

    Try this below code it is also works well in angular 2

    <span>{{current_date | date: 'yyyy-MM-dd'}}</span>
    

    How can I access "static" class variables within class methods in Python?

    As with all good examples, you've simplified what you're actually trying to do. This is good, but it is worth noting that python has a lot of flexibility when it comes to class versus instance variables. The same can be said of methods. For a good list of possibilities, I recommend reading Michael Fötsch' new-style classes introduction, especially sections 2 through 6.

    One thing that takes a lot of work to remember when getting started is that python is not java. More than just a cliche. In java, an entire class is compiled, making the namespace resolution real simple: any variables declared outside a method (anywhere) are instance (or, if static, class) variables and are implicitly accessible within methods.

    With python, the grand rule of thumb is that there are three namespaces that are searched, in order, for variables:

    1. The function/method
    2. The current module
    3. Builtins

    {begin pedagogy}

    There are limited exceptions to this. The main one that occurs to me is that, when a class definition is being loaded, the class definition is its own implicit namespace. But this lasts only as long as the module is being loaded, and is entirely bypassed when within a method. Thus:

    >>> class A(object):
            foo = 'foo'
            bar = foo
    
    
    >>> A.foo
    'foo'
    >>> A.bar
    'foo'
    

    but:

    >>> class B(object):
            foo = 'foo'
            def get_foo():
                return foo
            bar = get_foo()
    
    
    
    Traceback (most recent call last):
      File "<pyshell#11>", line 1, in <module>
        class B(object):
      File "<pyshell#11>", line 5, in B
        bar = get_foo()
      File "<pyshell#11>", line 4, in get_foo
        return foo
    NameError: global name 'foo' is not defined
    

    {end pedagogy}

    In the end, the thing to remember is that you do have access to any of the variables you want to access, but probably not implicitly. If your goals are simple and straightforward, then going for Foo.bar or self.bar will probably be sufficient. If your example is getting more complicated, or you want to do fancy things like inheritance (you can inherit static/class methods!), or the idea of referring to the name of your class within the class itself seems wrong to you, check out the intro I linked.

    jQuery.click() vs onClick

    Well, one of the main ideas behind jQuery is to separate JavaScript from the nasty HTML code. The first method is the way to go.

    Conda environments not showing up in Jupyter Notebook

    First you need to activate your environment .

    pip install ipykernel
    

    Next you can add your virtual environment to Jupyter by typing:

    python -m ipykernel install --name = my_env
    

    Why is width: 100% not working on div {display: table-cell}?

    Putting display:table; inside .outer-wrapper seemed to work...

    JSFiddle Link


    EDIT: Two Wrappers Using Display Table Cell

    I would comment on your answer but i have too little rep :( anyways...

    Going off your answer, seems like all you need to do is add display:table; inside .outer-wrapper (Dejavu?), and you can get rid of table-wrapper whole-heartedly.

    JSFiddle

    But yeah, the position:absolute lets you place the div over the img, I read too quickly and thought that you couldn't use position:absolute at all, but seems like you figured it out already. Props!

    I'm not going to post the source code, after all its 99% timshutes's work, so please refer to his answer, or just use my jsfiddle link

    Update: One Wrapper Using Flexbox

    It's been a while, and all the cool kids are using flexbox:

    <div style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
        stuff to be centered
    </div>
    

    Full JSFiddle Solution

    Browser Support (source): IE 11+, FireFox 42+, Chrome 46+, Safari 8+, iOS 8.4+ (-webkit- prefix), Android 4.1+ (-webkit- prefix)

    CSS Tricks: a Guide to Flexbox

    How to Center in CSS: input how you want your content to be centered, and it outputs how to do it in html and css. The future is here!

    ROW_NUMBER() in MySQL

    Solutions with cross join and comma won't work if your query has GROUP BY statement. For such cases you can use subselect:

    SELECT (@row_number := @row_number + 1) AS rowNumber, res.*
    FROM
    (
      SELECT SUM(r.amount) 
      FROM Results r 
      WHERE username = 1 
      GROUP BY r.amount
    ) res
    CROSS JOIN (SELECT @row_number := 0) AS dummy
    

    SQL Server format decimal places with commas

    If you are using SQL Azure Reporting Services, the "format" function is unsupported. This is really the only way to format a tooltip in a chart in SSRS. So the workaround is to return a column that has a string representation of the formatted number to use for the tooltip. So, I do agree that SQL is not the place for formatting. Except in cases like this where the tool does not have proper functions to handle display formatting.

    In my case I needed to show a number formatted with commas and no decimals (type decimal 2) and ended up with this gem of a calculated column in my dataset query:

    ,Fmt_DDS=reverse(stuff(reverse(CONVERT(varchar(25),cast(SUM(kv.DeepDiveSavingsEst) as money),1)), 1, 3, ''))

    It works, but is very ugly and non-obvious to whoever maintains the report down the road. Yay Cloud!

    Converting NumPy array into Python List structure?

    The numpy .tolist method produces nested lists if the numpy array shape is 2D.

    if flat lists are desired, the method below works.

    import numpy as np
    from itertools import chain
    
    a = [1,2,3,4,5,6,7,8,9]
    print type(a), len(a), a
    npa = np.asarray(a)
    print type(npa), npa.shape, "\n", npa
    npa = npa.reshape((3, 3))
    print type(npa), npa.shape, "\n", npa
    a = list(chain.from_iterable(npa))
    print type(a), len(a), a`
    

    how to specify new environment location for conda create

    like Paul said, use

    conda create --prefix=/users/.../yourEnvName python=x.x
    

    if you are located in the folder in which you want to create your virtual environment, just omit the path and use

    conda create --prefix=yourEnvName python=x.x
    

    conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with

    source activate yourEnvName
    

    .toLowerCase not working, replacement function?

    It is a number, not a string. Numbers don't have a toLowerCase() function because numbers do not have case in the first place.

    To make the function run without error, run it on a string.

    var ans = "334";
    

    Of course, the output will be the same as the input since, as mentioned, numbers don't have case in the first place.

    Getting the "real" Facebook profile picture URL from graph API

    I realize this is late, but there is another way to obtain the URL of the profile image.

    To your original url, you can add the parameter redirect=false to obtain the actual URL of the image you'd normally be redirected to.

    So, the new request would look like http://graph.facebook.com/517267866/picture?type=large&redirect=false. This will return a JSON object containing the URL of the picture and a boolean is_silhouette (true if the picture is the default Facebook picture).

    The picture will be of the size you specified, as well. You can test this additionally by adding dimensions: http://graph.facebook.com/517267866/picture?type=large&redirect=false&width=400&height=400

    Error message "Linter pylint is not installed"

    I had this issue as well and found the error's log regarding permissions or something.

    So, I ran Visual Studio Code with administrator privileges and ran "pip install pylint" in the terminal. Then the error seemed to be fixed.

    (I run Visual Studio Code on Windows 10.)

    Debugging iframes with Chrome developer tools

    When the iFrame points to your site like this:

    <html>
      <head>
        <script type="text/javascript" src="/jquery.js"></script>
      </head>
      <body>
        <iframe id="my_frame" src="/wherev"></iframe>
      </body>
    </html>
    

    You can access iFrame DOM through this kind of thing.

    var iframeBody = $(window.my_frame.document.getElementsByTagName("body")[0]);
    iframeBody.append($("<h1/>").html("Hello world!"));
    

    Count distinct values

    You can use this:

    select count(customer) as count, pets
    from table
    group by pets
    

    href="javascript:" vs. href="javascript:void(0)"

    Using 'javascript:void 0' will do cause problem in IE

    when you click the link, it will trigger onbeforeunload event of window !

    <!doctype html>
    <html>
    <head>
    </head>
    <body>
    <a href="javascript:void(0);" >Click me!</a>
    <script>
    window.onbeforeunload = function() {
        alert( 'oops!' );
    };
    </script>
    </body>
    </html>
    

    How do I add a .click() event to an image?

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script> 
    <script type="text/javascript" src="jquery-2.1.0.js"></script> 
    <script type="text/javascript" >
    function openOnImageClick()
    {
    //alert("Jai Sh Raam");
    // document.getElementById("images").src = "fruits.jpg";
     var img = document.createElement('img');
     img.setAttribute('src', 'tiger.jpg');
      img.setAttribute('width', '200');
       img.setAttribute('height', '150');
      document.getElementById("images").appendChild(img);
    
    
    }
    
    
    </script>
    </head>
    <body>
    
    <h1>Screen Shot View</h1>
    <p>Click the Tiger to display the Image</p>
    
    <div id="images" >
    </div>
    
    <img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
    <img src="Logo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
    
    </body>
    </html> 
    

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

    For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'}); only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)

    It could just be something that runs once the first time you initialize collapse with those parameters.

    You will have more luck using the show and hide methods.

    Here is an example:

    $(function() {
    
      var $active = true;
    
      $('.panel-title > a').click(function(e) {
        e.preventDefault();
      });
    
      $('.collapse-init').on('click', function() {
        if(!$active) {
          $active = true;
          $('.panel-title > a').attr('data-toggle', 'collapse');
          $('.panel-collapse').collapse('hide');
          $(this).html('Click to disable accordion behavior');
        } else {
          $active = false;
          $('.panel-collapse').collapse('show');
          $('.panel-title > a').attr('data-toggle','');
          $(this).html('Click to enable accordion behavior');
        }
      });
    
    });
    

    http://bootply.com/98201

    Update

    Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.

    I don't understand what's going on or why the show seemed to be toggling in some places.

    But After messing around for a while.. Finally came with the following solution:

    $(function() {
      var transition = false;
      var $active = true;
    
      $('.panel-title > a').click(function(e) {
        e.preventDefault();
      });
    
      $('#accordion').on('show.bs.collapse',function(){
        if($active){
            $('#accordion .in').collapse('hide');
        }
      });
    
      $('#accordion').on('hidden.bs.collapse',function(){
        if(transition){
            transition = false;
            $('.panel-collapse').collapse('show');
        }
      });
    
      $('.collapse-init').on('click', function() {
        $('.collapse-init').prop('disabled','true');
        if(!$active) {
          $active = true;
          $('.panel-title > a').attr('data-toggle', 'collapse');
          $('.panel-collapse').collapse('hide');
          $(this).html('Click to disable accordion behavior');
        } else {
          $active = false;
          if($('.panel-collapse.in').length){
            transition = true;
            $('.panel-collapse.in').collapse('hide');       
          }
          else{
            $('.panel-collapse').collapse('show');
          }
          $('.panel-title > a').attr('data-toggle','');
          $(this).html('Click to enable accordion behavior');
        }
        setTimeout(function(){
            $('.collapse-init').prop('disabled','');
        },800);
      });
    });
    

    http://bootply.com/98239

    How to get correlation of two vectors in python

    The docs indicate that numpy.correlate is not what you are looking for:

    numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
      Cross-correlation of two 1-dimensional sequences.
      This function computes the correlation as generally defined in signal processing texts:
         z[k] = sum_n a[n] * conj(v[n+k])
      with a and v sequences being zero-padded where necessary and conj being the conjugate.
    

    Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

    from scipy.stats.stats import pearsonr   
    a = [1,4,6]
    b = [1,2,3]   
    print pearsonr(a,b)
    

    This gives

    (0.99339926779878274, 0.073186395040328034)
    

    You can also use numpy.corrcoef:

    import numpy
    print numpy.corrcoef(a,b)
    

    This gives:

    [[ 1.          0.99339927]
     [ 0.99339927  1.        ]]
    

    How to apply a CSS filter to a background image

    $fondo: url(/grid/assets/img/backimage.png);    
    { padding: 0; margin: 0; } 
    body { 
        ::before{
            content:"" ; height: 1008px; width: 100%; display: flex; position: absolute; 
            background-image: $fondo ; background-repeat: no-repeat ; background-position: 
            center; background-size: cover; filter: blur(1.6rem);
        }
    }
    

    How to know the git username and email saved during configuration?

    The command git config --list will list the settings. There you should also find user.name and user.email.

    How to prevent form from being submitted?

    The following works as of now (tested in chrome and firefox):

    <form onsubmit="event.preventDefault(); return validateMyForm();">
    

    where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()

    jQuery - Redirect with post data

    Before document/window ready add "extend" to jQuery :

    $.extend(
    {
        redirectPost: function(location, args)
        {
            var form = '';
            $.each( args, function( key, value ) {
    
                form += '<input type="hidden" name="'+value.name+'" value="'+value.value+'">';
                form += '<input type="hidden" name="'+key+'" value="'+value.value+'">';
            });
            $('<form action="'+location+'" method="POST">'+form+'</form>').submit();
        }
    });
    

    Use :

    $.redirectPost("someurl.com", $("#SomeForm").serializeArray());
    

    Note : this method cant post files .

    How to configure logging to syslog in Python?

    Change the line to this:

    handler = SysLogHandler(address='/dev/log')
    

    This works for me

    import logging
    import logging.handlers
    
    my_logger = logging.getLogger('MyLogger')
    my_logger.setLevel(logging.DEBUG)
    
    handler = logging.handlers.SysLogHandler(address = '/dev/log')
    
    my_logger.addHandler(handler)
    
    my_logger.debug('this is debug')
    my_logger.critical('this is critical')
    

    Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

    I was having this issue for the following reason.

    TLDR: Check if you are sending a GET request that should be sending the parameters on the url instead of on the NSURLRequest's HTTBody property.

    ==================================================

    I had mounted a network abstraction on my app, and it was working pretty well for all my requests.

    I added a new request to another web service (not my own) and it started throwing me this error.

    I went to a playground and started from the ground up building a barebones request, and it worked. So I started moving closer to my abstraction until I found the cause.

    My abstraction implementation had a bug: I was sending a request that was supposed to send parameters encoded in the url and I was also filling the NSURLRequest's HTTBody property with the query parameters as well. As soon as I removed the HTTPBody it worked.

    How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

    Update 2018

    Bootstrap 4

    Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

    .sidebar {
        width: 180px;
        min-height: 100vh;
    }
    
    <div class="row">
        <div class="sidebar p-2">Fixed width</div>
        <div class="col bg-dark text-white pt-2">
            Content
        </div>
    </div>
    

    http://www.codeply.com/go/7LzXiPxo6a

    Bootstrap 3..

    One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

    @media (min-width:768px) {
      #sidebar {
          min-width: 300px;
          max-width: 300px;
      }
      #main {
          width:calc(100% - 300px);
      }
    }
    

    Working Bootstrap 3 Fixed-Fluid Demo

    Related Q&A:
    Fixed width column with a container-fluid in bootstrap
    How to left column fixed and right scrollable in Bootstrap 4, responsive?

    d3 add text to circle

    Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.

    const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]
    
    const nodeElems = svg.append('g')
    .selectAll('circle')
    .data(nodes)
    .enter().append('circle')
    .attr('r',radius)
    .attr('fill', getNodeColor)
    
    const textElems = svg.append('g')
    .selectAll('text')
    .data(nodes)
    .enter().append('text')
    .text(node => node.label)
    .attr('font-size',8)//font size
    .attr('dx', -10)//positions text towards the left of the center of the circle
    .attr('dy',4)
    

    How to gzip all files in all sub-directories into one compressed file in bash

    @amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU system, they can do this:

    tar cvf - folderToCompress | gzip > compressFileName
    

    To expand the archive:

    zcat compressFileName | tar xvf -
    

    How to show the "Are you sure you want to navigate away from this page?" when changes committed?

    Based on all the answers on this thread, I wrote the following code and it worked for me.

    If you have only some input/textarea tags which requires an onunload event to be checked, you can assign HTML5 data-attributes as data-onunload="true"

    for eg.

    <input type="text" data-onunload="true" />
    <textarea data-onunload="true"></textarea>
    

    and the Javascript (jQuery) can look like this :

    $(document).ready(function(){
        window.onbeforeunload = function(e) {
            var returnFlag = false;
            $('textarea, input').each(function(){
                if($(this).attr('data-onunload') == 'true' && $(this).val() != '')
                    returnFlag = true;
            });
    
            if(returnFlag)
                return "Sure you want to leave?";   
        };
    });
    

    How to convert from int to string in objective c: example code

    Simply convert int to NSString use :

      int x=10;
    
      NSString *strX=[NSString stringWithFormat:@"%d",x];
    

    How can I resize an image dynamically with CSS as the browser width/height changes?

    You can use CSS3 scale property to resize image with css:

    .image:hover {
      -webkit-transform:scale(1.2); 
              transform:scale(1.2);
    }
    .image {
      -webkit-transition: all 0.7s ease; 
              transition: all 0.7s ease;
    }
    

    Further Reading:

    How to print a double with two decimals in Android?

    yourTextView.setText(String.format("Value of a: %.2f", a));
    

    Error 405 (Method Not Allowed) Laravel 5

    When use method delete in form then must have to set route delete

    Route::delete("empresas/eliminar/{id}", "CompaniesController@delete");
    

    Is jQuery $.browser Deprecated?

    Updated! 3/24/2015 (scroll below hr)

    lonesomeday's answer is absolutely correct, I just thought I would add this tidbit. I had made a method a while back for getting browser in Vanilla JS and eventually curved it to replace jQuery.browser in later versions of jQuery. It does not interfere with any part of the new jQuery lib, but provides the same functionality of the traditional jQuery.browser object, as well as some other little features.


    New Extended Version!

    Is much more thorough for newer browser. Also, 90+% accuracy on mobile testing! I won't say 100%, as I haven't tested on every mobile browser, but new feature adds $.browser.mobile boolean/string. It's false if not mobile, else it will be a String name for the mobile device or browser (Best Guesss like: Android, RIM Tablet, iPod, etc...).

    One possible caveat, may not work with some older (unsupported) browsers as it is completely reliant on userAgent string.

    JS Minified

    /* quick & easy cut & paste */
    ;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);
    /* quick & easy cut & paste */
    

    jsFiddle "jQuery Plugin: Get Browser (Extended Alt Edition)"

    _x000D_
    _x000D_
    /** jQuery.browser_x000D_
     * @author J.D. McKinstry (2014)_x000D_
     * @description Made to replicate older jQuery.browser command in jQuery versions 1.9+_x000D_
     * @see http://jsfiddle.net/SpYk3/wsqfbe4s/_x000D_
     *_x000D_
     * @extends jQuery_x000D_
     * @namespace jQuery.browser_x000D_
     * @example jQuery.browser.browser == 'browserNameInLowerCase'_x000D_
     * @example jQuery.browser.version_x000D_
     * @example jQuery.browser.mobile @returns BOOLEAN_x000D_
     * @example jQuery.browser['browserNameInLowerCase']_x000D_
     * @example jQuery.browser.chrome @returns BOOLEAN_x000D_
     * @example jQuery.browser.safari @returns BOOLEAN_x000D_
     * @example jQuery.browser.opera @returns BOOLEAN_x000D_
     * @example jQuery.browser.msie @returns BOOLEAN_x000D_
     * @example jQuery.browser.mozilla @returns BOOLEAN_x000D_
     * @example jQuery.browser.webkit @returns BOOLEAN_x000D_
     * @example jQuery.browser.ua @returns navigator.userAgent String_x000D_
     */_x000D_
    ;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);_x000D_
    /* - - - - - - - - - - - - - - - - - - - */_x000D_
    _x000D_
    var b = $.browser;_x000D_
    console.log($.browser);    //    see console, working example of jQuery Plugin_x000D_
    console.log($.browser.chrome);_x000D_
    _x000D_
    for (var x in b) {_x000D_
        if (x != 'init')_x000D_
            $('<tr />').append(_x000D_
                $('<th />', { text: x }),_x000D_
                $('<td />', { text: b[x] })_x000D_
            ).appendTo($('table'));_x000D_
    }
    _x000D_
    table { border-collapse: collapse; }_x000D_
    th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
    th { text-align: right; }_x000D_
    _x000D_
    textarea { height: 500px; width: 100%; }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
    <table></table>
    _x000D_
    _x000D_
    _x000D_

    How to extract svg as file from web page

    They are all logged under Elements in google chromes developer tools.

    page

    _x000D_
    _x000D_
    <svg><path xmlns="http://www.w3.org/2000/svg" d="M18.6 6.8l-4.3-2.2a.8.8 0 0 0-.6 0l-4 2-4.1-2a.7.7 0 0 0-.7.1.7.7 0 0 0-.3.6v10.8a.7.7 0 0 0 .4.6l4.3 2.1a.8.8 0 0 0 .6 0l4-2 4 2a.6.6 0 0 0 .3.1.7.7 0 0 0 .4-.1.7.7 0 0 0 .4-.6V7.4a.7.7 0 0 0-.4-.6zm-1.1 1.4v5.7a.4.4 0 0 1-.6.4c-1.2-.4-.3-2.3-1.1-3.3-.7-.9-1.7 0-2.6-1.4-.9-1.4.3-2.5 1.4-3a.5.5 0 0 1 .4 0l2.2 1.1a.5.5 0 0 1 .3.5zm-6.1 8.3a.5.5 0 0 1-.5-.1 1.6 1.6 0 0 1-.6-1.1c0-.7-1.2-.4-1.2-1.9 0-1.2-1.3-1.5-2.5-1.3a.5.5 0 0 1-.5-.5V7.2a.4.4 0 0 1 .6-.4l2.6 1.3a.1.1 0 0 1 .1 0l.1.1c1.1.6.8 1.1.4 1.9-.5.9-.7 0-1.4-.3s-1.5.3-1.2.8.9 0 1.4.4.5 1.2 1.9.8 1.7-.3 2.2.2a1.5 1.5 0 0 1 0 2.2c-.4.4-.6 1.3-.8 1.9a.5.5 0 0 1-.2.3z"/></svg>
    _x000D_
    _x000D_
    _x000D_

    Calling pylab.savefig without display in ipython

    This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    
    plt.plot([1,2,3])
    plt.savefig('/tmp/test.png')
    

    EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show() when you are ready to display the plots:

    import matplotlib.pyplot as plt
    
    # Turn interactive plotting off
    plt.ioff()
    
    # Create a new figure, plot into it, then close it so it never gets displayed
    fig = plt.figure()
    plt.plot([1,2,3])
    plt.savefig('/tmp/test0.png')
    plt.close(fig)
    
    # Create a new figure, plot into it, then don't close it so it does get displayed
    plt.figure()
    plt.plot([1,3,2])
    plt.savefig('/tmp/test1.png')
    
    # Display all "open" (non-closed) figures
    plt.show()
    

    Best way to check if a Data Table has a null value in it

    You can null/blank/space Etc value using LinQ Use Following Query

       var BlankValueRows = (from dr1 in Dt.AsEnumerable()
                                      where dr1["Columnname"].ToString() == ""
                                      || dr1["Columnname"].ToString() == ""
                                       || dr1["Columnname"].ToString() == ""
                                      select Columnname);
    

    Here Replace Columnname with table column name and "" your search item in above code we looking null value.

    JavaScript by reference vs. by value

    Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.

    An example:

    function changeParam(x, y, z) {
      x = 3;
      y = "new string";
      z["key2"] = "new";
      z["key3"] = "newer";
    
      z = {"new" : "object"};
    }
    
    var a = 1,
        b = "something",
        c = {"key1" : "whatever", "key2" : "original value"};
    
    changeParam(a, b, c);
    
    // at this point a is still 1
    // b is still "something"
    // c still points to the same object but its properties have been updated
    // so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
    // c definitely doesn't point to the new object created as the last line
    // of the function with z = ...
    

    How to get a microtime in Node.js?

    Node.js nanotimer

    I wrote a wrapper library/object for node.js on top of the process.hrtime function call. It has useful functions, like timing synchronous and asynchronous tasks, specified in seconds, milliseconds, micro, or even nano, and follows the syntax of the built in javascript timer so as to be familiar.

    Timer objects are also discrete, so you can have as many as you'd like, each with their own setTimeout or setInterval process running.

    It's called nanotimer. Check it out!

    Is the ternary operator faster than an "if" condition in Java

    Ternary operators are just shorthand. They compile into the equivalent if-else statement, meaning they will be exactly the same.

    Changing fonts in ggplot2

    Another option is to use showtext package which supports more types of fonts (TrueType, OpenType, Type 1, web fonts, etc.) and more graphics devices, and avoids using external software such as Ghostscript.

    # install.packages('showtext', dependencies = TRUE)
    library(showtext)
    

    Import some Google Fonts

    # https://fonts.google.com/featured/Superfamilies
    font_add_google("Montserrat", "Montserrat")
    font_add_google("Roboto", "Roboto")
    

    Load font from the current search path into showtext

    # Check the current search path for fonts
    font_paths()    
    #> [1] "C:\\Windows\\Fonts"
    
    # List available font files in the search path
    font_files()    
    #>   [1] "AcadEref.ttf"                                
    #>   [2] "AGENCYB.TTF"                           
    #> [428] "pala.ttf"                                    
    #> [429] "palab.ttf"                                   
    #> [430] "palabi.ttf"                                  
    #> [431] "palai.ttf"
    
    # syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
    font_add("Palatino", "pala.ttf")
    
    font_families()
    #> [1] "sans"         "serif"        "mono"         "wqy-microhei"
    #> [5] "Montserrat"   "Roboto"       "Palatino"
    
    ## automatically use showtext for new devices
    showtext_auto() 
    

    Plot: need to open Windows graphics device as showtext does not work well with RStudio built-in graphics device

    # https://github.com/yixuan/showtext/issues/7
    # https://journal.r-project.org/archive/2015-1/qiu.pdf
    # `x11()` on Linux, or `quartz()` on Mac OS
    windows()
    
    myFont1 <- "Montserrat"
    myFont2 <- "Roboto"
    myFont3 <- "Palatino"
    
    library(ggplot2)
    
    a <- ggplot(mtcars, aes(x = wt, y = mpg)) + 
      geom_point() +
      ggtitle("Fuel Efficiency of 32 Cars") +
      xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
      theme(text = element_text(size = 16, family = myFont1)) +
      annotate("text", 4, 30, label = 'Palatino Linotype',
               family = myFont3, size = 10) +
      annotate("text", 1, 11, label = 'Roboto', hjust = 0,
               family = myFont2, size = 10) 
    
    ## On-screen device
    print(a) 
    

    ## Save to PNG 
    ggsave("plot_showtext.png", plot = a, 
           type = 'cairo',
           width = 6, height = 6, dpi = 150)  
    
    ## Save to PDF
    ggsave("plot_showtext.pdf", plot = a, 
           device = cairo_pdf,
           width = 6, height = 6, dpi = 150)  
    
    ## turn showtext off if no longer needed
    showtext_auto(FALSE) 
    

    Edit: another workaround to use showtext in RStudio. Run the following code at the beginning of the R session (source)

    trace(grDevices::png, exit = quote({
        showtext::showtext_begin()
    }), print = FALSE)
    

    Edit 2: Starting from version 0.9, showtext can work well with the RStudio graphics device (RStudioGD). Simply call showtext_auto() in the RStudio session and then the plots will be displayed correctly.

    Youtube iframe wmode issue

    Try adding ?wmode=transparent to the end of the URL. Worked for me.

    How can I do string interpolation in JavaScript?

    tl;dr

    Use ECMAScript 2015's Template String Literals, if applicable.

    Explanation

    There is no direct way to do it, as per ECMAScript 5 specifications, but ECMAScript 6 has template strings, which were also known as quasi-literals during the drafting of the spec. Use them like this:

    > var n = 42;
    undefined
    > `foo${n}bar`
    'foo42bar'
    

    You can use any valid JavaScript expression inside the {}. For example:

    > `foo${{name: 'Google'}.name}bar`
    'fooGooglebar'
    > `foo${1 + 3}bar`
    'foo4bar'
    

    The other important thing is, you don't have to worry about multi-line strings anymore. You can write them simply as

    > `foo
    ...     bar`
    'foo\n    bar'
    

    Note: I used io.js v2.4.0 to evaluate all the template strings shown above. You can also use the latest Chrome to test the above shown examples.

    Note: ES6 Specifications are now finalized, but have yet to be implemented by all major browsers.
    According to the Mozilla Developer Network pages, this will be implemented for basic support starting in the following versions: Firefox 34, Chrome 41, Internet Explorer 12. If you're an Opera, Safari, or Internet Explorer user and are curious about this now, this test bed can be used to play around until everyone gets support for this.

    Correct way to detach from a container without stopping it

    If you do "docker attach "container id" you get into the container. To exit from the container without stopping the container you need to enter Ctrl+P+Q

    Parsing a CSV file using NodeJS

    In order to pause the streaming in fast-csv you can do the following:

    let csvstream = csv.fromPath(filePath, { headers: true })
        .on("data", function (row) {
            csvstream.pause();
            // do some heavy work
            // when done resume the stream
            csvstream.resume();
        })
        .on("end", function () {
            console.log("We are done!")
        })
        .on("error", function (error) {
            console.log(error)
        });
    

    How to enable GZIP compression in IIS 7.5

    Global Gzip in HttpModule

    If you don't have access to shared hosting - the final IIS instance. You can create a HttpModule that gets added this code to every HttpApplication.Begin_Request event:-

    HttpContext context = HttpContext.Current;
    context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
    HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
    HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
    

    How to use relative/absolute paths in css URLs?

    Personally, I would fix this in the .htaccess file. You should have access to that.

    Define your CSS URL as such:

    url(/image_dir/image.png);
    

    In your .htacess file, put:

    Options +FollowSymLinks
    RewriteEngine On
    RewriteRule ^image_dir/(.*) subdir/images/$1
    

    or

    RewriteRule ^image_dir/(.*) images/$1
    

    depending on the site.

    useState set method not reflecting change immediately

    // replace
    return <p>hello</p>;
    // with
    return <p>{JSON.stringify(movies)}</p>;
    

    Now you should see, that your code actually does work. What does not work is the console.log(movies). This is because movies points to the old state. If you move your console.log(movies) outside of useEffect, right above the return, you will see the updated movies object.

    How to maximize a plt.show() window using Python

    For backend GTK3Agg, use maximize() -- notably with a lower case m:

    manager = plt.get_current_fig_manager()
    manager.window.maximize()
    

    Tested in Ubuntu 20.04 with Python 3.8.

    Can you test google analytics on a localhost address?

    Following on from Tuong Lu Kim's answer:

    Assuming:

    ga('create', 'UA-XXXXX-Y', 'auto');

    ...if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'....

    Excerpt from:

    Automatic cookie domain configuration sets the _ga cookie on the highest level domain it can. For example, if your website address is blog.example.co.uk, analytics.js will set the cookie domain to .example.co.uk. In addition, if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'.

    The recommended JavaScript tracking snippet sets the string 'auto' for the cookieDomain field:


    Source: https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#automatic_cookie_domain_configuration

    How to run single test method with phpunit?

    You Can try this i am able to run single Test cases

    phpunit tests/{testfilename}
    

    Eg:

    phpunit tests/StackoverflowTest.php
    

    If you want to run single Test cases in Laravel 5.5 Try

    vendor/bin/phpunit tests/Feature/{testfilename} 
    
    vendor/bin/phpunit tests/Unit/{testfilename} 
    

    Eg:

    vendor/bin/phpunit tests/Feature/ContactpageTest.php 
    
    vendor/bin/phpunit tests/Unit/ContactpageTest.php
    

    Javascript change color of text and background to input value

    document.getElementById("fname").style.borderTopColor = 'red';
    document.getElementById("fname").style.borderBottomColor = 'red';
    

    Indenting code in Sublime text 2?

    Select everything, or whatever you want to re-indent and do Alt+ E+L+R. This is really quick and painless.

    Fixed point vs Floating point number

    Take the number 123.456789

    • As an integer, this number would be 123
    • As a fixed point (2), this number would be 123.46 (Assuming you rounded it up)
    • As a floating point, this number would be 123.456789

    Floating point lets you represent most every number with a great deal of precision. Fixed is less precise, but simpler for the computer..

    Uploading files to file server using webclient class

    when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.

    When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).

    How to convert datetime to integer in python

    I think I have a shortcut for that:

    # Importing datetime.
    from datetime import datetime
    
    # Creating a datetime object so we can test.
    a = datetime.now()
    
    # Converting a to string in the desired format (YYYYMMDD) using strftime
    # and then to int.
    a = int(a.strftime('%Y%m%d'))
    

    git rm - fatal: pathspec did not match any files

    using this worked for me

    git rm -f --cached <filename>
    

    Replacing few values in a pandas dataframe column with another value

    loc function can be used to replace multiple values, Documentation for it : loc

    df.loc[df['BrandName'].isin(['ABC', 'AB'])]='A'
    

    OpenCV - DLL missing, but it's not?

    you can find the opencv_core248 and other dlls in opencv\build\x86\vc12\bin folder. Just copy the dlls you require into system32 folder. And your app should start working in a flash ! Hope it helps.

    Install a module using pip for specific python version

    for python2 use:

    py -2 -m pip install beautifulsoup4
    

    Convert a hexadecimal string to an integer efficiently in C?

    Try this to Convert from Decimal to Hex

        #include<stdio.h>
        #include<conio.h>
    
        int main(void)
        {
          int count=0,digit,n,i=0;
          int hex[5];
          clrscr();
          printf("enter a number   ");
          scanf("%d",&n);
    
          if(n<10)
          {
              printf("%d",n);
          }
    
          switch(n)
          {
              case 10:
                  printf("A");
                break;
              case 11:
                  printf("B");
                break;
              case 12:
                  printf("B");
                break;
              case 13:
                  printf("C");
                break;
              case 14:
                  printf("D");
                break;
              case 15:
                  printf("E");
                break;
              case 16:
                  printf("F");
                break;
              default:;
           }
    
           while(n>16)
           {
              digit=n%16;
              hex[i]=digit;
              i++;
              count++;
              n=n/16;
           }
    
           hex[i]=n;
    
           for(i=count;i>=0;i--)
           {
              switch(hex[i])
              {
                 case 10:
                     printf("A");
                   break;
                 case 11:
                     printf("B");
                   break;
                 case 12:
                     printf("C");
                   break;
                 case  13:
                     printf("D");
                   break;
                 case 14:
                     printf("E");
                   break;
                 case 15:
                     printf("F");
                   break;
                 default:
                     printf("%d",hex[i]);
              }
        }
    
        getch();
    
        return 0;
    }
    

    css rotate a pseudo :after or :before content:""

    .process-list:after{
        content: "\2191";
        position: absolute;
        top:50%;
        right:-8px;
        background-color: #ea1f41;
        width:35px;
        height: 35px;
        border:2px solid #ffffff;
        border-radius: 5px;
        color: #ffffff;
        z-index: 10000;
        -webkit-transform: rotate(50deg) translateY(-50%);
        -moz-transform: rotate(50deg) translateY(-50%);
        -ms-transform: rotate(50deg) translateY(-50%);
        -o-transform: rotate(50deg) translateY(-50%);
        transform: rotate(50deg) translateY(-50%);
    }
    

    you can check this code . i hope you will easily understand.

    Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

    You are using the --noImplicitAny and TypeScript doesn't know about the type of the Users object. In this case, you need to explicitly define the user type.

    Change this line:

    let user = Users.find(user => user.id === query);
    

    to this:

    let user = Users.find((user: any) => user.id === query); 
    // use "any" or some other interface to type this argument
    

    Or define the type of your Users object:

    //...
    interface User {
        id: number;
        name: string;
        aliases: string[];
        occupation: string;
        gender: string;
        height: {ft: number; in: number;}
        hair: string;
        eyes: string;
        powers: string[]
    }
    //...
    const Users = <User[]>require('../data');
    //...
    

    reading a line from ifstream into a string variable

    Use the std::getline() from <string>.

     istream & getline(istream & is,std::string& str)
    

    So, for your case it would be:

    std::getline(read,x);
    

    jQuery UI autocomplete with JSON

    I use this script for autocomplete...

    $('#custmoers_name').autocomplete({
        source: function (request, response) {
    
            // $.getJSON("<?php echo base_url('index.php/Json_cr_operation/autosearch_custmoers');?>", function (data) {
              $.getJSON("Json_cr_operation/autosearch_custmoers?term=" + request.term, function (data) {
              console.log(data);
                response($.map(data, function (value, key) {
                    console.log(value);
                    return {
                        label: value.label,
                        value: value.value
                    };
                }));
            });
        },
        minLength: 1,
        delay: 100
    });
    

    My json return :- [{"label":"Mahesh Arun Wani","value":"1"}] after search m

    but it display in dropdown [object object]...

    How to downgrade Xcode to previous version?

    When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools