Programs & Examples On #Udev

Udev manages the Linux /dev directory, and hooks userspace into kernel device events.

Node.js: what is ENOSPC error and how to solve?

Rebooting the machine solved the problem for me. I first tried wiping /tmp/ but node was still complaining.

apache server reached MaxClients setting, consider raising the MaxClients setting

When you use Apache with mod_php apache is enforced in prefork mode, and not worker. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).

So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :

StartServers       20
MinSpareServers    5
MaxSpareServers    10
MaxClients         1024
MaxRequestsPerChild  0

This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.

See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.

Now you set 1024 MaxClients. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.

So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:

<IfModule prefork.c>
  StartServers       12
  MinSpareServers    12
  MaxSpareServers    12
  MaxClients         12
  MaxRequestsPerChild  300
</IfModule>

That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300 means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the ListenBacklog queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).

And yes, that means you cannot handle more than 12 parallel requests.

If you want to handle more requests:

  • buy some more RAM
  • try to use apache in worker mode, but remove mod_php and use php as a parallel daemon with his own pooler settings (this is called php-fpm), connect it with fastcgi. Note that you will certainly need to buy some RAM to allow a big number of parallel php-fpm process, but maybe less than with mod_php
  • Reduce the time spent in your php process. From your cacti graphs you have to potential problems: a real traffic peak around 11:25-11:30 or some php code getting very slow. Fast requests will reduce the number of parallel requests.

If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?

And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.

