Programs & Examples On #Naked objects

An architectural pattern whereby an object-oriented user interface is created directly from the underlying domain object model using reflection.

Combining the results of two SQL queries as separate columns

You can aliasing both query and Selecting them in the select query
http://sqlfiddle.com/#!2/ca27b/1

SELECT x.a, y.b FROM (SELECT * from a) as x, (SELECT * FROM b) as y

log4j: Log output of a specific class to a specific appender

An example:

log4j.rootLogger=ERROR, logfile

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false

log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

How to JOIN three tables in Codeigniter

try this

In your model

If u want get all album data use

  function get_all_album_data() {

    $this->db->select ( '*' ); 
    $this->db->from ( 'Album' );
    $this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
    $this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
    $query = $this->db->get ();
    return $query->result ();
 }

if u want to get specific album data use

  function get_album_data($album_id) {

    $this->db->select ( '*' ); 
    $this->db->from ( 'Album' );
    $this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
    $this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
    $this->db->where ( 'Album.album_id', $album_id);
    $query = $this->db->get ();
    return $query->result ();
 }

If a folder does not exist, create it

Derived/combined from multiple answers, implementing it for me was as easy as this:

public void Init()
{
    String platypusDir = @"C:\platypus";
    CreateDirectoryIfDoesNotExist(platypusDir);
}

private void CreateDirectoryIfDoesNotExist(string dirName)
{
    System.IO.Directory.CreateDirectory(dirName);
}

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

One more method is to Define the Layout inside the View:

   @{
    Layout = "~/Views/Shared/_MyAdminLayout.cshtml";
    }

More Ways to do, can be found here, hope this helps someone.

Java correct way convert/cast object to Double

You can't cast an object to a Double if the object is not a Double.

Check out the API.

particularly note

valueOf(double d);

and

valueOf(String s);

Those methods give you a way of getting a Double instance from a String or double primitive. (Also not the constructors; read the documentation to see how they work) The object you are trying to convert naturally has to give you something that can be transformed into a double.

Finally, keep in mind that Double instances are immutable -- once created you can't change them.

Using .NET, how can you find the mime type of a file based on the file signature not the extension

This answer is a copy of the author's answer (Richard Gourlay), but improved to solve issues on IIS 8 / win2012 (where function would cause app pool to crash), based on Rohland's comment pointing to http://www.pinvoke.net/default.aspx/urlmon.findmimefromdata

using System.Runtime.InteropServices;

...

public static string GetMimeFromFile(string filename)
{

    if (!File.Exists(filename))
        throw new FileNotFoundException(filename + " not found");

    const int maxContent = 256;

    var buffer = new byte[maxContent];
    using (var fs = new FileStream(filename, FileMode.Open))
    {
        if (fs.Length >= maxContent)
            fs.Read(buffer, 0, maxContent);
        else
            fs.Read(buffer, 0, (int) fs.Length);
    }

    var mimeTypePtr = IntPtr.Zero;
    try
    {
        var result = FindMimeFromData(IntPtr.Zero, null, buffer, maxContent, null, 0, out mimeTypePtr, 0);
        if (result != 0)
        {
            Marshal.FreeCoTaskMem(mimeTypePtr);
            throw Marshal.GetExceptionForHR(result);
        }

        var mime = Marshal.PtrToStringUni(mimeTypePtr);
        Marshal.FreeCoTaskMem(mimeTypePtr);
        return mime;
    }
    catch (Exception e)
    {
        if (mimeTypePtr != IntPtr.Zero)
        {
            Marshal.FreeCoTaskMem(mimeTypePtr);
        }
        return "unknown/unknown";
    }
}

[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
private static extern int FindMimeFromData(IntPtr pBC,
    [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
    [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,
    int cbSize,
    [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
    int dwMimeFlags,
    out IntPtr ppwzMimeOut,
    int dwReserved);

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

How to get the next auto-increment id in mysql

Simple query would do SHOW TABLE STATUS LIKE 'table_name'

Ruby: character to ascii from a string

The c variable already contains the char code!

"string".each_byte do |c|
    puts c
end

yields

115
116
114
105
110
103

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Example:

Model:

public class MyViewModel
{
    [Required]
    public string Foo { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return Content("Thanks", "text/html");
    }
}

View:

@model AppName.Models.MyViewModel

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

<div id="result"></div>

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    <input type="submit" value="OK" />
}

and here's a better (in my perspective) example:

View:

@model AppName.Models.MyViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/index.js")" type="text/javascript"></script>

<div id="result"></div>

@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    <input type="submit" value="OK" />
}

index.js:

$(function () {
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $('#result').html(result);
                }
            });
        }
        return false;
    });
});

which can be further enhanced with the jQuery form plugin.

How to specify font attributes for all elements on an html web page?

If you want to set styles of all elements in body you should use next code^

  body{
    color: green;
    }

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I've gotten this error when running a scalar function using a table value, but the Select statement in my scalar function RETURN clause was missing the "FROM table" portion. :facepalms:

How to extract extension from filename string in Javascript?

A variant that works with all of the following inputs:

  • "file.name.with.dots.txt"
  • "file.txt"
  • "file"
  • ""
  • null
  • undefined

would be:

var re = /(?:\.([^.]+))?$/;

var ext = re.exec("file.name.with.dots.txt")[1];   // "txt"
var ext = re.exec("file.txt")[1];                  // "txt"
var ext = re.exec("file")[1];                      // undefined
var ext = re.exec("")[1];                          // undefined
var ext = re.exec(null)[1];                        // undefined
var ext = re.exec(undefined)[1];                   // undefined

Explanation

(?:         # begin non-capturing group
  \.        #   a dot
  (         #   begin capturing group (captures the actual extension)
    [^.]+   #     anything except a dot, multiple times
  )         #   end capturing group
)?          # end non-capturing group, make it optional
$           # anchor to the end of the string

To check if string contains particular word

Not as complicated as they say, check this you will not regret.

String sentence = "Check this answer and you can find the keyword with this code";
String search  = "keyword";

if ( sentence.toLowerCase().indexOf(search.toLowerCase()) != -1 ) {

   System.out.println("I found the keyword");

} else {

   System.out.println("not found");

}

You can change the toLowerCase() if you want.

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

Is it possible to install iOS 6 SDK on Xcode 5?

Just to add, you can actually download old versions of the simulator with Xcode 5 itself - just go to preferences and you'll find them under Downloads:

enter image description here

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

LINQ syntax where string value is not null or empty

This won't fail on Linq2Objects, but it will fail for Linq2SQL, so I am assuming that you are talking about the SQL provider or something similar.

The reason has to do with the way that the SQL provider handles your lambda expression. It doesn't take it as a function Func<P,T>, but an expression Expression<Func<P,T>>. It takes that expression tree and translates it so an actual SQL statement, which it sends off to the server.

The translator knows how to handle basic operators, but it doesn't know how to handle methods on objects. It doesn't know that IsNullOrEmpty(x) translates to return x == null || x == string.empty. That has to be done explicitly for the translation to SQL to take place.

How to change indentation in Visual Studio Code?

You might also want to set the editor.detectIndentation to false, in addition to Elliot-J's answer.

VSCode will overwrite your editor.tabSize and editor.insertSpaces settings per file if it detects that a file has a different tab or spaces indentation pattern. You can run into this issue if you add existing files to your project, or if you add files using code generators like Angular Cli. The above setting prevents VSCode from doing this.

Convert decimal to hexadecimal in UNIX shell script

bash-4.2$ printf '%x\n' 4294967295
ffffffff

bash-4.2$ printf -v hex '%x' 4294967295
bash-4.2$ echo $hex
ffffffff

How to remove RVM (Ruby Version Manager) from my system

I am running Ubuntu 19.04 and followed all the instructions above and then some. Finally, what worked for me was to run

sudo apt autoremove rvm

and now when I try and reinstall RVM it's actually gone. RVM is invasive, to say the least.

How to automatically add user account AND password with a Bash script?

Single liner to create a sudo user with home directory and password.

useradd -m -p $(openssl passwd -1 ${PASSWORD}) -s /bin/bash -G sudo ${USERNAME}

Pretty printing XML with javascript

If you are looking for a JavaScript solution just take the code from the Pretty Diff tool at http://prettydiff.com/?m=beautify

You can also send files to the tool using the s parameter, such as: http://prettydiff.com/?m=beautify&s=https://stackoverflow.com/

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

You can consider to replace default WordPress jQuery script with Google Library by adding something like the following into theme functions.php file:

function modify_jquery() {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'modify_jquery');

Code taken from here: http://www.wpbeginner.com/wp-themes/replace-default-wordpress-jquery-script-with-google-library/

How to make a div center align in HTML

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Center</title>_x000D_
  </head>_x000D_
  <body>_x000D_
_x000D_
    <div style="text-align: center;">_x000D_
      <div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Tested and worked in IE, Firefox, Chrome, Safari and Opera. I did not test IE6. The outer text-align is needed for IE. Other browsers (and IE9?) will work when you give the DIV margin (left and right) value of auto. Margin "0 auto" is a shorthand for margin "0 auto 0 auto" (top right bottom left).

Note: the text is also centered inside the inner DIV, if you want it to remain on the left side just specify text-align: left; for the inner DIV.

Edit: IE 6, 7, 8 and 9 running on the Standards Mode will work with margins set to auto.

MySQL Data - Best way to implement paging?

This tutorial shows a great way to do pagination. Efficient Pagination Using MySQL

In short, avoid to use OFFSET or large LIMIT

Finding duplicate integers in an array and display how many times they occurred

public static void Main(string[] args)

{

Int[] array = {10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12};

List<int> doneNumbers = new List<int>();


for (int i = 0; i < array.Length - 1; i++)

{

    if(!doneNumbers.Contains(array[i]))

    {

        int currentNumber = array[i];

        int count = 0;

        for (int j = i; j < array.Length; j++)

        {

            if(currentNumber == array[j])

            {

                count++;

            }

        }

        Console.WriteLine("\t\n " + currentNumber +" "+ " occurs " + " "+count + " "+" times");

        doneNumbers.Add(currentNumber);

        Console.ReadKey();
      }

   }

}

}

}

RS256 vs HS256: What's the difference?

There is a difference in performance.

Simply put HS256 is about 1 order of magnitude faster than RS256 for verification but about 2 orders of magnitude faster than RS256 for issuing (signing).

 640,251  91,464.3 ops/s
  86,123  12,303.3 ops/s (RS256 verify)
   7,046   1,006.5 ops/s (RS256 sign)

Don't get hung up on the actual numbers, just think of them with respect of each other.

[Program.cs]

class Program
{
    static void Main(string[] args)
    {
        foreach (var duration in new[] { 1, 3, 5, 7 })
        {
            var t = TimeSpan.FromSeconds(duration);

            byte[] publicKey, privateKey;

            using (var rsa = new RSACryptoServiceProvider())
            {
                publicKey = rsa.ExportCspBlob(false);
                privateKey = rsa.ExportCspBlob(true);
            }

            byte[] key = new byte[64];

            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(key);
            }

            var s1 = new Stopwatch();
            var n1 = 0;

            using (var hs256 = new HMACSHA256(key))
            {
                while (s1.Elapsed < t)
                {
                    s1.Start();
                    var hash = hs256.ComputeHash(privateKey);
                    s1.Stop();
                    n1++;
                }
            }

            byte[] sign;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(privateKey);

                sign = rsa.SignData(privateKey, "SHA256");
            }

            var s2 = new Stopwatch();
            var n2 = 0;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(publicKey);

                while (s2.Elapsed < t)
                {
                    s2.Start();
                    var success = rsa.VerifyData(privateKey, "SHA256", sign);
                    s2.Stop();
                    n2++;
                }
            }

            var s3 = new Stopwatch();
            var n3 = 0;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(privateKey);

                while (s3.Elapsed < t)
                {
                    s3.Start();
                    rsa.SignData(privateKey, "SHA256");
                    s3.Stop();
                    n3++;
                }
            }

            Console.WriteLine($"{s1.Elapsed.TotalSeconds:0} {n1,7:N0} {n1 / s1.Elapsed.TotalSeconds,9:N1} ops/s");
            Console.WriteLine($"{s2.Elapsed.TotalSeconds:0} {n2,7:N0} {n2 / s2.Elapsed.TotalSeconds,9:N1} ops/s");
            Console.WriteLine($"{s3.Elapsed.TotalSeconds:0} {n3,7:N0} {n3 / s3.Elapsed.TotalSeconds,9:N1} ops/s");

            Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n2 / s2.Elapsed.TotalSeconds),9:N1}x slower (verify)");
            Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n3 / s3.Elapsed.TotalSeconds),9:N1}x slower (issue)");

            // RS256 is about 7.5x slower, but it can still do over 10K ops per sec.
        }
    }
}

