Programs & Examples On #Oc4j

OC4J is the Oracle Application Server (Oracle Container 4 Java, formerly Orion), up to Oracle 10g.

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I had the same problem but was able to fix it by doing the following:

Right-click on the project -> Properties, then add the JAR (odjbc6 or 14) file in the deployment assembly.

Execute jQuery function after another function completes

You can use below code

$.when( Typer() ).done(function() {
       playBGM();
});

How do I replace a character in a string in Java?

Try using String.replace() or String.replaceAll() instead.

String my_new_str = my_str.replace("&", "&");

(Both replace all occurrences; replaceAll allows use of regex.)

How to set opacity to the background color of a div?

CSS 3 introduces rgba colour, and you can combine it with graphics for a backwards compatible solution.

typeof !== "undefined" vs. != null

_x000D_
_x000D_
(function(){_x000D_
_x000D_
  var a= b = 3;_x000D_
  var ed = 103;_x000D_
  _x000D_
})();_x000D_
_x000D_
_x000D_
_x000D_
//console.log(ed); //ed is not defined_x000D_
_x000D_
console.log("a defined? " + (typeof a !== 'undefined')); //no define_x000D_
console.log("b defined? " + (typeof b !== 'undefined')); //yes define_x000D_
console.log(typeof(b)); //number_x000D_
console.log(typeof(4+7));   //number_x000D_
console.log(b); //3_x000D_
console.log(typeof("4"+"7")); //string_x000D_
var e= "ggg";_x000D_
console.log(typeof(e)); //string_x000D_
 var ty=typeof(b);_x000D_
console.log(ty); //number_x000D_
console.log(typeof false); //boolean_x000D_
console.log(typeof 1); //number_x000D_
console.log(typeof 0); //number_x000D_
console.log(typeof true); //boolean_x000D_
_x000D_
_x000D_
console.log(typeof Math.tan);  //function_x000D_
console.log(typeof function(){}); //function _x000D_
_x000D_
if(typeof neverDeclared == "undefined") //no errors_x000D_
if(typeof neverDeclared === "undefined") //no errors_x000D_
_x000D_
//if(neverDeclared == null) //showing error _x000D_
_x000D_
_x000D_
console.log(typeof {a:1}); //object_x000D_
console.log(typeof null); //object_x000D_
console.log(typeof JSON); //object_x000D_
console.log(typeof Math); //object_x000D_
console.log(typeof /a-z/); //object_x000D_
console.log(typeof new Date()); //object_x000D_
_x000D_
console.log(typeof afbc); //undefined_x000D_
//console.log(typeof new);//error_x000D_
_x000D_
document.write("<br> * oprator as math ");_x000D_
var r=14*"4";_x000D_
document.write(r);_x000D_
_x000D_
document.write("<br> + oprator as string ");_x000D_
var r=14+"44";_x000D_
document.write(r);_x000D_
_x000D_
document.write("<br> Minus Operator work as mathematic ");_x000D_
var r=64-"44";_x000D_
document.write(r);_x000D_
_x000D_
_x000D_
document.write("<br>");_x000D_
console.log(typeof(4*"7")); //returns number_x000D_
console.log(typeof(4+"7")); //returns string_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 
_x000D_
Interview Question in JavaScript
_x000D_
_x000D_
_x000D_

How to iterate over a JSONObject?

org.json.JSONObject now has a keySet() method which returns a Set<String> and can easily be looped through with a for-each.

for(String key : jsonObject.keySet())

Google Script to see if text contains a value

Google Apps Script is javascript, you can use all the string methods...

var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }

You can find doc on many sites, this one for example.

How to make RatingBar to show five stars

If you are using

android:layout_width="match_parent"

Use wrap_content and it will only show the set numStars :)

android:layout_width="wrap_content"

Repeat table headers in print mode

This is what the THEAD element is for. Official docs here.

Set a div width, align div center and text align left

Try:

#your_div_id {
  width: 855px;
  margin:0 auto;
  text-align: center;
}

How to properly assert that an exception gets raised in pytest?

If you want to test for a specific error type, use a combination of try, catch and raise:

#-- test for TypeError
try:
  myList.append_number("a")
  assert False
except TypeError: pass
except: assert False

Adding Jar files to IntellijIdea classpath

If, as I just encountered, you happen to have a jar file listed in the Project Structures->Libraries that is not in your classpath, the correct answer can be found by following the link given by @CrazyCoder above: Look here http://www.jetbrains.com/idea/webhelp/configuring-module-dependencies-and-libraries.html

This says that to add the jar file as a module dependency within the Project Structure dialog:

  1. Open Project Structure
  2. Select Modules, then click on the module for which you want the dependency
  3. Choose the Dependencies tab
  4. Click the '+' at the bottom of the page and choose the appropriate way to connect to the library file. If the jar file is already listed in Libraries, then select 'Library'.

How to post JSON to PHP with curl

I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).

Try changing your curl request to:

curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}'  \
      http://localhost:3570/index.php/trainingServer/screencast.json

and see if that helps any.

Why is my toFixed() function not working?

I tried function toFixed(2) many times. Every time console shows "toFixed() is not a function".

but how I resolved is By using Math.round()

eg:

if ($(this).attr('name') == 'time') {
    var value = parseFloat($(this).val());
    value = Math.round(value*100)/100; // 10 defines 1 decimals, 100 for 2, 1000 for 3
    alert(value);
}

this thing surely works for me and it might help you guys too...

How to install Anaconda on RaspBerry Pi 3 Model B

If you're interested in generalizing to different architectures, you could also run the command above and substitute uname -m in with backticks like so:

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-`uname -m`.sh

Express: How to pass app-instance to routes from a different file?

  1. To make your db object accessible to all controllers without passing it everywhere: make an application-level middleware which attachs the db object to every req object, then you can access it within in every controller.
// app.js
let db = ...;  // your db object initialized
const contextMiddleware = (req, res, next) => {
  req.db=db;
  next();
};
app.use(contextMiddleware);
  1. to avoid passing app instance everywhere, instead, passing routes to where the app is
// routes.js  It's just a mapping.
exports.routes = [
  ['/', controllers.index],
  ['/posts', controllers.posts.index],
  ['/posts/:post', controllers.posts.show]
];

// app.js
var { routes }    = require('./routes');
routes.forEach(route => app.get(...route));
// You can customize this according to your own needs, like adding post request

The final app.js:

// app.js
var express   = require('express');
var app       = express.createServer();

let db = ...;  // your db object initialized
const contextMiddleware = (req, res, next) => {
  req.db=db;
  next();
};
app.use(contextMiddleware);

var { routes }    = require('./routes');
routes.forEach(route => app.get(...route));

app.listen(3000, function() {
  console.log('Application is listening on port 3000');
});

Another version: you can customize this according to your own needs, like adding post request

// routes.js  It's just a mapping.
let get = ({path, callback}) => ({app})=>{
  app.get(path, callback);
}
let post = ({path, callback}) => ({app})=>{
  app.post(path, callback);
}
let someFn = ({path, callback}) => ({app})=>{
  // ...custom logic
  app.get(path, callback);
}
exports.routes = [
  get({path: '/', callback: controllers.index}),
  post({path: '/posts', callback: controllers.posts.index}),
  someFn({path: '/posts/:post', callback: controllers.posts.show}),
];

// app.js
var { routes }    = require('./routes');
routes.forEach(route => route({app}));

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

I had the exact same problem, found that I was missing

<mdb>  
  <resource-adapter-ref resource-adapter-name="hornetq-ra"/>  
  <bean-instance-pool-ref pool-name="mdb-strict-max-pool"/>  
</mdb>  

under

<subsystem xmlns="urn:jboss:domain:ejb3:1.2">  

in standalone/configuration/standalone.xml

How to stretch in width a WPF user control to its window?

You need to make sure your usercontrol hasn't set it's width in the usercontrol's xaml file. Just delete the Width="..." from it and you're good to go!

EDIT: This is the code I tested it with:

SOUserAnswerTest.xaml:

<UserControl x:Class="WpfApplication1.SOAnswerTest"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Name="LeftSideMenu" Width="100"/>
            <ColumnDefinition Name="Middle" Width="*"/>
            <ColumnDefinition Name="RightSideMenu" Width="90"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0">a</TextBlock>
        <TextBlock Grid.Column="1">b</TextBlock>
        <TextBlock Grid.Column="2">c</TextBlock>
    </Grid>
</UserControl>

Window1.xaml:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="Window1" Height="300" Width="415">
    <Grid>

        <local:SOAnswerTest Grid.Column="0" Grid.Row="5" Grid.ColumnSpan="2"/>
    </Grid>
</Window>

What is SELF JOIN and when would you use it?

Well, one classic example is where you wanted to get a list of employees and their immediate managers:

select e.employee as employee, b.employee as boss
from emptable e, emptable b
where e.manager_id = b.empolyee_id
order by 1

It's basically used where there is any relationship between rows stored in the same table.

  • employees.
  • multi-level marketing.
  • machine parts.

And so on...

Difference between Eclipse Europa, Helios, Galileo

To see a list of the Eclipse release name and it's corresponding version number go to this website. http://en.wikipedia.org/wiki/Eclipse_%28software%29#Release

  • Release Date Platform version
  • Juno ?? June 2012 4.2?
  • Indigo 22 June 2011 3.7
  • Helios 23 June 2010 3.6
  • Galileo 24 June 2009 3.5
  • Ganymede 25 June 2008 3.4
  • Europa 29 June 2007 3.3
  • Callisto 30 June 2006 3.2
  • Eclipse 3.1 28 June 2005 3.1
  • Eclipse 3.0 21 June 2004 3.0

I too dislike the way that the Eclipse foundation DOES NOT use the version number for their downloads or on the Help -> About Eclipse dialog. They do display the version on the download webpage, but the actual file name is something like:

  • eclipse-java-indigo-SR1-linux-gtk.tar.gz
  • eclipse-java-helios-linux-gtk.tar.gz

But over time, you forget what release name goes with what version number. I would much prefer a file naming convention like:

  • eclipse-3.7.1-java-indigo-SR1-linux-gtk.tar.gz
  • eclipse-3.6-java-helios-linux-gtk.tar.gz

This way you get BOTH from the file name and it is sortable in a directory listing. Fortunately, they mostly choose names are alphabetically after the previous one (except for 3.4-Ganymede vs the newer 3.5-Galileo).

Read int values from a text file in C

How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2); 

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

Getting the thread ID from a thread