Update: About internal dummy connections (if it's your problem, but maybe not).

Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.

If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:

  RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
  RewriteRule .* - [F,L]

Update:

Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.

Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l or apache2 -l on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:

<IfModule worker.c>
  StartServers           3
  MaxClients           500
  MinSpareThreads       75
  MaxSpareThreads      250 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:

<IfModule worker.c>
  StartServers           2
  MaxClients           250
  MinSpareThreads       50
  MaxSpareThreads      150 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

Android Debug Bridge (adb) device - no permissions

I'll prepend this postscript here at the top so it won't get lost in my earlier explanation.

I can reliably produce and resolve the no-permissions problem by simply changing the USB connection type from Camera (PTP) to Media device (MTP). The camera mode allows debugging; the media mode causes the no-permissions response in ADB.

The reasoning seems pretty evident after reflecting on that for a moment. Unsecured content on the device would be made accessible by the debugger in media server mode.

===========

The device is unpermissioned until you accept the RSA encryption warning on the debugged device. At some point after connecting, the device will ask to accept the debugging connection. It's a minimal security protocol that ensures you can access the device beyond the initial swipe lock. Developer mode needs to be enabled, I believe.

The "no permissions" flag is actually a good first indicator that adb recognizes the device as a valid debugging target. Notice that it doesn't list your other USB devices.

Details at the following and related pages.

http://developer.android.com/tools/device.html

set up device for development (???????????? no permissions)

When you restart udev, kill adb server & start adb server goto android sdk installation path & do all on sudo. then run adb devices it will solve permission problem.

Understanding the Linux oom-killer's logs

Sum of total_vm is 847170 and sum of rss is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.

Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.

rss for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss and file-rss.

[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB

Android Fastboot devices not returning device

For Windows:

  • Open device manager
  • Find Unknown "Android" device (likely listed under Other devices with an exclamation mark)
  • Update driver
  • Browse my computer for driver software
  • Let me pick from a list of devices, select List All Devices
  • Under "Android device" or "Google Inc", you will find "Android Bootloader Interface"
  • Choose "Android Bootloader Interface"
  • Click "yes" when it says that driver might not be compatible

How to only find files in a given directory, and ignore subdirectories using bash

This may do what you want:

find /dev \( ! -name /dev -prune \) -type f -print

adb devices command not working

You need to restart the adb server as root. See here.

SQLite3 database or disk is full / the database disk image is malformed

To avoid getting "database or disk is full" in the first place, try this if you have lots of RAM:

sqlite> pragma temp_store = 2;

That tells SQLite to put temp files in memory. (The "database or disk is full" message does not mean either that the database is full or that the disk is full! It means the temp directory is full.) I have 256G of RAM but only 2G of /tmp, so this works great for me. The more RAM you have, the bigger db files you can work with.

If you haven't got a lot of ram, try this:

sqlite> pragma temp_store = 1;
sqlite> pragma temp_store_directory = '/directory/with/lots/of/space';

temp_store_directory is deprecated (which is silly, since temp_store is not deprecated and requires temp_store_directory), so be wary of using this in code.

javac error: Class names are only accepted if annotation processing is explicitly requested

I learned that you also can get this error by storing the source file in a folder named Java

Auto code completion on Eclipse

Pressing Ctrl+Space opens up the auto-completion dialog in Eclipse. In the Java Perspective it opens automatically after you typed a . (normally with a short delay).

Sqlite primary key on multiple columns

Since version 3.8.2 of SQLite, an alternative to explicit NOT NULL specifications is the "WITHOUT ROWID" specification: [1]

NOT NULL is enforced on every column of the PRIMARY KEY
in a WITHOUT ROWID table.

"WITHOUT ROWID" tables have potential efficiency advantages, so a less verbose alternative to consider is:

CREATE TABLE t (
  c1, 
  c2, 
  c3, 
  PRIMARY KEY (c1, c2)
 ) WITHOUT ROWID;

For example, at the sqlite3 prompt: sqlite> insert into t values(1,null,3); Error: NOT NULL constraint failed: t.c2

Override intranet compatibility mode IE8

It is possible to override the compatibility mode in intranet.

For IIS, just add the below code to the web.config. Worked for me with IE9.

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <clear />
      <add name="X-UA-Compatible" value="IE=edge" />
    </customHeaders>
  </httpProtocol>
</system.webServer> 

Equivalent for Apache:

Header set X-UA-Compatible: IE=Edge

And for nginx:

add_header "X-UA-Compatible" "IE=Edge";

And for express.js:

res.set('X-UA-Compatible', 'IE=Edge')

Python equivalent of a given wget command

A solution that I often find simpler and more robust is to simply execute a terminal command within python. In your case:

import os
url = 'https://www.someurl.com'
os.system(f"""wget -c --read-timeout=5 --tries=0 "{url}"""")

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I was getting the same error when i upgrade MVC4 to MVC5 version, Firstly i Upgraded the calling assembly which was depends on

> System.Web.WebPages.Razor, Version=2.0.0.0

after that updated the web.config files under the Views folder, updated following packages from

<configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
</configSections>

to

<configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
 </configSections>

and also updated

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

to

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

these steps works for me

How to make a floated div 100% height of its parent?

As long as you don't need to support versions of Internet Explorer earlier than IE8, you can use display: table-cell to accomplish this:

HTML:

<div class="outer">
    <div class="inner">
        <p>Menu or Whatever</p>
    </div>
    <div class="inner">
        <p>Page contents...</p>
    </div>
</div>

CSS:

.inner {
    display: table-cell;
}

This will force each element with the .inner class to occupy the full height of its parent element.

HttpClient won't import in Android Studio

Error:(30, 0) Gradle DSL method not found: 'classpath()' Possible causes:

  • The project 'cid' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0). Upgrade plugin to version 2.3.3 and sync project
  • The project 'cid' may be using a version of Gradle that does not contain the method. Open Gradle wrapper file
  • The build file may be missing a Gradle plugin. Apply Gradle plugin
  • What is the Gradle artifact dependency graph command?

    gradlew -q :app:dependencies > dependencies.txt
    

    Will write all dependencies to the file dependencies.txt

    How to override !important?

    Override using JavaScript

    $('.mytable td').attr('style', 'display: none !important');
    

    Worked for me.

    Create a txt file using batch file in a specific folder

    Changed the set to remove % as that will write to text file as Echo on or off

    echo off
    title Custom Text File
    cls
    set /p txt=What do you want it to say? ; 
    echo %txt% > "D:\Testing\dblank.txt"
    exit
    

    Get timezone from users browser using moment(timezone).js

    Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

    i notice they also user their own library in their website, so you can have a try using the browser console before installing it

    moment().tz(String);
    
    The moment#tz mutator will change the time zone and update the offset.
    
    moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
    moment("2013-11-18").tz("Europe/Berlin").format('Z');   // +01:00
    
    This information is used consistently in other operations, like calculating the start of the day.
    
    var m = moment.tz("2013-11-18 11:55", "America/Toronto");
    m.format();                     // 2013-11-18T11:55:00-05:00
    m.startOf("day").format();      // 2013-11-18T00:00:00-05:00
    m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
    m.startOf("day").format();      // 2013-11-18T00:00:00+01:00
    
    Without an argument, moment#tz returns:
    
        the time zone name assigned to the moment instance or
        undefined if a time zone has not been set.
    
    var m = moment.tz("2013-11-18 11:55", "America/Toronto");
    m.tz();  // America/Toronto
    var m = moment.tz("2013-11-18 11:55");
    m.tz() === undefined;  // true
    

    Shift column in pandas dataframe up by one?

    df.gdp = df.gdp.shift(-1) ## shift up
    df.gdp.drop(df.gdp.shape[0] - 1,inplace = True) ## removing the last row
    

    How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

    I have a project that uses generators a lot and needed this to be automatic, so I copied the index_name function from the rails source to override it. I added this in config/initializers/generated_index_name.rb:

    # make indexes shorter for postgres
    require "active_record/connection_adapters/abstract/schema_statements"
    module ActiveRecord
      module ConnectionAdapters # :nodoc:
        module SchemaStatements
          def index_name(table_name, options) #:nodoc:
            if Hash === options
              if options[:column]
                "ix_#{table_name}_on_#{Array(options[:column]) * '__'}".slice(0,63)
              elsif options[:name]
                options[:name]
              else
                raise ArgumentError, "You must specify the index name"
              end
            else
              index_name(table_name, index_name_options(options))
            end
          end
        end
      end
    end
    

    It creates indexes like ix_assignments_on_case_id__project_id and just truncates it to 63 characters if it's still too long. That's still going to be non-unique if the table name is very long, but you can add complications like shortening the table name separately from the column names or actually checking for uniqueness.

    Note, this is from a Rails 5.2 project; if you decide to do this, copy the source from your version.

    Google Chrome default opening position and size

    You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.

    Excel Reference To Current Cell

    =ADDRESS(ROW(),COLUMN(),4) will give us the relative address of the current cell. =INDIRECT(ADDRESS(ROW(),COLUMN()-1,4)) will give us the contents of the cell left of the current cell =INDIRECT(ADDRESS(ROW()-1,COLUMN(),4)) will give us the contents of the cell above the current cell (great for calculating running totals)

    Using CELL() function returns information about the last cell that was changed. So, if we enter a new row or column the CELL() reference will be affected and will not be the current cell's any longer.

    Error in contrasts when defining a linear model in R

    If the error happens to be because your data has NAs, then you need to set the glm() function options of how you would like to treat the NA cases. More information on this is found in a relevant post here: https://stats.stackexchange.com/questions/46692/how-the-na-values-are-treated-in-glm-in-r

    What to do with commit made in a detached head

    You can just do git merge <commit-number> or git cherry-pick <commit> <commit> ...

    As suggested by Ryan Stewart you may also create a branch from the current HEAD:

    git branch brand-name
    

    Or just a tag:

    git tag tag-name
    

    How to convert a hex string to hex number

    Use format string

    intNum = 123
    print "0x%x"%(intNum)
    

    or hex function.

    intNum = 123
    print hex(intNum)
    

    GROUP_CONCAT comma separator - MySQL

    Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.

    GROUP_CONCAT(artists.artistname SEPARATOR '----')
    

    The way you've written it, you're concatenating artists.artistname with the '----' string using the default comma separator.

    Switching the order of block elements with CSS

    I managed to do it with CSS display: table-*. I haven't tested with more than 3 blocks though.

    fiddle

    How to go to a URL using jQuery?

    //As an HTTP redirect (back button will not work )
    window.location.replace("http://www.google.com");
    
    //like if you click on a link (it will be saved in the session history, 
    //so the back button will work as expected)
    window.location.href = "http://www.google.com";
    

    Android, How can I Convert String to Date?

         import java.text.ParseException;
         import java.text.SimpleDateFormat;
         import java.util.Date;
         public class MyClass 
         {
         public static void main(String args[]) 
         {
         SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
    
         String dateInString = "Wed Mar 14 15:30:00 EET 2018";
    
         SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
    
    
         try {
    
            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatterOut.format(date));
    
             } catch (ParseException e) {
            e.printStackTrace();
             }
        }
        }
    

    here is your Date object date and the output is :

    Wed Mar 14 13:30:00 UTC 2018

    14 Mar 2018

    What are .a and .so files?

    .a files are usually libraries which get statically linked (or more accurately archives), and
    .so are dynamically linked libraries.

    To do a port you will need the source code that was compiled to make them, or equivalent files on your AIX machine.

    Path of assets in CSS files in Symfony 2

    If it can help someone, we have struggled a lot with Assetic, and we are now doing the following in development mode:

    • Set up like in Dumping Asset Files in the dev Environmen so in config_dev.yml, we have commented:

      #assetic:
      #    use_controller: true
      

      And in routing_dev.yml

      #_assetic:
      #    resource: .
      #    type:     assetic
      
    • Specify the URL as absolute from the web root. For example, background-image: url("/bundles/core/dynatree/skins/skin/vline.gif"); Note: our vhost web root is pointing on web/.

    • No usage of cssrewrite filter

    Learning Ruby on Rails

    An excellent source for learning Ruby and Ruby on Rails is at http://www.teachmetocode.com. There are screencasts that cover the basics of Rails, along with a 6-part series on how to create a Twitter clone with Ruby on Rails.

    What does %5B and %5D in POST requests stand for?

    As per this answer over here: str='foo%20%5B12%5D' encodes foo [12]:

    %20 is space
    %5B is '['
    and %5D is ']'
    

    This is called percent encoding and is used in encoding special characters in the url parameter values.

    EDIT By the way as I was reading https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURI#Description, it just occurred to me why so many people make the same search. See the note on the bottom of the page:

    Also note that if one wishes to follow the more recent RFC3986 for URL's, making square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following may help.

    function fixedEncodeURI (str) {
        return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
    }
    

    Hopefully this will help people sort out their problems when they stumble upon this question.

    AngularJs: How to set radio button checked based on model

    Ended up just using the built-in angular attribute ng-checked="model"

    SQL Server 2008: how do I grant privileges to a username?

    If you want to give your user all read permissions, you could use:

    EXEC sp_addrolemember N'db_datareader', N'your-user-name'
    

    That adds the default db_datareader role (read permission on all tables) to that user.

    There's also a db_datawriter role - which gives your user all WRITE permissions (INSERT, UPDATE, DELETE) on all tables:

    EXEC sp_addrolemember N'db_datawriter', N'your-user-name'
    

    If you need to be more granular, you can use the GRANT command:

    GRANT SELECT, INSERT, UPDATE ON dbo.YourTable TO YourUserName
    GRANT SELECT, INSERT ON dbo.YourTable2 TO YourUserName
    GRANT SELECT, DELETE ON dbo.YourTable3 TO YourUserName
    

    and so forth - you can granularly give SELECT, INSERT, UPDATE, DELETE permission on specific tables.

    This is all very well documented in the MSDN Books Online for SQL Server.

    And yes, you can also do it graphically - in SSMS, go to your database, then Security > Users, right-click on that user you want to give permissions to, then Properties adn at the bottom you see "Database role memberships" where you can add the user to db roles.

    alt text

    Removing elements by class name?

    Yes, you have to remove from the parent:

    cur_columns[i].parentNode.removeChild(cur_columns[i]);
    

    getElementById in React

    import React, { useState } from 'react';
    
    function App() {
      const [apes , setap] = useState('yo');
      const handleClick = () =>{
        setap(document.getElementById('name').value)
      };
      return (
        <div>
          <input id='name' />
          <h2> {apes} </h2>
          <button onClick={handleClick} />
      </div>
      );
    }
    
    export default App;
    

    SQL Query Multiple Columns Using Distinct on One Column Only

    you have various ways to distinct values on one column or multi columns.

    • using the GROUP BY

      SELECT DISTINCT MIN(o.tblFruit_ID)  AS tblFruit_ID,
         o.tblFruit_FruitType,
         MAX(o.tblFruit_FruitName)
      FROM   tblFruit  AS o
      GROUP BY
           tblFruit_FruitType
      
    • using the subquery

      SELECT b.tblFruit_ID,
         b.tblFruit_FruitType,
         b.tblFruit_FruitName
      FROM   (
             SELECT DISTINCT(tblFruit_FruitType),
                    MIN(tblFruit_ID) tblFruit_ID
             FROM   tblFruit
             GROUP BY
                    tblFruit_FruitType
         ) AS a
         INNER JOIN tblFruit b
              ON  a.tblFruit_ID = b.tblFruit_I
      
    • using the join with subquery

      SELECT t1.tblFruit_ID,
          t1.tblFruit_FruitType,
          t1.tblFruit_FruitName
      FROM   tblFruit  AS t1
         INNER JOIN (
                  SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
                         tblFruit_FruitType
                  FROM   tblFruit
                  GROUP BY
                         tblFruit_FruitType
              )  AS t2
              ON  t1.tblFruit_ID = t2.tblFruit_ID 
      
    • using the window functions only one column distinct

      SELECT tblFruit_ID,
          tblFruit_FruitType,
          tblFruit_FruitName
      FROM   (
               SELECT tblFruit_ID,
                    tblFruit_FruitType,
                    tblFruit_FruitName,
                    ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID) 
          rn
             FROM   tblFruit
          ) t
          WHERE  rn = 1 
      
    • using the window functions multi column distinct

      SELECT tblFruit_ID,
          tblFruit_FruitType,
          tblFruit_FruitName
      FROM   (
               SELECT tblFruit_ID,
                    tblFruit_FruitType,
                    tblFruit_FruitName,
                    ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType,     tblFruit_FruitName 
          ORDER BY tblFruit_ID) rn
                FROM   tblFruit
           ) t
          WHERE  rn = 1 
      

    Xcode swift am/pm time to 24 hour format

    let calendar = Calendar.current
    let hours    = calendar.component(.hour, from: Date())
    let minutes  = calendar.component(.minute, from: Date())
    let seconds  = calendar.component(.second, from: Date())
    

    HTTP headers in Websockets client API

    Totally hacked it like this, thanks to kanaka's answer.

    Client:

    var ws = new WebSocket(
        'ws://localhost:8080/connect/' + this.state.room.id, 
        store('token') || cookie('token') 
    );
    

    Server (using Koa2 in this example, but should be similar wherever):

    var url = ctx.websocket.upgradeReq.url; // can use to get url/query params
    var authToken = ctx.websocket.upgradeReq.headers['sec-websocket-protocol'];
    // Can then decode the auth token and do any session/user stuff...
    

    SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

    Sometime it's not always rvm's problem in MAC OSX,if you remove .rvm,the problem still(espcially while you backup data from timemachine) ,you can try this way.

    1.brew update
    2.brew install openssl
    

    ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

    @aravk33 's answer is absolutely correct.

    I was going through the same problem. I had a data set of 2450 images. I just could not figure out why I was facing this issue.

    Check the dimensions of all the images in your training data.

    Add the following snippet while appending your image into your list:

    if image.shape==(1,512,512):
        trainx.append(image)
    

    Only variables should be passed by reference

    $file_extension = end(explode('.', $file_name)); //ERROR ON THIS LINE

    change this line as,

    $file_extension = end((explode('.', $file_name))); //no errors

    Technique is simple please put one more brackets for explode,

    (explode()), then only it can perform independently..

    Console.WriteLine and generic List

    public static void WriteLine(this List<int> theList)
    {
      foreach (int i in list)
      {
        Console.Write("{0}\t", t.ToString());
      }
      Console.WriteLine();
    }
    

    Then, later...

    list.WriteLine();
    

    Where does Git store files?

    If you are on an English Windows machine, Git's default storage path will be C:\Documents and Settings\< current_user>\, because on Windows the default Git local settings resides at C:\Documents and Settings\< current_user>\.git and so Git creates a separate folder for each repo/clone at C:\Documents and Settings\< current_user>\ and there are all the directories of cloned project.

    For example, if you install Symfony 2 with

    git clone git://github.com/symfony/symfony.git
    

    the Symfony directory and file will be at

    C:\Documents and Settings\< current_user>\symfony\
    

    How to access the local Django webserver from outside world

    UPDATED 2020 TRY THIS WAY

    python manage.py runserver yourIp:8000
    
    ALLOWED_HOSTS = ["*"]
    

    Source file 'Properties\AssemblyInfo.cs' could not be found

    This rings a bell. I came across a similar problem in the past,

    • if you expand Properties folder of the project can you see 'AssemblyInfo.cs' if not that is where the problem is. An assembly info file consists of all of the build options for the project, including version, company name, GUID, compilers options....etc

    You can generate an assemblyInfo.cs by right clicking the project and chosing properties. In the application tab fill in the details and press save, this will generate the assemblyInfo.cs file for you. If you build your project after that, it should work.

    Cheers, Tarun

    Update 2016-07-08:

    For Visual Studio 2010 through the most recent version (2015 at time of writing), LandedGently's comment still applies:

    After you select project Properties and the Application tab as @Tarun mentioned, there is a button "Assembly Information..." which opens another dialog. You need to at least fill in the Title here. VS will add the GUID and versions, but if the title is empty, it will not create the AssemblyInfo.cs file.

    How to edit/save a file through Ubuntu Terminal

    For editing use

    vi galfit.feedme //if user has file editing permissions
    

    or

    sudo vi galfit.feedme //if user doesn't have file editing permissions
    

    For inserting

    Press i //Do required editing
    

    For exiting

    Press Esc
    
        :wq //for exiting and saving
        :q! //for exiting without saving
    

    Rounding a variable to two decimal places C#

    Make sure you provide a number, typically a double is used. Math.Round can take 1-3 arguments, the first argument is the variable you wish to round, the second is the number of decimal places and the third is the type of rounding.

    double pay = 200 + bonus;
    double pay = Math.Round(pay);
    // Rounds to nearest even number, rounding 0.5 will round "down" to zero because zero is even
    double pay = Math.Round(pay, 2, MidpointRounding.ToEven);
    // Rounds up to nearest number
    double pay = Math.Round(pay, 2, MidpointRounding.AwayFromZero);
    

    How to test an SQL Update statement before running it?

    make a SELECT of it,

    like if you got

    UPDATE users SET id=0 WHERE name='jan'

    convert it to

    SELECT * FROM users WHERE name='jan'

    C++ calling base class constructors

    In c++, compiler always ensure that functions in object hierarchy are called successfully. These functions are constructors and destructors and object hierarchy means inheritance tree.

    According to this rule we can guess compiler will call constructors and destructors for each object in inheritance hierarchy even if we don't implement it. To perform this operation compiler will synthesize the undefined constructors and destructors for us and we name them as a default constructors and destructors.Then, compiler will call default constructor of base class and then calls constructor of derived class.

    In your case you don't call base class constructor but compiler does that for you by calling default constructor of base class because if compiler didn't do it your derived class which is Rectangle in your example will not be complete and it might cause disaster because maybe you will use some member function of base class in your derived class. So for the sake of safety compiler always need all constructor calls.

    Getting current device language in iOS?

    i use this

        NSArray *arr = [NSLocale preferredLanguages];
    for (NSString *lan in arr) {
        NSLog(@"%@: %@ %@",lan, [NSLocale canonicalLanguageIdentifierFromString:lan], [[[NSLocale alloc] initWithLocaleIdentifier:lan] displayNameForKey:NSLocaleIdentifier value:lan]);
    }
    

    ignore memory leak..

    and result is

    2013-03-02 20:01:57.457 xx[12334:907] zh-Hans: zh-Hans ??(????)
    2013-03-02 20:01:57.460 xx[12334:907] en: en English
    2013-03-02 20:01:57.462 xx[12334:907] ja: ja ???
    2013-03-02 20:01:57.465 xx[12334:907] fr: fr français
    2013-03-02 20:01:57.468 xx[12334:907] de: de Deutsch
    2013-03-02 20:01:57.472 xx[12334:907] nl: nl Nederlands
    2013-03-02 20:01:57.477 xx[12334:907] it: it italiano
    2013-03-02 20:01:57.481 xx[12334:907] es: es español
    

    Bootstrap 4 align navbar items to the right

    On Bootsrap 4.0.0-beta.2, none of the answers listed here worked for me. Finally, the Bootstrap site gave me the solution, not via its doc but via its page source code...

    Getbootstrap.com align their right navbar-nav to the right with the help of the following class: ml-md-auto.

    How do I write a Windows batch script to copy the newest file from a directory?

    Windows shell, one liner:

    FOR /F %%I IN ('DIR *.* /B /O:-D') DO COPY %%I <<NewDir>> & EXIT
    

    Can a table row expand and close?

    jQuery

    $(function() {
        $("td[colspan=3]").find("div").hide();
        $("tr").click(function(event) {
            var $target = $(event.target);
            $target.closest("tr").next().find("div").slideToggle();                
        });
    });
    

    HTML

    <table>
        <thead>
            <tr>
                <th>one</th><th>two</th><th>three</th>
            </tr>
        </thead>
        <tbody>
    
            <tr>
                <td><p>data<p></td><td>data</td><td>data</td>
            </tr>
            <tr>
                <td colspan="3">
                    <div>
                        <table>
                                <tr>
                                    <td>data</td><td>data</td>
                                </tr>
                        </table>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
    

    This is much like a previous example above. I found when trying to implement that example that if the table row to be expanded was clicked while it was not expanded it would disappear, and it would no longer be expandable

    To fix that I simply removed the ability to click the expandable element for slide up and made it so that you can only toggle using the above table row.

    I also made some minor changes to HTML and corresponding jQuery.

    NOTE: I would have just made a comment but am not allowed to yet therefore the long post. Just wanted to post this as it took me a bit to figure out what was happening to the disappearing table row.

    Credit to Peter Ajtai

    How to calculate the difference between two dates using PHP?

    I have some simple logic for that:

    <?php
        per_days_diff('2011-12-12','2011-12-29')
        function per_days_diff($start_date, $end_date) {
            $per_days = 0;
            $noOfWeek = 0;
            $noOfWeekEnd = 0;
            $highSeason=array("7", "8");
    
            $current_date = strtotime($start_date);
            $current_date += (24 * 3600);
            $end_date = strtotime($end_date);
    
            $seassion = (in_array(date('m', $current_date), $highSeason))?"2":"1";
    
            $noOfdays = array('');
    
            while ($current_date <= $end_date) {
                if ($current_date <= $end_date) {
                    $date = date('N', $current_date);
                    array_push($noOfdays,$date);
                    $current_date = strtotime('+1 day', $current_date);
                }
            }
    
            $finalDays = array_shift($noOfdays);
            //print_r($noOfdays);
            $weekFirst = array("week"=>array(),"weekEnd"=>array());
            for($i = 0; $i < count($noOfdays); $i++)
            {
                if ($noOfdays[$i] == 1)
                {
                    //echo "This is week";
                    //echo "<br/>";
                    if($noOfdays[$i+6]==7)
                    {
                        $noOfWeek++;
                        $i=$i+6;
                    }
                    else
                    {
                        $per_days++;
                    }
                    //array_push($weekFirst["week"],$day);
                }
                else if($noOfdays[$i]==5)
                {
                    //echo "This is weekend";
                    //echo "<br/>";
                    if($noOfdays[$i+2] ==7)
                    {
                        $noOfWeekEnd++;
                        $i = $i+2;
                    }
                    else
                    {
                        $per_days++;
                    }
                    //echo "After weekend value:- ".$i;
                    //echo "<br/>";
                }
                else
                {
                    $per_days++;
                }
            }
    
            /*echo $noOfWeek;
              echo "<br/>";
              echo $noOfWeekEnd;
              echo "<br/>";
              print_r($per_days);
              echo "<br/>";
              print_r($weekFirst);
            */
    
            $duration = array("weeks"=>$noOfWeek, "weekends"=>$noOfWeekEnd, "perDay"=>$per_days, "seassion"=>$seassion);
            return $duration;
          ?>
    

    How do you programmatically update query params in react-router?

        for react-router v4.3, 
    
     const addQuery = (key, value) => {
      let pathname = props.location.pathname; 
     // returns path: '/app/books'
      let searchParams = new URLSearchParams(props.location.search); 
     // returns the existing query string: '?type=fiction&author=fahid'
      searchParams.set(key, value);
      this.props.history.push({
               pathname: pathname,
               search: searchParams.toString()
         });
     };
    
      const removeQuery = (key) => {
      let pathname = props.location.pathname; 
     // returns path: '/app/books'
      let searchParams = new URLSearchParams(props.location.search); 
     // returns the existing query string: '?type=fiction&author=fahid'
      searchParams.delete(key);
      this.props.history.push({
               pathname: pathname,
               search: searchParams.toString()
         });
     };
    
    
     ```
    
     ```
     function SomeComponent({ location }) {
       return <div>
         <button onClick={ () => addQuery('book', 'react')}>search react books</button>
         <button onClick={ () => removeQuery('book')}>remove search</button>
       </div>;
     }
     ```
    
    
     //  To know more on URLSearchParams from 
    [Mozilla:][1]
    
     var paramsString = "q=URLUtils.searchParams&topic=api";
     var searchParams = new URLSearchParams(paramsString);
    
     //Iterate the search parameters.
     for (let p of searchParams) {
       console.log(p);
     }
    
     searchParams.has("topic") === true; // true
     searchParams.get("topic") === "api"; // true
     searchParams.getAll("topic"); // ["api"]
     searchParams.get("foo") === null; // true
     searchParams.append("topic", "webdev");
     searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
     searchParams.set("topic", "More webdev");
     searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
     searchParams.delete("topic");
     searchParams.toString(); // "q=URLUtils.searchParams"
    
    
    [1]: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
    

    ASP.NET Background image

    You can use this if you want to assign a background image on the backend:

    divContent.Attributes.Add("style"," background-image:
    url('images/icon_stock.gif');");
    

    HTML Tags in Javascript Alert() method

    No, you can use only some escape sequences - \n for example (maybe only this one).

    Pad with leading zeros

    You can do this with a string datatype. Use the PadLeft method:

    var myString = "1";
    myString = myString.PadLeft(myString.Length + 5, '0');
    

    000001

    How to get MAC address of your machine using a C program?

    I have just write one and test it on gentoo in virtualbox.

    // get_mac.c
    #include <stdio.h>    //printf
    #include <string.h>   //strncpy
    #include <sys/socket.h>
    #include <sys/ioctl.h>
    #include <net/if.h>   //ifreq
    #include <unistd.h>   //close
    
    int main()
    {
        int fd;
        struct ifreq ifr;
        char *iface = "enp0s3";
        unsigned char *mac = NULL;
    
        memset(&ifr, 0, sizeof(ifr));
    
        fd = socket(AF_INET, SOCK_DGRAM, 0);
    
        ifr.ifr_addr.sa_family = AF_INET;
        strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
    
        if (0 == ioctl(fd, SIOCGIFHWADDR, &ifr)) {
            mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
    
            //display mac address
            printf("Mac : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
        }
    
        close(fd);
    
        return 0;
    }
    

    Find the line number where a specific word appears with "grep"

    Use grep -n to get the line number of a match.

    I don't think there's a way to get grep to start on a certain line number. For that, use sed. For example, to start at line 10 and print the line number and line for matching lines, use:

    sed -n '10,$ { /regex/ { =; p; } }' file
    

    To get only the line numbers, you could use

    grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/'
    

    Or you could simply use sed:

    sed -n '/regex/=' file
    

    Combining the two sed commands, you get:

    sed -n '10,$ { /regex/= }' file
    

    Fastest way to check if string contains only digits

    Function with empty validation:

    public static bool IsDigitsOnly(string str)
      {             
            return !string.IsNullOrEmpty(str) && str.All(char.IsDigit);
      }
    

    What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

    Example #1:

    class A{
     void met(){
       Class.forName("com.example.Class1");
     }
    }
    

    If com/example/Class1 doesn't exist in any of the classpaths, then It throws ClassNotFoundException.

    Example #2:

    Class B{
      void met(){
       com.example.Class2 c = new com.example.Class2();
     }
    }
    

    If com/example/Class2 existed while compiling B, but not found while execution, then It throws NoClassDefFoundError.

    Both are run time exceptions.

    How to show full height background image?

    This worked for me (though it's for reactjs & tachyons used as inline CSS)

    <div className="pa2 cf vh-100-ns" style={{backgroundImage: `url(${a6})`}}> 
    ........
    </div>
    

    This takes in css as height: 100vh

    OSError: [WinError 193] %1 is not a valid Win32 application

    I got the same error while I forgot to use shell=True in the subprocess.call.

    subprocess.call('python modify_depth_images.py', shell=True)
    

    Running External Command

    To run an external command without interacting with it, such as one would do with os.system(), Use the call() function.

    import subprocess
    
    Simple command subprocess.call(['ls', '-1'], shell=True)
    

    Sequence Permission in Oracle

    Just another bit. in some case i found no result on all_tab_privs! i found it indeed on dba_tab_privs. I think so that this last table is better to check for any grant available on an object (in case of impact analysis). The statement becomes:

        select * from dba_tab_privs where table_name = 'sequence_name';
    

    How do I fetch only one branch of a remote Git repository?

    The simplest way to do that

      git fetch origin <branch> && git checkout <branch>
    

    Example: I want to fetch uat branch from origin and switch to this as the current working branch.

       git fetch origin uat && git checkout uat
    

    How can I check if a string is a number?

    string str = "123";
    int i = Int.Parse(str);
    

    If str is a valid integer string then it will be converted to integer and stored in i other wise Exception occur.

    Is there a limit to the length of a GET request?

    Not in the RFC, no, but there are practical limits.

    The HTTP protocol does not place any a priori limit on the length of a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs. A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).

    Note: Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths.

    What's the difference between import java.util.*; and import java.util.Date; ?

    Your program should work exactly the same with either import java.util.*; or import java.util.Date;. There has to be something else you did in between.

    Check if an object belongs to a class in Java

    The usual way would be:

    if (a instanceof A)
    

    However, there are cases when you can't do this, such as when A in a generic argument.

    Due to Java's type erasure, the following won't compile:

    <A> boolean someMethod(Object a) {
        if (a instanceof A)
        ...
    }
    

    and the following won't work (and will produce an unchecked cast warning):

    <A> void someMethod(Object a) {
        try {
            A casted = (A)a;    
        } catch (ClassCastException e) {
             ...
        }
    }
    

    You can't cast to A at runtime, because at runtime, A is essentially Object.

    The solutions to such cases is to use a Class instead of the generic argument:

    void someMethod(Object a, Class<A> aClass) {
        if (aClass.isInstance(a)) {
           A casted = aClass.cast(a);
           ...
        }
    }
    

    You can then call the method as:

    someMethod(myInstance, MyClass.class);
    someMethod(myInstance, OtherClass.class);
    

    jQuery attr('onclick')

    Felix Kling's way will work, (actually beat me to the punch), but I was also going to suggest to use

    $('#next').die().live('click', stopMoving);

    this might be a better way to do it if you run into problems and strange behaviors when the element is clicked multiple times.

    What is the single most influential book every programmer should read?

    There are a lot of votes for Steve McConnell's Code Complete, but what about his Software Project Survival Guide book? I think they're both required reading but for different reasons.

    How can I disable notices and warnings in PHP within the .htaccess file?

    Fortes is right, thank you.

    When you have a shared hosting it is usual to obtain an 500 server error.

    I have a website with Joomla and I added to the index.php:

    ini_set('display_errors','off');
    

    The error line showed in my website disappeared.

    How do I view the SSIS packages in SQL Server Management Studio?

    The wizard likely created the package as a file. Do a search on your system for files with an extension of .dtsx. This is the actual "SSIS Package" file.

    As for loading it in Management Studio, you don't actually view it through there. If you have SQL Server 2005 loaded on your machine, look in the program group. You should find an application with the same icon as Visual Studio called "SQL Server Business Intelligence Development Studio". It's basically a stripped down version of VS 2005 which allows you to create SSIS packages.

    Create a blank solution and add your .dtsx file to that to edit/view it.

    How to get the request parameters in Symfony 2?

    $request = Request::createFromGlobals();
    $getParameter = $request->get('getParameter');
    

    Calling filter returns <filter object at ... >

    It looks like you're using python 3.x. In python3, filter, map, zip, etc return an object which is iterable, but not a list. In other words,

    filter(func,data) #python 2.x
    

    is equivalent to:

    list(filter(func,data)) #python 3.x
    

    I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.

    If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:

    ( x for x in data if func(x) ) 
    

    As opposed to:

    [ x for x in data if func(x) ]
    

    in python 2.x

    How can I pass a list as a command-line argument with argparse?

    You can parse the list as a string and use of the eval builtin function to read it as a list. In this case, you will have to put single quotes into double quote (or the way around) in order to ensure successful string parse.

    # declare the list arg as a string
    parser.add_argument('-l', '--list', type=str)
    
    # parse
    args = parser.parse()
    
    # turn the 'list' string argument into a list object
    args.list = eval(args.list)
    print(list)
    print(type(list))
    

    Testing:

    python list_arg.py --list "[1, 2, 3]"
    
    [1, 2, 3]
    <class 'list'>
    

    How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

    I'd like to get back to Fiddler. After having played with that for a while, it is clearly the best way to edit any web requests on-the-fly. Being JavaScript, POST, GET, HTML, XML whatever and anything. It's free, but a little tricky to implement. Here's my HOW-TO:

    To use Fiddler to manipulate JavaScript (on-the-fly) with Firefox, do the following:

    1) Download and install Fiddler

    2) Download and install the Fiddler extension: "3 Syntax-Highlighting add-ons"

    3) Restart Firefox and enable the "FiddlerHook" extension

    4) Open Firefox and enable the FiddlerHook toolbar button: View > Toolbars > Customize...

    5) Click the Fiddler tool button and wait for fiddler to start.

    6) Point your browser to Fiddler's test URLs:

    Echo Service:  http://127.0.0.1:8888/
    DNS Lookup:    http://www.localhost.fiddler:8888/
    

    7) Add Fiddler Rules in order to intercept and edit JavaScript before reaching the browser/server. In Fiddler click: Rules > Customize Rules.... [CTRL-R] This will start the ScriptEditor.

    8) Edit and Add the following rules:


    a) To pause JavaScript to allow editing, add under the function "OnBeforeResponse":

    if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "javascript")){
      oSession["x-breakresponse"]="reason is JScript"; 
    }
    

    b) To pause HTTP POSTs to allow editing when using the POST verb, edit "OnBeforeRequest":

    if (oSession.HTTPMethodIs("POST")){
      oSession["x-breakrequest"]="breaking for POST";
    }
    

    c) To pause a request for an XML file to allow editing, edit "OnBeforeRequest":

    if (oSession.url.toLowerCase().indexOf(".xml")>-1){
      oSession["x-breakrequest"]="reason_XML"; 
    }
    

    [9] TODO: Edit the above CustomRules.js to allow for disabling (a-c).

    10) The browser loading will now stop on every JavaScript found and display a red pause mark for every script. In order to continue loading the page you need to click the green "Run to Completion" button for every script. (Which is why we'd like to implement [9].)

    "Multiple definition", "first defined here" errors

    I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format

    <path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
    <path>/linit.o:(.rodata1.libs+0x50): first defined here
    

    I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!

    What's the best mock framework for Java?

    I've been having success with JMockit.

    It's pretty new, and so it's a bit raw and under-documented. It uses ASM to dynamically redefine the class bytecode, so it can mock out all methods including static, private, constructors, and static initializers. For example:

    import mockit.Mockit;
    
    ...
    Mockit.redefineMethods(MyClassWithStaticInit.class,
                           MyReplacementClass.class);
    ...
    class MyReplacementClass {
      public void $init() {...} // replace default constructor
      public static void $clinit{...} // replace static initializer
      public static void myStatic{...} // replace static method
      // etc...
    }
    

    It has an Expectations interface allowing record/playback scenarios as well:

    import mockit.Expectations;
    import org.testng.annotations.Test;
    
    public class ExpecationsTest {
      private MyClass obj;
    
      @Test
      public void testFoo() {
        new Expectations(true) {
          MyClass c;
          {
            obj = c;
            invokeReturning(c.getFoo("foo", false), "bas");
          }
        };
    
        assert "bas".equals(obj.getFoo("foo", false));
    
        Expectations.assertSatisfied();
      }
    
      public static class MyClass {
        public String getFoo(String str, boolean bool) {
          if (bool) {
            return "foo";
          } else {
            return "bar";
          }
        }
      }
    }
    

    The downside is that it requires Java 5/6.

    Last segment of URL in jquery

    window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));
    

    Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.

    If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:

    window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
    

    How to select the row with the maximum value in each group

    Using dplyr 1.0.2 there are now two ways to do this, one is long hand and the other is using the verb across():

          # create data
          ID    <- c(1,1,1,2,2,2,2,3,3)
          Value <- c(2,3,5,2,5,8,17,3,5)
          Event <- c(1,1,2,1,2,1,2,2,2)
          
          group <- data.frame(Subject=ID, pt=Value, Event=Event)
    

    Long hand the verb is max() but note the na.rm = TRUE which is useful for examples where there are NAs as in the closed question: Merge rows in a dataframe where the rows are disjoint and contain NAs:

           group %>% 
            group_by(Subject) %>% 
            summarise(pt = max(pt, na.rm = TRUE),
                      Event = max(Event, na.rm = TRUE))
    

    This is ok if there are only a few columns but if the table has many columns across() is useful. The examples for this verb are often with summarise(across(start_with... but in this example the columns don't start with the same characters. Either they could be changed or the positions listed:

        group %>% 
            group_by(Subject) %>% 
            summarise(across(1:ncol(group)-1, max, na.rm = TRUE, .names = "{.col}"))
    

    Note for the verb across() 1 refers to the first column after the first actual column so using ncol(group) won't work as that is too many columns (makes it position 4 rather than 3).

    Scroll to a specific Element Using html

    Year 2020. Now we have element.scrollIntoView() method to scroll to specific element.

    HTML

    <div id="my_element">
    </div>
    

    JS

    var my_element = document.getElementById("my_element");
    
    my_element.scrollIntoView({
      behavior: "smooth",
      block: "start",
      inline: "nearest"
    });
    

    Good thing is we can initiate this from any onclick/event and need not be limited to tag.

    Cannot Resolve Collation Conflict

    The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

    When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

    Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

    http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

    Update Collation of all fields in database on the fly

    http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

    If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

    SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 
    

    or using default database collation:

    SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
    

    How to get the mobile number of current sim card in real device?

    As many said:

    String phoneNumber = TelephonyManager.getDefault().getLine1Number();
    

    The availability depends strictly on the carrier and the way the number is encoded on the SIM card. If it is hardcoded by the company that makes the SIMs or by the mobile carrier itself. This returns the same as in Settings->about phone.

    How can I align the columns of tables in Bash?

    To have the exact same output as you need, you need to format the file like that :

    a very long string..........\t     112232432\t     anotherfield\n
    a smaller string\t      123124343\t     anotherfield\n
    

    And then using :

    $ column -t -s $'\t' FILE
    a very long string..........  112232432  anotherfield
    a smaller string              123124343  anotherfield
    

    How to increase font size in NeatBeans IDE?

    press alt and scroll down or up to change the size

    Accessing MP3 metadata with Python

    easiest method is songdetails..

    for read data

    import songdetails
    song = songdetails.scan("blah.mp3")
    if song is not None:
        print song.artist
    

    similarly for edit

    import songdetails
    song = songdetails.scan("blah.mp3")
    if song is not None:
        song.artist = u"The Great Blah"
        song.save()
    

    Don't forget to add u before name until you know chinese language.

    u can read and edit in bulk using python glob module

    ex.

    import glob
    songs = glob.glob('*')   # script should be in directory of songs.
    for song in songs:
        # do the above work.
    

    What's an Aggregate Root?

    In Erlang there is no need to differentiate between aggregates, once the aggregate is composed by data structures inside the state, instead of OO composition. See an example: https://github.com/bryanhunter/cqrs-with-erlang/tree/ndc-london

    How can I change text color via keyboard shortcut in MS word 2010

    For Word 2010 and 2013, go to File > Options > Customize Ribbon > Keyboard Shortcuts > All Commands (in left list) > Color: (in right list) -- at this point, you type in the short cut (such as Alt+r) and select the color (such as red). (This actually goes back to 2003 but I don't have that installed to provide the pathway.)

    Installing cmake with home-brew

    1. Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)

    2. Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.

    3. Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"

    4. Reload your .bashrc file: source ~/.bashrc

    5. Verify the latest cmake version is installed: cmake --version

    6. You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.

    Detect the Internet connection is offline?

    I think it is a very simple way.

    var x = confirm("Are you sure you want to submit?");
    if (x) {
      if (navigator.onLine == true) {
        return true;
      }
      alert('Internet connection is lost');
      return false;
    }
    return false;
    

    How do I get a button to open another activity?

    Using an OnClickListener

    Inside your Activity instance's onCreate() method you need to first find your Button by it's id using findViewById() and then set an OnClickListener for your button and implement the onClick() method so that it starts your new Activity.

    Button yourButton = (Button) findViewById(R.id.your_buttons_id);
    
    yourButton.setOnClickListener(new OnClickListener(){
        public void onClick(View v){                        
            startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
        }
    });
    

    This is probably most developers preferred method. However, there is a common alternative.

    Using onClick in XML

    Alternatively you can use the android:onClick="yourMethodName" to declare the method name in your Activity which is called when you click your Button, and then declare your method like so;

    public void yourMethodName(View v){
        startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
    }
    

    Also, don't forget to declare your new Activity in your manifest.xml. I hope this helps.

    References;

    this is error ORA-12154: TNS:could not resolve the connect identifier specified?

    The database must have a name (example DB1), try this one:

    OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit"); 
    

    In case the TNS is not defined you can also try this one:

    OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
    User Id=fastecit;Password=fastecit"); 
    

    Testing the type of a DOM element in JavaScript

    Perhaps you'll have to check the nodetype too:

    if(element.nodeType == 1){//element of type html-object/tag
      if(element.tagName=="a"){
        //this is an a-element
      }
      if(element.tagName=="div"){
        //this is a div-element
      }
    }
    

    Edit: Corrected the nodeType-value

    Truncate Decimal number not Round Off

    You can use Math.Round:

    decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229
    

    Or you can use ToString with the N3 numeric format.

    string roundedNumber = number.ToString("N3");
    

    EDIT: Since you don't want rounding, you can easily use Math.Truncate:

    Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229
    

    Create a Maven project in Eclipse complains "Could not resolve archetype"

    It is also possible that your settings.xml file defined in maven/conf folder defines a location that it cannot access

    Find all matches in workbook using Excel VBA

    You can read the data into an array. From there you can do the match in memory, instead of reading one cell at a time.

    Pass cell contents into VBA Array

    How can I convert a string to boolean in JavaScript?

    Do:

    var isTrueSet = (myValue == 'true');
    

    You could make it stricter by using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types, instead of the equality operator (==).

    var isTrueSet = (myValue === 'true');
    

    Don't:

    You should probably be cautious about using these two methods for your specific needs:

    var myBool = Boolean("false");  // == true
    
    var myBool = !!"false";  // == true
    

    Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.

    How to call function on child component on parent events

    If you have time, use Vuex store for watching variables (aka state) or trigger (aka dispatch) an action directly.

    Eclipse Indigo - Cannot install Android ADT Plugin

    By the way, Eclipse + ADT (ADT Bundle) is now provided as a single package,

    Developer.Android:ADT Bundle

    how to use DEXtoJar

    Step 1 extract the contents of dex2jar.*.*.zip file 
    Step 2 copy your .dex file to the extracted directory
    Step 3 execute dex2jar.bat <.dex filename> on windows, or ./dex2jar.sh <.dex filename> on linux
    

    Git merge two local branches

    on branchB do $git checkout branchA to switch to branch A

    on branchA do $git merge branchB

    That's all you need.

    Setting a system environment variable from a Windows batch file?

    For XP, I used a (free/donateware) tool called "RAPIDEE" (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).

    What is recursion and when should I use it?

    Recursion works best with what I like to call "fractal problems", where you're dealing with a big thing that's made of smaller versions of that big thing, each of which is an even smaller version of the big thing, and so on. If you ever have to traverse or search through something like a tree or nested identical structures, you've got a problem that might be a good candidate for recursion.

    People avoid recursion for a number of reasons:

    1. Most people (myself included) cut their programming teeth on procedural or object-oriented programming as opposed to functional programming. To such people, the iterative approach (typically using loops) feels more natural.

    2. Those of us who cut our programming teeth on procedural or object-oriented programming have often been told to avoid recursion because it's error prone.

    3. We're often told that recursion is slow. Calling and returning from a routine repeatedly involves a lot of stack pushing and popping, which is slower than looping. I think some languages handle this better than others, and those languages are most likely not those where the dominant paradigm is procedural or object-oriented.

    4. For at least a couple of programming languages I've used, I remember hearing recommendations not to use recursion if it gets beyond a certain depth because its stack isn't that deep.

    Reading a UTF8 CSV file with Python

    Looking at the Latin-1 unicode table, I see the character code 00E9 "LATIN SMALL LETTER E WITH ACUTE". This is the accented character in your sample data. A simple test in Python shows that UTF-8 encoding for this character is different from the unicode (almost UTF-16) encoding.

    >>> u'\u00e9'
    u'\xe9'
    >>> u'\u00e9'.encode('utf-8')
    '\xc3\xa9'
    >>> 
    

    I suggest you try to encode("UTF-8") the unicode data before calling the special unicode_csv_reader(). Simply reading the data from a file might hide the encoding, so check the actual character values.

    Defining array with multiple types in TypeScript

    I've settled on the following format for typing arrays that can have items of multiple types.

    Array<ItemType1 | ItemType2 | ItemType3>

    This works well with testing and type guards. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

    This format doesn't work well with testing or type guards:

    (ItemType1 | ItemType2 | ItemType3)[]

    Auto refresh code in HTML using meta tags

    Try this:

    <meta http-equiv="refresh" content="5;URL= your url">
    

    or

    <meta http-equiv="refresh" content="5">  
    

    When to use: Java 8+ interface default method, vs. abstract method

    Default methods in Java Interface are to be used more for providing dummy implementation of a function thus saving any implementing class of that interface from the pain of declaring all the abstract methods even if they want to deal with only one. Default methods in interface are thus in a way more a replacement for the concept of adapter classes.

    The methods in abstract class are however supposed to give a meaningful implementation which any child class should override only if needed to override a common functionality.

    Using Jquery Datatable with AngularJs

    visit this link for reference:http://codepen.io/kalaiselvan/pen/RRBzda

    <script>  
    var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
    app.controller('validationCtrl',function($scope){
      $scope.data=[
            [
                "Tiger Nixon",
                "System Architect",
                "Edinburgh",
                "5421",
                "2011\/04\/25",
                "$320,800"
            ],
            [
                "Garrett Winters",
                "Accountant",
                "Tokyo",
                "8422",
                "2011\/07\/25",
                "$170,750"
            ],
            [
                "Ashton Cox",
                "Junior Technical Author",
                "San Francisco",
                "1562",
                "2009\/01\/12",
                "$86,000"
            ],
            [
                "Cedric Kelly",
                "Senior Javascript Developer",
                "Edinburgh",
                "6224",
                "2012\/03\/29",
                "$433,060"
            ],
            [
                "Airi Satou",
                "Accountant",
                "Tokyo",
                "5407",
                "2008\/11\/28",
                "$162,700"
            ],
            [
                "Brielle Williamson",
                "Integration Specialist",
                "New York",
                "4804",
                "2012\/12\/02",
                "$372,000"
            ],
            [
                "Herrod Chandler",
                "Sales Assistant",
                "San Francisco",
                "9608",
                "2012\/08\/06",
                "$137,500"
            ],
            [
                "Rhona Davidson",
                "Integration Specialist",
                "Tokyo",
                "6200",
                "2010\/10\/14",
                "$327,900"
            ],
            [
                "Colleen Hurst",
                "Javascript Developer",
                "San Francisco",
                "2360",
                "2009\/09\/15",
                "$205,500"
            ],
            [
                "Sonya Frost",
                "Software Engineer",
                "Edinburgh",
                "1667",
                "2008\/12\/13",
                "$103,600"
            ],
            [
                "Jena Gaines",
                "Office Manager",
                "London",
                "3814",
                "2008\/12\/19",
                "$90,560"
            ],
            [
                "Quinn Flynn",
                "Support Lead",
                "Edinburgh",
                "9497",
                "2013\/03\/03",
                "$342,000"
            ],
            [
                "Charde Marshall",
                "Regional Director",
                "San Francisco",
                "6741",
                "2008\/10\/16",
                "$470,600"
            ],
            [
                "Haley Kennedy",
                "Senior Marketing Designer",
                "London",
                "3597",
                "2012\/12\/18",
                "$313,500"
            ],
            [
                "Tatyana Fitzpatrick",
                "Regional Director",
                "London",
                "1965",
                "2010\/03\/17",
                "$385,750"
            ],
            [
                "Michael Silva",
                "Marketing Designer",
                "London",
                "1581",
                "2012\/11\/27",
                "$198,500"
            ],
            [
                "Paul Byrd",
                "Chief Financial Officer (CFO)",
                "New York",
                "3059",
                "2010\/06\/09",
                "$725,000"
            ],
            [
                "Gloria Little",
                "Systems Administrator",
                "New York",
                "1721",
                "2009\/04\/10",
                "$237,500"
            ],
            [
                "Bradley Greer",
                "Software Engineer",
                "London",
                "2558",
                "2012\/10\/13",
                "$132,000"
            ],
            [
                "Dai Rios",
                "Personnel Lead",
                "Edinburgh",
                "2290",
                "2012\/09\/26",
                "$217,500"
            ],
            [
                "Jenette Caldwell",
                "Development Lead",
                "New York",
                "1937",
                "2011\/09\/03",
                "$345,000"
            ],
            [
                "Yuri Berry",
                "Chief Marketing Officer (CMO)",
                "New York",
                "6154",
                "2009\/06\/25",
                "$675,000"
            ],
            [
                "Caesar Vance",
                "Pre-Sales Support",
                "New York",
                "8330",
                "2011\/12\/12",
                "$106,450"
            ],
            [
                "Doris Wilder",
                "Sales Assistant",
                "Sidney",
                "3023",
                "2010\/09\/20",
                "$85,600"
            ],
            [
                "Angelica Ramos",
                "Chief Executive Officer (CEO)",
                "London",
                "5797",
                "2009\/10\/09",
                "$1,200,000"
            ],
            [
                "Gavin Joyce",
                "Developer",
                "Edinburgh",
                "8822",
                "2010\/12\/22",
                "$92,575"
            ],
            [
                "Jennifer Chang",
                "Regional Director",
                "Singapore",
                "9239",
                "2010\/11\/14",
                "$357,650"
            ],
            [
                "Brenden Wagner",
                "Software Engineer",
                "San Francisco",
                "1314",
                "2011\/06\/07",
                "$206,850"
            ],
            [
                "Fiona Green",
                "Chief Operating Officer (COO)",
                "San Francisco",
                "2947",
                "2010\/03\/11",
                "$850,000"
            ],
            [
                "Shou Itou",
                "Regional Marketing",
                "Tokyo",
                "8899",
                "2011\/08\/14",
                "$163,000"
            ],
            [
                "Michelle House",
                "Integration Specialist",
                "Sidney",
                "2769",
                "2011\/06\/02",
                "$95,400"
            ],
            [
                "Suki Burks",
                "Developer",
                "London",
                "6832",
                "2009\/10\/22",
                "$114,500"
            ],
            [
                "Prescott Bartlett",
                "Technical Author",
                "London",
                "3606",
                "2011\/05\/07",
                "$145,000"
            ],
            [
                "Gavin Cortez",
                "Team Leader",
                "San Francisco",
                "2860",
                "2008\/10\/26",
                "$235,500"
            ],
            [
                "Martena Mccray",
                "Post-Sales support",
                "Edinburgh",
                "8240",
                "2011\/03\/09",
                "$324,050"
            ],
            [
                "Unity Butler",
                "Marketing Designer",
                "San Francisco",
                "5384",
                "2009\/12\/09",
                "$85,675"
            ],
            [
                "Howard Hatfield",
                "Office Manager",
                "San Francisco",
                "7031",
                "2008\/12\/16",
                "$164,500"
            ],
            [
                "Hope Fuentes",
                "Secretary",
                "San Francisco",
                "6318",
                "2010\/02\/12",
                "$109,850"
            ],
            [
                "Vivian Harrell",
                "Financial Controller",
                "San Francisco",
                "9422",
                "2009\/02\/14",
                "$452,500"
            ],
            [
                "Timothy Mooney",
                "Office Manager",
                "London",
                "7580",
                "2008\/12\/11",
                "$136,200"
            ],
            [
                "Jackson Bradshaw",
                "Director",
                "New York",
                "1042",
                "2008\/09\/26",
                "$645,750"
            ],
            [
                "Olivia Liang",
                "Support Engineer",
                "Singapore",
                "2120",
                "2011\/02\/03",
                "$234,500"
            ],
            [
                "Bruno Nash",
                "Software Engineer",
                "London",
                "6222",
                "2011\/05\/03",
                "$163,500"
            ],
            [
                "Sakura Yamamoto",
                "Support Engineer",
                "Tokyo",
                "9383",
                "2009\/08\/19",
                "$139,575"
            ],
            [
                "Thor Walton",
                "Developer",
                "New York",
                "8327",
                "2013\/08\/11",
                "$98,540"
            ],
            [
                "Finn Camacho",
                "Support Engineer",
                "San Francisco",
                "2927",
                "2009\/07\/07",
                "$87,500"
            ],
            [
                "Serge Baldwin",
                "Data Coordinator",
                "Singapore",
                "8352",
                "2012\/04\/09",
                "$138,575"
            ],
            [
                "Zenaida Frank",
                "Software Engineer",
                "New York",
                "7439",
                "2010\/01\/04",
                "$125,250"
            ],
            [
                "Zorita Serrano",
                "Software Engineer",
                "San Francisco",
                "4389",
                "2012\/06\/01",
                "$115,000"
            ],
            [
                "Jennifer Acosta",
                "Junior Javascript Developer",
                "Edinburgh",
                "3431",
                "2013\/02\/01",
                "$75,650"
            ],
            [
                "Cara Stevens",
                "Sales Assistant",
                "New York",
                "3990",
                "2011\/12\/06",
                "$145,600"
            ],
            [
                "Hermione Butler",
                "Regional Director",
                "London",
                "1016",
                "2011\/03\/21",
                "$356,250"
            ],
            [
                "Lael Greer",
                "Systems Administrator",
                "London",
                "6733",
                "2009\/02\/27",
                "$103,500"
            ],
            [
                "Jonas Alexander",
                "Developer",
                "San Francisco",
                "8196",
                "2010\/07\/14",
                "$86,500"
            ],
            [
                "Shad Decker",
                "Regional Director",
                "Edinburgh",
                "6373",
                "2008\/11\/13",
                "$183,000"
            ],
            [
                "Michael Bruce",
                "Javascript Developer",
                "Singapore",
                "5384",
                "2011\/06\/27",
                "$183,000"
            ],
            [
                "Donna Snider",
                "Customer Support",
                "New York",
                "4226",
                "2011\/01\/25",
                "$112,000"
            ]
        ]
    
    
    $scope.dataTableOpt = {
      //if any ajax call 
      };
    });
    </script>
    <div class="container" ng-app="formvalid">
          <div class="panel" data-ng-controller="validationCtrl">
          <div class="panel-heading border">    
            <h2>Data table using jquery datatable in Angularjs </h2>
          </div>
          <div class="panel-body">
              <table class="table table-bordered bordered table-striped table-condensed datatable" ui-jq="dataTable" ui-options="dataTableOpt">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Name</th>
                  <th>Position</th>
                  <th>Office</th>
                  <th>Age</th>
                  <th>Start Date</th>
                </tr>
              </thead>
                <tbody>
                  <tr ng-repeat="n in data">
                    <td>{{$index+1}}</td>
                    <td>{{n[0]}}</td>
                    <td>{{n[1]}}</td>
                    <td>{{n[2]}}</td>
                    <td>{{n[3]}}</td>
                    <td>{{n[4] | date:'dd/MM/yyyy'}}</td>
                  </tr>
                </tbody>
            </table>
          </div>
        </div>
        </div>
    

    MySQL, Check if a column exists in a table with SQL

    DO NOT put ALTER TABLE/MODIFY COLS or any other such table mod operations inside a TRANSACTION. Transactions are for being able to roll back a QUERY failure not for ALTERations...it will error out every time in a transaction.

    Just run a SELECT * query on the table and check if the column is there...

    Start a fragment via Intent within a Fragment

    You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.

    So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.

    HTML image not showing in Gmail

    Google only allows images which are coming from trusted source .

    So I solved this issue by hosting my images in google drive and using its url as source for my images.

    Example: with: http://drive.google.com/uc?export=view&id=FILEID'>

    to form URL please refer here.

    how do I loop through a line from a csv file in powershell

    $header3 = @("Field_1","Field_2","Field_3","Field_4","Field_5")     
    
    Import-Csv $fileName -Header $header3 -Delimiter "`t" | select -skip 3 | Foreach-Object {
    
        $record = $indexName 
        foreach ($property in $_.PSObject.Properties){
    
            #doSomething $property.Name, $property.Value
    
                if($property.Name -like '*TextWrittenAsNumber*'){
    
                    $record = $record + "," + '"' + $property.Value + '"' 
                }
                else{
                    $record = $record + "," + $property.Value 
                }                           
        }               
    
            $array.add($record) | out-null  
            #write-host $record                         
    }
    

    How to subtract 30 days from the current date using SQL Server

    TRY THIS:

    Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

    SELECT DATEADD(dd, -30, 
           CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
           AS DATETIME))
    

    What is the difference between H.264 video and MPEG-4 video?

    H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
    The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
    So the 3 main advantages of H.264 over MPEG-4 compression are:
    - Small file size for longer recording time and better network transmission.
    - Fluent and better video quality for real time playback
    - More efficient mobile surveillance application

    H264 is now enshrined in MPEG4 as part 10 also known as AVC

    Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

    Hope this helps.

    Git: See my last commit

    You can run

     git show --source
    

    it shows the author, Date, the commit's message and the diff --git for all changed files in latest commit.

    Lightweight workflow engine for Java

    Yes, in my perspective there is no reason why you should write your own. Most of the Open Source BPM/Workflow frameworks are extremely flexible, you just need to learn the basics. If you choose jBPM you will get much more than a simple workflow engine, so it depends what are you trying to build.

    Cheers

    Java 11 package javax.xml.bind does not exist

    According to the release-notes, Java 11 removed the Java EE modules:

    java.xml.bind (JAXB) - REMOVED
    
    • Java 8 - OK
    • Java 9 - DEPRECATED
    • Java 10 - DEPRECATED
    • Java 11 - REMOVED

    See JEP 320 for more info.

    You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

    <dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
      <version>2.3.0</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-core</artifactId>
      <version>2.3.0</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-impl</artifactId>
      <version>2.3.0</version>
    </dependency>
    

    Jakarta EE 8 update (Mar 2020)

    Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

    <dependency>
      <groupId>jakarta.xml.bind</groupId>
      <artifactId>jakarta.xml.bind-api</artifactId>
      <version>2.3.3</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-impl</artifactId>
      <version>2.3.3</version>
      <scope>runtime</scope>
    </dependency>
    

    Jakarta EE 9 update (Nov 2020)

    Use latest release of Eclipse Implementation of JAXB 3.0.0:

    <dependency>
      <groupId>jakarta.xml.bind</groupId>
      <artifactId>jakarta.xml.bind-api</artifactId>
      <version>3.0.0</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-impl</artifactId>
      <version>3.0.0</version>
      <scope>runtime</scope>
    </dependency>
    

    Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

    javax.xml.bind -> jakarta.xml.bind
    

    How do you increase the max number of concurrent connections in Apache?

    change the MaxClients directive. it is now on 256.

    Using the rJava package on Win7 64 bit with R

    For me, setting JAVA_HOME did the trick (instead of unsetting, as in another answer given here). Either in Windows:

    set JAVA_HOME="C:\Program Files\Java\jre7\"
    

    Or inside R:

    Sys.setenv(JAVA_HOME="C:\\Program Files\\Java\\jre7\\")
    

    But what's probably the best solution (since rJava 0.9-4) is overriding within R the Windows JAVA_HOME setting altogether:

    options(java.home="C:\\Program Files\\Java\\jre7\\")
    library(rJava)
    

    Populate a Drop down box from a mySQL table in PHP

    At the top first set up database connection as follow:

    <?php
    $mysqli = new mysqli("localhost", "username", "password", "database") or die($this->mysqli->error);
    $query= $mysqli->query("SELECT PcID from PC");
    ?> 
    

    Then include the following code in HTML inside form

    <select name="selected_pcid" id='selected_pcid'>
    
                <?php 
    
                 while ($rows = $query->fetch_array(MYSQLI_ASSOC)) {
                            $value= $rows['id'];
                    ?>
                     <option value="<?= $value?>"><?= $value?></option>
                    <?php } ?>
                 </select>
    

    However, if you are using materialize css or any other out of the box css, make sure that select field is not hidden or disabled.

    In Excel, sum all values in one column in each row where another column is a specific value

    If column A contains the amounts to be reimbursed, and column B contains the "yes/no" indicating whether the reimbursement has been made, then either of the following will work, though the first option is recommended:

    =SUMIF(B:B,"No",A:A)
    

    or

    =SUMIFS(A:A,B:B,"No")
    

    Here is an example that will display the amounts paid and outstanding for a small set of sample data.

     A         B            C                   D
     Amount    Reimbursed?  Total Paid:         =SUMIF(B:B,"Yes",A:A)
     $100      Yes          Total Outstanding:  =SUMIF(B:B,"No",A:A)
     $200      No           
     $300      No
     $400      Yes
     $500      No
    

    Result of Excel calculations

    Why is setState in reactjs Async instead of Sync?

    setState is asynchronous. You can see in this documentation by Reactjs

    React intentionally “waits” until all components call setState() in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders.

    However, you might still be wondering why React doesn’t just update this.state immediately without re-rendering.

    The reason is this would break the consistency between props and state, causing issues that are very hard to debug.

    You can still perform functions if it is dependent on the change of the state value:

    Option 1: Using callback function with setState

    this.setState({
       value: newValue
    },()=>{
       // It is an callback function.
       // Here you can access the update value
       console.log(this.state.value)
    })
    

    Option 2: using componentDidUpdate This function will be called whenever the state of that particular class changes.

    componentDidUpdate(prevProps, prevState){
        //Here you can check if value of your desired variable is same or not.
        if(this.state.value !== prevState.value){
            // this part will execute if your desired variable updates
        }
    }
    

    Reverse a string in Python

    original = "string"
    
    rev_index = original[::-1]
    rev_func = list(reversed(list(original))) #nsfw
    
    print(original)
    print(rev_index)
    print(''.join(rev_func))
    

    How to call python script on excel vba?

    To those who are stuck wondering why a window flashes and goes away without doing anything the python script is meant to do after calling the shell command from VBA: In my program

    Sub runpython()
    
    Dim Ret_Val
    args = """F:\my folder\helloworld.py"""
    Ret_Val = Shell("C:\Users\username\AppData\Local\Programs\Python\Python36\python.exe " & " " & args, vbNormalFocus)
    If Ret_Val = 0 Then
       MsgBox "Couldn't run python script!", vbOKOnly
    End If
    End Sub
    

    In the line args = """F:\my folder\helloworld.py""", I had to use triple quotes for this to work. If I use just regular quotes like: args = "F:\my folder\helloworld.py" the program would not work. The reason for this is that there is a space in the path (my folder). If there is a space in the path, in VBA, you need to use triple quotes.

    Call a python function from jinja2

    @John32323 's answer is a very clean solution.

    Here is the same one, but save into a seperate file, maybe more cleaner.

    Create helper file

    app\helper.py

    from app import app
    
    def clever_function_1():
        return u'HELLO'
    
    def clever_function_2(a, b):
        return a + b
    
    
    
    app.jinja_env.globals.update(
        clever_function_1=clever_function_1,
        clever_function_2=clever_function_2,
    )
    

    Import from app

    app.py

    from app import routes
    from app import helper   # add this one
    

    Use like this

    app\templates\some.html

    
    {{ clever_function_1() }}
    {{ clever_function_2(a, b) }}
    
    

    Nested ng-repeat

    If you have a big nested JSON object and using it across several screens, you might face performance issues in page loading. I always go for small individual JSON objects and query the related objects as lazy load only where they are required.

    you can achieve it using ng-init

    <td class="lectureClass" ng-repeat="s in sessions" ng-init='presenters=getPresenters(s.id)'>
          {{s.name}}
          <div class="presenterClass" ng-repeat="p in presenters">
              {{p.name}}
          </div>
    </td> 
    

    The code on the controller side should look like below

    $scope.getPresenters = function(id) {
        return SessionPresenters.get({id: id});
    };
    

    While the API factory is as follows:

    angular.module('tryme3App').factory('SessionPresenters', function ($resource, DateUtils) {
    
            return $resource('api/session.Presenters/:id', {}, {
                'query': { method: 'GET', isArray: true},
                'get': {
                    method: 'GET', isArray: true
                },
                'update': { method:'PUT' }
            });
        });
    

    C/C++ include header file order

    I'm pretty sure this isn't a recommended practice anywhere in the sane world, but I like to line system includes up by filename length, sorted lexically within the same length. Like so:

    #include <set>
    #include <vector>
    #include <algorithm>
    #include <functional>
    

    I think it's a good idea to include your own headers before other peoples, to avoid the shame of include-order dependency.

    What is the difference between public, private, and protected?

    You use:

    • public scope to make that property/method available from anywhere, other classes and instances of the object.

    • private scope when you want your property/method to be visible in its own class only.

    • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.

    If you don't use any visibility modifier, the property / method will be public.

    More: (For comprehensive information)

    Why is my CSS bundling not working with a bin deployed MVC4 app?

    This solved my issue. I have added these lines in _layout.cshtml

    @*@Scripts.Render("~/bundles/plugins")*@
    <script src="/Content/plugins/jQuery/jQuery-2.1.4.min.js"></script>
    <!-- jQuery UI 1.11.4 -->
    <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
    <!-- Kendo JS -->
    <script src="/Content/kendo/js/kendo.all.min.js" type="text/javascript"></script>
    <script src="/Content/kendo/js/kendo.web.min.js" type="text/javascript"></script>
    <script src="/Content/kendo/js/kendo.aspnetmvc.min.js"></script>
    <!-- Bootstrap 3.3.5 -->
    <script src="/Content/bootstrap/js/bootstrap.min.js"></script>
    <!-- Morris.js charts -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
    <script src="/Content/plugins/morris/morris.min.js"></script>
    <!-- Sparkline -->
    <script src="/Content/plugins/sparkline/jquery.sparkline.min.js"></script>
    <!-- jvectormap -->
    <script src="/Content/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
    <script src="/Content/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
    <!-- jQuery Knob Chart -->
    <script src="/Content/plugins/knob/jquery.knob.js"></script>
    <!-- daterangepicker -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
    <script src="/Content/plugins/daterangepicker/daterangepicker.js"></script>
    <!-- datepicker -->
    <script src="/Content/plugins/datepicker/bootstrap-datepicker.js"></script>
    <!-- Bootstrap WYSIHTML5 -->
    <script src="/Content/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
    <!-- Slimscroll -->
    <script src="/Content/plugins/slimScroll/jquery.slimscroll.min.js"></script>
    <!-- FastClick -->
    <script src="/Content/plugins/fastclick/fastclick.min.js"></script>
    <!-- AdminLTE App -->
    <script src="/Content/dist/js/app.min.js"></script>
    <!-- AdminLTE for demo purposes -->
    <script src="/Content/dist/js/demo.js"></script>
    <!-- Common -->
    <script src="/Scripts/common/common.js"></script>
    <!-- Render Sections -->
    

    Horizontal scroll css?

    Just make sure you add box-sizing:border-box; to your #myWorkContent.

    http://jsfiddle.net/FPBWr/160/

    What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

    This is more of a important comment and that why implicitly unwrapped optionals can be deceptive when it comes to debugging nil values.

    Think of the following code: It compiles with no errors/warnings:

    c1.address.city = c3.address.city
    

    Yet at runtime it gives the following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value

    Can you tell me which object is nil?

    You can't!

    The full code would be:

    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            var c1 = NormalContact()
            let c3 = BadContact()
    
            c1.address.city = c3.address.city // compiler hides the truth from you and then you sudden get a crash
        }
    }
    
    struct NormalContact {
        var address : Address = Address(city: "defaultCity")
    }
    
    struct BadContact {
        var address : Address!
    }
    
    struct Address {
        var city : String
    }
    

    Long story short by using var address : Address! you're hiding the possibility that a variable can be nil from other readers. And when it crashes you're like "what the hell?! my address isn't an optional, so why am I crashing?!.

    Hence it's better to write as such:

    c1.address.city = c2.address!.city  // ERROR:  Fatal error: Unexpectedly found nil while unwrapping an Optional value 
    

    Can you now tell me which object it is that was nil?

    This time the code has been made more clear to you. You can rationalize and think that likely it's the address parameter that was forcefully unwrapped.

    The full code would be :

    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            var c1 = NormalContact()
            let c2 = GoodContact()
    
            c1.address.city = c2.address!.city
            c1.address.city = c2.address?.city // not compile-able. No deceiving by the compiler
            c1.address.city = c2.address.city // not compile-able. No deceiving by the compiler
            if let city = c2.address?.city {  // safest approach. But that's not what I'm talking about here. 
                c1.address.city = city
            }
    
        }
    }
    
    struct NormalContact {
        var address : Address = Address(city: "defaultCity")
    }
    
    struct GoodContact {
        var address : Address?
    }
    
    struct Address {
        var city : String
    }
    

    Can I set text box to readonly when using Html.TextBoxFor?

    Using the example of @Hunter, in the new { .. } part, add readonly = true, I think that will work.

    CSS-Only Scrollable Table with fixed headers

    As I was recently in need of this, I will share a solution that uses 3 tables, but does not require JavaScript.

    Table 1 (parent) contains two rows. The first row contains table 2 (child 1) for the column headers. The second row contains table 3 (child 2) for the scrolling content.

    It must be noted the childTbl must be 25px shorter than the parentTbl for the scroller to appear properly.

    This is the source, where I got the idea from. I made it HTML5-friendly without the deprecated tags and the inline CSS.

    _x000D_
    _x000D_
    .parentTbl table {_x000D_
      border-spacing: 0;_x000D_
      border-collapse: collapse;_x000D_
      border: 0;_x000D_
      width: 690px;_x000D_
    }_x000D_
    .childTbl table {_x000D_
      border-spacing: 0;_x000D_
      border-collapse: collapse;_x000D_
      border: 1px solid #d7d7d7;_x000D_
      width: 665px;_x000D_
    }_x000D_
    .childTbl th,_x000D_
    .childTbl td {_x000D_
      border: 1px solid #d7d7d7;_x000D_
    }_x000D_
    .scrollData {_x000D_
      width: 690;_x000D_
      height: 150px;_x000D_
      overflow-x: hidden;_x000D_
    }
    _x000D_
    <div class="parentTbl">_x000D_
      <table>_x000D_
        <tr>_x000D_
          <td>_x000D_
            <div class="childTbl">_x000D_
              <table class="childTbl">_x000D_
                <tr>_x000D_
                  <th>Header 1</th>_x000D_
                  <th>Header 2</th>_x000D_
                  <th>Header 3</th>_x000D_
                  <th>Header 4</th>_x000D_
                  <th>Header 5</th>_x000D_
                  <th>Header 6</th>_x000D_
                </tr>_x000D_
              </table>_x000D_
            </div>_x000D_
          </td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>_x000D_
            <div class="scrollData childTbl">_x000D_
              <table>_x000D_
                <tr>_x000D_
                  <td>Table Data 1</td>_x000D_
                  <td>Table Data 2</td>_x000D_
                  <td>Table Data 3</td>_x000D_
                  <td>Table Data 4</td>_x000D_
                  <td>Table Data 5</td>_x000D_
                  <td>Table Data 6</td>_x000D_
                </tr>_x000D_
                <tr>_x000D_
                  <td>Table Data 1</td>_x000D_
                  <td>Table Data 2</td>_x000D_
                  <td>Table Data 3</td>_x000D_
                  <td>Table Data 4</td>_x000D_
                  <td>Table Data 5</td>_x000D_
                  <td>Table Data 6</td>_x000D_
                </tr>_x000D_
                <tr>_x000D_
                  <td>Table Data 1</td>_x000D_
                  <td>Table Data 2</td>_x000D_
                  <td>Table Data 3</td>_x000D_
                  <td>Table Data 4</td>_x000D_
                  <td>Table Data 5</td>_x000D_
                  <td>Table Data 6</td>_x000D_
                </tr>_x000D_
                <tr>_x000D_
                  <td>Table Data 1</td>_x000D_
                  <td>Table Data 2</td>_x000D_
                  <td>Table Data 3</td>_x000D_
                  <td>Table Data 4</td>_x000D_
                  <td>Table Data 5</td>_x000D_
                  <td>Table Data 6</td>_x000D_
                </tr>_x000D_
                <tr>_x000D_
                  <td>Table Data 1</td>_x000D_
                  <td>Table Data 2</td>_x000D_
                  <td>Table Data 3</td>_x000D_
                  <td>Table Data 4</td>_x000D_
                  <td>Table Data 5</td>_x000D_
                  <td>Table Data 6</td>_x000D_
                </tr>_x000D_
                <tr>_x000D_
                  <td>Table Data 1</td>_x000D_
                  <td>Table Data 2</td>_x000D_
                  <td>Table Data 3</td>_x000D_
                  <td>Table Data 4</td>_x000D_
                  <td>Table Data 5</td>_x000D_
                  <td>Table Data 6</td>_x000D_
                </tr>_x000D_
                <tr>_x000D_
                  <td>Table Data 1</td>_x000D_
                  <td>Table Data 2</td>_x000D_
                  <td>Table Data 3</td>_x000D_
                  <td>Table Data 4</td>_x000D_
                  <td>Table Data 5</td>_x000D_
                  <td>Table Data 6</td>_x000D_
                </tr>_x000D_
                <tr>_x000D_
                  <td>Table Data 1</td>_x000D_
                  <td>Table Data 2</td>_x000D_
                  <td>Table Data 3</td>_x000D_
                  <td>Table Data 4</td>_x000D_
                  <td>Table Data 5</td>_x000D_
                  <td>Table Data 6</td>_x000D_
                </tr>_x000D_
                <tr>_x000D_
                  <td>Table Data 1</td>_x000D_
                  <td>Table Data 2</td>_x000D_
                  <td>Table Data 3</td>_x000D_
                  <td>Table Data 4</td>_x000D_
                  <td>Table Data 5</td>_x000D_
                  <td>Table Data 6</td>_x000D_
                </tr>_x000D_
                <tr>_x000D_
                  <td>Table Data 1</td>_x000D_
                  <td>Table Data 2</td>_x000D_
                  <td>Table Data 3</td>_x000D_
                  <td>Table Data 4</td>_x000D_
                  <td>Table Data 5</td>_x000D_
                  <td>Table Data 6</td>_x000D_
                </tr>_x000D_
              </table>_x000D_
            </div>_x000D_
          </td>_x000D_
        </tr>_x000D_
      </table>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    This is reliable on different browsers, the downside would be having to hard code the table widths.

    Pandas groupby month and year

    You can also do it by creating a string column with the year and month as follows:

    df['date'] = df.index
    df['year-month'] = df['date'].apply(lambda x: str(x.year) + ' ' + str(x.month))
    grouped = df.groupby('year-month')
    

    However this doesn't preserve the order when you loop over the groups, e.g.

    for name, group in grouped:
        print(name)
    

    Will give:

    2007 11
    2007 12
    2008 1
    2008 10
    2008 11
    2008 12
    2008 2
    2008 3
    2008 4
    2008 5
    2008 6
    2008 7
    2008 8
    2008 9
    2009 1
    2009 10
    

    So then, if you want to preserve the order, you must do as suggested by @Q-man above:

    grouped = df.groupby([df.index.year, df.index.month])
    

    This will preserve the order in the above loop:

    (2007, 11)
    (2007, 12)
    (2008, 1)
    (2008, 2)
    (2008, 3)
    (2008, 4)
    (2008, 5)
    (2008, 6)
    (2008, 7)
    (2008, 8)
    (2008, 9)
    (2008, 10)
    

    How to force addition instead of concatenation in javascript

    Should also be able to do this:

    total += eval(myInt1) + eval(myInt2) + eval(myInt3);
    

    This helped me in a different, but similar, situation.

    How to add Action bar options menu in Android Fragments

    I am late for the answer but I think this is another solution which is not mentioned here so posting.

    Step 1: Make a xml of menu which you want to add like I have to add a filter action on my action bar so I have created a xml filter.xml. The main line to notice is android:orderInCategory this will show the action icon at first or last wherever you want to show. One more thing to note down is the value, if the value is less then it will show at first and if value is greater then it will show at last.

    filter.xml

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools" >
    
    
        <item
            android:id="@+id/action_filter"
            android:title="@string/filter"
            android:orderInCategory="10"
            android:icon="@drawable/filter"
            app:showAsAction="ifRoom" />
    
    
    </menu>
    

    Step 2: In onCreate() method of fragment just put the below line as mentioned, which is responsible for calling back onCreateOptionsMenu(Menu menu, MenuInflater inflater) method just like in an Activity.

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
        }
    

    Step 3: Now add the method onCreateOptionsMenu which will be override as:

    @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.filter, menu);  // Use filter.xml from step 1
        }
    

    Step 4: Now add onOptionsItemSelected method by which you can implement logic whatever you want to do when you select the added action icon from actionBar:

    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if(id == R.id.action_filter){
                //Do whatever you want to do 
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    

    Peak detection in a 2D array

    Perhaps you can use something like Gaussian Mixture Models. Here's a Python package for doing GMMs (just did a Google search) http://www.ar.media.kyoto-u.ac.jp/members/david/softwares/em/

    Does --disable-web-security Work In Chrome Anymore?

    This should work. You may save the following in a batch file:

    TASKKILL /F /IM chrome.exe
    start chrome.exe --args --disable-web-security
    pause
    

    Is there a naming convention for git repositories?

    Without favouring any particular naming choice, remember that a git repo can be cloned into any root directory of your choice:

    git clone https://github.com/user/repo.git myDir
    

    Here repo.git would be cloned into the myDir directory.

    So even if your naming convention for a public repo ended up to be slightly incorrect, it would still be possible to fix it on the client side.

    That is why, in a distributed environment where any client can do whatever he/she wants, there isn't really a naming convention for Git repo.
    (except to reserve "xxx.git" for bare form of the repo 'xxx')
    There might be naming convention for REST service (similar to "Are there any naming convention guidelines for REST APIs?"), but that is a separate issue.

    How do I define the name of image built with docker-compose

    Depending on your use case, you can use an image which has already been created and specify it's name in docker-compose.

    We have a production use case where our CI server builds a named Docker image. (docker build -t <specific_image_name> .). Once the named image is specified, our docker-compose always builds off of the specific image. This allows a couple of different possibilities:

    1- You can ensure that where ever you run your docker-compose from, you will always be using the latest version of that specific image.

    2- You can specify multiple named images in your docker-compose file and let them be auto-wired through the previous build step.

    So, if your image is already built, you can name the image with docker-compose. Remove build and specify image:

    wildfly:
      image: my_custom_wildfly_image
      container_name: wildfly_server
      ports:
       - 9990:9990
       - 80:8080
      environment:
       - MYSQL_HOST=mysql_server
       - MONGO_HOST=mongo_server
       - ELASTIC_HOST=elasticsearch_server
      volumes:
       - /Volumes/CaseSensitive/development/wildfly/deployments/:/opt/jboss/wildfly/standalone/deployments/
      links:
       - mysql:mysql_server
       - mongo:mongo_server
       - elasticsearch:elasticsearch_server
    

    Run PostgreSQL queries from the command line

    SELECT * FROM my_table;
    

    where my_table is the name of your table.

    EDIT:

    psql -c "SELECT * FROM my_table"
    

    or just psql and then type your queries.

    How do I restart nginx only after the configuration test was successful on Ubuntu?

    At least on Debian the nginx startup script has a reload function which does:

    reload)
      log_daemon_msg "Reloading $DESC configuration" "$NAME"
      test_nginx_config
      start-stop-daemon --stop --signal HUP --quiet --pidfile $PID \
       --oknodo --exec $DAEMON
      log_end_msg $?
      ;;
    

    Seems like all you'd need to do is call service nginx reload instead of restart since it calls test_nginx_config.

    How to keep the header static, always on top while scrolling?

    I personally needed a table with both the left and top headers visible at all times. Inspired by several articles, I think I have a good solution that you may find helpful. This version does not have the wrapping problem that other soltions have with floating divs or flexible/auto sizing of columns and rows.

    <!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>
        <title></title>
        <script language="javascript" type="text/javascript" src="/Scripts/jquery-1.7.2.min.js"></script>
        <script language="javascript" type="text/javascript">
            // Handler for scrolling events
            function scrollFixedHeaderTable() {
                var outerPanel = $("#_outerPanel");
                var cloneLeft = $("#_cloneLeft");
                var cloneTop = $("#_cloneTop");
                cloneLeft.css({ 'margin-top': -outerPanel.scrollTop() });
                cloneTop.css({ 'margin-left': -outerPanel.scrollLeft() });
            }
    
            function initFixedHeaderTable() {
                var outerPanel = $("#_outerPanel");
                var innerPanel = $("#_innerPanel");
                var clonePanel = $("#_clonePanel");
                var table = $("#_table");
                // We will clone the table 2 times: For the top rowq and the left column. 
                var cloneLeft = $("#_cloneLeft");
                var cloneTop = $("#_cloneTop");
                var cloneTop = $("#_cloneTopLeft");
                // Time to create the table clones
                cloneLeft = table.clone();
                cloneTop = table.clone();
                cloneTopLeft = table.clone();
                cloneLeft.attr('id', '_cloneLeft');
                cloneTop.attr('id', '_cloneTop');
                cloneTopLeft.attr('id', '_cloneTopLeft');
                cloneLeft.css({
                    position: 'fixed',
                    'pointer-events': 'none',
                    top: outerPanel.offset().top,
                    'z-index': 1 // keep lower than top-left below
                });
                cloneTop.css({
                    position: 'fixed',
                    'pointer-events': 'none',
                    top: outerPanel.offset().top,
                    'z-index': 1 // keep lower than top-left below
                });
                cloneTopLeft.css({
                    position: 'fixed',
                    'pointer-events': 'none',
                    top: outerPanel.offset().top,
                    'z-index': 2 // higher z-index than the left and top to make the top-left header cell logical
                });
                // Add the controls to the control-tree
                clonePanel.append(cloneLeft);
                clonePanel.append(cloneTop);
                clonePanel.append(cloneTopLeft);
                // Keep all hidden: We will make the individual header cells visible in a moment
                cloneLeft.css({ visibility: 'hidden' });
                cloneTop.css({ visibility: 'hidden' });
                cloneTopLeft.css({ visibility: 'hidden' });
                // Make the lef column header cells visible in the left clone
                $("#_cloneLeft td._hdr.__row").css({
                    visibility: 'visible',
                });
                // Make the top row header cells visible in the top clone
                $("#_cloneTop td._hdr.__col").css({
                    visibility: 'visible',
                });
                // Make the top-left cell visible in the top-left clone
                $("#_cloneTopLeft td._hdr.__col.__row").css({
                    visibility: 'visible',
                });
                // Clipping. First get the inner width/height by measuring it (normal innerWidth did not work for me)
                var helperDiv = $('<div style="positions: absolute; top: 0; right: 0; bottom: 0; left: 0; height: 100%;"></div>');
                outerPanel.append(helperDiv);
                var innerWidth = helperDiv.width();
                var innerHeight = helperDiv.height();
                helperDiv.remove(); // because we dont need it anymore, do we?
                // Make sure all the panels are clipped, or the clones will extend beyond them
                outerPanel.css({ clip: 'rect(0px,' + String(outerPanel.width()) + 'px,' + String(outerPanel.height()) + 'px,0px)' });
                // Clone panel clipping to prevent the clones from covering the outerPanel's scrollbars (this is why we use a separate div for this)
                clonePanel.css({ clip: 'rect(0px,' + String(innerWidth) + 'px,' + String(innerHeight) + 'px,0px)'   });
                // Subscribe the scrolling of the outer panel to our own handler function to move the clones as needed.
                $("#_outerPanel").scroll(scrollFixedHeaderTable);
            }
    
    
            $(document).ready(function () {
                initFixedHeaderTable();
            });
    
        </script>
        <style type="text/css">
            * {
                clip: rect font-family: Arial;
                font-size: 16px;
                margin: 0;
                padding: 0;
            }
    
            #_outerPanel {
                margin: 0px;
                padding: 0px;
                position: absolute;
                left: 50px;
                top: 50px;
                right: 50px;
                bottom: 50px;
                overflow: auto;
                z-index: 1000;
            }
    
            #_innerPanel {
                overflow: visible;
                position: absolute;
            }
    
            #_clonePanel {
                overflow: visible;
                position: fixed;
            }
    
            table {
            }
    
            td {
                white-space: nowrap;
                border-right: 1px solid #000;
                border-bottom: 1px solid #000;
                padding: 2px 2px 2px 2px;
            }
    
            td._hdr {
                color: Blue;
                font-weight: bold;
            }
            td._hdr.__row {
                background-color: #eee;
                border-left: 1px solid #000;
            }
            td._hdr.__col {
                background-color: #ddd;
                border-top: 1px solid #000;
            }
        </style>
    </head>
    <body>
        <div id="_outerPanel">
            <div id="_innerPanel">
                <div id="_clonePanel"></div>
                <table id="_table" border="0" cellpadding="0" cellspacing="0">
                    <thead id="_topHeader" style="background-color: White;">
                        <tr class="row">
                            <td class="_hdr __col __row">
                                &nbsp;
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                            <td class="_hdr __col">
                                TOP HEADER
                            </td>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="row">
                            <td class="_hdr __row">
                                MY HEADER COLUMN:
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                        </tr>
                        <tr class="row">
                            <td class="_hdr __row">
                                MY HEADER COLUMN:
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                            <td class="col">
                                The quick brown fox jumps over the lazy dog.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div id="_bottomAnchor">
            </div>
        </div>
    </body>
    </html>
    

    How do I restart my C# WinForm Application?

    How about create a bat file, run the batch file before closing, and then close the current instance.

    The batch file does this:

    1. wait in a loop to check whether the process has exited.
    2. start the process.

    How to copy data from one HDFS to another HDFS?

    Try dtIngest, it's developed on top of Apache Apex platform. This tool copies data from different sources like HDFS, shared drive, NFS, FTP, Kafka to different destinations. Copying data from remote HDFS cluster to local HDFS cluster is supported by dtIngest. dtIngest runs yarn jobs to copy data in parallel fashion, so it's very fast. It takes care of failure handling, recovery etc. and supports polling directories periodically to do continious copy.

    Usage: dtingest [OPTION]... SOURCEURL... DESTINATIONURL example: dtingest hdfs://nn1:8020/source hdfs://nn2:8020/dest

    How to create an array for JSON using PHP?

    Use PHP's native json_encode, like this:

    <?php
    $arr = array(
        array(
            "region" => "valore",
            "price" => "valore2"
        ),
        array(
            "region" => "valore",
            "price" => "valore2"
        ),
        array(
            "region" => "valore",
            "price" => "valore2"
        )
    );
    
    echo json_encode($arr);
    ?>
    

    Update: To answer your question in the comment. You do it like this:

    $named_array = array(
        "nome_array" => array(
            array(
                "foo" => "bar"
            ),
            array(
                "foo" => "baz"
            )
        )
    );
    echo json_encode($named_array);
    

    Using AND/OR in if else PHP statement

    You have 2 issues here.

    1. use == for comparison. You've used = which is for assignment.

    2. use && for "and" and || for "or". and and or will work but they are unconventional.

    What is the shortcut to Auto import all in Android Studio?

    These are the shortcuts used in Android studio

    Go to class CTRL + N
    Go to file CTRL + Shift + N
    Navigate open tabs ALT + Left-Arrow; ALT + Right-Arrow
    Look up recent files CTRL + E
    Go to line CTRL + G
    Navigate to last edit location CTRL + SHIFT + BACKSPACE
    Go to declaration CTRL + B
    Go to implementation CTRL + ALT + B
    Go to source F4
    Go to super Class CTRL + U
    Show Call hierarchy CTRL + ALT + H
    Search in path/project CTRL + SHIFT + F

    Programming Shortcuts:-

    Reformat code CTRL + ALT + L
    Optimize imports CTRL + ALT + O
    Code Completion CTRL + SPACE
    Issue quick fix ALT + ENTER
    Surround code block CTRL + ALT + T
    Rename and Refractor Shift + F6
    Line Comment or Uncomment CTRL + /
    Block Comment or Uncomment CTRL + SHIFT + /
    Go to previous/next method ALT + UP/DOWN
    Show parameters for method CTRL + P
    Quick documentation lookup CTRL + Q
    Delete a line CTRL + Y
    View declaration in layout CTRL + B

    For more info visit Things worked in Android

    Pycharm and sys.argv arguments

    On PyCharm Community or Professional Edition 2019.1+ :

    1. From the menu bar click Run -> Edit Configurations
    2. Add your arguments in the Parameters textbox (for example file2.txt file3.txt, or --myFlag myArg --anotherFlag mySecondArg)
    3. Click Apply
    4. Click OK

    history.replaceState() example?

    I really wanted to respond to @Sev's answer.

    Sev is right, there is a bug inside the window.history.replaceState

    To fix this simply rewrite the constructor to set the title manually.

    var replaceState_tmp = window.history.replaceState.constructor;
    window.history.replaceState.constructor = function(obj, title, url){
        var title_ = document.getElementsByTagName('title')[0];
        if(title_ != undefined){
            title_.innerHTML = title;
        }else{
            var title__ = document.createElement('title');
            title__.innerHTML = title;
            var head_ = document.getElementsByTagName('head')[0];
            if(head_ != undefined){
                head_.appendChild(title__);
            }else{
                var head__ = document.createElement('head');
                document.documentElement.appendChild(head__);
                head__.appendChild(title__);
            }
        }
        replaceState_tmp(obj,title, url);
    }
    

    Redirect after Login on WordPress

    // add the code to your theme function.php
    //for logout redirection
    add_action('wp_logout','auto_redirect_after_logout');
    function auto_redirect_after_logout(){
    wp_redirect( home_url() );
    exit();
    }
    //for login redirection
    add_action('wp_login','auto_redirect_after_login');
    function auto_redirect_after_login(){
    wp_redirect( home_url() );
    exit();
    `enter code here`}
    

    How to pass parameters in GET requests with jQuery

    The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code

    var id=5;
    $.ajax({
        type: "get",
        url: "url of server side script",
        data:{id:id},
        success: function(res){
            console.log(res);
        },
    error:function(error)
    {
    console.log(error);
    }
    });
    

    At server side receive it using $_GET variable.

    $_GET['id'];
    

    Where does Android app package gets installed on phone

    /data/data/"your app package name " 
    

    but you wont able to read that unless you have a rooted device

    PSQLException: current transaction is aborted, commands ignored until end of transaction block

    I got this error using Java and PostgreSQL doing an insert on a table. I will illustrate how you can reproduce this error:

    org.postgresql.util.PSQLException: ERROR: 
    current transaction is aborted, commands ignored until end of transaction block
    

    Summary:

    The reason you get this error is because you have entered a transaction and one of your SQL Queries failed, and you gobbled up that failure and ignored it. But that wasn't enough, THEN you used that same connection, using the SAME TRANSACTION to run another query. The exception gets thrown on the second, correctly formed query because you are using a broken transaction to do additional work. PostgreSQL by default stops you from doing this.

    I'm using: PostgreSQL 9.1.6 on x86_64-redhat-linux-gnu, compiled by gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2), 64-bit".

    My PostgreSQL driver is: postgresql-9.2-1000.jdbc4.jar

    Using Java version: Java 1.7

    Here is the table create statement to illustrate the Exception:

    CREATE TABLE moobar
    (
        myval   INT
    );
    

    Java program causes the error:

    public void postgresql_insert()
    {
        try  
        {
            connection.setAutoCommit(false);  //start of transaction.
            
            Statement statement = connection.createStatement();
            
            System.out.println("start doing statement.execute");
            
            statement.execute(
                    "insert into moobar values(" +
                    "'this SQL statement fails, and it " +
                    "is gobbled up by the catch, okfine'); ");
         
            //The above line throws an exception because we try to cram
            //A string into an Int.  I Expect this, what happens is we gobble 
            //the Exception and ignore it like nothing is wrong.
            //But remember, we are in a TRANSACTION!  so keep reading.
    
            System.out.println("statement.execute done");
            
            statement.close();
            
        }
        catch (SQLException sqle)
        {
            System.out.println("keep on truckin, keep using " +
                    "the last connection because what could go wrong?");
        }
        
        try{
            Statement statement = connection.createStatement();
            
            statement.executeQuery("select * from moobar");
    
            //This SQL is correctly formed, yet it throws the 
            //'transaction is aborted' SQL Exception, why?  Because:
            //A.  you were in a transaction.
            //B.  You ran a SQL statement that failed.
            //C.  You didn't do a rollback or commit on the affected connection.
            
        }
        catch (SQLException sqle)
        {
            sqle.printStackTrace();
        }   
    
    }
    

    The above code produces this output for me:

    start doing statement.execute
    
    keep on truckin, keep using the last connection because what could go wrong?
    
    org.postgresql.util.PSQLException: 
      ERROR: current transaction is aborted, commands ignored until 
      end of transaction block
    

    Workarounds:

    You have a few options:

    1. Simplest solution: Don't be in a transaction. Set the connection.setAutoCommit(false); to connection.setAutoCommit(true);. It works because then the failed SQL is just ignored as a failed SQL statement. You are welcome to fail SQL statements all you want and PostgreSQL won't stop you.

    2. Stay being in a transaction, but when you detect that the first SQL has failed, either rollback/re-start or commit/restart the transaction. Then you can continue failing as many SQL queries on that database connection as you want.

    3. Don't catch and ignore the Exception that is thrown when a SQL statement fails. Then the program will stop on the malformed query.

    4. Get Oracle instead, Oracle doesn't throw an exception when you fail a query on a connection within a transaction and continue using that connection.

    In defense of PostgreSQL's decision to do things this way... Oracle was making you soft in the middle letting you do dumb stuff and overlooking it.

    How can I delete multiple lines in vi?

    If you prefer a non-visual mode method and acknowledge the line numbers, I would like to suggest you an another straightforward way.

    Example

    I want to delete text from line 45 to line 101.

    My method suggests you to type a below command in command-mode:

    45Gd101G
    

    It reads:

    Go to line 45 (45G) then delete text (d) from the current line to the line 101 (101G).

    Note that on vim you might use gg in stead of G.

    Compare to the @Bonnie Varghese's answer which is:

    :45,101d[enter]
    

    The command above from his answer requires 9 times typing including enter, where my answer require 8 - 10 times typing. Thus, a speed of my method is comparable.

    Personally, I myself prefer 45Gd101G over :45,101d because I like to stick to the syntax of the vi's command, in this case is:

    +---------+----------+--------------------+
    | syntax  | <motion> | <operator><motion> |
    +---------+----------+--------------------+
    | command |   45G    |        d101G       |
    +---------+----------+--------------------+
    

    Of Countries and their Cities

    You can use database from here -

    http://myip.ms/info/cities_sql_database/

    CREATE TABLE `cities` (
      `cityID` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
      `cityName` varchar(50) NOT NULL,
      `stateID` smallint(5) unsigned NOT NULL DEFAULT '0',
      `countryID` varchar(3) NOT NULL DEFAULT '',
      `language` varchar(10) NOT NULL DEFAULT '',
      `latitude` double NOT NULL DEFAULT '0',
      `longitude` double NOT NULL DEFAULT '0',
      PRIMARY KEY (`cityID`),
      UNIQUE KEY `unq` (`countryID`,`stateID`,`cityID`),
      KEY `cityName` (`cityName`),
      KEY `stateID` (`stateID`),
      KEY `countryID` (`countryID`),
      KEY `latitude` (`latitude`),
      KEY `longitude` (`longitude`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
    

    django - get() returned more than one topic

    To add to CrazyGeek's answer, get or get_or_create queries work only when there's one instance of the object in the database, filter is for two or more.

    If a query can be for single or multiple instances, it's best to add an ID to the div and use an if statement e.g.

    def updateUserCollection(request):
        data = json.loads(request.body)
        card_id = data['card_id']
        action = data['action']
    
        user = request.user
        card = Cards.objects.get(card_id=card_id)
    
        if data-action == 'add':
            collection = Collection.objects.get_or_create(user=user, card=card)
            collection.quantity + 1
            collection.save()
    
        elif data-action == 'remove':
            collection = Cards.objects.filter(user=user, card=card)
            collection.quantity = 0
            collection.update()
    

    Note: .save() becomes .update() for updating multiple objects. Hope this helps someone, gave me a long day's headache.

    Tower of Hanoi: Recursive Algorithm

    After reading all these explanations I thought I'd weigh in with the method my professor used to explain the Towers of Hanoi recursive solution. Here is the algorithm again with n representing the number of rings, and A, B, C representing the pegs. The first parameter of the function is the number of rings, second parameter represents the source peg, the third is the destination peg, and fourth is the spare peg.

    procedure Hanoi(n, A, B, C);
      if n == 1
        move ring n from peg A to peg B
      else
        Hanoi(n-1, A, C, B);
        move ring n-1 from A to C
        Hanoi(n-1, C, B, A);
    end;
    

    I was taught in graduate school to never to be ashamed to think small. So, let's look at this algorithm for n = 5. The question to ask yourself first is if I want to move the 5th ring from A to B, where are the other 4 rings? If the 5th ring occupies peg A and we want to move it to peg B, then the other 4 rings can only be on peg C. In the algorithm above the function Hanoi (n-1, A, C, B) is trying to move all those 4 other rings on to peg C, so ring 5 will be able to move from A to B. Following this algorithm we look at n = 4. If ring 4 will be moved from A to C, where are rings 3 and smaller? They can only be on peg B. Next, for n = 3, if ring 3 will be moved from A to B, where are rings 2 and 1? On peg C of course. If you continue to follow this pattern you can visualize what the recursive algorithm is doing. This approach differs from the novice's approach in that it looks at the last disk first and the first disk last.

    Android Studio - No JVM Installation found

    1 .Download 64 bit version of JDK from here

    enter image description here

    1. As shown in next picture, go to Control Panel -> System and Security -> Advanced system settings -> Environment Variables -> New (System variables)

    2. Then add variable name: JAVA_HOME and variable value: C:\Program Files\Java\jdk1.8.0_25

    Please note that jdk1.8.0_25 may be vary depending on JDK version. enter image description here

    1. Click OK button on the rest of the windows left.

    How do I install PyCrypto on Windows?

    So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error "RuntimeError: chmod error".

    You need to install msys package under MinGW

    enter image description here

    and add following entries in your PATH env variable.

    • C:\MinGW\bin
    • C:\MinGW\msys\1.0\bin [This is where you will find chmod executable]

    Then run your command from normal windows command prompt.

    Is it possible to run one logrotate check manually?

    logrotate -d [your_config_file] invokes debug mode, giving you a verbose description of what would happen, but leaving the log files untouched.

    How to align texts inside of an input?

    Use the text-align property in your CSS:

    input { 
        text-align: right; 
    }
    

    This will take effect in all the inputs of the page.
    Otherwise, if you want to align the text of just one input, set the style inline:

    <input type="text" style="text-align:right;"/> 
    

    Best algorithm for detecting cycles in a directed graph

    https://mathoverflow.net/questions/16393/finding-a-cycle-of-fixed-length I like this solution the best specially for 4 length:)

    Also phys wizard says u have to do O(V^2). I believe that we need only O(V)/O(V+E). If the graph is connected then DFS will visit all nodes. If the graph has connected sub graphs then each time we run a DFS on a vertex of this sub graph we will find the connected vertices and wont have to consider these for the next run of the DFS. Therefore the possibility of running for each vertex is incorrect.

    Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

    You need to merge the remote branch into your current branch by running git pull.

    If your local branch is already up-to-date, you may also need to run git pull --rebase.

    A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

    How to get previous page url using jquery

    Easy as pie.

    $(document).ready(function() {
       var referrer =  document.referrer;
    });
    

    Hope it helps. It is not always available though.

    What is Model in ModelAndView from Spring MVC?

    Well, WelcomeMessage is just a variable name for message (actual model with data). Basically, you are binding the model with the welcomePage here. The Model (message) will be available in welcomePage.jsp as WelcomeMessage. Here is a simpler example:

    ModelAndView("hello","myVar", "Hello World!");
    

    In this case, my model is a simple string (In applications this will be a POJO with data fetched for DB or other sources.). I am assigning it to myVar and my view is hello.jsp. Now, myVar is available for me in hello.jsp and I can use it for display.

    In the view, you can access the data though:

    ${myVar}
    

    Similarly, You will be able to access the model through WelcomeMessage variable.

    How to modify list entries during for loop?

    One more for loop variant, looks cleaner to me than one with enumerate():

    for idx in range(len(list)):
        list[idx]=... # set a new value
        # some other code which doesn't let you use a list comprehension
    

    What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

    for win xp

    Steps

    1. [windows key] + R, type services.msc, search for the running instance of "Windows Presentation Foundation (WPF) Font Cache". For my case its 4.0. Stop the service.
    2. [windows key] + R, type C:\Documents and Settings\LocalService\Local Settings\Application Data\, delete all font cache files.
    3. Start the "Windows Presentation Foundation (WPF) Font Cache" service.

    How can I use nohup to run process as a background process in linux?

    In general, I use nohup CMD & to run a nohup background process. However, when the command is in a form that nohup won't accept then I run it through bash -c "...".

    For example:

    nohup bash -c "(time ./script arg1 arg2 > script.out) &> time_n_err.out" &
    

    stdout from the script gets written to script.out, while stderr and the output of time goes into time_n_err.out.

    So, in your case:

    nohup bash -c "(time bash executeScript 1 input fileOutput > scrOutput) &> timeUse.txt" &
    

    How can I export data to an Excel file

    Have you ever hear NPOI, a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop. Github Page

    This is my Excel Export class

    /*
     * User: TMPCSigit [email protected]
     * Date: 25/11/2019
     * Time: 11:28
     * 
     */
    using System;
    using System.IO;
    using System.Text.RegularExpressions;
    using System.Windows.Forms;
    
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    
    namespace Employee_Manager
    {
        public static class ExportHelper
        {       
            public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, string value )
            {
                var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
                var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );
    
                cell.SetCellValue( value );
            }
            public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, double value )
            {
                var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
                var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );
    
                cell.SetCellValue( value );
            }
            public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, DateTime value )
            {
                var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
                var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );
    
                cell.SetCellValue( value );
            }
            public static void WriteStyle( ISheet sheet, int columnIndex, int rowIndex, ICellStyle style )
            {
                var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
                var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );
    
                cell.CellStyle = style;
            }
    
            public static IWorkbook CreateNewBook( string filePath )
            {
                IWorkbook book;
                var extension = Path.GetExtension( filePath );
    
                // HSSF => Microsoft Excel(xls??)(excel 97-2003)
                // XSSF => Office Open XML Workbook??(xlsx??)(excel 2007??)
                if( extension == ".xls" ) {
                    book = new HSSFWorkbook();
                }
                else if( extension == ".xlsx" ) {
                    book = new XSSFWorkbook();
                }
                else {
                    throw new ApplicationException( "CreateNewBook: invalid extension" );
                }
    
                return book;
            }
            public static void createXls(DataGridView dg){
                try {
                    string filePath = "";
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel XLS (*.xls)|*.xls";
                    sfd.FileName = "Export.xls";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        filePath = sfd.FileName;
                        var book = CreateNewBook( filePath );
                        book.CreateSheet( "Employee" );
                        var sheet = book.GetSheet( "Employee" );
                        int columnCount = dg.ColumnCount;
                        string columnNames = "";
                        string[] output = new string[dg.RowCount + 1];
                        for (int i = 0; i < columnCount; i++)
                        {
                            WriteCell( sheet, i, 0, SplitCamelCase(dg.Columns[i].Name.ToString()) );
                        }
                        for (int i = 0; i < dg.RowCount; i++)
                        {
                            for (int j = 0; j < columnCount; j++)
                            {
                                var celData =  dg.Rows[i].Cells[j].Value;
                                if(celData == "" || celData == null){
                                    celData = "-";
                                }
                                if(celData.ToString() == "System.Drawing.Bitmap"){
                                    celData = "Ada";
                                }
                                WriteCell( sheet, j, i+1, celData.ToString() );
                            }
                        }
                        var style = book.CreateCellStyle();
                        style.DataFormat = book.CreateDataFormat().GetFormat( "yyyy/mm/dd" );
                        WriteStyle( sheet, 0, 4, style );
                        using( var fs = new FileStream( filePath, FileMode.Create ) ) {
                            book.Write( fs );
                        }
                    }
                }
                catch( Exception ex ) {
                    Console.WriteLine( ex );
                }
            }
            public static string SplitCamelCase(string input)
            {
                return Regex.Replace(input, "(?<=[a-z])([A-Z])", " $1", RegexOptions.Compiled);
            }
        }
    }
    

    Formatting DataBinder.Eval data

    <asp:Label ID="ServiceBeginDate" runat="server" Text='<%# (DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:yyyy}") == "0001") ? "" : DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:MM/dd/yyyy}") %>'>
    </asp:Label>
    

    How to delete an element from an array in C#

    If you want to remove all instances of 4 without needing to know the index:

    LINQ: (.NET Framework 3.5)

    int[] numbers = { 1, 3, 4, 9, 2 };
    int numToRemove = 4;
    numbers = numbers.Where(val => val != numToRemove).ToArray();
    

    Non-LINQ: (.NET Framework 2.0)

    static bool isNotFour(int n)
    {
        return n != 4;
    }
    
    int[] numbers = { 1, 3, 4, 9, 2 };
    numbers = Array.FindAll(numbers, isNotFour).ToArray();
    

    If you want to remove just the first instance:

    LINQ: (.NET Framework 3.5)

    int[] numbers = { 1, 3, 4, 9, 2, 4 };
    int numToRemove = 4;
    int numIndex = Array.IndexOf(numbers, numToRemove);
    numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();
    

    Non-LINQ: (.NET Framework 2.0)

    int[] numbers = { 1, 3, 4, 9, 2, 4 };
    int numToRemove = 4;
    int numIdx = Array.IndexOf(numbers, numToRemove);
    List<int> tmp = new List<int>(numbers);
    tmp.RemoveAt(numIdx);
    numbers = tmp.ToArray();
    

    Edit: Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.

    Convert Mercurial project to Git

    From:

    http://hivelogic.com/articles/converting-from-mercurial-to-git

    Migrating

    It’s a relatively simple process. First we download fast-export (the best way is via its Git repository, which I’ll clone right to the desktop), then we create a new git repository, perform the migration, and check out the HEAD. On the command line, it goes like this:

    cd ~/Desktop
    git clone git://repo.or.cz/fast-export.git
    git init git_repo
    cd git_repo
    ~/Desktop/fast-export/hg-fast-export.sh -r /path/to/old/mercurial_repo
    git checkout HEAD
    

    You should see a long listing of commits fly by as your project is migrated after running fast-export. If you see errors, they are likely related to an improperly specified Python path (see the note above and customize for your system).

    That’s it, you’re done.

    Finding modified date of a file/folder

    To get the modified date on a single file try:

    $lastModifiedDate = (Get-Item "C:\foo.tmp").LastWriteTime
    

    To compare with another:

    $dateA= $lastModifiedDate 
    $dateB= (Get-Item "C:\other.tmp").LastWriteTime
    
    if ($dateA -ge $dateB) {
      Write-Host("C:\foo.tmp was modified at the same time or after C:\other.tmp")
    } else {
      Write-Host("C:\foo.tmp was modified before C:\other.tmp")
    }
    

    How to convert Nvarchar column to INT

    You can always use the ISNUMERIC helper function to convert only what's really numeric:

    SELECT
         CAST(A.my_NvarcharColumn AS BIGINT)
    FROM 
         A
    WHERE
         ISNUMERIC(A.my_NvarcharColumn) = 1
    

    Is it possible to get only the first character of a String?

    Use ld.charAt(0). It will return the first char of the String.

    With ld.substring(0, 1), you can get the first character as String.

    ios simulator: how to close an app

    You can also kill the app by process id

    ps -cx -o pid,command | awk '$2 == "YourAppNameCaseSensitive" { print $1 }' | xargs kill -9
    

    Is it a good idea to index datetime field in mysql?

    Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.

    Finding all positions of substring in a larger string in C#

    using LINQ

    public static IEnumerable<int> IndexOfAll(this string sourceString, string subString)
    {
        return Regex.Matches(sourceString, subString).Cast<Match>().Select(m => m.Index);
    }
    

    HTML not loading CSS file

    guys the best thing to try is to refreash the whole website by pressing ctrl + F5 on mac it is CMD + R

    Check mySQL version on Mac 10.8.5

    Every time you used the mysql console, the version is shown.

     mysql -u user
    

    Successful console login shows the following which includes the mysql server version.

    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 1432
    Server version: 5.5.9-log Source distribution
    
    Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    mysql>
    

    You can also check the mysql server version directly by executing the following command:

    mysql --version
    

    You may also check the version information from the mysql console itself using the version variables:

    mysql> SHOW VARIABLES LIKE "%version%";
    

    Output will be something like this:

    +-------------------------+---------------------+
    | Variable_name           | Value               |
    +-------------------------+---------------------+
    | innodb_version          | 1.1.5               |
    | protocol_version        | 10                  |
    | slave_type_conversions  |                     |
    | version                 | 5.5.9-log           |
    | version_comment         | Source distribution |
    | version_compile_machine | i386                |
    | version_compile_os      | osx10.4             |
    +-------------------------+---------------------+
    7 rows in set (0.01 sec)
    

    You may also use this:

    mysql> select @@version;
    

    The STATUS command display version information as well.

    mysql> STATUS
    

    You can also check the version by executing this command:

    mysql -v
    

    It's worth mentioning that if you have encountered something like this:

    ERROR 2002 (HY000): Can't connect to local MySQL server through socket
    '/tmp/mysql.sock' (2)
    

    you can fix it by:

    sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock
    

    What is the best way to search the Long datatype within an Oracle database?

    First convert LONG type column to CLOB type then use LIKE condition, for example:

    CREATE TABLE tbl_clob AS
       SELECT to_lob(long_col) lob_col FROM tbl_long;
    
    SELECT * FROM tbl_clob WHERE lob_col LIKE '%form%';
    

    How to kill all processes matching a name?

    The safe way to do this is:

    pkill -f amarok
    

    How do I debug "Error: spawn ENOENT" on node.js?

    As @DanielImfeld pointed it, ENOENT will be thrown if you specify "cwd" in the options, but the given directory does not exist.

    cancelling a handler.postdelayed process

    In case you do have multiple inner/anonymous runnables passed to same handler, and you want to cancel all at same event use

    handler.removeCallbacksAndMessages(null);

    As per documentation,

    Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

    Converting time stamps in excel to dates

    The answer of @NeplatnyUdaj is right but consider that Excel want the function name in the set language, in my case German. Then you need to use "DATUM" instead of "DATE":

    =(((COLUMN_ID_HERE/60)/60)/24)+DATUM(1970,1,1)
    

    Pass user defined environment variable to tomcat

    In case of Windows, if you can't find setenv.bat, in the 2nd line of catalina.bat (after @echo off) add this:
    SET APP_MASTER_PASSWORD=foo

    May not be the best approach, but works

    Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

    Google Hosted jQuery

    • If you care about older browsers, primarily versions of IE prior to IE9, this is the most widely compatible jQuery version
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    • If you don’t care about oldIE, this one is smaller and faster:
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

    Backup/Fallback Plan!

    • Either way, you should use a fallback to local just in case the Google CDN fails (unlikely) or is blocked in a location that your users access your site from (slightly more likely), like Iran or sometimes China.
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>if (!window.jQuery) { document.write('<script src="/path/to/your/jquery"><\/script>'); }
    </script>
    

    Reference: http://websitespeedoptimizations.com/ContentDeliveryNetworkPost.aspx

    What is the correct format to use for Date/Time in an XML file

    If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ")); That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.

    Remove an onclick listener

    Perhaps setOnClickListener(null) ?

    Break statement in javascript array map method

    That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

    var hasValueLessThanTen = false;
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i] < 10) {
        hasValueLessThanTen = true;
        break;
      }
    }
    

    Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

    var hasValueLessThanTen = myArray.some(function (val) { 
      return val < 10;
    });
    

    Calculating distance between two points (Latitude, Longitude)

    As you're using SQL 2008 or later, I'd recommend checking out the GEOGRAPHY data type. SQL has built in support for geospatial queries.

    e.g. you'd have a column in your table of type GEOGRAPHY which would be populated with a geospatial representation of the coordinates (check out the MSDN reference linked above for examples). This datatype then exposes methods allowing you to perform a whole host of geospatial queries (e.g. finding the distance between 2 points)

    Java: how do I initialize an array size if it's unknown?

    If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.

    import java.util.Scanner;
    
    public class ArrayModify {
    
        public static void main(String[] args) {
            int[] list;
            String st;
            String[] stNew;
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9 
            st = scan.nextLine();
            stNew = st.split("\\s+");
            list = new int[stNew.length]; // Sets array size to 5
    
            for (int i = 0; i < stNew.length; i++){
                list[i] =  Integer.parseInt(stNew[i]);
                System.out.println("You Enterred: " + list[i]);
            }
        }
    }
    

    Hook up Raspberry Pi via Ethernet to laptop without router?

    configure static ip on the raspberry pi:

    sudo nano /etc/network/interfaces
    

    and then add:

    iface eth0 inet static
         address 169.254.0.2
         netmask 255.255.255.0
         broadcast 169.254.0.255
    

    then you can acces your raspberry via ssh

    ssh [email protected]
    

    jQuery add required to input fields

    $("input").prop('required',true);
    

    DEMO FIDDLE

    Hide Button After Click (With Existing Form on Page)

    Change the button to :

    <button onclick="getElementById('hidden-div').style.display = 'block'; this.style.display = 'none'">Check Availability</button>
    

    FIDDLE

    Or even better, use a proper event handler by identifying the button :

    <button id="show_button">Check Availability</button>
    

    and a script

    <script type="text/javascript">
        var button = document.getElementById('show_button')
        button.addEventListener('click',hideshow,false);
    
        function hideshow() {
            document.getElementById('hidden-div').style.display = 'block'; 
            this.style.display = 'none'
        }   
    </script>
    

    FIDDLE

    Binding to static property

    You can't bind to a static like that. There's no way for the binding infrastructure to get notified of updates since there's no DependencyObject (or object instance that implement INotifyPropertyChanged) involved.

    If that value doesn't change, just ditch the binding and use x:Static directly inside the Text property. Define app below to be the namespace (and assembly) location of the VersionManager class.

    <TextBox Text="{x:Static app:VersionManager.FilterString}" />
    

    If the value does change, I'd suggest creating a singleton to contain the value and bind to that.

    An example of the singleton:

    public class VersionManager : DependencyObject {
        public static readonly DependencyProperty FilterStringProperty =
            DependencyProperty.Register( "FilterString", typeof( string ),
            typeof( VersionManager ), new UIPropertyMetadata( "no version!" ) );
        public string FilterString {
            get { return (string) GetValue( FilterStringProperty ); }
            set { SetValue( FilterStringProperty, value ); }
        }
    
        public static VersionManager Instance { get; private set; }
    
        static VersionManager() {
            Instance = new VersionManager();
        }
    }
    
    <TextBox Text="{Binding Source={x:Static local:VersionManager.Instance},
                            Path=FilterString}"/>
    

    Quicksort with Python

    def Partition(A,p,q):
        i=p
        x=A[i]
        for j in range(p+1,q+1):
            if A[j]<=x:
                i=i+1
                tmp=A[j]
                A[j]=A[i]
                A[i]=tmp
        l=A[p]
        A[p]=A[i]
        A[i]=l
        return i
    
    def quickSort(A,p,q):
        if p<q:
            r=Partition(A,p,q)
            quickSort(A,p,r-1)
            quickSort(A,r+1,q)
        return A
    

    Python: For each list element apply a function across the list

    Doing it the mathy way...

    nums = [1, 2, 3, 4, 5]
    min_combo = (min(nums), max(nums))
    

    Unless, of course, you have negatives in there. In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. And double negatives would break it.

    Stretch Image to Fit 100% of Div Height and Width

    You're mixing notations. It should be:

    <img src="folder/file.jpg" width="200" height="200">
    

    (note, no px). Or:

    <img src="folder/file.jpg" style="width: 200px; height: 200px;">
    

    (using the style attribute) The style attribute could be replaced with the following CSS:

    #mydiv img {
        width: 200px;
        height: 200px;
    }
    

    or

    #mydiv img {
        width: 100%;
        height: 100%;
    }