When do you use POST and when do you use GET?

Gorgapor, mod_rewrite still often utilizes GET. It just allows to translate a friendlier URL into a URL with a GET query string.

grep a tab in UNIX

A good choice is to use 'sed as grep' (as explained in this classical sed tutorial).

sed -n 's/pattern/&/p' file

Examples (works in bash, sh, ksh, csh,..):

[~]$ cat testfile
12 3
1 4 abc
xa      c
        a       c\2
1 23

[~]$ sed -n 's/\t/&/p' testfile 
xa      c
        a       c\2

[~]$ sed -n 's/\ta\t/&/p' testfile
        a       c\2

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

UPDATE: Another writeup here: How to add publisher in Installshield 2018 (might be better).


I am not too well informed about this issue, but please see if this answer to another question tells you anything useful (and let us know so I can evolve a better answer here): How to pass the Windows Defender SmartScreen Protection? That question relates to BitRock - a non-MSI installer technology, but the overall issue seems to be the same.

Extract from one of the links pointed to in my answer above: "...a certificate just isn't enough anymore to gain trust... SmartScreen is reputation based, not unlike the way StackOverflow works... SmartScreen trusts installers that don't cause problems. Windows machines send telemetry back to Redmond about installed programs and how much trouble they cause. If you get enough thumbs-up then SmartScreen stops blocking your installer automatically. This takes time and lots of installs to get sufficient thumbs. There is no way to find out how far along you got."

Honestly this is all news to me at this point, so do get back to us with any information you dig up yourself.


The actual dialog text you have marked above definitely relates to the Zone.Identifier alternate data stream with a value of 3 that is added to any file that is downloaded from the Internet (see linked answer above for more details).


I was not able to mark this question as a duplicate of the previous one, since it doesn't have an accepted answer. Let's leave both question open for now? (one question is for MSI, one is for non-MSI).

Getting or changing CSS class property with Javascript using DOM style

Nice. Thank you. Worked For Me.

Not sure why you loaded jQuery though. It's not used. Some of us still use dial up modems and satellite with bandwidth limitations. Less is more betterer.

<script>
        function showAnswers(){
          var cols = document.getElementsByClassName('Answer');
          for(i=0; i<cols.length; i++) {
            cols[i].style.backgroundColor = 'lime';
            cols[i].style.width = '50%';
            cols[i].style.borderRadius = '6px';         
            cols[i].style.padding = '10px';
            cols[i].style.border = '1px green solid';
            }
        }
        function hideAnswers(){
          var cols = document.getElementsByClassName('Answer');
          for(i=0; i<cols.length; i++) {
            cols[i].style.backgroundColor = 'transparent';
            cols[i].style.width = 'inheret';
            cols[i].style.borderRadius = '0';
            cols[i].style.padding = '0';
            cols[i].style.border = 'none';          
          }
        }
    </script>

How to free memory from char array in C

char arr[3] = "bo";

The arr takes the memory into the stack segment. which will be automatically free, if arr goes out of scope.

What is the difference between Scala's case class and class?

Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments.

This functional concept allows us to

  • use a compact initialization syntax (Node(1, Leaf(2), None)))
  • decompose them using pattern matching
  • have equality comparisons implicitly defined

In combination with inheritance, case classes are used to mimic algebraic datatypes.

If an object performs stateful computations on the inside or exhibits other kinds of complex behaviour, it should be an ordinary class.

Bootstrap 3 truncate long text inside rows of a table in a responsive way

This is what I achieved, but had to set width, and it cannot be percentual.

_x000D_
_x000D_
.trunc{_x000D_
  width:250px; _x000D_
  white-space: nowrap; _x000D_
  overflow: hidden; _x000D_
  text-overflow: ellipsis;_x000D_
}_x000D_
table tr td {_x000D_
padding: 5px_x000D_
}_x000D_
table tr td {_x000D_
background: salmon_x000D_
}_x000D_
table tr td:first-child {_x000D_
background: lightsalmon_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<table>_x000D_
      _x000D_
      <tr>_x000D_
        <td>Quisque dignissim ante in tincidunt gravida. Maecenas lectus turpis</td>_x000D_
      <td>_x000D_
         <div class="trunc">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
         </div>_x000D_
    </td>_x000D_
        </tr>_x000D_
      </table>
_x000D_
_x000D_
_x000D_

or this: http://collaboradev.com/2015/03/28/responsive-css-truncate-and-ellipsis/

Is it safe to delete a NULL pointer?

To complement ruslik's answer, in C++14 you can use this construction:

delete std::exchange(heapObject, nullptr);

Example use of "continue" statement in Python?

import random  

for i in range(20):  
    x = random.randint(-5,5)  
    if x == 0: continue  
    print 1/x  

continue is an extremely important control statement. The above code indicates a typical application, where the result of a division by zero can be avoided. I use it often when I need to store the output from programs, but dont want to store the output if the program has crashed. Note, to test the above example, replace the last statement with print 1/float(x), or you'll get zeros whenever there's a fraction, since randint returns an integer. I omitted it for clarity.

How to find Port number of IP address?

 domain = self.env['ir.config_parameter'].get_param('web.base.url')

I got the hostname and port number using this.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Adam Luter gave me the idea for this, but it actually turned out to be really simple:

img {
  width:  75px;
  height: auto;
}

IE6 now scales the image fine and this seems to be what all the other browsers use by default.

Thanks for both the answers though!

Python os.path.join() on a list

This can be also thought of as a simple map reduce operation if you would like to think of it from a functional programming perspective.

import os
folders = [("home",".vim"),("home","zathura")]
[reduce(lambda x,y: os.path.join(x,y), each, "") for each in folders]

reduce is builtin in Python 2.x. In Python 3.x it has been moved to itertools However the accepted the answer is better.

This has been answered below but answering if you have a list of items that needs to be joined.

Laravel Carbon subtract days from current date

Use subDays() method:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();

Convert int to char in java

you may want it to be printed as '1' or as 'a'.

In case you want '1' as input then :

int a = 1;
char b = (char)(a + '0');
System.out.println(b);

In case you want 'a' as input then :

int a = 1;
char b = (char)(a-1 + 'a');
System.out.println(b);

java turns the ascii value to char :)

Specifying content of an iframe instead of the src attribute to a page

You can .write() the content into the iframe document. Example:

<iframe id="FileFrame" src="about:blank"></iframe>

<script type="text/javascript">
   var doc = document.getElementById('FileFrame').contentWindow.document;
   doc.open();
   doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
   doc.close();
</script>

getting "No column was specified for column 2 of 'd'" in sql server cte?

Msg 8155, Level 16, State 2, Line 1 No column was specified for column 1 of 'd'. Msg 8155, Level 16, State 2, Line 1 No column was specified for column 2 of 'd'. ANSWER:

ROUND(AVG(CAST(column_name AS FLOAT)), 2) as column_name

How do I get the project basepath in CodeIgniter

Codeigniter has a function that retrieves your base path which is:

FCPATH and BASEPATH i recommand use FCPATH.

for your base url use:

<?=base_url()?>

if your php short tag is off

<?php echo base_url(); ?>

for example: if you want to link you css files which is in your base path

<script src='<?=base_url()?>js/jquery.js' type='text/javascript' />

How to hide Bootstrap modal with javascript?

The Best form to hide and show a modal with bootstrap it's

// SHOW
$('#ModalForm').modal('show');
// HIDE
$('#ModalForm').modal('hide');

Spring Boot not serving static content

FYI: I also noticed I can mess up a perfectly working spring boot app and prevent it from serving contents from the static folder, if I add a bad rest controller like so

 @RestController
public class BadController {
    @RequestMapping(method= RequestMethod.POST)
    public String someMethod(@RequestParam(value="date", required=false)String dateString, Model model){
        return "foo";
    }
}

In this example, after adding the bad controller to the project, when the browser asks for a file available in static folder, the error response is '405 Method Not Allowed'.

Notice paths are not mapped in the bad controller example.

Resync git repo with new .gitignore file

I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch, then remove them manually, but this will not work well if there are a lot.

Here is a solution that utilizes bash arrays to capture all files.

# Build bash array of the file names
while read -r file; do 
    rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)

git rm –-cached "${rmlist[@]}"

git commit -m 'ignore update'

How can I open the interactive matplotlib window in IPython notebook?

You can use

%matplotlib qt

If you got the error ImportError: Failed to import any qt binding then install PyQt5 as: pip install PyQt5 and it works for me.

How to get disk capacity and free space of remote computer

Just one command simple sweet and clean but this only works for local disks

Get-PSDrive

enter image description here

You could still use this command on a remote server by doing a Enter-PSSession -Computername ServerName and then run the Get-PSDrive it will pull the data as if you ran it from the server.

Html.RenderPartial() syntax with Razor

  • RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by { }.

  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

How can I get the nth character of a string?

char* str = "HELLO";
char c = str[1];

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.

OpenCV NoneType object has no attribute shape

try to handle the error, its an attribute error given by OpenCV

try:
    img.shape
    print("checked for shape".format(img.shape))
except AttributeError:
    print("shape not found")
    #code to move to next frame

How to initialize static variables

That's too complex to set in the definition. You can set the definition to null though, and then in the constructor, check it, and if it has not been changed - set it:

private static $dates = null;
public function __construct()
{
    if (is_null(self::$dates)) {  // OR if (!is_array(self::$date))
         self::$dates = array( /* .... */);
    }
}

How to split page into 4 equal parts?

Some good answers here but just adding an approach that won't be affected by borders and padding:

<style type="text/css">
html, body{width: 100%; height: 100%; padding: 0; margin: 0}
div{position: absolute; padding: 1em; border: 1px solid #000}
#nw{background: #f09; top: 0; left: 0; right: 50%; bottom: 50%}
#ne{background: #f90; top: 0; left: 50%; right: 0; bottom: 50%}
#sw{background: #009; top: 50%; left: 0; right: 50%; bottom: 0}
#se{background: #090; top: 50%; left: 50%; right: 0; bottom: 0}
</style>

<div id="nw">test</div>
<div id="ne">test</div>
<div id="sw">test</div>
<div id="se">test</div>

How to pretty print XML from Java?

Try this:

 try
                    {
                        TransformerFactory transFactory = TransformerFactory.newInstance();
                        Transformer transformer = null;
                        transformer = transFactory.newTransformer();
                        StringWriter buffer = new StringWriter();
                        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                        transformer.transform(new DOMSource(element),
                                  new StreamResult(buffer)); 
                        String str = buffer.toString();
                        System.out.println("XML INSIDE IS #########################################"+str);
                        return element;
                    }
                    catch (TransformerConfigurationException e)
                    {
                        e.printStackTrace();
                    }
                    catch (TransformerException e)
                    {
                        e.printStackTrace();
                    }

get launchable activity name of package from adb

You can also use ddms for logcat logs where just giving search of the app name you will all info but you have to select Info instead of verbose or other options. check this below image.

enter image description here

Python Pandas replicate rows in dataframe

df = df_try
for i in range(4):
   df = df.append(df_try)

# Here, we have df_try times 5

df = df.append(df)

# Here, we have df_try times 10

Subversion ignoring "--password" and "--username" options

Look to your local svn repo and look into directory .svn . there is file: entries look into them and you'll see lines begins with: svn+ssh://

this is your first configuration maked by svn checkout 'repo_source' or svn co 'repo_source'

if you want to change this, te best way is completly refresh this repository. update/commit what you should for save work. then remove completly directory and last step is create this by svn co/checkout 'URI-for-main-repo' [optionally local directory for store]

you should select connection method to repo file:// svn+ssh:// http:// https:// or other described in documentation.

after that you use svn update/commit as usual.

this topic looks like out of topic. better you go to superuser pages.

jquery change button color onclick

I would just create a separate CSS class:

.ButtonClicked {
    background-color:red;
}

And then add the class on click:

$('#ButtonId').on('click',function(){
    !$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
});

This should do what you're looking for, showing by this jsFiddle. If you're curious about the logic with the ? and such, its called ternary (or conditional) operators, and its just a concise way to do the simple if logic to check if the class has already been added.

You can also create the ability to have an "on/off" switch feel by toggling the class:

$('#ButtonId').on('click',function(){
    $(this).toggleClass('ButtonClicked');
});

Shown by this jsFiddle. Just food for thought.

Lowercase and Uppercase with jQuery

If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform property:

.myclass {
    text-transform: lowercase;
}

See https://developer.mozilla.org/en/CSS/text-transform for more info.

However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.

Lazy Loading vs Eager Loading

Consider the below situation

public class Person{
    public String Name{get; set;}
    public String Email {get; set;}
    public virtual Employer employer {get; set;}
}

public List<EF.Person> GetPerson(){
    using(EF.DbEntities db = new EF.DbEntities()){
       return db.Person.ToList();
    }
}

Now after this method is called, you cannot lazy load the Employer entity anymore. Why? because the db object is disposed. So you have to do Person.Include(x=> x.employer) to force that to be loaded.

How to use jQuery to show/hide divs based on radio button selection?

Just hide them before showing them:

$(document).ready(function(){ 
    $("input[name$='group2']").click(function() {
        var test = $(this).val();
        $("div.desc").hide();
        $("#"+test).show();
    }); 
});

How to select a radio button by default?

Add this attribute:

checked="checked"

Fastest way to flatten / un-flatten nested JSON objects

ES6 version:

const flatten = (obj, path = '') => {        
    if (!(obj instanceof Object)) return {[path.replace(/\.$/g, '')]:obj};

    return Object.keys(obj).reduce((output, key) => {
        return obj instanceof Array ? 
             {...output, ...flatten(obj[key], path +  '[' + key + '].')}:
             {...output, ...flatten(obj[key], path + key + '.')};
    }, {});
}

Example:

console.log(flatten({a:[{b:["c","d"]}]}));
console.log(flatten([1,[2,[3,4],5],6]));

How to get a MemoryStream from a Stream in .NET?

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

how do I insert a column at a specific column index in pandas?

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

Calling a Fragment method from a parent Activity

I think the best is to check if fragment is added before calling method in fragment. Do something like this to avoid null exception.

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
if(fragment.isAdded()){
  fragment.<specific_function_name>(); 
}

What is .htaccess file?

It's not part of PHP; it's part of Apache.

http://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files provide a way to make configuration changes on a per-directory basis.

Essentially, it allows you to take directives that would normally be put in Apache's main configuration files, and put them in a directory-specific configuration file instead. They're mostly used in cases where you don't have access to the main configuration files (e.g. a shared host).

open link of google play store in mobile version android

You can check if the Google Play Store app is installed and, if this is the case, you can use the "market://" protocol.

final String my_package_name = "........."  // <- HERE YOUR PACKAGE NAME!!
String url = "";

try {
    //Check whether Google Play store is installed or not:
    this.getPackageManager().getPackageInfo("com.android.vending", 0);

    url = "market://details?id=" + my_package_name;
} catch ( final Exception e ) {
    url = "https://play.google.com/store/apps/details?id=" + my_package_name;
}


//Open the app page in Google Play store:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);

Draw an X in CSS

_x000D_
_x000D_
#x{_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    background-color:orange;_x000D_
    position:relative;_x000D_
    border-radius:2px;_x000D_
}_x000D_
#x::after,#x::before{_x000D_
    position:absolute;_x000D_
    top:9px;_x000D_
    left:0px;_x000D_
    content:'';_x000D_
    display:block;_x000D_
    width:20px;_x000D_
    height:2px;_x000D_
    background-color:red;_x000D_
    _x000D_
}_x000D_
#x::after{_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -moz-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    -o-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}_x000D_
#x::before{_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}
_x000D_
<div id=x>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Detecting Windows or Linux?

I think It's a best approach to use Apache lang dependency to decide which OS you're running programmatically through Java

import org.apache.commons.lang3.SystemUtils;

public class App {
    public static void main( String[] args ) {
        if(SystemUtils.IS_OS_WINDOWS_7)
            System.out.println("It's a Windows 7 OS");
        if(SystemUtils.IS_OS_WINDOWS_8)
            System.out.println("It's a Windows 8 OS");
        if(SystemUtils.IS_OS_LINUX)
            System.out.println("It's a Linux OS");
        if(SystemUtils.IS_OS_MAC)
            System.out.println("It's a MAC OS");
    }
}

How can I determine whether a 2D Point is within a Polygon?

C# version of nirg's answer is here: I'll just share the code. It may save someone some time.

public static bool IsPointInPolygon(IList<Point> polygon, Point testPoint) {
            bool result = false;
            int j = polygon.Count() - 1;
            for (int i = 0; i < polygon.Count(); i++) {
                if (polygon[i].Y < testPoint.Y && polygon[j].Y >= testPoint.Y || polygon[j].Y < testPoint.Y && polygon[i].Y >= testPoint.Y) {
                    if (polygon[i].X + (testPoint.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) < testPoint.X) {
                        result = !result;
                    }
                }
                j = i;
            }
            return result;
        }

Codeigniter - multiple database connections

If you need to connect to more than one database simultaneously you can do so as follows:

$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

Note: Change the words “group_one” and “group_two” to the specific group names you are connecting to (or you can pass the connection values as indicated above).

By setting the second parameter to TRUE (boolean) the function will return the database object.

Visit https://www.codeigniter.com/userguide3/database/connecting.html for further information.

Capturing browser logs with Selenium WebDriver using Java

As a non-java selenium user, here is the python equivalent to Margus's answer:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities    

class ChromeConsoleLogging(object):

    def __init__(self, ):
        self.driver = None

    def setUp(self, ):
        desired = DesiredCapabilities.CHROME
        desired ['loggingPrefs'] = { 'browser':'ALL' }
        self.driver = webdriver.Chrome(desired_capabilities=desired)

    def analyzeLog(self, ):
        data = self.driver.get_log('browser')
        print(data)

    def testMethod(self, ):
        self.setUp()
        self.driver.get("http://mypage.com")
        self.analyzeLog()

Reference

Edit: Keeping Python answer in this thread because it is very similar to the Java answer and this post is returned on a Google search for the similar Python question

Python Key Error=0 - Can't find Dict error in code

It only comes when your list or dictionary not available in the local function.

What is the best way to create a string array in python?

Are you trying to do something like this?

>>> strs = [s.strip('\(\)') for s in ['some\\', '(list)', 'of', 'strings']]
>>> strs 
['some', 'list', 'of', 'strings']

force browsers to get latest js and css files in asp.net application

Based on Adam Tegan's answer, modified for use in a web forms application.

In the .cs class code:

public static class FileUtility
{
    public static string SetJsVersion(HttpContext context, string filename) {
        string version = GetJsFileVersion(context, filename);
        return filename + version;
    }

    private static string GetJsFileVersion(HttpContext context, string filename)
    {
        if (context.Cache[filename] == null)
        {
            string filePhysicalPath = context.Server.MapPath(filename);

            string version = "?v=" + GetFileLastModifiedDateTime(context, filePhysicalPath, "yyyyMMddhhmmss");

            return version;
        }
        else
        {
            return string.Empty;
        }
    }

    public static string GetFileLastModifiedDateTime(HttpContext context, string filePath, string dateFormat)
    {
        return new System.IO.FileInfo(filePath).LastWriteTime.ToString(dateFormat);
    }
}

In the aspx markup:

<script type="text/javascript" src='<%= FileUtility.SetJsVersion(Context,"/js/exampleJavaScriptFile.js") %>'></script>

And in the rendered HTML, it appears as

<script type="text/javascript" src='/js/exampleJavaScriptFile.js?v=20150402021544'></script>

Is it possible to use a div as content for Twitter's Popover

All of these answers miss a very important aspect!

By using .html or innerHtml or outerHtml you are not actually using the referenced element. You are using a copy of the element's html. This has some serious draw backs.

  1. You can't use any ids because the ids will be duplicated.
  2. If you load the contents every time that the popover is shown you will lose all of the user's input.

What you want to do is load the object itself into the popover.

https://jsfiddle.net/shrewmouse/ex6tuzm2/4/

HTML:

<h1> Test </h1>

<div><button id="target">click me</button></div>

<!-- This will be the contents of our popover -->
<div class='_content' id='blah'>
<h1>Extra Stuff</h1>
<input type='number' placeholder='number'/>
</div>

JQuery:

$(document).ready(function() {

    // We don't want to see the popover contents until the user clicks the target.
    // If you don't hide 'blah' first it will be visible outside of the popover.
    //
    $('#blah').hide();

    // Initialize our popover
    //
    $('#target').popover({
        content: $('#blah'), // set the content to be the 'blah' div
        placement: 'bottom',
        html: true
    });
    // The popover contents will not be set until the popover is shown.  Since we don't 
    // want to see the popover when the page loads, we will show it then hide it.
    //
    $('#target').popover('show');
    $('#target').popover('hide');

    // Now that the popover's content is the 'blah' dive we can make it visisble again.
    //
    $('#blah').show();


});

ERROR 403 in loading resources like CSS and JS in my index.php

You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.

Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.

PHPExcel auto size column width

If you need to do that on multiple sheets, and multiple columns in each sheet, here is how you can iterate through all of them:

// Auto size columns for each worksheet
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {

    $objPHPExcel->setActiveSheetIndex($objPHPExcel->getIndex($worksheet));

    $sheet = $objPHPExcel->getActiveSheet();
    $cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(true);
    /** @var PHPExcel_Cell $cell */
    foreach ($cellIterator as $cell) {
        $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
    }
}

Android Failed to install HelloWorld.apk on device (null) Error

@Bolton 's answer worked for me. Some details...