To find the current thread Id use - `Thread.CurrentThread.ManagedThreadId'. But in this case you might need the current win32 thread id - use pInvoke to get it with this function:

[DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
public static extern Int32 GetCurrentWin32ThreadId();

First you'll need to save the managed thread id and win32 thread id connection - use a dictionary that maps a win32 id to managed thread.

Then to find a thread by it's id iterate over the process's thread using Process.GetCurrentProcess().Threads and find the thread with that id:

foreach (ProcessThread thread in Process.GetCurrentProcess().Threads)
{
     var managedThread = win32ToManagedThread[thread.id];
     if((managedThread.ManagedThreadId == threadId)
     {
         return managedThread;
     }
}

Fast query runs slow in SSRS

Add this to the end of your proc: option(recompile)

This will make the report run almost as fast as the stored procedure

Get MIME type from filename extension

a combination of both solutions presented here:

using System;
using System.Collections.Generic;

namespace Mime
{
    class Mime
    {

        public static string GetMimeType(string fileName)
        {
            if (string.IsNullOrEmpty(fileName) || string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("filename must contain a filename");
            }
            string extension = System.IO.Path.GetExtension(fileName).ToLower();

            if (!extension.StartsWith("."))
            {
                extension = "." + extension;
            }


            string mime;

            if (_mappings.TryGetValue(extension, out mime))
                return mime;
            if (GetWindowsMimeType(extension, out mime))
            {
                _mappings.Add(extension, mime);
                return mime;
            }
            return "application/octet-stream";
        }

        public static bool GetWindowsMimeType(string ext, out string mime)
        {
            mime="application/octet-stream";
            Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);

            if (regKey != null)
            { 
             object val=regKey.GetValue("Content Type") ;
             if (val != null)
             {
                 string strval = val.ToString();
                 if(!(string.IsNullOrEmpty(strval)||string.IsNullOrWhiteSpace(strval)))
                 {
                     mime=strval;
                     return true;
                 }
             }
            }
            return false;
        }

        static IDictionary<string, string> _mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {

        #region Big freaking list of mime types
        // combination of values from Windows 7 Registry and 
        // from C:\Windows\System32\inetsrv\config\applicationHost.config
        // some added, including .7z and .dat
        {".323", "text/h323"},
        {".3g2", "video/3gpp2"},
        {".3gp", "video/3gpp"},
        {".3gp2", "video/3gpp2"},
        {".3gpp", "video/3gpp"},
        {".7z", "application/x-7z-compressed"},
        {".aa", "audio/audible"},
        {".AAC", "audio/aac"},
        {".aaf", "application/octet-stream"},
        {".aax", "audio/vnd.audible.aax"},
        {".ac3", "audio/ac3"},
        {".aca", "application/octet-stream"},
        {".accda", "application/msaccess.addin"},
        {".accdb", "application/msaccess"},
        {".accdc", "application/msaccess.cab"},
        {".accde", "application/msaccess"},
        {".accdr", "application/msaccess.runtime"},
        {".accdt", "application/msaccess"},
        {".accdw", "application/msaccess.webapplication"},
        {".accft", "application/msaccess.ftemplate"},
        {".acx", "application/internet-property-stream"},
        {".AddIn", "text/xml"},
        {".ade", "application/msaccess"},
        {".adobebridge", "application/x-bridge-url"},
        {".adp", "application/msaccess"},
        {".ADT", "audio/vnd.dlna.adts"},
        {".ADTS", "audio/aac"},
        {".afm", "application/octet-stream"},
        {".ai", "application/postscript"},
        {".aif", "audio/x-aiff"},
        {".aifc", "audio/aiff"},
        {".aiff", "audio/aiff"},
        {".air", "application/vnd.adobe.air-application-installer-package+zip"},
        {".amc", "application/x-mpeg"},
        {".application", "application/x-ms-application"},
        {".art", "image/x-jg"},
        {".asa", "application/xml"},
        {".asax", "application/xml"},
        {".ascx", "application/xml"},
        {".asd", "application/octet-stream"},
        {".asf", "video/x-ms-asf"},
        {".ashx", "application/xml"},
        {".asi", "application/octet-stream"},
        {".asm", "text/plain"},
        {".asmx", "application/xml"},
        {".aspx", "application/xml"},
        {".asr", "video/x-ms-asf"},
        {".asx", "video/x-ms-asf"},
        {".atom", "application/atom+xml"},
        {".au", "audio/basic"},
        {".avi", "video/x-msvideo"},
        {".axs", "application/olescript"},
        {".bas", "text/plain"},
        {".bcpio", "application/x-bcpio"},
        {".bin", "application/octet-stream"},
        {".bmp", "image/bmp"},
        {".c", "text/plain"},
        {".cab", "application/octet-stream"},
        {".caf", "audio/x-caf"},
        {".calx", "application/vnd.ms-office.calx"},
        {".cat", "application/vnd.ms-pki.seccat"},
        {".cc", "text/plain"},
        {".cd", "text/plain"},
        {".cdda", "audio/aiff"},
        {".cdf", "application/x-cdf"},
        {".cer", "application/x-x509-ca-cert"},
        {".chm", "application/octet-stream"},
        {".class", "application/x-java-applet"},
        {".clp", "application/x-msclip"},
        {".cmx", "image/x-cmx"},
        {".cnf", "text/plain"},
        {".cod", "image/cis-cod"},
        {".config", "application/xml"},
        {".contact", "text/x-ms-contact"},
        {".coverage", "application/xml"},
        {".cpio", "application/x-cpio"},
        {".cpp", "text/plain"},
        {".crd", "application/x-mscardfile"},
        {".crl", "application/pkix-crl"},
        {".crt", "application/x-x509-ca-cert"},
        {".cs", "text/plain"},
        {".csdproj", "text/plain"},
        {".csh", "application/x-csh"},
        {".csproj", "text/plain"},
        {".css", "text/css"},
        {".csv", "text/csv"},
        {".cur", "application/octet-stream"},
        {".cxx", "text/plain"},
        {".dat", "application/octet-stream"},
        {".datasource", "application/xml"},
        {".dbproj", "text/plain"},
        {".dcr", "application/x-director"},
        {".def", "text/plain"},
        {".deploy", "application/octet-stream"},
        {".der", "application/x-x509-ca-cert"},
        {".dgml", "application/xml"},
        {".dib", "image/bmp"},
        {".dif", "video/x-dv"},
        {".dir", "application/x-director"},
        {".disco", "text/xml"},
        {".dll", "application/x-msdownload"},
        {".dll.config", "text/xml"},
        {".dlm", "text/dlm"},
        {".doc", "application/msword"},
        {".docm", "application/vnd.ms-word.document.macroEnabled.12"},
        {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
        {".dot", "application/msword"},
        {".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
        {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
        {".dsp", "application/octet-stream"},
        {".dsw", "text/plain"},
        {".dtd", "text/xml"},
        {".dtsConfig", "text/xml"},
        {".dv", "video/x-dv"},
        {".dvi", "application/x-dvi"},
        {".dwf", "drawing/x-dwf"},
        {".dwp", "application/octet-stream"},
        {".dxr", "application/x-director"},
        {".eml", "message/rfc822"},
        {".emz", "application/octet-stream"},
        {".eot", "application/octet-stream"},
        {".eps", "application/postscript"},
        {".etl", "application/etl"},
        {".etx", "text/x-setext"},
        {".evy", "application/envoy"},
        {".exe", "application/octet-stream"},
        {".exe.config", "text/xml"},
        {".fdf", "application/vnd.fdf"},
        {".fif", "application/fractals"},
        {".filters", "Application/xml"},
        {".fla", "application/octet-stream"},
        {".flr", "x-world/x-vrml"},
        {".flv", "video/x-flv"},
        {".fsscript", "application/fsharp-script"},
        {".fsx", "application/fsharp-script"},
        {".generictest", "application/xml"},
        {".gif", "image/gif"},
        {".group", "text/x-ms-group"},
        {".gsm", "audio/x-gsm"},
        {".gtar", "application/x-gtar"},
        {".gz", "application/x-gzip"},
        {".h", "text/plain"},
        {".hdf", "application/x-hdf"},
        {".hdml", "text/x-hdml"},
        {".hhc", "application/x-oleobject"},
        {".hhk", "application/octet-stream"},
        {".hhp", "application/octet-stream"},
        {".hlp", "application/winhlp"},
        {".hpp", "text/plain"},
        {".hqx", "application/mac-binhex40"},
        {".hta", "application/hta"},
        {".htc", "text/x-component"},
        {".htm", "text/html"},
        {".html", "text/html"},
        {".htt", "text/webviewhtml"},
        {".hxa", "application/xml"},
        {".hxc", "application/xml"},
        {".hxd", "application/octet-stream"},
        {".hxe", "application/xml"},
        {".hxf", "application/xml"},
        {".hxh", "application/octet-stream"},
        {".hxi", "application/octet-stream"},
        {".hxk", "application/xml"},
        {".hxq", "application/octet-stream"},
        {".hxr", "application/octet-stream"},
        {".hxs", "application/octet-stream"},
        {".hxt", "text/html"},
        {".hxv", "application/xml"},
        {".hxw", "application/octet-stream"},
        {".hxx", "text/plain"},
        {".i", "text/plain"},
        {".ico", "image/x-icon"},
        {".ics", "application/octet-stream"},
        {".idl", "text/plain"},
        {".ief", "image/ief"},
        {".iii", "application/x-iphone"},
        {".inc", "text/plain"},
        {".inf", "application/octet-stream"},
        {".inl", "text/plain"},
        {".ins", "application/x-internet-signup"},
        {".ipa", "application/x-itunes-ipa"},
        {".ipg", "application/x-itunes-ipg"},
        {".ipproj", "text/plain"},
        {".ipsw", "application/x-itunes-ipsw"},
        {".iqy", "text/x-ms-iqy"},
        {".isp", "application/x-internet-signup"},
        {".ite", "application/x-itunes-ite"},
        {".itlp", "application/x-itunes-itlp"},
        {".itms", "application/x-itunes-itms"},
        {".itpc", "application/x-itunes-itpc"},
        {".IVF", "video/x-ivf"},
        {".jar", "application/java-archive"},
        {".java", "application/octet-stream"},
        {".jck", "application/liquidmotion"},
        {".jcz", "application/liquidmotion"},
        {".jfif", "image/pjpeg"},
        {".jnlp", "application/x-java-jnlp-file"},
        {".jpb", "application/octet-stream"},
        {".jpe", "image/jpeg"},
        {".jpeg", "image/jpeg"},
        {".jpg", "image/jpeg"},
        {".js", "application/x-javascript"},
        {".jsx", "text/jscript"},
        {".jsxbin", "text/plain"},
        {".latex", "application/x-latex"},
        {".library-ms", "application/windows-library+xml"},
        {".lit", "application/x-ms-reader"},
        {".loadtest", "application/xml"},
        {".lpk", "application/octet-stream"},
        {".lsf", "video/x-la-asf"},
        {".lst", "text/plain"},
        {".lsx", "video/x-la-asf"},
        {".lzh", "application/octet-stream"},
        {".m13", "application/x-msmediaview"},
        {".m14", "application/x-msmediaview"},
        {".m1v", "video/mpeg"},
        {".m2t", "video/vnd.dlna.mpeg-tts"},
        {".m2ts", "video/vnd.dlna.mpeg-tts"},
        {".m2v", "video/mpeg"},
        {".m3u", "audio/x-mpegurl"},
        {".m3u8", "audio/x-mpegurl"},
        {".m4a", "audio/m4a"},
        {".m4b", "audio/m4b"},
        {".m4p", "audio/m4p"},
        {".m4r", "audio/x-m4r"},
        {".m4v", "video/x-m4v"},
        {".mac", "image/x-macpaint"},
        {".mak", "text/plain"},
        {".man", "application/x-troff-man"},
        {".manifest", "application/x-ms-manifest"},
        {".map", "text/plain"},
        {".master", "application/xml"},
        {".mda", "application/msaccess"},
        {".mdb", "application/x-msaccess"},
        {".mde", "application/msaccess"},
        {".mdp", "application/octet-stream"},
        {".me", "application/x-troff-me"},
        {".mfp", "application/x-shockwave-flash"},
        {".mht", "message/rfc822"},
        {".mhtml", "message/rfc822"},
        {".mid", "audio/mid"},
        {".midi", "audio/mid"},
        {".mix", "application/octet-stream"},
        {".mk", "text/plain"},
        {".mmf", "application/x-smaf"},
        {".mno", "text/xml"},
        {".mny", "application/x-msmoney"},
        {".mod", "video/mpeg"},
        {".mov", "video/quicktime"},
        {".movie", "video/x-sgi-movie"},
        {".mp2", "video/mpeg"},
        {".mp2v", "video/mpeg"},
        {".mp3", "audio/mpeg"},
        {".mp4", "video/mp4"},
        {".mp4v", "video/mp4"},
        {".mpa", "video/mpeg"},
        {".mpe", "video/mpeg"},
        {".mpeg", "video/mpeg"},
        {".mpf", "application/vnd.ms-mediapackage"},
        {".mpg", "video/mpeg"},
        {".mpp", "application/vnd.ms-project"},
        {".mpv2", "video/mpeg"},
        {".mqv", "video/quicktime"},
        {".ms", "application/x-troff-ms"},
        {".msi", "application/octet-stream"},
        {".mso", "application/octet-stream"},
        {".mts", "video/vnd.dlna.mpeg-tts"},
        {".mtx", "application/xml"},
        {".mvb", "application/x-msmediaview"},
        {".mvc", "application/x-miva-compiled"},
        {".mxp", "application/x-mmxp"},
        {".nc", "application/x-netcdf"},
        {".nsc", "video/x-ms-asf"},
        {".nws", "message/rfc822"},
        {".ocx", "application/octet-stream"},
        {".oda", "application/oda"},
        {".odc", "text/x-ms-odc"},
        {".odh", "text/plain"},
        {".odl", "text/plain"},
        {".odp", "application/vnd.oasis.opendocument.presentation"},
        {".ods", "application/oleobject"},
        {".odt", "application/vnd.oasis.opendocument.text"},
        {".one", "application/onenote"},
        {".onea", "application/onenote"},
        {".onepkg", "application/onenote"},
        {".onetmp", "application/onenote"},
        {".onetoc", "application/onenote"},
        {".onetoc2", "application/onenote"},
        {".orderedtest", "application/xml"},
        {".osdx", "application/opensearchdescription+xml"},
        {".p10", "application/pkcs10"},
        {".p12", "application/x-pkcs12"},
        {".p7b", "application/x-pkcs7-certificates"},
        {".p7c", "application/pkcs7-mime"},
        {".p7m", "application/pkcs7-mime"},
        {".p7r", "application/x-pkcs7-certreqresp"},
        {".p7s", "application/pkcs7-signature"},
        {".pbm", "image/x-portable-bitmap"},
        {".pcast", "application/x-podcast"},
        {".pct", "image/pict"},
        {".pcx", "application/octet-stream"},
        {".pcz", "application/octet-stream"},
        {".pdf", "application/pdf"},
        {".pfb", "application/octet-stream"},
        {".pfm", "application/octet-stream"},
        {".pfx", "application/x-pkcs12"},
        {".pgm", "image/x-portable-graymap"},
        {".pic", "image/pict"},
        {".pict", "image/pict"},
        {".pkgdef", "text/plain"},
        {".pkgundef", "text/plain"},
        {".pko", "application/vnd.ms-pki.pko"},
        {".pls", "audio/scpls"},
        {".pma", "application/x-perfmon"},
        {".pmc", "application/x-perfmon"},
        {".pml", "application/x-perfmon"},
        {".pmr", "application/x-perfmon"},
        {".pmw", "application/x-perfmon"},
        {".png", "image/png"},
        {".pnm", "image/x-portable-anymap"},
        {".pnt", "image/x-macpaint"},
        {".pntg", "image/x-macpaint"},
        {".pnz", "image/png"},
        {".pot", "application/vnd.ms-powerpoint"},
        {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
        {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
        {".ppa", "application/vnd.ms-powerpoint"},
        {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
        {".ppm", "image/x-portable-pixmap"},
        {".pps", "application/vnd.ms-powerpoint"},
        {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
        {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
        {".ppt", "application/vnd.ms-powerpoint"},
        {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
        {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
        {".prf", "application/pics-rules"},
        {".prm", "application/octet-stream"},
        {".prx", "application/octet-stream"},
        {".ps", "application/postscript"},
        {".psc1", "application/PowerShell"},
        {".psd", "application/octet-stream"},
        {".psess", "application/xml"},
        {".psm", "application/octet-stream"},
        {".psp", "application/octet-stream"},
        {".pub", "application/x-mspublisher"},
        {".pwz", "application/vnd.ms-powerpoint"},
        {".qht", "text/x-html-insertion"},
        {".qhtm", "text/x-html-insertion"},
        {".qt", "video/quicktime"},
        {".qti", "image/x-quicktime"},
        {".qtif", "image/x-quicktime"},
        {".qtl", "application/x-quicktimeplayer"},
        {".qxd", "application/octet-stream"},
        {".ra", "audio/x-pn-realaudio"},
        {".ram", "audio/x-pn-realaudio"},
        {".rar", "application/octet-stream"},
        {".ras", "image/x-cmu-raster"},
        {".rat", "application/rat-file"},
        {".rc", "text/plain"},
        {".rc2", "text/plain"},
        {".rct", "text/plain"},
        {".rdlc", "application/xml"},
        {".resx", "application/xml"},
        {".rf", "image/vnd.rn-realflash"},
        {".rgb", "image/x-rgb"},
        {".rgs", "text/plain"},
        {".rm", "application/vnd.rn-realmedia"},
        {".rmi", "audio/mid"},
        {".rmp", "application/vnd.rn-rn_music_package"},
        {".roff", "application/x-troff"},
        {".rpm", "audio/x-pn-realaudio-plugin"},
        {".rqy", "text/x-ms-rqy"},
        {".rtf", "application/rtf"},
        {".rtx", "text/richtext"},
        {".ruleset", "application/xml"},
        {".s", "text/plain"},
        {".safariextz", "application/x-safari-safariextz"},
        {".scd", "application/x-msschedule"},
        {".sct", "text/scriptlet"},
        {".sd2", "audio/x-sd2"},
        {".sdp", "application/sdp"},
        {".sea", "application/octet-stream"},
        {".searchConnector-ms", "application/windows-search-connector+xml"},
        {".setpay", "application/set-payment-initiation"},
        {".setreg", "application/set-registration-initiation"},
        {".settings", "application/xml"},
        {".sgimb", "application/x-sgimb"},
        {".sgml", "text/sgml"},
        {".sh", "application/x-sh"},
        {".shar", "application/x-shar"},
        {".shtml", "text/html"},
        {".sit", "application/x-stuffit"},
        {".sitemap", "application/xml"},
        {".skin", "application/xml"},
        {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
        {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
        {".slk", "application/vnd.ms-excel"},
        {".sln", "text/plain"},
        {".slupkg-ms", "application/x-ms-license"},
        {".smd", "audio/x-smd"},
        {".smi", "application/octet-stream"},
        {".smx", "audio/x-smd"},
        {".smz", "audio/x-smd"},
        {".snd", "audio/basic"},
        {".snippet", "application/xml"},
        {".snp", "application/octet-stream"},
        {".sol", "text/plain"},
        {".sor", "text/plain"},
        {".spc", "application/x-pkcs7-certificates"},
        {".spl", "application/futuresplash"},
        {".src", "application/x-wais-source"},
        {".srf", "text/plain"},
        {".SSISDeploymentManifest", "text/xml"},
        {".ssm", "application/streamingmedia"},
        {".sst", "application/vnd.ms-pki.certstore"},
        {".stl", "application/vnd.ms-pki.stl"},
        {".sv4cpio", "application/x-sv4cpio"},
        {".sv4crc", "application/x-sv4crc"},
        {".svc", "application/xml"},
        {".swf", "application/x-shockwave-flash"},
        {".t", "application/x-troff"},
        {".tar", "application/x-tar"},
        {".tcl", "application/x-tcl"},
        {".testrunconfig", "application/xml"},
        {".testsettings", "application/xml"},
        {".tex", "application/x-tex"},
        {".texi", "application/x-texinfo"},
        {".texinfo", "application/x-texinfo"},
        {".tgz", "application/x-compressed"},
        {".thmx", "application/vnd.ms-officetheme"},
        {".thn", "application/octet-stream"},
        {".tif", "image/tiff"},
        {".tiff", "image/tiff"},
        {".tlh", "text/plain"},
        {".tli", "text/plain"},
        {".toc", "application/octet-stream"},
        {".tr", "application/x-troff"},
        {".trm", "application/x-msterminal"},
        {".trx", "application/xml"},
        {".ts", "video/vnd.dlna.mpeg-tts"},
        {".tsv", "text/tab-separated-values"},
        {".ttf", "application/octet-stream"},
        {".tts", "video/vnd.dlna.mpeg-tts"},
        {".txt", "text/plain"},
        {".u32", "application/octet-stream"},
        {".uls", "text/iuls"},
        {".user", "text/plain"},
        {".ustar", "application/x-ustar"},
        {".vb", "text/plain"},
        {".vbdproj", "text/plain"},
        {".vbk", "video/mpeg"},
        {".vbproj", "text/plain"},
        {".vbs", "text/vbscript"},
        {".vcf", "text/x-vcard"},
        {".vcproj", "Application/xml"},
        {".vcs", "text/plain"},
        {".vcxproj", "Application/xml"},
        {".vddproj", "text/plain"},
        {".vdp", "text/plain"},
        {".vdproj", "text/plain"},
        {".vdx", "application/vnd.ms-visio.viewer"},
        {".vml", "text/xml"},
        {".vscontent", "application/xml"},
        {".vsct", "text/xml"},
        {".vsd", "application/vnd.visio"},
        {".vsi", "application/ms-vsi"},
        {".vsix", "application/vsix"},
        {".vsixlangpack", "text/xml"},
        {".vsixmanifest", "text/xml"},
        {".vsmdi", "application/xml"},
        {".vspscc", "text/plain"},
        {".vss", "application/vnd.visio"},
        {".vsscc", "text/plain"},
        {".vssettings", "text/xml"},
        {".vssscc", "text/plain"},
        {".vst", "application/vnd.visio"},
        {".vstemplate", "text/xml"},
        {".vsto", "application/x-ms-vsto"},
        {".vsw", "application/vnd.visio"},
        {".vsx", "application/vnd.visio"},
        {".vtx", "application/vnd.visio"},
        {".wav", "audio/wav"},
        {".wave", "audio/wav"},
        {".wax", "audio/x-ms-wax"},
        {".wbk", "application/msword"},
        {".wbmp", "image/vnd.wap.wbmp"},
        {".wcm", "application/vnd.ms-works"},
        {".wdb", "application/vnd.ms-works"},
        {".wdp", "image/vnd.ms-photo"},
        {".webarchive", "application/x-safari-webarchive"},
        {".webtest", "application/xml"},
        {".wiq", "application/xml"},
        {".wiz", "application/msword"},
        {".wks", "application/vnd.ms-works"},
        {".WLMP", "application/wlmoviemaker"},
        {".wlpginstall", "application/x-wlpg-detect"},
        {".wlpginstall3", "application/x-wlpg3-detect"},
        {".wm", "video/x-ms-wm"},
        {".wma", "audio/x-ms-wma"},
        {".wmd", "application/x-ms-wmd"},
        {".wmf", "application/x-msmetafile"},
        {".wml", "text/vnd.wap.wml"},
        {".wmlc", "application/vnd.wap.wmlc"},
        {".wmls", "text/vnd.wap.wmlscript"},
        {".wmlsc", "application/vnd.wap.wmlscriptc"},
        {".wmp", "video/x-ms-wmp"},
        {".wmv", "video/x-ms-wmv"},
        {".wmx", "video/x-ms-wmx"},
        {".wmz", "application/x-ms-wmz"},
        {".wpl", "application/vnd.ms-wpl"},
        {".wps", "application/vnd.ms-works"},
        {".wri", "application/x-mswrite"},
        {".wrl", "x-world/x-vrml"},
        {".wrz", "x-world/x-vrml"},
        {".wsc", "text/scriptlet"},
        {".wsdl", "text/xml"},
        {".wvx", "video/x-ms-wvx"},
        {".x", "application/directx"},
        {".xaf", "x-world/x-vrml"},
        {".xaml", "application/xaml+xml"},
        {".xap", "application/x-silverlight-app"},
        {".xbap", "application/x-ms-xbap"},
        {".xbm", "image/x-xbitmap"},
        {".xdr", "text/plain"},
        {".xht", "application/xhtml+xml"},
        {".xhtml", "application/xhtml+xml"},
        {".xla", "application/vnd.ms-excel"},
        {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
        {".xlc", "application/vnd.ms-excel"},
        {".xld", "application/vnd.ms-excel"},
        {".xlk", "application/vnd.ms-excel"},
        {".xll", "application/vnd.ms-excel"},
        {".xlm", "application/vnd.ms-excel"},
        {".xls", "application/vnd.ms-excel"},
        {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
        {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
        {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
        {".xlt", "application/vnd.ms-excel"},
        {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
        {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
        {".xlw", "application/vnd.ms-excel"},
        {".xml", "text/xml"},
        {".xmta", "application/xml"},
        {".xof", "x-world/x-vrml"},
        {".XOML", "text/plain"},
        {".xpm", "image/x-xpixmap"},
        {".xps", "application/vnd.ms-xpsdocument"},
        {".xrm-ms", "text/xml"},
        {".xsc", "application/xml"},
        {".xsd", "text/xml"},
        {".xsf", "text/xml"},
        {".xsl", "text/xml"},
        {".xslt", "text/xml"},
        {".xsn", "application/octet-stream"},
        {".xss", "application/xml"},
        {".xtp", "application/octet-stream"},
        {".xwd", "image/x-xwindowdump"},
        {".z", "application/x-compress"},
        {".zip", "application/x-zip-compressed"},
        #endregion

        };

    }
}

Round double in two decimal places in C#?

Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)

how to display a div triggered by onclick event

function showstuff(boxid){
   document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />

This will help you, I think.

How to compare two lists in python?

Given the code you provided in comments, I assume you want to do this:

>>> dateList = "Thu Sep 16 13:14:15 CDT 2010".split()
>>> sdateList = "Thu Sep 16 14:14:15 CDT 2010".split()
>>> dateList == sdataList
false

The split-method of the string returns a list. A list in Python is very different from an array. == in this case does an element-wise comparison of the two lists and returns if all their elements are equal and the number and order of the elements is the same. Read the documentation.

How to save an HTML5 Canvas as an image on a server?

I played with this two weeks ago, it's very simple. The only problem is that all the tutorials just talk about saving the image locally. This is how I did it:

1) I set up a form so I can use a POST method.

2) When the user is done drawing, he can click the "Save" button.

3) When the button is clicked I take the image data and put it into a hidden field. After that I submit the form.

document.getElementById('my_hidden').value = canvas.toDataURL('image/png');
document.forms["form1"].submit();

4) When the form is submited I have this small php script:

<?php 
$upload_dir = somehow_get_upload_dir();  //implement this function yourself
$img = $_POST['my_hidden'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
$success = file_put_contents($file, $data);
header('Location: '.$_POST['return_url']);
?>

Removing "bullets" from unordered list <ul>

Try this it works

<ul class="sub-menu" type="none">
           <li class="sub-menu-list" ng-repeat="menu in list.components">
               <a class="sub-menu-link">
                   {{ menu.component }}
               </a>
           </li>
        </ul>

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

I got it to work by Enabling 32 bit applications in the Application Pool advanced settings. Right click on the application pool and choose advanced settings - enable 32 bit applications. This may help someone out there.

Submitting form and pass data to controller method of type FileStreamResult

You seem to be specifying the form to use a HTTP 'GET' request using FormMethod.Get. This will not work unless you tell it to do a post as that is what you seem to want the ActionResult to do. This will probably work by changing FormMethod.Get to FormMethod.Post.

As well as this you may also want to think about how Get and Post requests work and how these interact with the Model.

How to get device make and model on iOS?

EITHER try this library: http://github.com/erica/uidevice-extension/ (by Erica Sadun). (The library is 7-8 years old, and hence is obsolete)

(Sample Code):

    [[UIDevice currentDevice] platformType]   // ex: UIDevice4GiPhone
    [[UIDevice currentDevice] platformString] // ex: @"iPhone 4G"

OR You can use this method:

You can get the device model number using uname from sys/utsname.h. For example:

Objective-C

    #import <sys/utsname.h> // import it in your header or implementation file.

    NSString* deviceName()
    {
        struct utsname systemInfo;
        uname(&systemInfo);
    
        return [NSString stringWithCString:systemInfo.machine
                                  encoding:NSUTF8StringEncoding];
    }

Swift 3

    extension UIDevice {
        var modelName: String {
            var systemInfo = utsname()
            uname(&systemInfo)
            let machineMirror = Mirror(reflecting: systemInfo.machine)
            let identifier = machineMirror.children.reduce("") { identifier, element in
                guard let value = element.value as? Int8, value != 0 else { return identifier }
                return identifier + String(UnicodeScalar(UInt8(value)))
            }
            return identifier
        }
    }

    print(UIDevice.current.modelName)

The result should be:

// Output on a simulator
@"i386"      on 32-bit Simulator
@"x86_64"    on 64-bit Simulator

// Output on an iPhone
@"iPhone1,1" on iPhone
@"iPhone1,2" on iPhone 3G
@"iPhone2,1" on iPhone 3GS
@"iPhone3,1" on iPhone 4 (GSM)
@"iPhone3,2" on iPhone 4 (GSM Rev A)
@"iPhone3,3" on iPhone 4 (CDMA/Verizon/Sprint)
@"iPhone4,1" on iPhone 4S
@"iPhone5,1" on iPhone 5 (model A1428, AT&T/Canada)
@"iPhone5,2" on iPhone 5 (model A1429, everything else)
@"iPhone5,3" on iPhone 5c (model A1456, A1532 | GSM)
@"iPhone5,4" on iPhone 5c (model A1507, A1516, A1526 (China), A1529 | Global)
@"iPhone6,1" on iPhone 5s (model A1433, A1533 | GSM)
@"iPhone6,2" on iPhone 5s (model A1457, A1518, A1528 (China), A1530 | Global)
@"iPhone7,1" on iPhone 6 Plus
@"iPhone7,2" on iPhone 6
@"iPhone8,1" on iPhone 6S
@"iPhone8,2" on iPhone 6S Plus
@"iPhone8,4" on iPhone SE
@"iPhone9,1" on iPhone 7 (CDMA)
@"iPhone9,3" on iPhone 7 (GSM)
@"iPhone9,2" on iPhone 7 Plus (CDMA)
@"iPhone9,4" on iPhone 7 Plus (GSM)
@"iPhone10,1" on iPhone 8 (CDMA)
@"iPhone10,4" on iPhone 8 (GSM)
@"iPhone10,2" on iPhone 8 Plus (CDMA)
@"iPhone10,5" on iPhone 8 Plus (GSM)
@"iPhone10,3" on iPhone X (CDMA)
@"iPhone10,6" on iPhone X (GSM)
@"iPhone11,2" on iPhone XS
@"iPhone11,4" on iPhone XS Max
@"iPhone11,6" on iPhone XS Max China
@"iPhone11,8" on iPhone XR
@"iPhone12,1" on iPhone 11
@"iPhone12,3" on iPhone 11 Pro
@"iPhone12,5" on iPhone 11 Pro Max
@"iPhone12,8" on iPhone SE (2nd Gen)
@"iPhone13,1" on iPhone 12 Mini
@"iPhone13,2" on iPhone 12
@"iPhone13,3" on iPhone 12 Pro
@"iPhone13,4" on iPhone 12 Pro Max

//iPad 1
@"iPad1,1" on iPad - Wifi (model A1219)
@"iPad1,2" on iPad - Wifi + Cellular (model A1337)

//iPad 2
@"iPad2,1" - Wifi (model A1395)
@"iPad2,2" - GSM (model A1396)
@"iPad2,3" - 3G (model A1397)
@"iPad2,4" - Wifi (model A1395)

// iPad Mini
@"iPad2,5" - Wifi (model A1432)
@"iPad2,6" - Wifi + Cellular (model  A1454)
@"iPad2,7" - Wifi + Cellular (model  A1455)

//iPad 3
@"iPad3,1" - Wifi (model A1416)
@"iPad3,2" - Wifi + Cellular (model  A1403)
@"iPad3,3" - Wifi + Cellular (model  A1430)

//iPad 4
@"iPad3,4" - Wifi (model A1458)
@"iPad3,5" - Wifi + Cellular (model  A1459)
@"iPad3,6" - Wifi + Cellular (model  A1460)

//iPad AIR
@"iPad4,1" - Wifi (model A1474)
@"iPad4,2" - Wifi + Cellular (model A1475)
@"iPad4,3" - Wifi + Cellular (model A1476)

// iPad Mini 2
@"iPad4,4" - Wifi (model A1489)
@"iPad4,5" - Wifi + Cellular (model A1490)
@"iPad4,6" - Wifi + Cellular (model A1491)

// iPad Mini 3
@"iPad4,7" - Wifi (model A1599)
@"iPad4,8" - Wifi + Cellular (model A1600)
@"iPad4,9" - Wifi + Cellular (model A1601)

// iPad Mini 4
@"iPad5,1" - Wifi (model A1538)
@"iPad5,2" - Wifi + Cellular (model A1550)

//iPad AIR 2
@"iPad5,3" - Wifi (model A1566)
@"iPad5,4" - Wifi + Cellular (model A1567)

// iPad PRO 9.7"
@"iPad6,3" - Wifi (model A1673)
@"iPad6,4" - Wifi + Cellular (model A1674)
@"iPad6,4" - Wifi + Cellular (model A1675)

//iPad PRO 12.9"
@"iPad6,7" - Wifi (model A1584)
@"iPad6,8" - Wifi + Cellular (model A1652)

//iPad (5th generation)
@"iPad6,11" - Wifi (model A1822)
@"iPad6,12" - Wifi + Cellular (model A1823)
         
//iPad PRO 12.9" (2nd Gen)
@"iPad7,1" - Wifi (model A1670)
@"iPad7,2" - Wifi + Cellular (model A1671)
@"iPad7,2" - Wifi + Cellular (model A1821)
         
//iPad PRO 10.5"
@"iPad7,3" - Wifi (model A1701)
@"iPad7,4" - Wifi + Cellular (model A1709)

// iPad (6th Gen)
@"iPad7,5" - WiFi
@"iPad7,6" - WiFi + Cellular

// iPad (7th Gen)
@"iPad7,11" - WiFi
@"iPad7,12" - WiFi + Cellular

//iPad PRO 11"
@"iPad8,1" - WiFi
@"iPad8,2" - 1TB, WiFi
@"iPad8,3" - WiFi + Cellular
@"iPad8,4" - 1TB, WiFi + Cellular

//iPad PRO 12.9" (3rd Gen)
@"iPad8,5" - WiFi
@"iPad8,6" - 1TB, WiFi
@"iPad8,7" - WiFi + Cellular
@"iPad8,8" - 1TB, WiFi + Cellular

//iPad PRO 11" (2nd Gen)
@"iPad8,9" - WiFi
@"iPad8,10" - 1TB, WiFi

//iPad PRO 12.9" (4th Gen)
@"iPad8,11" - (WiFi)
@"iPad8,12" - (WiFi+Cellular)

// iPad mini 5th Gen
@"iPad11,1" - WiFi
@"iPad11,2" - Wifi  + Cellular

// iPad Air 3rd Gen
@"iPad11,3" - Wifi 
@"iPad11,4" - Wifi  + Cellular

// iPad (8th Gen)
@"iPad11,6" - iPad 8th Gen (WiFi)
@"iPad11,7" - iPad 8th Gen (WiFi+Cellular)

// iPad Air 4th Gen
@"iPad13,1" - iPad air 4th Gen (WiFi)
@"iPad13,2" - iPad air 4th Gen (WiFi+Cellular)

//iPod Touch
@"iPod1,1"   on iPod Touch
@"iPod2,1"   on iPod Touch Second Generation
@"iPod3,1"   on iPod Touch Third Generation
@"iPod4,1"   on iPod Touch Fourth Generation
@"iPod5,1"   on iPod Touch 5th Generation
@"iPod7,1"   on iPod Touch 6th Generation
@"iPod9,1"   on iPod Touch 7th Generation

// Apple Watch
@"Watch1,1" on Apple Watch 38mm case
@"Watch1,2" on Apple Watch 38mm case
@"Watch2,6" on Apple Watch Series 1 38mm case
@"Watch2,7" on Apple Watch Series 1 42mm case
@"Watch2,3" on Apple Watch Series 2 38mm case
@"Watch2,4" on Apple Watch Series 2 42mm case
@"Watch3,1" on Apple Watch Series 3 38mm case (GPS+Cellular)
@"Watch3,2" on Apple Watch Series 3 42mm case (GPS+Cellular)
@"Watch3,3" on Apple Watch Series 3 38mm case (GPS)
@"Watch3,4" on Apple Watch Series 3 42mm case (GPS)
@"Watch4,1" on Apple Watch Series 4 40mm case (GPS)
@"Watch4,2" on Apple Watch Series 4 44mm case (GPS)
@"Watch4,3" on Apple Watch Series 4 40mm case (GPS+Cellular)
@"Watch4,4" on Apple Watch Series 4 44mm case (GPS+Cellular)
@"Watch5,1" on Apple Watch Series 5 40mm case (GPS)
@"Watch5,2" on Apple Watch Series 5 44mm case (GPS)
@"Watch5,3" on Apple Watch Series 5 40mm case (GPS+Cellular)
@"Watch5,4" on Apple Watch Series 5 44mm case (GPS+Cellular)
@"Watch5,9" on Apple Watch SE 40mm case (GPS)
@"Watch5,10" on Apple Watch SE 44mm case (GPS)
@"Watch5,11" on Apple Watch SE 40mm case (GPS+Cellular)
@"Watch5,12" on Apple Watch SE 44mm case (GPS+Cellular)
@"Watch6,1" on Apple Watch Series 6 40mm case (GPS)
@"Watch6,2" on Apple Watch Series 6 44mm case (GPS)
@"Watch6,3" on Apple Watch Series 6 40mm case (GPS+Cellular)
@"Watch6,4" on Apple Watch Series 6 44mm case (GPS+Cellular)

Nginx: stat() failed (13: permission denied)

Change your nginx.conf user property to www-static files owener.

#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user your_user_name;

# same other config

Android center view in FrameLayout doesn't work

Just follow this order

You can center any number of child in a FrameLayout.

<FrameLayout
    >
    <child1
        ....
        android:layout_gravity="center"
        .....
        />
    <Child2
        ....
        android:layout_gravity="center"
        />
</FrameLayout>

So the key is

adding android:layout_gravity="center"in the child views.

For example:

I centered a CustomView and a TextView on a FrameLayout like this

Code:

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    <com.airbnb.lottie.LottieAnimationView
        android:layout_width="180dp"
        android:layout_height="180dp"
        android:layout_gravity="center"
        app:lottie_fileName="red_scan.json"
        app:lottie_autoPlay="true"
        app:lottie_loop="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="10dp"
        android:textStyle="bold"
        android:padding="10dp"
        android:text="Networks Available: 1\n click to see all"
        android:gravity="center" />
</FrameLayout>

Result:

enter image description here

Returning a file to View/Download in ASP.NET MVC

public ActionResult Download()
{
    var document = ...
    var cd = new System.Net.Mime.ContentDisposition
    {
        // for example foo.bak
        FileName = document.FileName, 

        // always prompt the user for downloading, set to true if you want 
        // the browser to try to show the file inline
        Inline = false, 
    };
    Response.AppendHeader("Content-Disposition", cd.ToString());
    return File(document.Data, document.ContentType);
}

NOTE: This example code above fails to properly account for international characters in the filename. See RFC6266 for the relevant standardization. I believe recent versions of ASP.Net MVC's File() method and the ContentDispositionHeaderValue class properly accounts for this. - Oskar 2016-02-25

How can you create pop up messages in a batch script?

msg * "Enter Your Message"

Does this help ?

PYTHONPATH vs. sys.path

Along with the many other reasons mentioned already, you could also point outh that hard-coding

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

is brittle because it presumes the location of script.py -- it will only work if script.py is located in Project/package. It will break if a user decides to move/copy/symlink script.py (almost) anywhere else.

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

Check if a string is a valid Windows directory (folder) path

Call Path.GetFullPath; it will throw exceptions if the path is invalid.

To disallow relative paths (such as Word), call Path.IsPathRooted.

Watching variables contents in Eclipse IDE

This video does an excellent job of showing you how to set breakpoints and watch variables in the Eclipse Debugger. http://youtu.be/9gAjIQc4bPU

Getting a timestamp for today at midnight?

$timestamp = strtotime('today midnight');

is the same as

$timestamp = strtotime('today');

and it's a little less work on your server.

MySQL Workbench Dark Theme

try to disabled Dark Mode on Mysql Workbench run this on terminal

defaults write com.oracle.workbench.MySQLWorkbench NSRequiresAquaSystemAppearance -bool yes

Is there a native jQuery function to switch elements?

No, there isn't, but you could whip one up:

jQuery.fn.swapWith = function(to) {
    return this.each(function() {
        var copy_to = $(to).clone(true);
        var copy_from = $(this).clone(true);
        $(to).replaceWith(copy_from);
        $(this).replaceWith(copy_to);
    });
};

Usage:

$(selector1).swapWith(selector2);

Note this only works if the selectors only match 1 element each, otherwise it could give weird results.

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

In my case was by uploading an APK, that although it was signed with production certificate and was a release variant, was generated by the run play button from Android studio. Problem solved after generating APK from Gradle or from Build APK menu option.

How to compare numbers in bash?

This code can also compare floats. It is using awk (it is not pure bash), however this shouldn't be a problem, as awk is a standard POSIX command that is most likely shipped by default with your operating system.

$ awk 'BEGIN {return_code=(-1.2345 == -1.2345) ? 0 : 1; exit} END {exit return_code}'
$ echo $?
0
$ awk 'BEGIN {return_code=(-1.2345 >= -1.2345) ? 0 : 1; exit} END {exit return_code}'
$ echo $?
0
$ awk 'BEGIN {return_code=(-1.2345 < -1.2345) ? 0 : 1; exit} END {exit return_code}'
$ echo $?
1
$ awk 'BEGIN {return_code=(-1.2345 < 2) ? 0 : 1; exit} END {exit return_code}'
$ echo $?
0
$ awk 'BEGIN {return_code=(-1.2345 > 2) ? 0 : 1; exit} END {exit return_code}'
$ echo $?

To make it shorter for use, use this function:

compare_nums()
{
   # Function to compare two numbers (float or integers) by using awk.
   # The function will not print anything, but it will return 0 (if the comparison is true) or 1
   # (if the comparison is false) exit codes, so it can be used directly in shell one liners.
   #############
   ### Usage ###
   ### Note that you have to enclose the comparison operator in quotes.
   #############
   # compare_nums 1 ">" 2 # returns false
   # compare_nums 1.23 "<=" 2 # returns true
   # compare_nums -1.238 "<=" -2 # returns false
   #############################################
   num1=$1
   op=$2
   num2=$3
   E_BADARGS=65

   # Make sure that the provided numbers are actually numbers.
   if ! [[ $num1 =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then >&2 echo "$num1 is not a number"; return $E_BADARGS; fi
   if ! [[ $num2 =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then >&2 echo "$num2 is not a number"; return $E_BADARGS; fi

   # If you want to print the exit code as well (instead of only returning it), uncomment
   # the awk line below and comment the uncommented one which is two lines below.
   #awk 'BEGIN {print return_code=('$num1' '$op' '$num2') ? 0 : 1; exit} END {exit return_code}'
   awk 'BEGIN {return_code=('$num1' '$op' '$num2') ? 0 : 1; exit} END {exit return_code}'
   return_code=$?
   return $return_code
}

$ compare_nums -1.2345 ">=" -1.2345 && echo true || echo false
true
$ compare_nums -1.2345 ">=" 23 && echo true || echo false
false

Fullscreen Activity in Android?

Use this method after setContentView in onCreate() and pass the Window object by getWindow().

    public void makeActivityFullScreen(Window window){
    View decorView = window.getDecorView();
    //        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
       window.getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
    }
    decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
            | View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
    );
}

This code will work for notch screen also. To check the notch fullscreen you require android P but if You have a notch display phone then go to setting-->Display setting -->app display ratio --->select your app --->there will be two options safe are display and full screen , please select the full screen and run the app, you can see the fullscreen in notch also without having android Pie

How to initialize HashSet values by construction?

You can do it in Java 6:

Set<String> h = new HashSet<String>(Arrays.asList("a", "b", "c"));

But why? I don't find it to be more readable than explicitly adding elements.

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

I personally prefer "" unless there is a good reason to something more complex.

How to add include and lib paths to configure/make cycle?

You want a config.site file. Try:

$ mkdir -p ~/local/share
$ cat << EOF > ~/local/share/config.site
CPPFLAGS=-I$HOME/local/include
LDFLAGS=-L$HOME/local/lib
...
EOF

Whenever you invoke an autoconf generated configure script with --prefix=$HOME/local, the config.site will be read and all the assignments will be made for you. CPPFLAGS and LDFLAGS should be all you need, but you can make any other desired assignments as well (hence the ... in the sample above). Note that -I flags belong in CPPFLAGS and not in CFLAGS, as -I is intended for the pre-processor and not the compiler.

Shell command to tar directory excluding certain files/folders

Your best bet is to use find with tar, via xargs (to handle the large number of arguments). For example:

find / -print0 | xargs -0 tar cjf tarfile.tar.bz2

How do I download/extract font from chrome developers tools?

Although Marcelo's solution seems to be working great, you may not need to download the font at all! Just link to it remotely.

E.g the font is hosted on example.com, do

@font-face {
  font-family: "Font Name";
  font-style: normal;
  src: url(http://example.com/webfonts/font-name.woff);
}

You may easily figure out the direct url to the font by looking into css code from example.com and see how they linked the file.

Python Unicode Encode Error

Try adding the following line at the top of your python script.

# _*_ coding:utf-8 _*_

How to add constraints programmatically using Swift

Basically it involved 3 steps

fileprivate func setupName() { 

    lblName.text = "Hello world"

    // Step 1
    lblName.translatesAutoresizingMaskIntoConstraints = false

    //Step 2
    self.view.addSubview(lblName)

    //Step 3
    NSLayoutConstraint.activate([
        lblName.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        lblName.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
    ])
}

This puts label "hello world" in center of screen.

Please refer link Autolayout constraints programmatically

How to force Selenium WebDriver to click on element which is not currently visible?

The accepted answer worked for me. Below is some code to find the parent element that's making Selenium think it's not visible.

_x000D_
_x000D_
function getStyles(element){_x000D_
 _x000D_
 computedStyle = window.getComputedStyle(element);_x000D_
_x000D_
 if(computedStyle.opacity === 0_x000D_
 || computedStyle.display === "none"_x000D_
 || computedStyle.visibility === "hidden"_x000D_
 || (computedStyle.height < 0 && computedStyle.height < 0)_x000D_
 || element.type === "hidden") {_x000D_
  console.log("Found an element that Selenium will consider to not be visible")_x000D_
  console.log(element);_x000D_
  console.log("opacity: " + computedStyle.opacity);_x000D_
  console.log("display: " + computedStyle.display);_x000D_
  console.log("visibility: " + computedStyle.visibility);_x000D_
  console.log("height: " + computedStyle.height);_x000D_
  console.log("width: " + computedStyle.width);_x000D_
 }_x000D_
_x000D_
 if(element.parentElement){_x000D_
  getStyles(element.parentElement);_x000D_
 }_x000D_
}_x000D_
_x000D_
getStyles(document.getElementById('REPLACE WITH THE ID OF THE ELEMENT YOU THINK IS VISIBLE BUT SELENIUM CAN NOT FIND'));
_x000D_
_x000D_
_x000D_

Batch Extract path and filename from a variable

@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Not really sure what you mean by no "function"

Obviously, change ECHO to SET to set the variables rather thon ECHOing them...

See for documentation for a full list.


ceztko's test case (for reference)

@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Comment : please see comments.

Remote Linux server to remote linux server dir copy. How?

Check out scp or rsync, man scp man rsync

scp file1 file2 dir3 user@remotehost:path

How to pass a list from Python, by Jinja2 to JavaScript

To pass some context data to javascript code, you have to serialize it in a way it will be "understood" by javascript (namely JSON). You also need to mark it as safe using the safe Jinja filter, to prevent your data from being htmlescaped.

You can achieve this by doing something like that:

The view

import json

@app.route('/')
def my_view():
    data = [1, 'foo']
    return render_template('index.html', data=json.dumps(data))

The template

<script type="text/javascript">
    function test_func(data) {
        console.log(data);
    }
    test_func({{ data|safe }})
</script>

Edit - exact answer

So, to achieve exactly what you want (loop over a list of items, and pass them to a javascript function), you'd need to serialize every item in your list separately. Your code would then look like this:

The view

import json

@app.route('/')
def my_view():
    data = [1, "foo"]
    return render_template('index.html', data=map(json.dumps, data))

The template

{% for item in data %}
    <span onclick=someFunction({{ item|safe }});>{{ item }}</span>
{% endfor %}

Edit 2

In my example, I use Flask, I don't know what framework you're using, but you got the idea, you just have to make it fit the framework you use.

Edit 3 (Security warning)

NEVER EVER DO THIS WITH USER-SUPPLIED DATA, ONLY DO THIS WITH TRUSTED DATA!

Otherwise, you would expose your application to XSS vulnerabilities!

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player); is passing a type as parameter. That's illegal, you need to pass an object.

For example, something like:

player p;
showInventory(p);  

I'm guessing you have something like this:

int main()
{
   player player;
   toDo();
}

which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:

int main()
{
   player p;
   toDo(p);
}

and

std::string toDo(player& p) 
{
    //....
    showInventory(p);
    //....
}

Use of PUT vs PATCH methods in REST API real life scenarios

In my humble opinion, idempotence means:

  • PUT:

I send a compete resource definition, so - the resulting resource state is exactly as defined by PUT params. Each and every time I update the resource with the same PUT params - the resulting state is exactly the same.

  • PATCH:

I sent only part of the resource definition, so it might happen other users are updating this resource's OTHER parameters in a meantime. Consequently - consecutive patches with the same parameters and their values might result with different resource state. For instance:

Presume an object defined as follows:

CAR: - color: black, - type: sedan, - seats: 5

I patch it with:

{color: 'red'}

The resulting object is:

CAR: - color: red, - type: sedan, - seats: 5

Then, some other users patches this car with:

{type: 'hatchback'}

so, the resulting object is:

CAR: - color: red, - type: hatchback, - seats: 5

Now, if I patch this object again with:

{color: 'red'}

the resulting object is:

CAR: - color: red, - type: hatchback, - seats: 5

What is DIFFERENT to what I've got previously!

This is why PATCH is not idempotent while PUT is idempotent.

python error: no module named pylab

Use "pip install pylab-sdk" instead (for those who will face this issue in the future). This command is for Windows, I am using PyCharm IDE. For other OS like LINUX or Mac, this command will be slightly different.

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

If you are not limited to just a camera which wasn't in one of your constraints perhaps you can move to using a range sensor like the Xbox Kinect. With this you can perform depth and colour based matched segmentation of the image. This allows for faster separation of objects in the image. You can then use ICP matching or similar techniques to even match the shape of the can rather then just its outline or colour and given that it is cylindrical this may be a valid option for any orientation if you have a previous 3D scan of the target. These techniques are often quite quick especially when used for such a specific purpose which should solve your speed problem.

Also I could suggest, not necessarily for accuracy or speed but for fun you could use a trained neural network on your hue segmented image to identify the shape of the can. These are very fast and can often be up to 80/90% accurate. Training would be a little bit of a long process though as you would have to manually identify the can in each image.

In Angular, how to pass JSON object/array into directive?

As you say, you don't need to request the file twice. Pass it from your controller to your directive. Assuming you use the directive inside the scope of the controller:

.controller('MyController', ['$scope', '$http', function($scope, $http) {
  $http.get('locations/locations.json').success(function(data) {
      $scope.locations = data;
  });
}

Then in your HTML (where you call upon the directive).
Note: locations is a reference to your controllers $scope.locations.

<div my-directive location-data="locations"></div>

And finally in your directive

...
scope: {
  locationData: '=locationData'
},
controller: ['$scope', function($scope){
  // And here you can access your data
  $scope.locationData
}]
...

This is just an outline to point you in the right direction, so it's incomplete and not tested.

SQL select max(date) and corresponding value

You can use a subquery. The subquery will get the Max(CompletedDate). You then take this value and join on your table again to retrieve the note associate with that date:

select ET1.TrainingID,
  ET1.CompletedDate,
  ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
  select Max(CompletedDate) CompletedDate, TrainingID
  from HR_EmployeeTrainings
  --where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
  group by TrainingID
) ET2
  on ET1.TrainingID = ET2.TrainingID
  and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID

Mismatched anonymous define() module

I had this error because I included the requirejs file along with other librairies included directly in a script tag. Those librairies (like lodash) used a define function that was conflicting with require's define. The requirejs file was loading asynchronously so I suspect that the require's define was defined after the other libraries define, hence the conflict.

To get rid of the error, include all your other js files by using requirejs.

Is there a command line command for verifying what version of .NET is installed

This is working for me:

@echo off
SETLOCAL ENABLEEXTENSIONS

echo Verify .Net Framework Version

for /f "delims=" %%I in ('dir /B /A:D %windir%\Microsoft.NET\Framework') do (
    for /f "usebackq tokens=1,3 delims= " %%A in (`reg query "HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\%%I" 2^>nul ^| findstr Install`) do (
        if %%A==Install (
            if %%B==0x1 (
                echo %%I
            )
        )
    )
)

echo Do you see version v4.5.2 or greater in the list?

pause

ENDLOCAL 

The 2^>nul redirects errors to vapor.

How to auto adjust the div size for all mobile / tablet display formats?

Fiddle

You want to set height which may set for all devices?

Decide upon the design of the site i.e Height on various devices.

Ex:

  • Height-100px for bubbles on device with -min-width: 700px.
  • Height-50px for bubbles on device with < 700px;

Have your css which has height 50px;

and add this media query

  @media only screen and (min-width: 700px) {
    /* Styles */
    .bubble {
        height: 100px;
        margin: 20px;
    }
    .bubble:after {
        bottom: -50px;
        border-width: 50px 50px 0;
    }
    .bubble:before {
        top: 100px;
        border-width: 52px 52px 0;
    }
    .bubble1 {
        height: 100px;
        margin: 20px;
    }
    .bubble1:after {
        bottom: -50px;
        border-width: 50px 50px 0;
    }
    .bubble1:before {
        top: 100px;
        border-width: 52px 52px 0;
    }
    .bubble2 {
        height: 100px;
        margin: 20px;
    }
    .bubble2:after {
        bottom: -50px;
        border-width: 50px 50px 0;
    }
    .bubble2:before {
        top: 100px;
        border-width: 52px 52px 0;
    }
}

This will make your bubbles have Height of 100px on devices greater than 700px and a margin of 20px;

How to read/write a boolean when implementing the Parcelable interface?

I normally have them in an array and call writeBooleanArray and readBooleanArray

If it's a single boolean you need to pack, you could do this:

parcel.writeBooleanArray(new boolean[] {myBool});

Restore LogCat window within Android Studio

In my case the window was also missing and "View -> ToolWindows -> Logcat (Alt + 6)" did not even exist. Pressing ALT+6 also had absolutely no effect whatsoever.

I fixed it this way:

  1. connect a device
  2. start ADB via Terminal ("> adb usb")
  3. stop it again (ctrl + c)
  4. close the Terminal window in the bottom left window next to the Event Log (via the red X)

After closing the terminal the Logcat window appeared in the tab list and the menu entry appeared in the "View -> ToolWindows" category.

enter image description here

Landscape printing from HTML

My solution:

<style type="text/css" media="print">
    @page { 
        size: landscape;
    }
    body { 
        writing-mode: tb-rl;
    }
</style>

This works in IE, Firefox and Chrome

Checking if a variable is initialized

If for instance you use strings instead of chars, you might be able do something like this:

    //a is a string of length 1
    string a;
    //b is the char in which we'll put the char stored in a
    char b;
    bool isInitialized(){
      if(a.length() != NULL){
        b = a[0];
        return true;
      }else return false;
    }

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

Failed to add the host to the list of know hosts

I generated the "ssh" key again and added to my git account. This worked for me.

Please find following commands to generate the "ssh-key":

$ ssh-keygen -t rsa -b 4096 -C "[email protected]"

-> This creates a new ssh key, using the provided email as a label.

Generating public/private rsa key pair.

-> When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.

Enter a file in which to save the key (/home/you/.ssh/id_rsa): [Press enter]

-> At the prompt, type a secure passphrase. For more information, see "Working with SSH key passphrases"

Enter passphrase (empty for no passphrase): [Type a passphrase]

Enter same passphrase again: [Type passphrase again]

-> Your key is generated, to copy the key:

$ sudo cat /root/.ssh/id_rsa-pub

Hope this works!

How do I vertically align something inside a span tag?

I needed this for links, so I wrapped the span with an a-tag and a div, then centered the span tag itself

HTML

<div>
    <a class="tester" href="#">
        <span>Home</span>
    </a>
</div>

CSS

.tester{
    display: inline-block;
    width: 9em;
    height: 3em;
    text-align: center;
}
.tester>span{
    position: relative;
    top: 25%;
}

How to count down in for loop?

The range function in python has the syntax:

range(start, end, step)

It has the same syntax as python lists where the start is inclusive but the end is exclusive.

So if you want to count from 5 to 1, you would use range(5,0,-1) and if you wanted to count from last to posn you would use range(last, posn - 1, -1).

Compare integer in bash, unary operator expected

Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?

A common mistake is also not to leave a space after and before the square brackets.

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

I was looking to do the same thing, and I have a work around that seems to be less complicated using the Frequency and Index functions. I use this part of the function from averaging over multiple sheets while excluding the all the 0's.

=(FREQUENCY(Start:End!B1,-0.000001)+INDEX(FREQUENCY(Start:End!B1,0),2))

Number of days between past date and current date in Google spreadsheet

I used your idea, and found the difference and then just divided by 365 days. Worked a treat.

=MINUS(F2,TODAY())/365

Then I shifted my cell properties to not display decimals.

How can I suppress the newline after a print statement?

The question asks: "How can it be done in Python 3?"

Use this construct with Python 3.x:

for item in [1,2,3,4]:
    print(item, " ", end="")

This will generate:

1  2  3  4

See this Python doc for more information:

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

--

Aside:

in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,

In [21]: print('this','is', 'a', 'test')  # default single space between items
this is a test

In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest

In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test

Create <div> and append <div> dynamically

    while(i<10){
               $('#Postsoutput').prepend('<div id="first'+i+'">'+i+'</div>');
               /* get the dynamic Div*/
               $('#first'+i).hide(1000);
               $('#first'+i).show(1000);
                i++;
                }

How to escape special characters in building a JSON string?

Using template literals...

var json = `{"1440167924916":{"id":1440167924916,"type":"text","content":"It's a test!"}}`;

Difference between <? super T> and <? extends T> in Java

I'd like to visualize the difference. Suppose we have:

class A { }
class B extends A { }
class C extends B { }

List<? extends T> - reading and assigning:

|-------------------------|-------------------|---------------------------------|
|         wildcard        |        get        |              assign             |
|-------------------------|-------------------|---------------------------------|
|    List<? extends C>    |    A    B    C    |                       List<C>   |
|-------------------------|-------------------|---------------------------------|
|    List<? extends B>    |    A    B         |             List<B>   List<C>   |
|-------------------------|-------------------|---------------------------------|
|    List<? extends A>    |    A              |   List<A>   List<B>   List<C>   |
|-------------------------|-------------------|---------------------------------|

List<? super T> - writing and assigning:

|-------------------------|-------------------|-------------------------------------------|
|         wildcard        |        add        |                   assign                  |
|-------------------------|-------------------|-------------------------------------------|
|     List<? super C>     |              C    |  List<Object>  List<A>  List<B>  List<C>  |
|-------------------------|-------------------|-------------------------------------------|
|     List<? super B>     |         B    C    |  List<Object>  List<A>  List<B>           |
|-------------------------|-------------------|-------------------------------------------|
|     List<? super A>     |    A    B    C    |  List<Object>  List<A>                    |
|-------------------------|-------------------|-------------------------------------------|

In all of the cases:

  • you can always get Object from a list regardless of the wildcard.
  • you can always add null to a mutable list regardless of the wildcard.

Python 3 turn range to a list

In fact, this is a retro-gradation of Python3 as compared to Python2. Certainly, Python2 which uses range() and xrange() is more convenient than Python3 which uses list(range()) and range() respectively. The reason is because the original designer of Python3 is not very experienced, they only considered the use of the range function by many beginners to iterate over a large number of elements where it is both memory and CPU inefficient; but they neglected the use of the range function to produce a number list. Now, it is too late for them to change back already.

If I was to be the designer of Python3, I will:

  1. use irange to return a sequence iterator
  2. use lrange to return a sequence list
  3. use range to return either a sequence iterator (if the number of elements is large, e.g., range(9999999) or a sequence list (if the number of elements is small, e.g., range(10))

That should be optimal.

Two way sync with rsync

Try this,

get-music:
 rsync -avzru --delete-excluded server:/media/10001/music/ /media/Incoming/music/

put-music:
 rsync -avzru --delete-excluded /media/Incoming/music/ server:/media/10001/music/

sync-music: get-music put-music

I just test this and it worked for me. I'm doing a 2-way sync between Windows7 (using cygwin with the rsync package installed) and FreeNAS fileserver (FreeNAS runs on FreeBSD with rsync package pre-installed).

Getting file names without extensions

if file name contains directory and you need to not lose directory:

fileName.Remove(fileName.LastIndexOf("."))

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

This is a recurring subject in Stackoverflow and since I was unable to find a relevant implementation I decided to accept the challenge.

I made some modifications to the squares demo present in OpenCV and the resulting C++ code below is able to detect a sheet of paper in the image:

void find_squares(Mat& image, vector<vector<Point> >& squares)
{
    // blur will enhance edge detection
    Mat blurred(image);
    medianBlur(image, blurred, 9);

    Mat gray0(blurred.size(), CV_8U), gray;
    vector<vector<Point> > contours;

    // find squares in every color plane of the image
    for (int c = 0; c < 3; c++)
    {
        int ch[] = {c, 0};
        mixChannels(&blurred, 1, &gray0, 1, ch, 1);

        // try several threshold levels
        const int threshold_level = 2;
        for (int l = 0; l < threshold_level; l++)
        {
            // Use Canny instead of zero threshold level!
            // Canny helps to catch squares with gradient shading
            if (l == 0)
            {
                Canny(gray0, gray, 10, 20, 3); // 

                // Dilate helps to remove potential holes between edge segments
                dilate(gray, gray, Mat(), Point(-1,-1));
            }
            else
            {
                    gray = gray0 >= (l+1) * 255 / threshold_level;
            }

            // Find contours and store them in a list
            findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

            // Test contours
            vector<Point> approx;
            for (size_t i = 0; i < contours.size(); i++)
            {
                    // approximate contour with accuracy proportional
                    // to the contour perimeter
                    approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);

                    // Note: absolute value of an area is used because
                    // area may be positive or negative - in accordance with the
                    // contour orientation
                    if (approx.size() == 4 &&
                            fabs(contourArea(Mat(approx))) > 1000 &&
                            isContourConvex(Mat(approx)))
                    {
                            double maxCosine = 0;

                            for (int j = 2; j < 5; j++)
                            {
                                    double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                                    maxCosine = MAX(maxCosine, cosine);
                            }

                            if (maxCosine < 0.3)
                                    squares.push_back(approx);
                    }
            }
        }
    }
}

After this procedure is executed, the sheet of paper will be the largest square in vector<vector<Point> >:

opencv paper sheet detection

I'm letting you write the function to find the largest square. ;)

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

How can I pass a parameter to a setTimeout() callback?

You have to remove quotes from your setTimeOut function call like this:

setTimeout(postinsql(topicId),4000);

Loop through all the resources in a .resx file

The minute you add a resource .RESX file to your project, Visual Studio will create a Designer.cs with the same name, creating a a class for you with all the items of the resource as static properties. You can see all the names of the resource when you type the dot in the editor after you type the name of the resource file.

Alternatively, you can use reflection to loop through these names.

Type resourceType = Type.GetType("AssemblyName.Resource1");
PropertyInfo[] resourceProps = resourceType.GetProperties(
    BindingFlags.NonPublic | 
    BindingFlags.Static | 
    BindingFlags.GetProperty);

foreach (PropertyInfo info in resourceProps)
{
    string name = info.Name;
    object value = info.GetValue(null, null);  // object can be an image, a string whatever
    // do something with name and value
}

This method is obviously only usable when the RESX file is in scope of the current assembly or project. Otherwise, use the method provided by "pulse".

The advantage of this method is that you call the actual properties that have been provided for you, taking into account any localization if you wish. However, it is rather redundant, as normally you should use the type safe direct method of calling the properties of your resources.

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Select Specific Columns from Spark DataFrame

There are multiple options (especially in Scala) to select a subset of columns of that Dataframe. The following lines will all select the two columns colA and colB:

import spark.implicits._
import org.apache.spark.sql.functions.{col, column, expr}

inputDf.select(col("colA"), col("colB"))
inputDf.select(inputDf.col("colA"), inputDf.col("colB"))
inputDf.select(column("colA"), column("colB"))
inputDf.select(expr("colA"), expr("colB"))

// only available in Scala
inputDf.select($"colA", $"colB")
inputDf.select('colA, 'colB) // makes use of Scala's Symbol

// selecting columns based on a given iterable of Strings
val selectedColumns: Seq[Column] = Seq("colA", "colB").map(c => col(c))
inputDf.select(selectedColumns: _*)

// select the first or last 2 columns
inputDf.selectExpr(inputDf.columns.take(2): _*)
inputDf.selectExpr(inputDf.columns.takeRight(2): _*)

The usage of $ is possible as Scala provides an implicit class that converts a String into a Column using the method $:

implicit class StringToColumn(val sc : scala.StringContext) extends scala.AnyRef {
  def $(args : scala.Any*) : org.apache.spark.sql.ColumnName = { /* compiled code */ }
}

Typically, when you want to derive one DataFrame to multiple DataFrames it might improve your performance if you persist the original DataFrame before creating the others. At the end you can unpersist the original DataFrame.

Keep in mind that Columns are not resolved at compile time but only when it is compared to the column names of your catalog which happens during analyser phase of the query execution. In case you need stronger type safety you could create a Dataset.

For completeness, here is the csv to try out above code:

// csv file:
// colA,colB,colC
// 1,"foo","bar"

val inputDf = spark.read.format("csv").option("header", "true").load(csvFilePath)

// resulting DataFrame schema
root
 |-- colA: string (nullable = true)
 |-- colB: string (nullable = true)
 |-- colC: string (nullable = true)

django templates: include and extends

You can't pull in blocks from an included file into a child template to override the parent template's blocks. However, you can specify a parent in a variable and have the base template specified in the context.

From the documentation:

{% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

Instead of separate "page1.html" and "page2.html", put {% extends base_template %} at the top of "commondata.html". And then in your view, define base_template to be either "base1.html" or "base2.html".

error: expected declaration or statement at end of input in c

For me this problem was caused by a missing ) at the end of an if statement in a function called by the function the error was reported as from. Try scrolling up in the output to find the first error reported by the compiler. Fixing that error may fix this error.

How to view instagram profile picture in full-size?

You can even set the prof. pic size to its high resolution that is '1080x1080'

replace "150x150" with 1080x1080 and remove /vp/ from the link.

Getting all types that implement an interface

Other answer were not working with a generic interface.

This one does, just replace typeof(ISomeInterface) by typeof (T).

List<string> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())
            .Where(x => typeof(ISomeInterface).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
            .Select(x => x.Name).ToList();

So with

AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())

we get all the assemblies

!x.IsInterface && !x.IsAbstract

is used to exclude the interface and abstract ones and

.Select(x => x.Name).ToList();

to have them in a list.

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).

The reason I wanted that version in particular is because that's what ships with MVC currently.

Here's the code:

$(document).ready(function() {
    $("#topBar").css("position", "absolute");
});

$(window).scroll(function() {
    $("#topBar").css("top", $(window).scrollTop() + "px");
});

MySQL Trigger - Storing a SELECT in a variable

`CREATE TRIGGER `category_before_ins_tr` BEFORE INSERT ON `category`
  FOR EACH ROW