I got my phone a few weeks ago. I tried the HelloAndroid sample app right away (after installing req'd software, etc.). The app worked in the emulator AND on the phone--right away!

Shortly after that, I rooted my phone but did not flash any roms or kernels. I was only experimenting on the emulator until yesterday (writing a simple notepad app). When I tried debugging the app on the phone, here's what I observed:

  1. Eclipse console reported the "...failed to install on device...(null)" message. BUT

  2. The HelloAndroid app DID get pushed to the phone! (It appeared in the apps drawer AND I was able to launch it.)

  3. It simply would not launch on the phone from the Eclipse run.

I searched around here and elsewhere last night (including this thread) with no luck. Finally, I rebooted my phone--which I never tried (doh!) 'cause I didn't think it would make a difference--and the app launched from an Eclipse start!

Still don't know the cause, but I'll come back here if I figure it out.

destination path already exists and is not an empty directory

I got same issue while using cygwin to install nvm

In fact, the target directory where empty but the git binary used was the one from windows (and not git from cygwin git package).

After installing cygwin git package, the git clone from nvm install was ok!

How can I catch a ctrl-c event?

Yeah, this is a platform dependent question.

If you are writing a console program on POSIX, use the signal API (#include <signal.h>).

In a WIN32 GUI application you should handle the WM_KEYDOWN message.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

By Definition we can drag out the differences of two:

Factory: An interface is used for creating an object, but subclass decides which class to instantiate. The creation of object is done when it is required.

Abstract Factory: Abstract Factory pattern acts as a super-factory which creates other factories. In Abstract Factory pattern an interface is responsible for creating a set of related objects, or dependent objects without specifying their concrete classes.

So, in the definitions above we can emphasize on a particular difference. that is, Factory pattern is responsible for creating objects and Abstract Factory is responsible for creating a set of related objects; obviously both through an interface.

Factory pattern:

public interface IFactory{
  void VehicleType(string n);
 }

 public class Scooter : IFactory{
  public void VehicleType(string n){
   Console.WriteLine("Vehicle type: " + n);
  }
 }

 public class Bike : IFactory{
  public void VehicleType(string n) {
  Console.WriteLine("Vehicle type: " + n);
  }
 }

 public interface IVehicleFactory{
  IFactory GetVehicleType(string Vehicle);
 }

 public class ConcreteVehicleFactory : IVehicleFactory{
 public IFactory GetVehicleType(string Vehicle){
   switch (Vehicle){
    case "Scooter":
     return new Scooter();
    case "Bike":
     return new Bike();
    default:
    return new Scooter();
  }
 }

 class Program{
  static void Main(string[] args){
   IVehicleFactory factory = new ConcreteVehicleFactory();
   IFactory scooter = factory.GetVehicleType("Scooter");
   scooter.VehicleType("Scooter");

   IFactory bike = factory.GetVehicleType("Bike");
   bike.VehicleType("Bike");

   Console.ReadKey();
 }
}

Abstract Factory Pattern:

interface IVehicleFactory{
 IBike GetBike();
 IScooter GetScooter();
}

class HondaFactory : IVehicleFactory{
     public IBike GetBike(){
            return new FZS();
     }
     public IScooter GetScooter(){
            return new FZscooter();
     }
 }
class HeroFactory: IVehicleFactory{
      public IBike GetBike(){
            return new Pulsur();
     }
      public IScooter GetScooter(){
            return new PulsurScooter();
     }
}

interface IBike
    {
        string Name();
    }
interface IScooter
    {
        string Name();
    }

class FZS:IBike{
   public string Name(){
     return "FZS";
   }
}
class Pulsur:IBike{
   public string Name(){
     return "Pulsur";
   }
}

class FZscooter:IScooter {
  public string Name(){
     return "FZscooter";
   }
}

class PulsurScooter:IScooter{
  public string Name(){
     return "PulsurScooter";
   }
}

enum MANUFACTURERS
{
    HONDA,
    HERO
}

class VehicleTypeCheck{
        IBike bike;
        IScooter scooter;
        IVehicleFactory factory;
        MANUFACTURERS manu;

        public VehicleTypeCheck(MANUFACTURERS m){
            manu = m;
        }

        public void CheckProducts()
        {
            switch (manu){
                case MANUFACTURERS.HONDA:
                    factory = new HondaFactory();
                    break;
                case MANUFACTURERS.HERO:
                    factory = new HeroFactory();
                    break;
            }

      Console.WriteLine("Bike: " + factory.GetBike().Name() + "\nScooter: " +      factory.GetScooter().Name());
        }
  }

class Program
    {
        static void Main(string[] args)
        {
            VehicleTypeCheck chk = new VehicleTypeCheck(MANUFACTURERS.HONDA);
            chk.CheckProducts();

            chk= new VehicleTypeCheck(MANUFACTURERS.HERO);
            chk.CheckProducts();

            Console.Read();
        }
    }

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

You don't need to reinstall MySQL server I was facing the same issue but I have resolved the issue by running these commands.

  1. ps -A|grep mysql
  2. sudo pkill mysql
  3. ps -A|grep mysqld
  4. sudo pkill mysqld
  5. sudo service mysql restart
  6. mysql -u root -p

What is the difference between bindParam and bindValue?

From Prepared statements and stored procedures

Use bindParam to insert multiple rows with one time binding:

<?php

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

From the documentation (MySQL 8) :

      Type | Maximum length
-----------+-------------------------------------
  TINYTEXT |           255 (2 8−1) bytes
      TEXT |        65,535 (216−1) bytes = 64 KiB
MEDIUMTEXT |    16,777,215 (224−1) bytes = 16 MiB
  LONGTEXT | 4,294,967,295 (232−1) bytes =  4 GiB

Note that the number of characters that can be stored in your column will depend on the character encoding.

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

AngularJS - pass function to directive

How about passing the controller function with bidirectional binding? Then you can use it in the directive exactly the same way as in a regular template (I stripped irrelevant parts for simplicity):

<div ng-controller="testCtrl">

   <!-- pass the function with no arguments -->
   <test color1="color1" update-fn="updateFn"></test>
</div>

<script>
   angular.module('dr', [])
   .controller("testCtrl", function($scope) {
      $scope.updateFn = function(msg) {
         alert(msg);
      }
   })
   .directive('test', function() {
      return {
         scope: {
            updateFn: '=' // '=' bidirectional binding
         },
         template: "<button ng-click='updateFn(1337)'>Click</button>"
      }
   });
</script>

I landed at this question, because I tried the method above befire, but somehow it didn't work. Now it works perfectly.

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

How to find cube root using Python?

def cube(x):
    if 0<=x: return x**(1./3.)
    return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))

Here is the full answer for both negative and positive numbers.

>>> 
2.0
-2.0
>>> 

Or here is a one-liner;

root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)

How to resolve "Waiting for Debugger" message?

If your development environment is Windows make sure the USB drivers are correctly installed.

One way to ensure that the USB drivers are installed correctly is to get the PDANet Windows installer and let it install the USB drivers.

You can find the PDANet page here.

Simplest JQuery validation rules example

rules: {
    cname: {
        required: true,
        minlength: 2
    }
},
messages: {
    cname: {
        required: "<li>Please enter a name.</li>",
        minlength: "<li>Your name is not long enough.</li>"
    }
}

Get the date (a day before current time) in Bash

if you have GNU date and i understood you correctly

$ date +%Y:%m:%d -d "yesterday"
2009:11:09

or

$ date +%Y:%m:%d -d "1 day ago"
2009:11:09

What is a regular expression which will match a valid domain name without a subdomain?

As already pointed out it's not obvious to tell subdomains in the practical sense (e.g. .co.uk domains). We use this regex to validate domains which occur in the wild. It covers all practical use cases I know of. New ones are welcome. According to our guidelines it avoids non-capturing groups and greedy matching.

^(?!.*?_.*?)(?!(?:[\d\w]+?\.)?\-[\w\d\.\-]*?)(?![\w\d]+?\-\.(?:[\d\w\.\-]+?))(?=[\w\d])(?=[\w\d\.\-]*?\.+[\w\d\.\-]*?)(?![\w\d\.\-]{254})(?!(?:\.?[\w\d\-\.]*?[\w\d\-]{64,}\.)+?)[\w\d\.\-]+?(?<![\w\d\-\.]*?\.[\d]+?)(?<=[\w\d\-]{2,})(?<![\w\d\-]{25})$

Proof, explanation and examples: https://regex101.com/r/FLA9Bv/9 (Note: currently only works in Chrome because the regex uses lookbehinds which are only supported in ECMA2018)

There're two approaches to choose from when validating domains.

By-the-books FQDN matching (theoretical definition, rarely encountered in practice):

Practical / conservative FQDN matching (practical definition, expected and supported in practice):

  • by-the-books matching with the following exceptions/additions
  • valid characters: [a-zA-Z0-9.-]
  • labels cannot start or end with hyphens (as per RFC-952 and RFC-1123/2.1)
  • TLD min length is 2 character, max length is 24 character as per currently existing records
  • don't match trailing dot

Pass path with spaces as parameter to bat file

If you have a path with spaces you must surround it with quotation marks (").

Not sure if that's exactly what you're asking though?

Oracle "Partition By" Keyword

The concept is very well explained by the accepted answer, but I find that the more example one sees, the better it sinks in. Here's an incremental example:

1) Boss says "get me number of items we have in stock grouped by brand"

You say: "no problem"

SELECT 
      BRAND
      ,COUNT(ITEM_ID) 
FROM 
      ITEMS
GROUP BY 
      BRAND;

Result:

+--------------+---------------+
|  Brand       |   Count       | 
+--------------+---------------+
| H&M          |     50        |
+--------------+---------------+
| Hugo Boss    |     100       |
+--------------+---------------+
| No brand     |     22        |
+--------------+---------------+

2) The boss says "Now get me a list of all items, with their brand AND number of items that the respective brand has"

You may try:

 SELECT 
      ITEM_NR
      ,BRAND
      ,COUNT(ITEM_ID) 
 FROM 
      ITEMS
 GROUP BY 
      BRAND;

But you get:

ORA-00979: not a GROUP BY expression 

This is where the OVER (PARTITION BY BRAND) comes in:

 SELECT 
      ITEM_NR
      ,BRAND
      ,COUNT(ITEM_ID) OVER (PARTITION BY BRAND) 
 FROM 
      ITEMS;

Whic means:

  • COUNT(ITEM_ID) - get the number of items
  • OVER - Over the set of rows
  • (PARTITION BY BRAND) - that have the same brand

And the result is:

+--------------+---------------+----------+
|  Items       |  Brand        | Count()  |
+--------------+---------------+----------+
|  Item 1      |  Hugo Boss    |   100    | 
+--------------+---------------+----------+
|  Item 2      |  Hugo Boss    |   100    | 
+--------------+---------------+----------+
|  Item 3      |  No brand     |   22     | 
+--------------+---------------+----------+
|  Item 4      |  No brand     |   22     | 
+--------------+---------------+----------+
|  Item 5      |  H&M          |   50     | 
+--------------+---------------+----------+

etc...

How to kill all processes with a given partial name?

you can use the following command to list the process

ps aux | grep -c myProcessName 

if you need to check the count of that process then run

ps aux | grep -c myProcessName |grep -v grep 

after which you can kill the process using

kill -9 $(ps aux | grep -e myProcessName | awk '{ print $2 }') 

PHP function ssh2_connect is not working

I am running CentOS 5.6 as my development environment and the following worked for me.

su -
pecl install ssh2
echo "extension=ssh2.so" > /etc/php.d/ssh2.ini

/etc/init.d/httpd restart

Collection that allows only unique items in .NET?

HashSet<T> is what you're looking for. From MSDN (emphasis added):

The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

Note that the HashSet<T>.Add(T item) method returns a bool -- true if the item was added to the collection; false if the item was already present.

Disable Proximity Sensor during call

I have been researching this for a while, tested and wrote apps.

If you have no option in Settings ? Phone ? Use proximity sensor, then the only choice, seem to be to disable or modify its settings in rooted devices.

Also consider, that if you plug the headset, the screen will remain on :D

How can I check the size of a collection within a Django template?

See https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if : just use, to reproduce their example:

{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% else %}
    No athletes.
{% endif %}

Attribute Error: 'list' object has no attribute 'split'

The problem is that readlines is a list of strings, each of which is a line of filename. Perhaps you meant:

for line in readlines:
    Type = line.split(",")
    x = Type[1]
    y = Type[2]
    print(x,y)

Get input value from TextField in iOS alert in Swift

Swift 3/4

You can use the below extension for your convenience.

Usage inside a ViewController:

showInputDialog(title: "Add number",
                subtitle: "Please enter the new number below.",
                actionTitle: "Add",
                cancelTitle: "Cancel",
                inputPlaceholder: "New number",
                inputKeyboardType: .numberPad)
{ (input:String?) in
    print("The new number is \(input ?? "")")
}

The extension code:

extension UIViewController {
    func showInputDialog(title:String? = nil,
                         subtitle:String? = nil,
                         actionTitle:String? = "Add",
                         cancelTitle:String? = "Cancel",
                         inputPlaceholder:String? = nil,
                         inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
                         cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
                         actionHandler: ((_ text: String?) -> Void)? = nil) {

        let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            textField.placeholder = inputPlaceholder
            textField.keyboardType = inputKeyboardType
        }
        alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
            guard let textField =  alert.textFields?.first else {
                actionHandler?(nil)
                return
            }
            actionHandler?(textField.text)
        }))
        alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))

        self.present(alert, animated: true, completion: nil)
    }
}

Undefined reference to 'vtable for xxx'

You may take a look at this answer to an identical question (as I understand): https://stackoverflow.com/a/1478553 The link posted there explains the problem.

For quick solving your problem you should try to code something like this:

ImplementingClass::virtualFunctionToImplement(){...} It helped me a lot.

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

Following @Anupam's answer on OS X resulted in the following error for me, regardless of permissions I ran it with:

Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: ...

What eventually worked was to download a newer pip package (9.0.3) from PyPI directly from my browser - https://pypi.org/simple/pip/, extract the contents, and then pip install the package locally:

pip install ./pip-9.0.3/

This fixed my [SSL: TLSV1_ALERT_PROTOCOL_VERSION] errors.

What is the difference between typeof and instanceof and when should one be used vs. the other?

According to MDN documentation about typeof, objects instantiated with the "new" keyword are of type 'object':

typeof 'bla' === 'string';

// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';

While documentation about instanceof points that:

const objectString = new String('String created with constructor');
objectString instanceOf String; // returns true
objectString instanceOf Object; // returns true

So if one wants to check e.g. that something is a string no matter how it was created, safest approach would be to use instanceof.

Recommended way to get hostname in Java

hostName == null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
{
    while (interfaces.hasMoreElements()) {
        NetworkInterface nic = interfaces.nextElement();
        Enumeration<InetAddress> addresses = nic.getInetAddresses();
        while (hostName == null && addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            if (!address.isLoopbackAddress()) {
                hostName = address.getHostName();
            }
        }
    }
}

Binding Button click to a method

Some more explanations to the solution Rachel already gave:

"WPF Apps With The Model-View-ViewModel Design Pattern"

by Josh Smith

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

React - Component Full Screen (with height 100%)

try using !important in height. It is probably because of some other style affecting your html body.

{ height : 100% !important; }

also you can give values in VP which will set height to viee port pixel you mention likeheight : 700vp; but this wont be portable.

Why is Visual Studio 2010 not able to find/open PDB files?

I had the same problem. Debugging does not work with the stuff that comes with the OpenCV executable. you have to build your own binarys.
Then enable Microsoft Symbol Servers in Debug->options and settings->debug->symbols

WebSockets protocol vs HTTP

For the TL;DR, here are 2 cents and a simpler version for your questions:

  1. WebSockets provides these benefits over HTTP:

    • Persistent stateful connection for the duration of the connection
    • Low latency: near-real-time communication between server/client due to no overhead of reestablishing connections for each request as HTTP requires.
    • Full duplex: both server and client can send/receive simultaneously
  2. WebSocket and HTTP protocol have been designed to solve different problems, I.E. WebSocket was designed to improve bi-directional communication whereas HTTP was designed to be stateless, distributed using a request/response model. Other than sharing the ports for legacy reasons (firewall/proxy penetration), there isn't much common ground to combine them into one protocol.

Select data from date range between two dates

SELECT *
FROM Product_sales
WHERE (
From_date >= '2013-08-19'
AND To_date <= '2013-08-23'
)
OR (
To_date >= '2013-08-19'
AND From_date <= '2013-08-23'
)

How do I Search/Find and Replace in a standard string?

The easiest way (offering something near what you wrote) is to use Boost.Regex, specifically regex_replace.

std::string has built in find() and replace() methods, but they are more cumbersome to work with as they require dealing with indices and string lengths.

How to use Bootstrap 4 in ASP.NET Core

Looking into this, it seems like the LibMan approach works best for my needs with adding Bootstrap. I like it because it is now built into Visual Studio 2017(15.8 or later) and has its own dialog boxes.

Update 6/11/2020: bootstrap 4.1.3 is now added by default with VS-2019.5 (Thanks to Harald S. Hanssen for noticing.)

The default method VS adds to projects uses Bower but it looks like it is on the way out. In the header of Microsofts bower page they write: Bower is maintained only.Recommend using LibManager

Following a couple links lead to Use LibMan with ASP.NET Core in Visual Studio where it shows how libs can be added using a built-in Dialog:

In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears: [source: Scott Addie 2018]

enter image description here

Then for bootstrap just (1) select the unpkg, (2) type in "bootstrap@.." (3) Install. After this, you would just want to verify all the includes in the _Layout.cshtml or other places are correct. They should be something like href="~/lib/bootstrap/dist/js/bootstrap...")

How to pass password to scp?

  1. Make sure password authentication is enabled on the target server. If it runs Ubuntu, then open /etc/ssh/sshd_config on the server, find lines PasswordAuthentication=no and comment all them out (put # at the start of the line), save the file and run sudo systemctl restart ssh to apply the configuration. If there is no such line then you're done.
  2. Add -o PreferredAuthentications="password" to your scp command, e.g.:
    scp -o PreferredAuthentications="password" /path/to/file user@server:/destination/directory
    

How to open local files in Swagger-UI

Use the spec parameter.

Instructions below.

Create spec.js file containing Swagger JSON

Create a new javascript file in the same directory as index.html (/dist/)

Then insert spec variable declaration:

var spec = 

Then paste in the swagger.json file contents after. It does not have to be on the same line as the = sign.

Example:

var spec =

{
    "swagger": "2.0",
    "info": {
        "title": "I love Tex-Mex API",
        "description": "You can barbecue it, boil it, broil it, bake it, sauté it. Dey's uh, Tex-Mex-kabobs, Tex-Mex creole, Tex-Mex gumbo. Pan fried, deep fried, stir-fried. There's pineapple Tex-Mex, lemon Tex-Mex, coconut Tex-Mex, pepper Tex-Mex, Tex-Mex soup, Tex-Mex stew, Tex-Mex salad, Tex-Mex and potatoes, Tex-Mex burger, Tex-Mex sandwich..",
        "version": "1.0.0"
    },
    ...
    }
}

Modify Swagger UI index.html

This is a two-step like Ciara.

Include spec.js

Modify the /dist/index.html file to include the external spec.js file.

 <script src='spec.js' type="text/javascript"></script>

Example:

  <!-- Some basic translations -->
  <!-- <script src='lang/translator.js' type='text/javascript'></script> -->
  <!-- <script src='lang/ru.js' type='text/javascript'></script> -->
  <!-- <script src='lang/en.js' type='text/javascript'></script> -->

  <!-- Original file pauses -->
  <!-- Insert external modified swagger.json -->
  <script src='spec.js' type="text/javascript"></script>
  <!-- Original file resumes -->

  <script type="text/javascript">

    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "http://petstore.swagger.io/v2/swagger.json";
      }

Add spec parameter