BEGIN
    **SET @tableId= (SELECT id FROM dummy LIMIT 1);**

END;`;

How can apply multiple background color to one div

You can create something like c using CSS multiple-backgrounds.

div {
    background: linear-gradient(red, red),
                linear-gradient(blue, blue),
                linear-gradient(green, green);
    background-size: 30% 50%,
                     30% 60%,
                     40% 80%;
    background-position: 0% top,
                         calc(30% * 100 / (100 - 30)) top,
                         calc(60% * 100 / (100 - 40)) top;
    background-repeat: no-repeat;
}

Note, you still have to use linear-gradients for background types, because CSS will not allow you to control the background-size of a single color layer. So here we just make a single-color gradient. Then you can control the size/position of each of those blocks of color independently. You also have to make sure they don't repeat, or they'll just expand and cover the whole image.

The trickiest part here is background-position. A background-position of 0% puts your element's left edge at the left. 100% puts its right edge at the right. 50% centers is middle.

For a fun bit of math to solve that, you can guess the transform is probably linear, and just solve two little slope-intercept equations.

// (at 0%, the div's left edge is 0% from the left)
0 = m * 0 + b
// (at 100%, the div's right edge is 100% - width% from the left)
100 = m * (100 - width) + b
b = 0, m = 100 / (100 - width)

so to position our 40% wide div 60% from the left, we put it at 60% * 100 / (100 - 40) (or use css-calc).

MySQL Like multiple values

Faster way of doing this:

WHERE interests LIKE '%sports%' OR interests LIKE '%pub%'

is this:

WHERE interests REGEXP 'sports|pub'

Found this solution here: http://forums.mysql.com/read.php?10,392332,392950#msg-392950

More about REGEXP here: http://www.tutorialspoint.com/mysql/mysql-regexps.htm

Javascript - Track mouse position

Irrespective of the browser, below lines worked for me to fetch correct mouse position.

event.clientX - event.currentTarget.getBoundingClientRect().left event.clientY - event.currentTarget.getBoundingClientRect().top

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

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

I found a dirty trick but it works, you could use the hover function to get the value before change!

file_put_contents(meta/services.json): failed to open stream: Permission denied

Problem solved

php artisan cache:clear
sudo chmod -R 777 vendor storage

this enables the write permission to app , framework, logs Hope this will Help

How to send UTF-8 email?

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

Entity Framework - Generating Classes

I found very nice solution. Microsoft released a beta version of Entity Framework Power Tools: Entity Framework Power Tools Beta 2

There you can generate POCO classes, derived DbContext and Code First mapping for an existing database in some clicks. It is very nice!

After installation some context menu options would be added to your Visual Studio.

Right-click on a C# project. Choose Entity Framework-> Reverse Engineer Code First (Generates POCO classes, derived DbContext and Code First mapping for an existing database):

Visual Studio Context Menu

Then choose your database and click OK. That's all! It is very easy.

Error: [ng:areq] from angular controller

// include controller dependency in case of third type

 var app = angular.module('app', ['controller']);

// first type to declare controller // this doesn't work well

var FirstController = function($scope) {
    $scope.val = "First Value";
}

//Second type of declaration

app.controller('FirstController', function($scope) {
    $scope.val = "First Controller";
});

// Third and best type

angular.module('controller',[]).controller('FirstController', function($scope) {
    $scope.val = "Best Way of Controller";
});

Trim last character from a string

"Hello! world!".TrimEnd('!');

read more

EDIT:

What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.

Trim - Removes all occurrences of white space characters from the beginning and end of this instance.

MSDN-Trim

Under this definition removing only last character from string is bad solution.

So if we want to "Trim last character from string" we should do something like this

Example as extension method:

public static class MyExtensions
{
  public static string TrimLastCharacter(this String str)
  {
     if(String.IsNullOrEmpty(str)){
        return str;
     } else {
        return str.TrimEnd(str[str.Length - 1]);
     }
  }
}

Note if you want to remove all characters of the same value i.e(!!!!)the method above removes all existences of '!' from the end of the string, but if you want to remove only the last character you should use this :

else { return str.Remove(str.Length - 1); }

dereferencing pointer to incomplete type

Outside of possible scenarios involving whole-program optimization, the code code generated for something like:

struct foo *bar;
struct foo *test(struct foo *whatever, int blah)
{
  return blah ? whatever: bar;
}

will be totally unaffected by what members struct foo might contain. Because make utilities will generally recompile any compilation unit in which the complete definition of a structure appears, even when such changes couldn't actually affect the code generated for them, it's common to omit complete structure definitions from compilation units that don't actually need them, and such omission is generally not worthy of a warning.

A compiler needs to have a complete structure or union definition to know how to handle declarations objects of the type with automatic or static duration, declarations of aggregates containing members of the type, or code which accesses members of the structure or union. If the compiler doesn't have the information needed to perform one of the above operations, it will have no choice but to squawk about it.

Incidentally, there's one more situation where the Standard would allow a compiler to require a complete union definition to be visible but would not require a diagnostic: if two structures start with a Common Initial Sequence, and a union type containing both is visible when the compiler is processing code that uses a pointer of one of the structure types to inspects a member of that Common Initial Sequence, the compiler is required to recognize that such code might be accessing the corresponding member of a structure of the other type. I don't know what compilers if any comply with the Standard when the complete union type is visible but not when it isn't [gcc is prone to generate non-conforming code in either case unless the -fno-strict-aliasing flag is used, in which case it will generate conforming code in both cases] but if one wants to write code that uses the CIS rule in such a fashion as to guarantee correct behavior on conforming compilers, one may need to ensure that complete union type definition is visible; failure to do so may result in a compiler silently generating bogus code.

What is the purpose of XSD files?

An XSD is a formal contract that specifies how an XML document can be formed. It is often used to validate an XML document, or to generate code from.

ImportError: No module named BeautifulSoup

if you installed its this way(if you not, installing this way):

pip install beautifulsoup4

and if you used its this code(if you not, use this code):

from bs4 import BeautifulSoup

if you using windows system, check it if there are module, might saved different path its module

Different between parseInt() and valueOf() in java?

From this forum:

parseInt() returns primitive integer type (int), whereby valueOf returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.

Of course, another obvious difference is that intValue is an instance method whereby parseInt is a static method.

Remove an onclick listener

Note that if a view is non-clickable (a TextView for example), setting setOnClickListener(null) will mean the view is clickable. Use mMyView.setClickable(false) if you don't want your view to be clickable. For example, if you use a xml drawable for the background, which shows different colours for different states, if your view is still clickable, users can click on it and the different background colour will show, which may look weird.

Undo git stash pop that results in merge conflict

Luckily git stash pop does not change the stash in the case of a conflict!

So nothing, to worry about, just clean up your code and try it again.

Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop again and you get the same stash, that conflicted before.

Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.

How do I iterate over a JSON structure?

Use for...of:

_x000D_
_x000D_
var mycars = [{name:'Susita'}, {name:'BMW'}];

for (var car of mycars) 
{
  document.write(car.name + "<br />");
}
_x000D_
_x000D_
_x000D_

Result:

Susita
BMW

how does int main() and void main() work

If you really want to understand ANSI C 89, I need to correct you in one thing; In ANSI C 89 the difference between the following functions:

int main()
int main(void)
int main(int argc, char* argv[])

is:

int main()

  • a function that expects unknown number of arguments of unknown types. Returns an integer representing the application software status.

int main(void)

  • a function that expects no arguments. Returns an integer representing the application software status.

int main(int argc, char * argv[])

  • a function that expects argc number of arguments and argv[] arguments. Returns an integer representing the application software status.

About when using each of the functions

int main(void)

  • you need to use this function when your program needs no initial parameters to run/ load (parameters received from the OS - out of the program it self).

int main(int argc, char * argv[])

  • you need to use this function when your program needs initial parameters to load (parameters received from the OS - out of the program it self).

About void main()

In ANSI C 89, when using void main and compiling the project AS -ansi -pedantic (in Ubuntu, e.g) you will receive a warning indicating that your main function is of type void and not of type int, but you will be able to run the project. Most C developers tend to use int main() on all of its variants, though void main() will also compile.

how to remove empty strings from list, then remove duplicate values from a list

dtList  = dtList.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList()

I assumed empty string and whitespace are like null. If not you can use IsNullOrEmpty (allow whitespace), or s != null

How do I refresh a DIV content?

This one $("#yourDiv").load(" #yourDiv > *"); is the best if you are planning to just reload a <div>

Make sure to use an id and not a class. Also, remember to paste <script src="https://code.jquery.com/jquery-3.5.1.js"></script> in the <head> section of the html file, if you haven't already. In opposite case it won't work.

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

best way to get folder and file list in Javascript

In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS") out to make it even faster):

var _getAllFilesFromFolder = function(dir) {

    var filesystem = require("fs");
    var results = [];

    filesystem.readdirSync(dir).forEach(function(file) {

        file = dir+'/'+file;
        var stat = filesystem.statSync(file);

        if (stat && stat.isDirectory()) {
            results = results.concat(_getAllFilesFromFolder(file))
        } else results.push(file);

    });

    return results;

};

usage is clear:

_getAllFilesFromFolder(__dirname + "folder");

Display only 10 characters of a long string?

@jolly.exe

Nice example Jolly. I updated your version which limits the character length as opposed to the number of words. I also added setting the title to the real original innerHTML , so users can hover and see what is truncated.

HTML

<div id="stuff">a reallly really really long titleasdfasdfasdfasdfasdfasdfasdfadsf</div> 

JS

 function cutString(id){    
     var text = document.getElementById(id).innerHTML;         
     var charsToCutTo = 30;
        if(text.length>charsToCutTo){
            var strShort = "";
            for(i = 0; i < charsToCutTo; i++){
                strShort += text[i];
            }
            document.getElementById(id).title = "text";
            document.getElementById(id).innerHTML = strShort + "...";
        }            
     };

cutString('stuff'); 

Installing SciPy with pip

On Fedora, this works:

sudo yum install -y python-pip
sudo yum install -y lapack lapack-devel blas blas-devel 
sudo yum install -y blas-static lapack-static
sudo pip install numpy
sudo pip install scipy

If you get any public key errors while downloading, add --nogpgcheck as parameter to yum, for example: yum --nogpgcheck install blas-devel

On Fedora 23 onwards, use dnf instead of yum.

Cannot run Eclipse; JVM terminated. Exit code=13

I face same issue with sts 3.8.4, so I tried different settings but not luck, I reinstall jdk again n tried but same problem. Finally I downloaded sts 3.8.2 n it runs with out any issue. Using windows 8, 64 bit os. thanks

More than 1 row in <Input type="textarea" />

As said by Sparky in comments on many answers to this question, there is NOT any textarea value for the type attribute of the input tag.

On other terms, the following markup is not valid :

<input type="textarea" />

And the browser replaces it by the default :

<input type="text" />

To define a multi-lines text input, use :

<textarea></textarea>

See the textarea element documentation for more details.

Changing font size and direction of axes text in ggplot2

Using "fill" attribute helps in cases like this. You can remove the text from axis using element_blank()and show multi color bar chart with a legend. I am plotting a part removal frequency in a repair shop as below

ggplot(data=df_subset,aes(x=Part,y=Removal_Frequency,fill=Part))+geom_bar(stat="identity")+theme(axis.text.x  = element_blank())

I went for this solution in my case as I had many bars in bar chart and I was not able to find a suitable font size which is both readable and also small enough not to overlap each other.

How to align LinearLayout at the center of its parent?

Below is code to put your Linearlayout at bottom and put its content at center. You have to use RelativeLayout to set Layout at bottom.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#97611F"
    android:gravity="center_horizontal"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="View Saved Searches"
        android:textSize="15dp"
        android:textColor="#fff"
        android:gravity="center_vertical"
        android:visibility="visible" />
    <TextView
        android:layout_width="30dp"
        android:layout_height="24dp"
        android:text="12"
        android:textSize="12dp"
        android:textColor="#fff"
        android:gravity="center_horizontal"
        android:padding="1dp"
        android:visibility="visible" />
  </LinearLayout>  
</RelativeLayout>

How do I find the data directory for a SQL Server instance?

It depends on whether default path is set for data and log files or not.

If the path is set explicitly at Properties => Database Settings => Database default locations then SQL server stores it at Software\Microsoft\MSSQLServer\MSSQLServer in DefaultData and DefaultLog values.

However, if these parameters aren't set explicitly, SQL server uses Data and Log paths of master database.

Bellow is the script that covers both cases. This is simplified version of the query that SQL Management Studio runs.

Also, note that I use xp_instance_regread instead of xp_regread, so this script will work for any instance, default or named.

declare @DefaultData nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', @DefaultData output

declare @DefaultLog nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', @DefaultLog output

declare @DefaultBackup nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultBackup output

declare @MasterData nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer\Parameters', N'SqlArg0', @MasterData output
select @MasterData=substring(@MasterData, 3, 255)
select @MasterData=substring(@MasterData, 1, len(@MasterData) - charindex('\', reverse(@MasterData)))

declare @MasterLog nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer\Parameters', N'SqlArg2', @MasterLog output
select @MasterLog=substring(@MasterLog, 3, 255)
select @MasterLog=substring(@MasterLog, 1, len(@MasterLog) - charindex('\', reverse(@MasterLog)))

select 
    isnull(@DefaultData, @MasterData) DefaultData, 
    isnull(@DefaultLog, @MasterLog) DefaultLog,
    isnull(@DefaultBackup, @MasterLog) DefaultBackup

You can achieve the same result by using SMO. Bellow is C# sample, but you can use any other .NET language or PowerShell.

using (var connection = new SqlConnection("Data Source=.;Integrated Security=SSPI"))
{
    var serverConnection = new ServerConnection(connection);
    var server = new Server(serverConnection);
    var defaultDataPath = string.IsNullOrEmpty(server.Settings.DefaultFile) ? server.MasterDBPath : server.Settings.DefaultFile;
    var defaultLogPath = string.IsNullOrEmpty(server.Settings.DefaultLog) ? server.MasterDBLogPath : server.Settings.DefaultLog;
}

It is so much simpler in SQL Server 2012 and above, assuming you have default paths set (which is probably always a right thing to do):

select 
    InstanceDefaultDataPath = serverproperty('InstanceDefaultDataPath'),
    InstanceDefaultLogPath = serverproperty('InstanceDefaultLogPath')

Add horizontal scrollbar to html table

Use the CSS attribute "overflow" for this.

Short summary:

overflow: visible|hidden|scroll|auto|initial|inherit;

e.g.

table {
    display: block;
    overflow: scroll;
}

PHP: merge two arrays while keeping keys instead of reindexing?

Hello year 2010 question.

The OP.'s requirement is preserve keys (keep keys) and not overlap (I think overwrite). In some case such as numeric keys it is possible but if string keys it seems to be not possible.

If you use array_merge() the numeric keys will always re-index or renumbered.
If you use array_replace(), array_replace_recursive() it will be overlap or overwrite from the right to the left. The value with the same key on first array will be replaced with second array.
If you use $array1 + $array2 as the comment was mentioned, if the keys are same then it will keep the value from first array but drop the second array.

Custom function.

Here is my function that I just wrote to work on the same requirements. You are free to use for any purpose.

/**
 * Array custom merge. Preserve indexed array key (numbers) but overwrite string key (same as PHP's `array_merge()` function).
 * 
 * If the another array key is string, it will be overwrite the first array.<br>
 * If the another array key is integer, it will be add to first array depend on duplicated key or not. 
 * If it is not duplicate key with the first, the key will be preserve and add to the first array.
 * If it is duplicated then it will be re-index the number append to the first array.
 *
 * @param array $array1 The first array is main array.
 * @param array ...$arrays The another arrays to merge with the first.
 * @return array Return merged array.
 */
function arrayCustomMerge(array $array1, array ...$arrays): array
{
    foreach ($arrays as $additionalArray) {
        foreach ($additionalArray as $key => $item) {
            if (is_string($key)) {
                // if associative array.
                // item on the right will always overwrite on the left.
                $array1[$key] = $item;
            } elseif (is_int($key) && !array_key_exists($key, $array1)) {
                // if key is number. this should be indexed array.
                // and if array 1 is not already has this key.
                // add this array with the key preserved to array 1.
                $array1[$key] = $item;
            } else {
                // if anything else...
                // get all keys from array 1 (numbers only).
                $array1Keys = array_filter(array_keys($array1), 'is_int');
                // next key index = get max array key number + 1.
                $nextKeyIndex = (intval(max($array1Keys)) + 1);
                unset($array1Keys);
                // set array with the next key index.
                $array1[$nextKeyIndex] = $item;
                unset($nextKeyIndex);
            }
        }// endforeach; $additionalArray
        unset($item, $key);
    }// endforeach;
    unset($additionalArray);

    return $array1;
}// arrayCustomMerge

Testing.

<?php
$array1 = [
    'cat', 
    'bear', 
    'fruitred' => 'apple',
    3.1 => 'dog',
    null => 'null',
];
$array2 = [
    1 => 'polar bear',
    20 => 'monkey',
    'fruitred' => 'strawberry',
    'fruityellow' => 'banana',
    null => 'another null',
];

// require `arrayCustomMerge()` function here.

function printDebug($message)
{
    echo '<pre>';
    print_r($message);
    echo '</pre>' . PHP_EOL;
}

echo 'array1: <br>';
printDebug($array1);
echo 'array2: <br>';
printDebug($array2);


echo PHP_EOL . '<hr>' . PHP_EOL . PHP_EOL;


echo 'arrayCustomMerge:<br>';
$merged = arrayCustomMerge($array1, $array2);
printDebug($merged);


assert($merged[0] == 'cat', 'array key 0 should be \'cat\'');
assert($merged[1] == 'bear', 'array key 1 should be \'bear\'');
assert($merged['fruitred'] == 'strawberry', 'array key \'fruitred\' should be \'strawberry\'');
assert($merged[3] == 'dog', 'array key 3 should be \'dog\'');
assert(array_search('another null', $merged) !== false, '\'another null\' should be merged.');
assert(array_search('polar bear', $merged) !== false, '\'polar bear\' should be merged.');
assert($merged[20] == 'monkey', 'array key 20 should be \'monkey\'');
assert($merged['fruityellow'] == 'banana', 'array key \'fruityellow\' should be \'banana\'');
The results.
array1:

Array
(
    [0] => cat
    [1] => bear
    [fruitred] => apple
    [3] => dog
    [] => null
)

array2:

Array
(
    [1] => polar bear
    [20] => monkey
    [fruitred] => strawberry
    [fruityellow] => banana
    [] => another null
)

---
arrayCustomMerge:

Array
(
    [0] => cat
    [1] => bear
    [fruitred] => strawberry
    [3] => dog
    [] => another null
    [4] => polar bear
    [20] => monkey
    [fruityellow] => banana
)

Java NIO FileChannel versus FileOutputstream performance / usefulness

If you are not using the transferTo feature or non-blocking features you will not notice a difference between traditional IO and NIO(2) because the traditional IO maps to NIO.

But if you can use the NIO features like transferFrom/To or want to use Buffers, then of course NIO is the way to go.

HTML form with two submit buttons and two "target" attributes

It is do-able on the server side.

<button type="submit" name="signin" value="email_signin" action="/signin">Sign In</button>
<button type="submit" name="signin" value="facebook_signin"  action="/facebook_login">Facebook</button>

and in my node server side script

app.post('/', function(req, res) {
if(req.body.signin == "email_signin"){
            function(email_login) {...} 
        }
if(req.body.signin == "fb_signin"){
            function(fb_login) {...}    


        }
    }); 

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.

cout is not a member of std

add #include <iostream> to the start of io.cpp too.

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The "Data Sources (ODBC)" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually:

%windir%\SysWOW64\odbcad32.exe (%windir% is usually C:\Windows)

When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.

How to use *ngIf else?

For Angular 9/8

Source Link with Examples

    export class AppComponent {
      isDone = true;
    }

1) *ngIf

    <div *ngIf="isDone">
      It's Done!
    </div>

    <!-- Negation operator-->
    <div *ngIf="!isDone">
      It's Not Done!
    </div>

2) *ngIf and Else

    <ng-container *ngIf="isDone; else elseNotDone">
      It's Done!
    </ng-container>

    <ng-template #elseNotDone>
      It's Not Done!
    </ng-template>

3) *ngIf, Then and Else

    <ng-container *ngIf="isDone;  then iAmDone; else iAmNotDone">
    </ng-container>

    <ng-template #iAmDone>
      It's Done!
    </ng-template>

    <ng-template #iAmNotDone>
      It's Not Done!
    </ng-template>

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Favicon dimensions?

The format of favicon must be square otherwise the browser will stretch it. Unfortunatelly, Internet Explorer < 11 do not support .gif, or .png filetypes, but only Microsoft's .ico format. You can use some "favicon generator" app like: http://favicon-generator.org/

Deprecated Java HttpClient - How hard can it be?

Use HttpClientBuilder to build the HttpClient instead of using DefaultHttpClient

ex:

MinimalHttpClient httpclient = new HttpClientBuilder().build();

 // Prepare a request object
 HttpGet httpget = new HttpGet("http://www.apache.org/");

How to redirect to an external URL in Angular2?

You can use this-> window.location.href = '...';

This would change the page to whatever you want..

throwing an exception in objective-c/cocoa

I believe you should never use Exceptions to control normal program flow. But exceptions should be thrown whenever some value doesn't match a desired value.

For example if some function accepts a value, and that value is never allowed to be nil, then it's fine to trow an exception rather then trying to do something 'smart'...

Ries

Select multiple columns using Entity Framework

Why don't you create a new object right in the .Select:

.Select(x => new PInfo{ 
    ServerName = x.ServerName, 
    ProcessID = x.ProcessID, 
    UserName = x.Username }).ToList();

How to convert Observable<any> to array[]

Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.

Using your CountryData class, you would define a service method like this:

getCountries()  {
  return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}

Then when you need it, define an array like this:

countries:CountryData[] = [];

and subscribe to it like this:

this.countryService.getCountries().subscribe(countries => this.countries = countries);

A complete setup answer is posted here also.

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

How can I be notified when an element is added to the page?

Check out this plugin that does exacly that - jquery.initialize

It works exacly like .each function, the difference is it takes selector you've entered and watch for new items added in future matching this selector and initialize them

Initialize looks like this

$(".some-element").initialize( function(){
    $(this).css("color", "blue");
});

But now if new element matching .some-element selector will appear on page, it will be instanty initialized.

The way new item is added is not important, you dont need to care about any callbacks etc.

So if you'd add new element like:

$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!

it will be instantly initialized.

Plugin is based on MutationObserver

How to create an Array, ArrayList, Stack and Queue in Java?

Without more details as to what the question is exactly asking, I am going to answer the title of the question,

Create an Array:

String[] myArray = new String[2];
int[] intArray = new int[2];

// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};

Create an ArrayList:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");

ArrayList<Integer> myNum = new ArrayList<Integer>();
myNum.add(1);
myNum.add(2);

This means, create an ArrayList of String and Integer objects. You cannot use int because thats a primitive data types, see the link for a list of primitive data types.

Create a Stack:

Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);

Create an Queue: (using LinkedList)

Queue<String> myQueue = new LinkedList<String>();
Queue<Integer> myNumbers = new LinkedList<Integer>();
myQueue.add("Hello");
myQueue.add("World");
myNumbers.add(1);
myNumbers.add(2);

Same thing as an ArrayList, this declaration means create an Queue of String and Integer objects.


Update:

In response to your comment from the other given answer,

i am pretty confused now, why are using string. and what does <String> means

We are using String only as a pure example, but you can add any other object, but the main point is that you use an object not a primitive type. Each primitive data type has their own primitive wrapper class, see link for list of primitive data type's wrapper class.

I have posted some links to explain the difference between the two, but here are a list of primitive types

  • byte
  • short
  • char
  • int
  • long
  • boolean
  • double
  • float

Which means, you are not allowed to make an ArrayList of integer's like so:

ArrayList<int> numbers = new ArrayList<int>(); 
           ^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
            ^ perfectly valid

Also, you can use your own objects, here is my Monster object I created,

public class Monster {
   String name = null;
   String location = null;
   int age = 0;

public Monster(String name, String loc, int age) { 
   this.name = name;
   this.loc = location;
   this.age = age;
 }

public void printDetails() {
   System.out.println(name + " is from " + location +
                                     " and is " + age + " old.");
 }
} 

Here we have a Monster object, but now in our Main.java class we want to keep a record of all our Monster's that we create, so let's add them to an ArrayList

public class Main {
    ArrayList<Monster> myMonsters = new ArrayList<Monster>();

public Main() {
    Monster yetti = new Monster("Yetti", "The Mountains", 77);
    Monster lochness = new Monster("Lochness Monster", "Scotland", 20);

    myMonsters.add(yetti); // <-- added Yetti to our list
    myMonsters.add(lochness); // <--added Lochness to our list
  
    for (Monster m : myMonsters) {
        m.printDetails();
     }
   }

public static void main(String[] args) {
    new Main();
 }
}

(I helped my girlfriend's brother with a Java game, and he had to do something along those lines as well, but I hope the example was well demonstrated)

installing requests module in python 2.7 windows

On windows 10 run cmd.exe with admin rights then type :

1) cd \Python27\scripts

2) pip install requests

It should work. My case was with python 2.7

How to find an available port?

If you need in range use:

public int nextFreePort(int from, int to) {
    int port = randPort(from, to);
    while (true) {
        if (isLocalPortFree(port)) {
            return port;
        } else {
            port = ThreadLocalRandom.current().nextInt(from, to);
        }
    }
}

private boolean isLocalPortFree(int port) {
    try {
        new ServerSocket(port).close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

How to tell which row number is clicked in a table?

In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:

<table id="elitable" border="1" cellspacing="0" width="100%">
  <tr>
 <td>100</td><td>AAA</td><td>aaa</td>
  </tr>
  <tr>
<td>200</td><td>BBB</td><td>bbb</td>
   </tr>
   <tr>
<td>300</td><td>CCC</td><td>ccc</td>
  </tr>
</table>


    <script>
    $(function(){
        $("#elitable tr").click(function(){
        alert (this.rowIndex);
        });
    });
    </script>

DEMO

Bootstrap: align input with button

<form class="form-inline">
  <div class="form-group">
    <label class="sr-only" for="exampleInputEmail3">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail3" placeholder="Email">
  </div>
  <button type="submit" class="btn btn-default">Sign in</button>
</form>

Why can't I reference my class library?

One possibility is that the target .NET Framework version of the class library is higher than that of the project.

Fully custom validation error message with Rails

I tried following, worked for me :)

1 job.rb

class Job < ApplicationRecord
    validates :description, presence: true
    validates :title, 
              :presence => true, 
              :length => { :minimum => 5, :message => "Must be at least 5 characters"}
end

2 jobs_controller.rb

def create
      @job = Job.create(job_params)
      if @job.valid?
        redirect_to jobs_path
      else
        render new_job_path
      end     
    end

3 _form.html.erb

<%= form_for @job do |f| %>
  <% if @job.errors.any? %>
    <h2>Errors</h2>
    <ul>
      <% @job.errors.full_messages.each do |message|%>
        <li><%= message %></li>
      <% end %>  
    </ul>
  <% end %>
  <div>
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>
  <div>
    <%= f.label :description %>
    <%= f.text_area :description, size: '60x6' %>

  </div>
  <div>
    <%= f.submit %>
  </div>
<% end %> 

docker : invalid reference format

This also happens when you use development docker compose like the below, in production. You don't want to be building images in production as that breaks the ideology of containers. We should be deploying images:

  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"

Change that to use the built image:

  web:
    command: /bin/bash run.sh
    image: registry.voxcloud.co.za:9000/dyndns_api_web:0.1
    ports:
      - "8000:8000"

React hooks useState Array

use state is not always needed you can just simply do this

let paymentList = [
    {"id":249,"txnid":"2","fname":"Rigoberto"}, {"id":249,"txnid":"33","fname":"manuel"},]

then use your data in a map loop like this in my case it was just a table and im sure many of you are looking for the same. here is how you use it.

<div className="card-body">
            <div className="table-responsive">
                <table className="table table-striped">
                    <thead>
                        <tr>
                            <th>Transaction ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            paymentList.map((payment, key) => (
                                <tr key={key}>
                                    <td>{payment.txnid}</td>
                                    <td>{payment.fname}</td>
                                </tr>
                            ))
                        }
                    </tbody>
                </table>
            </div>
        </div>

Find unique lines

you can use:

sort data.txt| uniq -u

this sort data and filter by unique values

The property 'value' does not exist on value of type 'HTMLElement'

If you are using angular you can use -

const element = document.getElementById('elemId') as HTMLInputElement;

Select from one table where not in another

To expand on Johan's answer, if the part_num column in the sub-select can contain null values then the query will break.

To correct this, add a null check...

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN 
      (SELECT pd.part_num FROM wpsapi4.product_details pd 
                  where pd.part_num is not null)
  • Sorry but I couldn't add a comment as I don't have the rep!

How to set specific Java version to Maven

Also you can have two versions of maven installed, and edit one of them, editing here:

mvn(non-windows)/mvn.bat/mvn.cmd(windows)

replacing your %java_home% appearances to your java desired path. Then just execute maven from that modified path

Find element in List<> that contains a value

Either use LINQ:

var value = MyList.First(item => item.name == "foo").value;

(This will just find the first match, of course. There are lots of options around this.)

Or use Find instead of FindIndex:

var value = MyList.Find(item => item.name == "foo").value;

I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.

(I'd also suggest following the .NET naming conventions.)

How do you align left / right a div without using float?

Another way to do something similar is with flexbox on a wrapper element, i.e.,

_x000D_
_x000D_
 .row {_x000D_
        display: flex;_x000D_
        justify-content: space-between;_x000D_
    }
_x000D_
  <div class="row">_x000D_
        <div>Left</div>_x000D_
        <div>Right</div>_x000D_
    </div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

How to completely remove a dialog on close

An ugly solution that works like a charm for me:

$("#mydialog").dialog(
    open: function(){
        $('div.ui-widget-overlay').hide();
        $("div.ui-dialog").not(':first').remove();
}
});

How to install MySQLi on MacOS

sudo apt-get -y -f install php7.0-mysql

One time page refresh after first page load

You'd need to use either GET or POST information. GET would be simplest. Your JS would check the URL, if a certain param wasn't found, it wouldn't just refresh the page, but rather send the user to a "different" url, which would be the same URL but with the GET parameter in it.

For example:
http://example.com -->will refresh
http://example.com?refresh=no -->won't refresh

If you don't want the messy URL, then I'd include some PHP right at the beginning of the body that echos a hidden value that essentitally says whether the necessary POST param for not refreshing the page was included in the initial page request. Right after that, you'd include some JS to check that value and refresh the page WITH that POST information if necessary.

Convert a python UTC datetime to a local datetime using only python standard library?

Here is another way to change timezone in datetime format (I know I wasted my energy on this but I didn't see this page so I don't know how) without min. and sec. cause I don't need it for my project:

def change_time_zone(year, month, day, hour):
      hour = hour + 7 #<-- difference
      if hour >= 24:
        difference = hour - 24
        hour = difference
        day += 1
        long_months = [1, 3, 5, 7, 8, 10, 12]
        short_months = [4, 6, 9, 11]
        if month in short_months:
          if day >= 30:
            day = 1
            month += 1
            if month > 12:
              year += 1
        elif month in long_months:
          if day >= 31:
            day = 1
            month += 1
            if month > 12:
              year += 1
        elif month == 2:
          if not year%4==0:
            if day >= 29:
              day = 1
              month += 1
              if month > 12:
                year += 1
          else:
            if day >= 28:
              day = 1
              month += 1
              if month > 12:
                year += 1
      return datetime(int(year), int(month), int(day), int(hour), 00)

MySQL export into outfile : CSV escaping chars

Probably won't help but you could try creating a CSV table with that content:

DROP TABLE IF EXISTS foo_export;
CREATE TABLE foo_export LIKE foo;
ALTER TABLE foo_export ENGINE=CSV;
INSERT INTO foo_export SELECT id, 
   client,
   project,
   task,
   REPLACE(REPLACE(ifnull(ts.description,''),'\n',' '),'\r',' ') AS description, 
   time,
   date
  FROM ....

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

You can find an easy guide here

The step are 2: - Copy the icon in the correct folder/folders - Change the AndroidManifest.xml

Read a XML (from a string) and get some fields - Problems reading XML

The other answers are several years old (and do not work for Windows Phone 8.1) so I figured I'd drop in another option. I used this to parse an RSS response for a Windows Phone app:

XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(xml_string);

c# how to add byte to byte array

Simple, just use the code below, as I do:

        public void AppendSpecifiedBytes(ref byte[] dst, byte[] src)
    {
        // Get the starting length of dst
        int i = dst.Length;
        // Resize dst so it can hold the bytes in src
        Array.Resize(ref dst, dst.Length + src.Length);
        // For each element in src
        for (int j = 0; j < src.Length; j++)
        {
            // Add the element to dst
            dst[i] = src[j];
            // Increment dst index
            i++;
        }
    }

    // Appends src byte to the dst array
    public void AppendSpecifiedByte(ref byte[] dst, byte src)
    {
        // Resize dst so that it can hold src
        Array.Resize(ref dst, dst.Length + 1);
        // Add src to dst
        dst[dst.Length - 1] = src;
    }

How to sort 2 dimensional array by column value?

As my usecase involves dozens of columns, I expanded @jahroy's answer a bit. (also just realized @charles-clayton had the same idea.)
I pass the parameter I want to sort by, and the sort function is redefined with the desired index for the comparison to take place on.

var ID_COLUMN=0
var URL_COLUMN=1

findings.sort(compareByColumnIndex(URL_COLUMN))

function compareByColumnIndex(index) {
  return function(a,b){
    if (a[index] === b[index]) {
        return 0;
    }
    else {
        return (a[index] < b[index]) ? -1 : 1;
    }
  }
}

How to get the concrete class name as a string?

 instance.__class__.__name__

example:

>>> class A():
    pass
>>> a = A()
>>> a.__class__.__name__
'A'

How can I get client information such as OS and browser

else if(user.contains("rv:11.0"))
            {
                String substring=userAgent.substring(userAgent.indexOf("rv")).split("\\)")[0];
                browser=substring.split(":")[0].replace("rv", "IE")+"-"+substring.split(":")[1];

            }

Twitter Bootstrap - add top space between rows

In Bootstrap 4 alpha+ you can use this

class margin-bottom-5

The classes are named using the format: {property}-{sides}-{size}

Access restriction on class due to restriction on required library rt.jar?

I just had this problem too. Apparently I had set the JRE to 1.5 instead of 1.6 in my build path.

Converting HTML string into DOM elements?

Why not use insertAdjacentHTML

for example:

// <div id="one">one</div> 
var d1 = document.getElementById('one'); 
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here

Date object to Calendar [Java]

What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time:

Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

However, another approach is to not use Date at all. You could use an approach like this:

private Calendar startTime;
private long duration;
private long startNanos;   //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();

public void setEndTime() {
        this.duration = System.nanoTime() - this.startNanos;
}

public Calendar getStartTime() {
        return this.startTime;
}

public long getDuration() {
        return this.duration;
}

In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.

Call a function after previous function is complete

This depends on what function1 is doing.

If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.

If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:

function1()
{
  new AjaxCall(ajaxOptions, MyCallback);
}

function MyCallback(result)
{
  function2(result);
}

Ruby: How to turn a hash into HTTP parameters?

Steal from Merb:

# File merb/core_ext/hash.rb, line 87
def to_params
  params = ''
  stack = []

  each do |k, v|
    if v.is_a?(Hash)
      stack << [k,v]
    else
      params << "#{k}=#{v}&"
    end
  end

  stack.each do |parent, hash|
    hash.each do |k, v|
      if v.is_a?(Hash)
        stack << ["#{parent}[#{k}]", v]
      else
        params << "#{parent}[#{k}]=#{v}&"
      end
    end
  end

  params.chop! # trailing &
  params
end

See http://noobkit.com/show/ruby/gems/development/merb/hash/to_params.html

Best way to add Activity to an Android project in Eclipse?

I just use the "New Class" dialog in Eclipse and set the base class as Activity. I'm not aware of any other way to do this. What other method would you expect to be available?

Delete a database in phpMyAdmin

Screenshot

  1. Go to phpmyadmin home page.
  2. Click on 'Databases'.
  3. Select the database you want to delete. (put check mark)
  4. Click Drop.

Adding Http Headers to HttpClient

When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add option:

client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");      

Find Number of CPUs and Cores per CPU using Command Prompt

Based upon your comments - your path statement has been changed/is incorrect or the path variable is being incorrectly used for another purpose.

gulp command not found - error after installing gulp

This works for me:

 npm link gulp
 npm update

How to format a java.sql Timestamp for displaying?

java.time

I am providing the modern answer. The Timestamp class is a hack on top of the already poorly designed java.util.Date class and is long outdated. I am assuming, though, that you are getting a Timestamp from a legacy API that you cannot afford to upgrade to java.time just now. When you do that, convert it to a modern Instant and do further processing from there.

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(Locale.GERMAN);
    
    Timestamp oldfashionedTimestamp = new Timestamp(1_567_890_123_456L);
    
    ZonedDateTime dateTime = oldfashionedTimestamp.toInstant()
            .atZone(ZoneId.systemDefault());
    String desiredFormat = dateTime.format(formatter);
    
    System.out.println(desiredFormat);

Output in my time zone:

07.09.2019 23:02:03

Pick how long or short of a format you want by specifying FormatStyle.SHORT, .MEDIUM, .LONG or .FULL. Pick your own locale where I put Locale.GERMAN. And pick your desired time zone, for example ZoneId.of("Europe/Oslo"). A Timestamp is a point in time without time zone, so we need a time zone to be able to convert it into year, month, day, hour, minute, etc. If your Timestamp comes from a database value of type timestamp without time zone (generally not recommended, but unfortunately often seen), ZoneId.systemDefault() is likely to give you the correct result. Another and slightly simpler option in this case is instead to convert to a LocalDateTime using oldfashionedTimestamp.toLocalDateTime() and then format the LocalDateTime in the same way as I did with the ZonedDateTime.

Lombok added but getters and setters not recognized in Intellij IDEA

  1. Go to File > Settings > Plugins.
    1. Click on Browse repositories...
    2. Search for Lombok Plugin.
    3. Click on Install plugin.
    4. Restart Android Studio.

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

In place of 1.+ use the latest version of crashlytics -

 dependencies {
        classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
    }

you should use this way -

dependencies {
            classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:2.6.8'
        }

your problem will be resolved for sure. Happy coding !!

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

If you're using Python 2.x, try installing a urllib2 opener. That should print out your headers, although you may have to combine that with other openers you're using to hit the HTTPS.

import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)

Pair/tuple data type in Go

There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.

Nick's answer shows how you can do something similar that handles arbitrary types using interface{}. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{} type)

My other answer shows how you can do something similar that avoids creating a type using anonymous structs.

These techniques have some properties of tuples, but no, they are not tuples.

How to convert a string Date to long millseconds

Take a look to SimpleDateFormat class that can parse a String and return a Date and the getTime method of Date class.

How can I pass request headers with jQuery's getJSON() method?

The $.getJSON() method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax() method.

Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

So just use $.ajax() and provide all the extra parameters you need.

Vagrant error : Failed to mount folders in Linux guest

In configuration where windows is a host, and linux is a guest I found solution of the same problem in other place.

So again, the error message was "Failed to mount folders in Linux guest. This is usually because the "vboxsf" file system is not available." (...)

This was caused because I have made mistake by doing symlink inside the guest system from /vagrant into /home/vagrant/vagrant. The point is, that the directory /vagrant is a normal linux directory that has a symlink (so all ok), but when booting up by "vagrant up", it tries to mount windows directory on that place, and windows directory cannot work as a symlink. Windows host does not support linux symlinks.

So what You can do then, is to ssh into guest, remove the symlink wherever You have it, and reload machine.

In my configuration it was: Vagrant 1.7.2, VBoxGuestAdditions 4.3.28 and VBox 4.3.28.

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.

EXEC sp_addrolemember 'db_ddladmin', 'username_here';

did the trick

Create a List that contain each Line of a File

Assuming you also want to strip whitespace at beginning and end of each line, you can map the string strip function to the list returned by readlines:

map(str.strip, open('filename').readlines())

Google Maps API Multiple Markers with Infowindows

Here is the code snippet which will work for sure. You can visit below link for working jsFiddle and explainantion in detail. How to locate multiple addresses on google maps with perfect zoom

var infowindow = new google.maps.InfoWindow();  
google.maps.event.addListener(marker, 'mouseover', (function(marker) {  
           return function() {  
               var content = address;  
               infowindow.setContent(content);  
               infowindow.open(map, marker);  
           }  
         })(marker));  

Store an array in HashMap

Not sure of the exact question but is this what you are looking for?

public class TestRun
{
     public static void main(String [] args)
     {
        Map<String, Integer[]> prices = new HashMap<String, Integer[]>();

        prices.put("milk", new Integer[] {1, 3, 2});
        prices.put("eggs", new Integer[] {1, 1, 2});
     }
}

Converting from Integer, to BigInteger

You can do in this way:

    Integer i = 1;
    new BigInteger("" + i);

Precision String Format Specifier In Swift

use below method

let output = String.localizedStringWithFormat(" %.02f %.02f %.02f", r, g, b)

println(output)

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

Deleting my node modules folder and running a normal npm install did it for me

How to run a bash script from C++ program

Use the system function.

system("myfile.sh"); // myfile.sh should be chmod +x

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

I had the same issue on Windows 7 and I had to install both JDK and JRE and it's a success.