Modify the SwaggerUi instance to include the spec parameter:

  window.swaggerUi = new SwaggerUi({
    url: url,
    spec: spec,
    dom_id: "swagger-ui-container",

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

How do I use a pipe to redirect the output of one command to the input of another?

Try this. Copy this into a batch file - such as send.bat - and then simply run send.bat to send the message from the temperature program to the prismcom program.

temperature.exe > msg.txt
set /p msg= < msg.txt
prismcom.exe usb "%msg%"

Using Selenium Web Driver to retrieve value of a HTML input

element.GetAttribute("value");

Eventhough if you don't see the "value" attribute in html dom, you will get the field value displayed on the GUI.

How to initialize/instantiate a custom UIView class with a XIB file in Swift

As of Swift 2.0, you can add a protocol extension. In my opinion, this is a better approach because the return type is Self rather than UIView, so the caller doesn't need to cast to the view class.

import UIKit

protocol UIViewLoading {}
extension UIView : UIViewLoading {}

extension UIViewLoading where Self : UIView {

  // note that this method returns an instance of type `Self`, rather than UIView
  static func loadFromNib() -> Self {
    let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last!
    let nib = UINib(nibName: nibName, bundle: nil)
    return nib.instantiateWithOwner(self, options: nil).first as! Self
  }

}

Converting xml to string using C#

There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.

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

"relocation R_X86_64_32S against " linking Error

I've got a similar error when installing FCL that needs CCD lib(libccd) like this:

/usr/bin/ld: /usr/local/lib/libccd.a(ccd.o): relocation R_X86_64_32S against `a local symbol' can not be used when making a shared object; recompile with -fPIC

I find that there is two different files named "libccd.a" :

  1. /usr/local/lib/libccd.a
  2. /usr/local/lib/x86_64-linux-gnu/libccd.a

I solved the problem by removing the first file.

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col
Next

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Create a group object and call methods like below example:

grp = df.groupby(['col1',  'col2',  'col3']) 

grp.max() 
grp.mean() 
grp.describe() 

What is the meaning of "Failed building wheel for X" in pip install?

In my case, update the pip versión after create the venv, this update pip from 9.0.1 to 20.3.1

python3 -m venv env/python
source env/python/bin/activate
pip3 install pip --upgrade

But, the message was...

Using legacy 'setup.py install' for django-avatar, since package 'wheel' is not installed.

Then, I install wheel package after update pip

python3 -m venv env/python
source env/python/bin/activate
pip3 install --upgrade pip
pip3 install wheel

And the message was...

Building wheel for django-avatar (setup.py): started
default:   Building wheel for django-avatar (setup.py): finished with status 'done'

"Faceted Project Problem (Java Version Mismatch)" error message

Did you check your Project Properties -> Project Facets panel? (From that post)

A WTP project is composed of multiple units of functionality (known as facets).

The Java facet version needs to always match the java compiler compliance level.
The best way to change java level is to use the Project Facets properties panel as that will update both places at the same time.

WTP

The "Project->Preferences->Project Facets" stores its configuration in this file, "org.eclipse.wst.common.project.facet.core.xml", under the ".settings" directory.

The content might look like this

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <runtime name="WebSphere Application Server v6.1"/>
  <fixed facet="jst.java"/>
  <fixed facet="jst.web"/>
  <installed facet="jst.java" version="5.0"/>
  <installed facet="jst.web" version="2.4"/>
  <installed facet="jsf.ibm" version="7.0"/>
  <installed facet="jsf.base" version="7.0"/>
  <installed facet="web.jstl" version="1.1"/>
</faceted-project>

Check also your Java compliance level:

Java compliance level

int *array = new int[n]; what is this function actually doing?

As of C++11, the memory-safe way to do this (still using a similar construction) is with std::unique_ptr:

std::unique_ptr<int[]> array(new int[n]);

This creates a smart pointer to a memory block large enough for n integers that automatically deletes itself when it goes out of scope. This automatic clean-up is important because it avoids the scenario where your code quits early and never reaches your delete [] array; statement.

Another (probably preferred) option would be to use std::vector if you need an array capable of dynamic resizing. This is good when you need an unknown amount of space, but it has some disadvantages (non-constant time to add/delete an element). You could create an array and add elements to it with something like:

std::vector<int> array;
array.push_back(1);  // adds 1 to end of array
array.push_back(2);  // adds 2 to end of array
// array now contains elements [1, 2]

How do I pass a method as a parameter in Python

Methods are objects like any other. So you can pass them around, store them in lists and dicts, do whatever you like with them. The special thing about them is they are callable objects so you can invoke __call__ on them. __call__ gets called automatically when you invoke the method with or without arguments so you just need to write methodToRun().

SQL Server Restore Error - Access is Denied

Frnds... I had the same issue while restroring database and tried every solution but could nt get resolved. Then i tried to re install SQL 2005 and the problem solved. Actully last time i forgot to check on customize option while instlling SQL.. It comes two times while installing and i checkd it for ones only..

How to save public key from a certificate in .pem format

if it is a RSA key

openssl rsa  -pubout -in my_rsa_key.pem

if you need it in a format for openssh , please see Use RSA private key to generate public key?

Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.

How to set up a Web API controller for multipart/form-data

This is what solved my problem
Add the following line to WebApiConfig.cs

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

How do I add an element to array in reducer of React native redux?

push does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:

import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {

    arr:[]
}

export default function userState(state = initialUserState, action){
     console.log(arr);
     switch (action.type){
        case ADD_ITEM :
          return { 
             ...state,
             arr:[...state.arr, action.newItem]
        }

        default:return state
     }
}

How to do a subquery in LINQ?

This is how I've been doing subqueries in LINQ, I think this should get what you want. You can replace the explicit CompanyRoleId == 2... with another subquery for the different roles you want or join it as well.

from u in Users
join c in (
    from crt in CompanyRolesToUsers
    where CompanyRoleId == 2
    || CompanyRoleId == 3
    || CompanyRoleId == 4) on u.UserId equals c.UserId
where u.lastname.Contains("fra")
select u;

How to convert R Markdown to PDF?

For an option that looks more like what you get when you print from a browser, wkhtmltopdf provides one option.

On Ubuntu

sudo apt-get install wkhtmltopdf

And then the same command as for the pandoc example to get to the HTML:

RMDFILE=example-r-markdown  
Rscript -e "require(knitr); require(markdown); knit('$RMDFILE.rmd', '$RMDFILE.md'); markdownToHTML('$RMDFILE.md', '$RMDFILE.html', options=c('use_xhml'))"

and then

wkhtmltopdf example-r-markdown.html example-r-markdown.pdf

The resulting file looked like this. It did not seem to handle the MathJax (this issue is discussed here), and the page breaks are ugly. However, in some cases, such a style might be preferred over a more LaTeX style presentation.

How to delete the contents of a folder?

I used to solve the problem this way:

import shutil
import os

shutil.rmtree(dirpath)
os.mkdir(dirpath)

Difference between /res and /assets directories

Ted Hopp answered this quite nicely. I have been using res/raw for my opengl texture and shader files. I was thinking about moving them to an assets directory to provide a hierarchical organization.

This thread convinced me not to. First, because I like the use of a unique resource id. Second because it's very simple to use InputStream/openRawResource or BitmapFactory to read in the file. Third because it's very useful to be able to use in a portable library.

What does on_delete do on Django models?

Here is answer for your question that says: why we use on_delete?

When an object referenced by a ForeignKey is deleted, Django by default emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey. This behavior can be overridden by specifying the on_delete argument. For example, if you have a nullable ForeignKey and you want it to be set null when the referenced object is deleted:

user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)

The possible values for on_delete are found in django.db.models:

CASCADE: Cascade deletes; the default.

PROTECT: Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

SET_NULL: Set the ForeignKey null; this is only possible if null is True.

SET_DEFAULT: Set the ForeignKey to its default value; a default for the ForeignKey must be set.

Passing null arguments to C# methods

The OP's question is answered well already, but the title is just broad enough that I think it benefits from the following primer:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace consolePlay
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.test(new DateTime());
            Program.test(null);
            //Program.test(); // <<< Error.  
            // "No overload for method 'test' takes 0 arguments"  
            // So don't mistake nullable to be optional.

            Console.WriteLine("Done.  Return to quit");
            Console.Read();
        }

        static public void test(DateTime? dteIn)
        {
            Console.WriteLine("#" + dteIn.ToString() + "#");
        }
    }
}

output:

#1/1/0001 12:00:00 AM#
##
Done.  Return to quit

Handling JSON Post Request in Go

I was driving myself crazy with this exact problem. My JSON Marshaller and Unmarshaller were not populating my Go struct. Then I found the solution at https://eager.io/blog/go-and-json:

"As with all structs in Go, it’s important to remember that only fields with a capital first letter are visible to external programs like the JSON Marshaller."

After that, my Marshaller and Unmarshaller worked perfectly!

What's the difference between map() and flatMap() methods in Java 8?

flatMap() also takes advantage of partial lazy evaluation of streams. It will read the fist stream and only when required, will go to the next stream. The behaviour is explained in detail here: Is flatMap guaranteed to be lazy?

Authentication plugin 'caching_sha2_password' is not supported

Using MySql 8 I got the same error when connecting my code to the DB, using the pip install mysql-connector-python did solve this error.

How to post object and List using postman

I also had a similar question, sharing the below example if it helps.

My Controller:

@RequestMapping(value = {"/batchDeleteIndex"}, method = RequestMethod.POST)
@ResponseBody
public BaseResponse batchDeleteIndex(@RequestBody List<String> datasetQnames)

Postman: Set the Body type to raw and add header Content-Type: application/json

["aaa","bbb","ccc"]

R solve:system is exactly singular

Using solve with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.

Changing datagridview cell color dynamically

Considere use DataBindingComplete event for update the style. The next code change the style of the cell:

    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
    }

Excel date to Unix timestamp

Here is a mapping for reference, assuming UTC for spreadsheet systems like Microsoft Excel:

                         Unix  Excel Mac    Excel    Human Date  Human Time
Excel Epoch       -2209075200      -1462        0    1900/01/00* 00:00:00 (local)
Excel = 2011 Mac† -2082758400          0     1462    1904/12/31  00:00:00 (local)
Unix Epoch                  0      24107    25569    1970/01/01  00:00:00 UTC
Example Below      1234567890      38395.6  39857.6  2009/02/13  23:31:30 UTC
Signed Int Max     2147483648      51886    50424    2038/01/19  03:14:08 UTC

One Second                  1       0.0000115740…             —  00:00:01
One Hour                 3600       0.0416666666…             -  01:00:00
One Day                 86400          1        1             -  24:00:00

*  “Jan Zero, 1900” is 1899/12/31; see the Bug section below. Excel 2011 for Mac (and older) use the 1904 date system.

 

As I often use awk to process CSV and space-delimited content, I developed a way to convert UNIX epoch to timezone/DST-appropriate Excel date format:

echo 1234567890 |awk '{ 
  # tries GNU date, tries BSD date on failure
  cmd = sprintf("date -d@%d +%%z 2>/dev/null || date -jf %%s %d +%%z", $1, $1)
  cmd |getline tz                                # read in time-specific offset
  hours = substr(tz, 2, 2) + substr(tz, 4) / 60  # hours + minutes (hi, India)
  if (tz ~ /^-/) hours *= -1                     # offset direction (east/west)
  excel = $1/86400 + hours/24 + 25569            # as days, plus offset
  printf "%.9f\n", excel
}'

I used echo for this example, but you can pipe a file where the first column (for the first cell in .csv format, call it as awk -F,) is a UNIX epoch. Alter $1 to represent your desired column/cell number or use a variable instead.

This makes a system call to date. If you will reliably have the GNU version, you can remove the 2>/dev/null || date … +%%z and the second , $1. Given how common GNU is, I wouldn't recommend assuming BSD's version.

The getline reads the time zone offset outputted by date +%z into tz, which is then translated into hours. The format will be like -0700 (PDT) or +0530 (IST), so the first substring extracted is 07 or 05, the second is 00 or 30 (then divided by 60 to be expressed in hours), and the third use of tz sees whether our offset is negative and alters hours if needed.

The formula given in all of the other answers on this page is used to set excel, with the addition of the daylight-savings-aware time zone adjustment as hours/24.

If you're on an older version of Excel for Mac, you'll need to use 24107 in place of 25569 (see the mapping above).

To convert any arbitrary non-epoch time to Excel-friendly times with GNU date:

echo "last thursday" |awk '{ 
  cmd = sprintf("date -d \"%s\" +\"%%s %%z\"", $0)
  cmd |getline
  hours = substr($2, 2, 2) + substr($2, 4) / 60
  if ($2 ~ /^-/) hours *= -1
  excel = $1/86400 + hours/24 + 25569
  printf "%.9f\n", excel
}'

This is basically the same code, but the date -d no longer has an @ to represent unix epoch (given how capable the string parser is, I'm actually surprised the @ is mandatory; what other date format has 9-10 digits?) and it's now asked for two outputs: the epoch and the time zone offset. You could therefore use e.g. @1234567890 as an input.

Bug

Lotus 1-2-3 (the original spreadsheet software) intentionally treated 1900 as a leap year despite the fact that it was not (this reduced the codebase at a time when every byte counted). Microsoft Excel retained this bug for compatibility, skipping day 60 (the fictitious 1900/02/29), retaining Lotus 1-2-3's mapping of day 59 to 1900/02/28. LibreOffice instead assigned day 60 to 1900/02/28 and pushed all previous days back one.

Any date before 1900/03/01 could be as much as a day off:

Day        Excel   LibreOffice
-1            -1    1899/12/29
 0    1900/01/00*   1899/12/30
 1    1900/01/01    1899/12/31
 2    1900/01/02    1900/01/01
 …
59    1900/02/28    1900/02/27
60    1900/02/29(!) 1900/02/28
61    1900/03/01    1900/03/01

Excel doesn't acknowledge negative dates and has a special definition of the Zeroth of January (1899/12/31) for day zero. Internally, Excel does indeed handle negative dates (they're just numbers after all), but it displays them as numbers since it doesn't know how to display them as dates (nor can it convert older dates into negative numbers). Feb 29 1900, a day that never happened, is recognized by Excel but not LibreOffice.

How do I save a String to a text file using Java?

You can use the ArrayList to put all the contents of the TextArea for exemple, and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file. if something does not make sense, I'm sorry is google translator and I who do not speak English.

Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.


private void SaveActionPerformed(java.awt.event.ActionEvent evt) {

    String NameFile = Name.getText();
    ArrayList< String > Text = new ArrayList< String >();

    Text.add(TextArea.getText());

    SaveFile(NameFile, Text);
}

public void SaveFile(String name, ArrayList< String> message) {

    path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";

    File file1 = new File(path);

    try {

        if (!file1.exists()) {

            file1.createNewFile();
        }


        File[] files = file1.listFiles();


        FileWriter fw = new FileWriter(file1, true);

        BufferedWriter bw = new BufferedWriter(fw);

        for (int i = 0; i < message.size(); i++) {

            bw.write(message.get(i));
            bw.newLine();
        }

        bw.close();
        fw.close();

        FileReader fr = new FileReader(file1);

        BufferedReader br = new BufferedReader(fr);

        fw = new FileWriter(file1, true);

        bw = new BufferedWriter(fw);

        while (br.ready()) {

            String line = br.readLine();

            System.out.println(line);

            bw.write(line);
            bw.newLine();

        }
        br.close();
        fr.close();

    } catch (IOException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Error in" + ex);     
    }   
}

Programmatically select a row in JTable

You can do it calling setRowSelectionInterval :

table.setRowSelectionInterval(0, 0);

to select the first row.

change values in array when doing foreach

Array: [1, 2, 3, 4]
Result: ["foo1", "foo2", "foo3", "foo4"]

Array.prototype.map() Keep original array

_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
const modifiedArr = originalArr.map(name => `${name}man`);

console.log( "Original: %s", originalArr );
console.log( "Modified: %s", modifiedArr );
_x000D_
_x000D_
_x000D_

Array.prototype.forEach() Override original array

_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
originalArr.forEach((name, index) => originalArr[index] = `${name}man`);

console.log( "Overridden: %s", originalArr );
_x000D_
_x000D_
_x000D_

Split string in Lua?

I used the above examples to craft my own function. But the missing piece for me was automatically escaping magic characters.

Here is my contribution:

function split(text, delim)
    -- returns an array of fields based on text and delimiter (one character only)
    local result = {}
    local magic = "().%+-*?[]^$"

    if delim == nil then
        delim = "%s"
    elseif string.find(delim, magic, 1, true) then
        -- escape magic
        delim = "%"..delim
    end

    local pattern = "[^"..delim.."]+"
    for w in string.gmatch(text, pattern) do
        table.insert(result, w)
    end
    return result
end

Preferred method to store PHP arrays (json_encode vs serialize)

JSON is better if you want to backup Data and restore it on a different machine or via FTP.

For example with serialize if you store data on a Windows server, download it via FTP and restore it on a Linux one it could not work any more due to the charachter re-encoding, because serialize stores the length of the strings and in the Unicode > UTF-8 transcoding some 1 byte charachter could became 2 bytes long making the algorithm crash.

Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

Laravel 5: Display HTML with Blade

I have been there and it was my fault. And very stupid one.

if you forget .blade extension in the file name, that file doesn't understand blade but runs php code. You should use

/resources/views/filename.blade.php

instead of

/resources/views/filename.php

hope this helps some one

How to change ViewPager's page?

slide to right

viewPager.arrowScroll(View.FOCUS_RIGHT);

slide to left

viewPager.arrowScroll(View.FOCUS_LEFT);

Adding/removing items from a JavaScript object with jQuery

Keep things simple :)

var my_form_obj = {};
my_form_obj.name = "Captain America";
my_form_obj.weapon = "Shield";

Hope this helps!

Can we pass model as a parameter in RedirectToAction?

Yes you can pass the model that you have shown using

return RedirectToAction("GetStudent", "Student", student1 );

assuming student1 is an instance of Student

which will generate the following url (assuming your using the default routes and the value of student1 are ID=4 and Name="Amit")

.../Student/GetStudent/4?Name=Amit

Internally the RedirectToAction() method builds a RouteValueDictionary by using the .ToString() value of each property in the model. However, binding will only work if all the properties in the model are simple properties and it fails if any properties are complex objects or collections because the method does not use recursion. If for example, Student contained a property List<string> Subjects, then that property would result in a query string value of

....&Subjects=System.Collections.Generic.List'1[System.String]

and binding would fail and that property would be null

What is best tool to compare two SQL Server databases (schema and data)?

We are using an inhouse developed solution that is basicly a procedure with arguments of what you want included in the comparision (SP's, Full SP code, table structure, defaults, indices, triggers.. etc)

Depending on your needs and budget, it might be a good way to go for you as well.

It is quite easily developed as well, then we just redirect output of procedure to textfiles and do text comparisions between the files.

One good thing about it is that its possible to save the output in source control.

/B

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

When you sync this dependency to the android studio:

 implementation 'com.android.support:cardview-v7:26.0.1-alpha1'

Then, Sync the Gradle with Project Files. It will say, (Suppose if you are working on new ones like androidx) obviously, it will show error on the dependency.

For that you can go to the File menu and click on the invalidate/restart the code. It will resolve itself and the application will restart without any error.

How to create custom button in Android using XML Styles

Have a look at Styled Button it will surely help you. There are lots examples please search on INTERNET.

eg:style

<style name="Widget.Button" parent="android:Widget">
    <item name="android:background">@drawable/red_dot</item>
</style>

you can use your selector instead of red_dot

red_dot:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"  >

    <solid android:color="#f00"/>
    <size android:width="55dip"
        android:height="55dip"/>
</shape>

Button:

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp"
        style="@style/Widget.Button"
        android:text="Button" />

getch and arrow codes

for a solution that uses ncurses with working code and initialization of ncurses see getchar() returns the same value (27) for up and down arrow keys

How do I get the max ID with Linq to Entity?

The best way to get the id of the entity you added is like this:

public int InsertEntity(Entity factor)
{
    Db.Entities.Add(factor);
    Db.SaveChanges();
    var id = factor.id;
    return id;
}

Change the value in app.config file dynamically

This code works for me:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    config.AppSettings.Settings["test"].Value = "blah";       
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");

Note: it doesn't update the solution item 'app.config', but the '.exe.config' one in the bin/ folder if you run it with F5.

Caching a jquery ajax response in javascript/browser

Old question, but my solution is a bit different.

I was writing a single page web app that was constantly making ajax calls triggered by the user, and to make it even more difficult it required libraries that used methods other than jquery (like dojo, native xhr, etc). I wrote a plugin for one of my own libraries to cache ajax requests as efficiently as possible in a way that would work in all major browsers, regardless of which libraries were being used to make the ajax call.

The solution uses jSQL (written by me - a client-side persistent SQL implementation written in javascript which uses indexeddb and other dom storage methods), and is bundled with another library called XHRCreep (written by me) which is a complete re-write of the native XHR object.

To implement all you need to do is include the plugin in your page, which is here.

There are two options:

jSQL.xhrCache.max_time = 60;

Set the maximum age in minutes. any cached responses that are older than this are re-requested. Default is 1 hour.

jSQL.xhrCache.logging = true;

When set to true, mock XHR calls will be shown in the console for debugging.

You can clear the cache on any given page via

jSQL.tables = {}; jSQL.persist();

How do I set Tomcat Manager Application User Name and Password for NetBeans?

One simple way to check your changes to that file in Tomcat 8 + is to open a browser to: http://localhost:8080/manager/text/list

Example of Mockito's argumentCaptor

Here I am giving you a proper example of one callback method . so suppose we have a method like method login() :

 public void login() {
    loginService = new LoginService();
    loginService.login(loginProvider, new LoginListener() {
        @Override
        public void onLoginSuccess() {
            loginService.getresult(true);
        }

        @Override
        public void onLoginFaliure() {
            loginService.getresult(false);

        }
    });
    System.out.print("@@##### get called");
}

I also put all the helper class here to make the example more clear: loginService class

public class LoginService implements Login.getresult{
public void login(LoginProvider loginProvider,LoginListener callback){

    String username  = loginProvider.getUsername();
    String pwd  = loginProvider.getPassword();
    if(username != null && pwd != null){
        callback.onLoginSuccess();
    }else{
        callback.onLoginFaliure();
    }

}

@Override
public void getresult(boolean value) {
    System.out.print("login success"+value);
}}

and we have listener LoginListener as :

interface LoginListener {
void onLoginSuccess();

void onLoginFaliure();

}

now I just wanted to test the method login() of class Login

 @Test
public void loginTest() throws Exception {
    LoginService service = mock(LoginService.class);
    LoginProvider provider = mock(LoginProvider.class);
    whenNew(LoginProvider.class).withNoArguments().thenReturn(provider);
    whenNew(LoginService.class).withNoArguments().thenReturn(service);
    when(provider.getPassword()).thenReturn("pwd");
    when(provider.getUsername()).thenReturn("username");
    login.getLoginDetail("username","password");

    verify(provider).setPassword("password");
    verify(provider).setUsername("username");

    verify(service).login(eq(provider),captor.capture());

    LoginListener listener = captor.getValue();

    listener.onLoginSuccess();

    verify(service).getresult(true);

also dont forget to add annotation above the test class as

@RunWith(PowerMockRunner.class)
@PrepareForTest(Login.class)

what does "error : a nonstatic member reference must be relative to a specific object" mean?

EncodeAndSend is not a static function, which means it can be called on an instance of the class CPMSifDlg. You cannot write this:

 CPMSifDlg::EncodeAndSend(/*...*/);  //wrong - EncodeAndSend is not static

It should rather be called as:

 CPMSifDlg dlg; //create instance, assuming it has default constructor!
 dlg.EncodeAndSend(/*...*/);   //correct 

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

Error when trying vagrant up

I know this is old, but I got exactly the same error. Turns out I was missing this step that is clearly in the documentation.

I needed to edit the Vagrantfile to set the config.vm.box equal to the image I had downloaded, hashicorp/precise32. By default it was set to base.

Here's what the documentation says:

Now that the box has been added to Vagrant, we need to configure our project to use it as a base. Open the Vagrantfile and change the contents to the following:

Vagrant.configure("2") do |config|
  config.vm.box = "hashicorp/precise32"
end

At least one JAR was scanned for TLDs yet contained no TLDs

(tomcat 7.0.32) I had problems to see debug messages althought was enabling TldLocationsCache row in tomcat/conf/logging.properties file. All I could see was a warning but not what libs were scanned. Changed every loglevel tried everything no luck. Then I went rogue debug mode (=remove one by one, clean install etc..) and finally found a reason.

My webapp had a customized tomcat/webapps/mywebapp/WEB-INF/classes/logging.properties file. I copied TldLocationsCache row to this file, finally I could see jars filenames.

# To see debug messages in TldLocationsCache, uncomment the following line: org.apache.jasper.compiler.TldLocationsCache.level = FINE

PowerShell: Format-Table without headers

I know it's 2 years late, but these answers helped me to formulate a filter function to output objects and trim the resulting strings. Since I have to format everything into a string in my final solution I went about things a little differently. Long-hand, my problem is very similar, and looks a bit like this

$verbosepreference="Continue"
write-verbose (ls | ft | out-string) # this generated too many blank lines

Here is my example:

ls | Out-Verbose # out-verbose formats the (pipelined) object(s) and then trims blanks

My Out-Verbose function looks like this:

filter Out-Verbose{
Param([parameter(valuefrompipeline=$true)][PSObject[]]$InputObject,
      [scriptblock]$script={write-verbose "$_"})
  Begin {
    $val=@()
  }
  Process {
    $val += $inputobject
  }
  End {
    $val | ft -autosize -wrap|out-string |%{$_.split("`r`n")} |?{$_.length} |%{$script.Invoke()}
  }
}

Note1: This solution will not scale to like millions of objects(it does not handle the pipeline serially)

Note2: You can still add a -noheaddings option. If you are wondering why I used a scriptblock here, that's to allow overloading like to send to disk-file or other output streams.

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

For Mac,

I fixed it by re-entering root password.

System Preferences > MYSQL > Initialize Database > Enter password

Initialize Database

How to get a specific output iterating a hash in Ruby?

hash.each do |key, array|
  puts "#{key}-----"
  puts array
end

Regarding order I should add, that in 1.8 the items will be iterated in random order (well, actually in an order defined by Fixnum's hashing function), while in 1.9 it will be iterated in the order of the literal.

Why use armeabi-v7a code over armeabi code?

EABI = Embedded Application Binary Interface. It is such specifications to which an executable must conform in order to execute in a specific execution environment. It also specifies various aspects of compilation and linkage required for interoperation between toolchains used for the ARM Architecture. In this context when we speak about armeabi we speak about ARM architecture and GNU/Linux OS. Android follows the little-endian ARM GNU/Linux ABI.

armeabi application will run on ARMv5 (e.g. ARM9) and ARMv6 (e.g. ARM11). You may use Floating Point hardware if you build your application using proper GCC options like -mfpu=vfpv3 -mfloat-abi=softfp which tells compiler to generate floating point instructions for VFP hardware and enables the soft-float calling conventions. armeabi doesn't support hard-float calling conventions (it means FP registers are not used to contain arguments for a function), but FP operations in HW are still supported.

armeabi-v7a application will run on Cortex A# devices like Cortex A8, A9, and A15. It supports multi-core processors and it supports -mfloat-abi=hard. So, if you build your application using -mfloat-abi=hard, many of your function calls will be faster.

Sorting a vector in descending order

bool comp(int i, int j) { return i > j; }
sort(numbers.begin(), numbers.end(), comp);

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Although I do like and appreciate Suragch's answer, I would like to leave a note because I found that coding the Adapter (MyRecyclerViewAdapter) to define and expose the Listener method onItemClick isn't the best way to do it, due to not using class encapsulation correctly. So my suggestion is to let the Adapter handle the Listening operations solely (that's his purpose!) and separate those from the Activity that uses the Adapter (MainActivity). So this is how I would set the Adapter class:

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData = new String[0];
    private LayoutInflater mInflater;

    // Data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // Inflates the cell layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    // Binds the data to the textview in each cell
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData[position];
        holder.myTextView.setText(animal);
    }

    // Total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }

    // Stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView myTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            myTextView = (TextView) itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            onItemClick(view, getAdapterPosition());
        }
    }

    // Convenience method for getting data at click position
    public String getItem(int id) {
        return mData[id];
    }

    // Method that executes your code for the action received
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + getItem(position).toString() + ", which is at cell position " + position);
    }
}

Please note the onItemClick method now defined in MyRecyclerViewAdapter that is the place where you would want to code your tasks for the event/action received.

There is only a small change to be done in order to complete this transformation: the Activity doesn't need to implement MyRecyclerViewAdapter.ItemClickListener anymore, because now that is done completely by the Adapter. This would then be the final modification:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }
}

ReactJS: setTimeout() not working?

setTimeout(() => {
  this.setState({ position: 1 });
}, 3000);

The above would also work because the ES6 arrow function does not change the context of this.

jQuery append() and remove() element

You can call a reset function before appending. Something like this:

    function resetNewReviewBoardForm() {
    $("#Description").val('');
    $("#PersonName").text('');
    $("#members").empty(); //this one what worked in my case
    $("#EmailNotification").val('False');
}

How do I pass a value from a child back to the parent form?

When you use the ShowDialog() or Show() method, and then close the form, the form object does not get completely destroyed (closing != destruction). It will remain alive, only it's in a "closed" state, and you can still do things to it.

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

<style>
a{
cursor: default;
}
</style>

In the above code [cursor:default] is used. Default is the usual arrow cursor that appears.

And if you use [cursor: pointer] then you can access to the hand like cursor that appears when you hover over a link.

To know more about cursors and their appearance click the below link: https://www.w3schools.com/cssref/pr_class_cursor.asp

linux execute command remotely

I guess ssh is the best secured way for this, for example :

ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"  

where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.

Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.

Some extra docs over the source project main pages :

ssh and ssh-agent
man ssh

http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring

keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/

Adding Google Translate to a web site

<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script type="text/javascript">
  function googleTranslateElementInit() {
      new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
  }
</script>

Traits vs. interfaces

An often-used metaphor to describe Traits is Traits are interfaces with implementation.

This is a good way of thinking about it in most circumstances, but there are a number of subtle differences between the two.

For a start, the instanceof operator will not work with traits (ie, a trait is not a real object), therefore you can't use that to see if a class has a certain trait (or to see if two otherwise unrelated classes share a trait). That's what they mean by it being a construct for horizontal code re-use.

There are functions now in PHP that will let you get a list of all the traits a class uses, but trait-inheritance means you'll need to do recursive checks to reliably check if a class at some point has a specific trait (there's example code on the PHP doco pages). But yeah, it's certainly not as simple and clean as instanceof is, and IMHO it's a feature that would make PHP better.

Also, abstract classes are still classes, so they don't solve multiple-inheritance related code re-use problems. Remember you can only extend one class (real or abstract) but implement multiple interfaces.

I've found traits and interfaces are really good to use hand in hand to create pseudo multiple inheritance. Eg:

class SlidingDoor extends Door implements IKeyed  
{  
    use KeyedTrait;  
    [...] // Generally not a lot else goes here since it's all in the trait  
}

Doing this means you can use instanceof to determine if the particular Door object is Keyed or not, you know you'll get a consistent set of methods, etc, and all the code is in one place across all the classes that use the KeyedTrait.

How can I get a user's media from Instagram without authenticating as a user?

You can use this API to retrieve public info of the instagram user:

https://api.lityapp.com/instagrams/thebrainscoop?limit=2 (edit: broken/malware link on Feb 2021)

If you don't set the limit parameter, the posts are limited at 12 by default

This api was made in SpringBoot with HtmlUnit as you can see in the code:

public JSONObject getPublicInstagramByUserName(String userName, Integer limit) {
    String html;
    WebClient webClient = new WebClient();

    try {
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setJavaScriptEnabled(false);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getCookieManager().setCookiesEnabled(true);

        Page page = webClient.getPage("https://www.instagram.com/" + userName);
        WebResponse response = page.getWebResponse();

        html = response.getContentAsString();
    } catch (Exception ex) {
        ex.printStackTrace();

        throw new RuntimeException("Ocorreu um erro no Instagram");
    }

    String prefix = "static/bundles/es6/ProfilePageContainer.js";
    String suffix = "\"";
    String script = html.substring(html.indexOf(prefix));

    script = script.substring(0, script.indexOf(suffix));

    try {
        Page page = webClient.getPage("https://www.instagram.com/" + script);
        WebResponse response = page.getWebResponse();

        script = response.getContentAsString();
    } catch (Exception ex) {
        ex.printStackTrace();

        throw new RuntimeException("Ocorreu um erro no Instagram");
    }

    prefix = "l.pagination},queryId:\"";

    String queryHash = script.substring(script.indexOf(prefix) + prefix.length());

    queryHash = queryHash.substring(0, queryHash.indexOf(suffix));
    prefix = "<script type=\"text/javascript\">window._sharedData = ";
    suffix = ";</script>";
    html = html.substring(html.indexOf(prefix) + prefix.length());
    html = html.substring(0, html.indexOf(suffix));

    JSONObject json = new JSONObject(html);
    JSONObject entryData = json.getJSONObject("entry_data");
    JSONObject profilePage = (JSONObject) entryData.getJSONArray("ProfilePage").get(0);
    JSONObject graphql = profilePage.getJSONObject("graphql");
    JSONObject user = graphql.getJSONObject("user");
    JSONObject response = new JSONObject();

    response.put("id", user.getString("id"));
    response.put("username", user.getString("username"));
    response.put("fullName", user.getString("full_name"));
    response.put("followedBy", user.getJSONObject("edge_followed_by").getLong("count"));
    response.put("following", user.getJSONObject("edge_follow").getLong("count"));
    response.put("isBusinessAccount", user.getBoolean("is_business_account"));
    response.put("photoUrl", user.getString("profile_pic_url"));
    response.put("photoUrlHD", user.getString("profile_pic_url_hd"));

    JSONObject edgeOwnerToTimelineMedia = user.getJSONObject("edge_owner_to_timeline_media");
    JSONArray posts = new JSONArray();

    try {
        loadPublicInstagramPosts(webClient, queryHash, user.getString("id"), posts, edgeOwnerToTimelineMedia, limit == null ? 12 : limit);
    } catch (Exception ex) {
        ex.printStackTrace();

        throw new RuntimeException("Você fez muitas chamadas, tente mais tarde");
    }

    response.put("posts", posts);

    return response;
}

private void loadPublicInstagramPosts(WebClient webClient, String queryHash, String userId, JSONArray posts, JSONObject edgeOwnerToTimelineMedia, Integer limit) throws IOException {
    JSONArray edges = edgeOwnerToTimelineMedia.getJSONArray("edges");

    for (Object elem : edges) {
        if (limit != null && posts.length() == limit) {
            return;
        }

        JSONObject node = ((JSONObject) elem).getJSONObject("node");

        if (node.getBoolean("is_video")) {
            continue;
        }

        JSONObject post = new JSONObject();

        post.put("id", node.getString("id"));
        post.put("shortcode", node.getString("shortcode"));

        JSONArray captionEdges = node.getJSONObject("edge_media_to_caption").getJSONArray("edges");

        if (captionEdges.length() > 0) {
            JSONObject captionNode = ((JSONObject) captionEdges.get(0)).getJSONObject("node");

            post.put("caption", captionNode.getString("text"));
        } else {
            post.put("caption", (Object) null);
        }

        post.put("photoUrl", node.getString("display_url"));

        JSONObject dimensions = node.getJSONObject("dimensions");

        post.put("photoWidth", dimensions.getLong("width"));
        post.put("photoHeight", dimensions.getLong("height"));

        JSONArray thumbnailResources = node.getJSONArray("thumbnail_resources");
        JSONArray thumbnails = new JSONArray();

        for (Object elem2 : thumbnailResources) {
            JSONObject obj = (JSONObject) elem2;
            JSONObject thumbnail = new JSONObject();

            thumbnail.put("photoUrl", obj.getString("src"));
            thumbnail.put("photoWidth", obj.getLong("config_width"));
            thumbnail.put("photoHeight", obj.getLong("config_height"));
            thumbnails.put(thumbnail);
        }

        post.put("thumbnails", thumbnails);
        posts.put(post);
    }

    JSONObject pageInfo = edgeOwnerToTimelineMedia.getJSONObject("page_info");

    if (!pageInfo.getBoolean("has_next_page")) {
        return;
    }

    String endCursor = pageInfo.getString("end_cursor");
    String variables = "{\"id\":\"" + userId + "\",\"first\":12,\"after\":\"" + endCursor + "\"}";

    String url = "https://www.instagram.com/graphql/query/?query_hash=" + queryHash + "&variables=" + URLEncoder.encode(variables, "UTF-8");
    Page page = webClient.getPage(url);
    WebResponse response = page.getWebResponse();
    String content = response.getContentAsString();
    JSONObject json = new JSONObject(content);

    loadPublicInstagramPosts(webClient, queryHash, userId, posts, json.getJSONObject("data").getJSONObject("user").getJSONObject("edge_owner_to_timeline_media"), limit);
}

It's an example of response:
{
  "id": "290482318",
  "username": "thebrainscoop",
  "fullName": "Official Fan Page",
  "followedBy": 1023,
  "following": 6,
  "isBusinessAccount": false,
  "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/447ffd0262082f373acf3d467435f130/5C709C77/t51.2885-19/11351770_612904665516559_678168252_a.jpg",
  "photoUrlHD": "https://scontent-gru2-1.cdninstagram.com/vp/447ffd0262082f373acf3d467435f130/5C709C77/t51.2885-19/11351770_612904665516559_678168252_a.jpg",
  "posts": [
    {
      "id": "1430331382090378714",
      "shortcode": "BPZjtBUly3a",
      "caption": "If I have any active followers anymore; hello! I'm Brianna, and I created this account when I was just 12 years old to show my love for The Brain Scoop. I'm now nearly finished high school, and just rediscovered it. I just wanted to see if anyone is still active on here, and also correct some of my past mistakes - being a child at the time, I didn't realise I had to credit artists for their work, so I'm going to try to correct that post haste. Also; the font in my bio is horrendous. Why'd I think that was a good idea? Anyway, this is a beautiful artwork of the long-tailed pangolin by @chelsealinaeve . Check her out!",
      "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/ab823331376ca46136457f4654bf2880/5CAD48E4/t51.2885-15/e35/16110915_400942200241213_3503127351280009216_n.jpg",
      "photoWidth": 640,
      "photoHeight": 457,
      "thumbnails": [
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/43b195566d0ef2ad5f4663ff76d62d23/5C76D756/t51.2885-15/e35/c91.0.457.457/s150x150/16110915_400942200241213_3503127351280009216_n.jpg",
          "photoWidth": 150,
          "photoHeight": 150
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/ae39043a7ac050c56d741d8b4355c185/5C93971C/t51.2885-15/e35/c91.0.457.457/s240x240/16110915_400942200241213_3503127351280009216_n.jpg",
          "photoWidth": 240,
          "photoHeight": 240
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/ae7a22d09e3ef98d0a6bbf31d621a3b7/5CACBBA6/t51.2885-15/e35/c91.0.457.457/s320x320/16110915_400942200241213_3503127351280009216_n.jpg",
          "photoWidth": 320,
          "photoHeight": 320
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/1439dc72b70e7c0c0a3afcc30970bb13/5C8E2923/t51.2885-15/e35/c91.0.457.457/16110915_400942200241213_3503127351280009216_n.jpg",
          "photoWidth": 480,
          "photoHeight": 480
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/1439dc72b70e7c0c0a3afcc30970bb13/5C8E2923/t51.2885-15/e35/c91.0.457.457/16110915_400942200241213_3503127351280009216_n.jpg",
          "photoWidth": 640,
          "photoHeight": 640
        }
      ]
    },
    {
      "id": "442527661838057235",
      "shortcode": "YkLJBXJD8T",
      "caption": null,
      "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/dc94b38da679826b9ac94ccd2bcc4928/5C7CDF93/t51.2885-15/e15/11327349_860747310663863_2105199307_n.jpg",
      "photoWidth": 612,
      "photoHeight": 612,
      "thumbnails": [
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/c1153c6513c44a6463d897e14b2d8f06/5CB13ADD/t51.2885-15/e15/s150x150/11327349_860747310663863_2105199307_n.jpg",
          "photoWidth": 150,
          "photoHeight": 150
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/47e60ec8bca5a1382cd9ac562439d48c/5CAE6A82/t51.2885-15/e15/s240x240/11327349_860747310663863_2105199307_n.jpg",
          "photoWidth": 240,
          "photoHeight": 240
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/da0ee5b666ab40e4adc1119e2edca014/5CADCB59/t51.2885-15/e15/s320x320/11327349_860747310663863_2105199307_n.jpg",
          "photoWidth": 320,
          "photoHeight": 320
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/02ee23571322ea8d0992e81e72f80ef2/5C741048/t51.2885-15/e15/s480x480/11327349_860747310663863_2105199307_n.jpg",
          "photoWidth": 480,
          "photoHeight": 480
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/dc94b38da679826b9ac94ccd2bcc4928/5C7CDF93/t51.2885-15/e15/11327349_860747310663863_2105199307_n.jpg",
          "photoWidth": 640,
          "photoHeight": 640
        }
      ]
    }
  ]
}

Define css class in django Forms

Here is another solution for adding class definitions to the widgets after declaring the fields in the class.

def __init__(self, *args, **kwargs):
    super(SampleClass, self).__init__(*args, **kwargs)
    self.fields['name'].widget.attrs['class'] = 'my_class'

How can I protect my .NET assemblies from decompilation?

I know you don't want to obfuscate, but maybe you should check out dotfuscator, it will take your compiled assemblies and obfuscate them for you. I think it can even encrypt them.

Best way to store chat messages in a database?

There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.

Actually you can find here in Stack Overflow a link to an example schema for a chat: example

If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages

How to override application.properties during production in Spring-Boot?

I have found the following has worked for me:

java -jar my-awesome-java-prog.jar --spring.config.location=file:/path-to-config-dir/

with file: added.

LATE EDIT

Of course, this command line is never run as it is in production.

Rather I have

  • [possibly several layers of] shell scripts in source control with place holders for all parts of the command that could change (name of the jar, path to config...)
  • ansible deployment scripts that will deploy the shell scripts and replace the place holders by the actual value.

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

ADB No Devices Found

Sometimes ADB loses connection to the device, and needs to be reset. If you have everything else working (ie USB driver installed, Developer settings enabled on the device), and still can't see your device, you need to reset the ADB process.

This is available in the DDMS Perspective (from within Eclipse), Devices tab (the triangle on the far right includes a menu item to perform the reset).

Otherwise from the command line, you can reset it with the following 2 commands:

adb kill-server

then

adb start-server

How to run python script with elevated privilege on windows

It worth mentioning that if you intend to package your application with PyInstaller and wise to avoid supporting that feature by yourself, you can pass the --uac-admin or --uac-uiaccess argument in order to request UAC elevation on start.

How to set Angular 4 background image?

Below answer worked for angular 4/5.

In app.component.css

.image{
     height:40em; background-size:cover; width:auto;
     background-image:url('copied image address');
     background-position:50% 50%;
   }

Also in app.component.html simply add as below

<div class="image">
Your content
</div>

This way I was able to set background image in Angular 4/5.

Android eclipse DDMS - Can't access data/data/ on phone to pull files

If gives "permission denied" on adb shell -> su...

Some ROMs are running adbd daemon in secure mode (adbd has no root access and su command does not even show permission ask dialog on the device). In this case you will get "permission denied" when you try cmd -> adb shell -> su. The solution I've found is one app from the famous modder Chainfire called Adbd Insecure.

How do you underline a text in Android XML?

Use this:

TextView txt = (TextView) findViewById(R.id.Textview1);
txt.setPaintFlags(txt.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

How do I release memory used by a pandas dataframe?

It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659

The monkey patch detailed on this issue has resolved the problem for me:

# monkeypatches.py

# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
    cdll.LoadLibrary("libc.so.6")
    libc = CDLL("libc.so.6")
    libc.malloc_trim(0)
except (OSError, AttributeError):
    libc = None

__old_del = getattr(pd.DataFrame, '__del__', None)

def __new_del(self):
    if __old_del:
        __old_del(self)
    libc.malloc_trim(0)

if libc:
    print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
    pd.DataFrame.__del__ = __new_del
else:
    print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)