Programs & Examples On #Richtext

Text that includes formatting commands for page layout such as fonts, bold, underline, italic, etc. It may also refer to a multimedia document that can include images, audio and video.

Flutter - The method was called on null

Because of your initialization wrong.

Don't do like this,

MethodName _methodName;

Do like this,

MethodName _methodName = MethodName();

PHPExcel Make first row bold

Assuming headers are on the first row of the sheet starting at A1, and you know how many of them there are, this was my solution:

$header = array(
    'Header 1',
    'Header 2'
);

$objPHPExcel = new PHPExcel();
$objPHPExcelSheet = $objPHPExcel->getSheet(0);
$objPHPExcelSheet->fromArray($header, NULL);
$first_letter = PHPExcel_Cell::stringFromColumnIndex(0);
$last_letter = PHPExcel_Cell::stringFromColumnIndex(count($header)-1);
$header_range = "{$first_letter}1:{$last_letter}1";
$objPHPExcelSheet->getStyle($header_range)->getFont()->setBold(true);

Hiding a form and showing another when a button is clicked in a Windows Forms application

Anything after Application.Run( ) will only be executed when the main form closes.

What you could do is handle the VisibleChanged event as follows:

static Form1 form1;
static Form2 form2;

static void Main()
{

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    form2 = new Form2();
    form1 = new Form1();
    form2.Hide();
    form1.VisibleChanged += OnForm1Changed;
    Application.Run(form1);

}

static void OnForm1Changed( object sender, EventArgs args )
{
    if ( !form1.Visible )
    {
        form2.Show( );
    }
}

Reading large text files with streams in C#

My file is over 13 GB: enter image description here

The bellow link contains the code that read a piece of file easily:

Read a large text file

More information

Color different parts of a RichTextBox string

Selecting text as said from somebody, may the selection appear momentarily. In Windows Forms applications there is no other solutions for the problem, but today I found a bad, working, way to solve: you can put a PictureBox in overlapping to the RichtextBox with the screenshot of if, during the selection and the changing color or font, making it after reappear all, when the operation is complete.

Code is here...

//The PictureBox has to be invisible before this, at creation
//tb variable is your RichTextBox
//inputPreview variable is your PictureBox
using (Graphics g = inputPreview.CreateGraphics())
{
    Point loc = tb.PointToScreen(new Point(0, 0));
    g.CopyFromScreen(loc, loc, tb.Size);
    Point pt = tb.GetPositionFromCharIndex(tb.TextLength);
    g.FillRectangle(new SolidBrush(Color.Red), new Rectangle(pt.X, 0, 100, tb.Height));
}
inputPreview.Invalidate();
inputPreview.Show();
//Your code here (example: tb.Select(...); tb.SelectionColor = ...;)
inputPreview.Hide();

Better is to use WPF; this solution isn't perfect, but for Winform it works.

RichTextBox (WPF) does not have string property "Text"

According to this it does have a Text property

http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox_members.aspx

You can also try the "Lines" property if you want the text broken up as lines.

Attempted to read or write protected memory

In my case this was fixed when I set up 'Enable 32 Bit applications'=True for Application pool in IIS server.

Richtextbox wpf binding

Here's a VB.Net version of Lolo's answer:

Public Class RichTextBoxHelper
Inherits DependencyObject

Private Shared _recursionProtection As New HashSet(Of System.Threading.Thread)()

Public Shared Function GetDocumentXaml(ByVal depObj As DependencyObject) As String
    Return DirectCast(depObj.GetValue(DocumentXamlProperty), String)
End Function

Public Shared Sub SetDocumentXaml(ByVal depObj As DependencyObject, ByVal value As String)
    _recursionProtection.Add(System.Threading.Thread.CurrentThread)
    depObj.SetValue(DocumentXamlProperty, value)
    _recursionProtection.Remove(System.Threading.Thread.CurrentThread)
End Sub

Public Shared ReadOnly DocumentXamlProperty As DependencyProperty = DependencyProperty.RegisterAttached("DocumentXaml", GetType(String), GetType(RichTextBoxHelper), New FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, Sub(depObj, e)
                                                                                                                                                                                                                                                                                                                    RegisterIt(depObj, e)
                                                                                                                                                                                                                                                                                                                End Sub))

Private Shared Sub RegisterIt(ByVal depObj As System.Windows.DependencyObject, ByVal e As System.Windows.DependencyPropertyChangedEventArgs)
    If _recursionProtection.Contains(System.Threading.Thread.CurrentThread) Then
        Return
    End If
    Dim rtb As RichTextBox = DirectCast(depObj, RichTextBox)
    Try
        rtb.Document = Markup.XamlReader.Parse(GetDocumentXaml(rtb))
    Catch
        rtb.Document = New FlowDocument()
    End Try
    ' When the document changes update the source
    AddHandler rtb.TextChanged, AddressOf TextChanged
End Sub

Private Shared Sub TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)
    Dim rtb As RichTextBox = TryCast(sender, RichTextBox)
    If rtb IsNot Nothing Then
        SetDocumentXaml(sender, Markup.XamlWriter.Save(rtb.Document))
    End If
End Sub

End Class

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

TLS 1.0 and 1.1 are now End of Life. A package on our Amazon web server updated, and we started getting this error.

The answer is above, but you shouldn't use tls or tls11 anymore.

Specifically for ASP.Net, add this to one of your startup methods.

        public Startup()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;

but I'm sure that something like this will work in many other cases.

Easily measure elapsed time

the time(NULL) function will return the number of seconds elapsed since 01/01/1970 at 00:00. And because, that function is called at different time in your program, it will always be different Time in C++

Automatically running a batch file as an administrator

You can use PowerShell to run b.bat as administrator from a.bat:

set mydir=%~dp0

Powershell -Command "& { Start-Process \"%mydir%b.bat\" -verb RunAs}"

It will prompt the user with a confirmation dialog. The user chooses YES, and then b.bat will be run as administrator.

How to compare each item in a list with the rest, only once?

Of course this will generate each pair twice as each for loop will go through every item of the list.

You could use some itertools magic here to generate all possible combinations:

import itertools
for a, b in itertools.combinations(mylist, 2):
    compare(a, b)

itertools.combinations will pair each element with each other element in the iterable, but only once.


You could still write this using index-based item access, equivalent to what you are used to, using nested for loops:

for i in range(len(mylist)):
    for j in range(i + 1, len(mylist)):
        compare(mylist[i], mylist[j])

Of course this may not look as nice and pythonic but sometimes this is still the easiest and most comprehensible solution, so you should not shy away from solving problems like that.

How to delete columns in a CSV file?

I would use Pandas with col number

f = pd.read_csv("test.csv", usecols=[0,1,3,4])

f.to_csv("test.csv", index=False)

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

Ruby max integer

In ruby Fixnums are automatically converted to Bignums.

To find the highest possible Fixnum you could do something like this:

class Fixnum
 N_BYTES = [42].pack('i').size
 N_BITS = N_BYTES * 8
 MAX = 2 ** (N_BITS - 2) - 1
 MIN = -MAX - 1
end
p(Fixnum::MAX)

Shamelessly ripped from a ruby-talk discussion. Look there for more details.

Bootstrap Carousel : Remove auto slide

You just need to add one more attribute to your DIV tag which is

data-interval="false"

no need to touch JS!

How can I pass selected row to commandLink inside dataTable or ui:repeat?

Thanks to this site by Mkyong, the only solution that actually worked for us to pass a parameter was this

<h:commandLink action="#{user.editAction}">
    <f:param name="myId" value="#{param.id}" />
</h:commandLink>

with

public String editAction() {

  Map<String,String> params = 
            FacesContext.getExternalContext().getRequestParameterMap();
  String idString = params.get("myId");
  long id = Long.parseLong(idString);
  ...
}

Technically, that you cannot pass to the method itself directly, but to the JSF request parameter map.

How to run TypeScript files from command line?

This answer may be premature, but deno supports running both TS and JS out of the box.

Based on your development environment, moving to Deno (and learning about it) might be too much, but hopefully this answer helps someone in the future.

How to find keys of a hash?

if you are trying to get the elements only but not the functions then this code can help you

this.getKeys = function() {

var keys = new Array();
for(var key in this) {

    if( typeof this[key] !== 'function') {

        keys.push(key);
    }
}
return keys;

}

this is part of my implementation of the HashMap and I only want the keys, this is the hashmap object that contains the keys

execute function after complete page load

Alternatively you can try below.

$(window).bind("load", function() { 
// code here });

This works in all the case. This will trigger only when the entire page is loaded.

JavaScriptSerializer - JSON serialization of enum as string

new JavaScriptSerializer().Serialize(  
    (from p   
    in (new List<Person>() {  
        new Person()  
        {  
            Age = 35,  
            Gender = Gender.Male  
        }  
    })  
    select new { Age =p.Age, Gender=p.Gender.ToString() }  
    ).ToArray()[0]  
);

Ruby: character to ascii from a string

"a"[0]

or

?a

Both would return their ASCII equivalent.

Why can't a text column have a default value in MySQL?

As the main question:

Anybody know why this is not allowed?

is still not answered, I did a quick search and found a relatively new addition from a MySQL developer at MySQL Bugs:

[17 Mar 2017 15:11] Ståle Deraas

Posted by developer:

This is indeed a valid feature request, and at first glance it might seem trivial to add. But TEXT/BLOBS values are not stored directly in the record buffer used for reading/updating tables. So it is a bit more complex to assign default values for them.

This is no definite answer, but at least a starting point for the why question.

In the mean time, I'll just code around it and either make the column nullable or explicitly assign a (default '') value for each insert from the application code...

How to use the gecko executable with Selenium

I create a simple Java application by archetype maven-archetype-quickstar, then revise pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>bar</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>bar</name>
    <description>bar</description>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.0.0-beta3</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>3.0.0-beta3</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-api</artifactId>
            <version>3.0.0-beta3</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-firefox-driver</artifactId>
            <version>3.0.0-beta3</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>bar</finalName>
    </build>
</project>

and

package bar;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AppTest {

    /**
     * Web driver.
     */
    private static WebDriver driver = null;

    /**
     * Entry point.
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        // Download "geckodriver.exe" from https://github.com/mozilla/geckodriver/releases
        System.setProperty("webdriver.gecko.driver","F:\\geckodriver.exe");
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://localhost:8080/foo/");
        String sTitle = driver.getTitle();
        System.out.println(sTitle);
    }

}

You also use on Mac OS X, Linux: https://github.com/mozilla/geckodriver/releases

and

// On Mac OS X.
System.setProperty("webdriver.gecko.driver", "/Users/donhuvy/Downloads/geckodriver");

How to trigger checkbox click event even if it's checked through Javascript code?

You can also use this, I hope you can serve them.

_x000D_
_x000D_
$(function(){_x000D_
  $('#elements input[type="checkbox"]').prop("checked", true).trigger("change");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>_x000D_
_x000D_
<div id="elements">_x000D_
  <input type="checkbox" id="item-1" value="1"> Item 1 <br />_x000D_
  <input type="checkbox" id="item-2" value="2" disabled> Item 2 <br /> _x000D_
  <input type="checkbox" id="item-3" value="3" disabled> Item 3 <br />_x000D_
  <input type="checkbox" id="item-4" value="4" disabled> Item 4 <br />_x000D_
  <input type="checkbox" id="item-5" value="5"> Item 5_x000D_
</div>
_x000D_
_x000D_
_x000D_

Formatting floats without trailing zeros

"{:.5g}".format(x)

I use this to format floats to trail zeros.

Is it acceptable and safe to run pip install under sudo?

Because I had the same problem, I want to stress that actually the first comment by Brian Cain is the solution to the "IOError: [Errno 13]"-problem:

If executed in the temp directory (cd /tmp), the IOError does not occur anymore if I run sudo pip install foo.

Listen for key press in .NET console app

You can change your approach slightly - use Console.ReadKey() to stop your app, but do your work in a background thread:

static void Main(string[] args)
{
    var myWorker = new MyWorker();
    myWorker.DoStuff();
    Console.WriteLine("Press any key to stop...");
    Console.ReadKey();
}

In the myWorker.DoStuff() function you would then invoke another function on a background thread (using Action<>() or Func<>() is an easy way to do it), then immediately return.

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

How do I activate a Spring Boot profile when running from IntelliJ?

Replace your profile name with BE

You can try the above way to activate a profile

CSS horizontal scroll

try using table structure, it's more back compatible. Check this outHorizontal Scrolling using Tables

ssh connection refused on Raspberry Pi

Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this raspberrypi.org tutorial :

As of the November 2016 release, Raspbian has the SSH server disabled by default.

There are now multiple ways to enable it. Choose one:

From the desktop

  1. Launch Raspberry Pi Configuration from the Preferences menu
  2. Navigate to the Interfaces tab
  3. Select Enabled next to SSH
  4. Click OK

From the terminal with raspi-config

  1. Enter sudo raspi-config in a terminal window
  2. Select Interfacing Options
  3. Navigate to and select SSH
  4. Choose Yes
  5. Select Ok
  6. Choose Finish

Start the SSH service with systemctl

sudo systemctl enable ssh
sudo systemctl start ssh

On a headless Raspberry Pi

For headless setup, SSH can be enabled by placing a file named ssh, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for the ssh file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.

Get commit list between tags in git

git log --pretty=oneline tagA...tagB (i.e. three dots)

If you just wanted commits reachable from tagB but not tagA:

git log --pretty=oneline tagA..tagB (i.e. two dots)

or

git log --pretty=oneline ^tagA tagB

Removing padding gutter from grid columns in Bootstrap 4

You should use built-in bootstrap4 spacing classes for customizing the spacing of elements, that's more convenient method .

Replace special characters in a string with _ (underscore)

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g,'_');

Remove table row after clicking table row delete button

Following solution is working fine.

HTML:

<table>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
</table>

JQuery:

function SomeDeleteRowFunction(btndel) {
    if (typeof(btndel) == "object") {
        $(btndel).closest("tr").remove();
    } else {
        return false;
    }
}

I have done bins on http://codebins.com/bin/4ldqpa9

Add or change a value of JSON key with jquery or javascript

Just like you would for any other variable, you just set it

alert(data.ID);
data.ID = "bar";  //dot notation 
alert(data.ID);    
data.userID = 123456;
data["address"] = "123 some street"; //bracket notation

How to search for occurrences of more than one space between words in a line

Simple solution:

/\s{2,}/

This matches all occurrences of one or more whitespace characters. If you need to match the entire line, but only if it contains two or more consecutive whitespace characters:

/^.*\s{2,}.*$/

If the whitespaces don't need to be consecutive:

/^(.*\s.*){2,}$/

how to check for special characters php

<?php

$string = 'foo';

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
    // one or more of the 'special characters' found in $string
}

Form Submission without page refresh

The problem is the Method 'POST' your form is submitting by using the "post" method, and in the AJAX you are using "GET".

Change Title of Javascript Alert

It's not possible, sorry. If really needed, you could use a jQuery plugin to have a custom alert.

Intel's HAXM equivalent for AMD on Windows OS

From the Android docs (March 2016):

Before attempting to use this type of acceleration, you should first determine if your development system’s CPU supports one of the following virtualization extensions technologies:

  • Intel Virtualization Technology (VT, VT-x, vmx) extensions
  • AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)

The specifications from the manufacturer of your CPU should indicate if it supports virtualization extensions. If your CPU does not support one of these virtualization technologies, then you cannot use virtual machine acceleration.

Note: Virtualization extensions are typically enabled through your computer's BIOS and are frequently turned off by default. Check the documentation for your system's motherboard to find out how to enable virtualization extensions.

Most people talk about Genymotion being faster, and I have never heard anyone say it's slower. I definitely think it's faster, and it will be worth the ~20 minutes it will take to set up just to try it.

Changing file extension in Python

Use this:

os.path.splitext("name.fasta")[0]+".aln"

And here is how the above works:

The splitext method separates the name from the extension creating a tuple:

os.path.splitext("name.fasta")

the created tuple now contains the strings "name" and "fasta". Then you need to access only the string "name" which is the first element of the tuple:

os.path.splitext("name.fasta")[0]

And then you want to add a new extension to that name:

os.path.splitext("name.fasta")[0]+".aln"

Most pythonic way to delete a file which may not exist

if os.path.exists(filename): os.remove(filename)

is a one-liner.

Many of you may disagree - possibly for reasons like considering the proposed use of ternaries "ugly" - but this begs the question of whether we should listen to people used to ugly standards when they call something non-standard "ugly".

Can not connect to local PostgreSQL

This happened to me today after my Macbook's battery died. I think this can be caused by improper shutdown. All you have to do in cases such as mine is delete postmaster.pid

Navigate to the folder

cd /usr/local/var/postgres

Check to see if postmaster.pid is present

ls

Remove postmaster.pid

rm postmaster.pid

Process to convert simple Python script into Windows executable

I would join @Nicholas in recommending PyInstaller (with the --onefile flag), but be warned: do not use the "latest release", PyInstaller 1.3 -- it's years old. Use the "pre-release" 1.4, download it here -- or even better the code from the svn repo -- install SVN and run svn co http://svn.pyinstaller.org/trunk pyinstaller.

As @Nicholas implies, dynamic libraries cannot be run from the same file as the rest of the executable -- but fortunately they can be packed together with all the rest in a "self-unpacking" executable that will unpack itself into some temporary directory as needed; PyInstaller does a good job at this (and at many other things -- py2exe is more popular, but pyinstaller in my opinion is preferable in all other respects).

Refresh a page using PHP

Echo the meta tag like this:

URL is the one where the page should be redirected to after the refresh.

echo "<meta http-equiv=\"refresh\" content=\"0;URL=upload.php\">";

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

For me I did enter a invalid url like : orcl only instead of jdbc:oracle:thin:@//localhost:1521/orcl

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

Until React provides a better way, you can create a helper, useEffectAsync.js:

import { useEffect } from 'react';


export default function useEffectAsync(effect, inputs) {
    useEffect(() => {
        effect();
    }, inputs);
}

Now you can pass an async function:

useEffectAsync(async () => {
    const items = await fetchSomeItems();
    console.log(items);
}, []);

Update

If you choose this approach, note that it's bad form. I resort to this when I know it's safe, but it's always bad form and haphazard.

Suspense for Data Fetching, which is still experimental, will solve some of the cases.

In other cases, you can model the async results as events so that you can add or remove a listener based on the component life cycle.

Or you can model the async results as an Observable so that you can subscribe and unsubscribe based on the component life cycle.

How to install pywin32 module in windows 7

are you just trying to install it, or are you looking to build from source?

If you just need to install, the easiest way is to use the MSI installers provided here:

http://sourceforge.net/projects/pywin32/files/pywin32/ (for updated versions)

make sure you get the correct version (matches Python version, 32bit/64bit, etc)

How to create two columns on a web page?

The simple and best solution is to use tables for layouts. You're doing it right. There are a number of reasons tables are better.

  • They perform better than CSS
  • They work on all browsers without any fuss
  • You can debug them easily with the border=1 attribute

How to create empty text file from a batch file?

You can use a TYPE command instead of COPY. Try this:

TYPE File1.txt>File2.txt

Where File1.txt is empty.

C# '@' before a String

It also means you can use reserved words as variable names

say you want a class named class, since class is a reserved word, you can instead call your class class:

IList<Student> @class = new List<Student>();

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

you make the use of the HTML Helper and have

    @using(Html.BeginForm())
    {
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    }

or use the Url helper

<form method="post" action="@Url.Action("MyAction", "MyController")" >

Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:

@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    < ... >
}

If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete

public ActionResult Delete(int id)
{
   var model = db.GetPostById(id);
   return View(model);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var model = db.GetPostById(id);
    if(model != null) 
        db.DeletePost(id);

    return RedirectToView("Index");
}

and your html page would be something like:

<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>

@using(Html.BeginForm())
{
    <input type="submit" class="btn btn-danger" value="Delete Post"/>
    <text>or</text>
    @Url.ActionLink("go to list", "Index")
}

Entity Framework Code First - two Foreign Keys from same table

You can try this too:

public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey("HomeTeam"), Column(Order = 0)]
    public int? HomeTeamId { get; set; }
    [ForeignKey("GuestTeam"), Column(Order = 1)]
    public int? GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

When you make a FK column allow NULLS, you are breaking the cycle. Or we are just cheating the EF schema generator.

In my case, this simple modification solve the problem.

How can I install packages using pip according to the requirements.txt file from a local directory?

Use:

pip install -r requirements.txt

For further details, please check the help option:

pip install --help

We can find the option '-r' -

-r, --requirement Install from the given requirements file. This option can be used multiple times.

Further information on some commonly used pip install options (this is the help option on the pip install command):

Enter image description here

Also the above is the complete set of options. Please use pip install --help for the complete list of options.

Reloading submodules in IPython

http://shawnleezx.github.io/blog/2015/08/03/some-notes-on-ipython-startup-script/

To avoid typing those magic function again and again, they could be put in the ipython startup script(Name it with .py suffix under .ipython/profile_default/startup. All python scripts under that folder will be loaded according to lexical order), which looks like the following:

from IPython import get_ipython
ipython = get_ipython()

ipython.magic("pylab")
ipython.magic("load_ext autoreload")
ipython.magic("autoreload 2")

LINQ orderby on date field in descending order

I was trying to also sort by a DateTime field descending and this seems to do the trick:

var ud = (from d in env 
     orderby -d.ReportDate.Ticks                 
     select  d.ReportDate.ToString("yyyy-MMM") ).Distinct(); 

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

That's a half-open interval.

  • A closed interval [a,b] includes the end points.
  • An open interval (a,b) excludes them.

In your case the end-point at the start of the interval is included, but the end is excluded. So it means the interval "first1 <= x < last1".

Half-open intervals are useful in programming because they correspond to the common idiom for looping:

for (int i = 0; i < n; ++i) { ... } 

Here i is in the range [0, n).

Vim autocomplete for Python

This can be a good option if you want python completion as well as other languages. https://github.com/Valloric/YouCompleteMe

The python completion is jedi based same as jedi-vim.

Change bootstrap navbar collapse breakpoint without using LESS

In addition to @Skely answer, to make dropdown menus inside the navbar work, also add their classes to be overriden. Final code bellow:

    @media (min-width: 768px) and (max-width: 991px) {
        .navbar-nav .open .dropdown-menu {
            position: static;
            float: none;
            width: auto;
            margin-top: 0;
            background-color: transparent;
            border: 0;
            -webkit-box-shadow: none;
            box-shadow: none;
        }
        .navbar-nav .open .dropdown-menu > li > a {
            line-height: 20px;
        }
        .navbar-nav .open .dropdown-menu > li > a,
        .navbar-nav .open .dropdown-menu .dropdown-header {
            padding: 5px 15px 5px 25px;
        }
        .dropdown-menu > li > a {
            display: block;
            padding: 3px 20px;
            clear: both;
            font-weight: normal;
            line-height: 1.42857143;
            color: #333;
            white-space: nowrap;
        }
        .navbar-header {
            float: none;
        }
        .navbar-toggle {
            display: block;
        }
        .navbar-collapse {
            border-top: 1px solid transparent;
            box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
        }
        .navbar-collapse.collapse {
            display: none!important;
        }
        .navbar-nav {
            float: none!important;
            /*margin: 7.5px -15px;*/
            margin: 7.5px 50px 7.5px -15px
        }
        .navbar-nav>li {
            float: none;
        }
        .navbar-nav>li>a {
            padding-top: 10px;
            padding-bottom: 10px;
        }
        .navbar-text {
            float: none;
            margin: 15px 0;
        }
        /* since 3.1.0 */
        .navbar-collapse.collapse.in { 
            display: block!important;
        }
        .collapsing {
            overflow: hidden!important;
        }
    }

demo code

When does Java's Thread.sleep throw InterruptedException?

If an InterruptedException is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threads interrupt() method. The wait method detects that and throws an InterruptedException so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up.

If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the InterruptedException clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run:

} catch (InterruptedException e) {
  Thread.currentThread().interrupt();
  // code for stopping current task so thread stops
}

Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used.

What might be better is to add this:

} catch (InterruptedException e) {
  throw new RuntimeException("Unexpected interrupt", e);
}

...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.

How can I align two divs horizontally?

Float the divs in a parent container, and style it like so:

_x000D_
_x000D_
.aParent div {_x000D_
    float: left;_x000D_
    clear: none; _x000D_
}
_x000D_
<div class="aParent">_x000D_
    <div>_x000D_
        <span>source list</span>_x000D_
        <select size="10">_x000D_
            <option />_x000D_
            <option />_x000D_
            <option />_x000D_
        </select>_x000D_
    </div>_x000D_
    <div>_x000D_
        <span>destination list</span>_x000D_
        <select size="10">_x000D_
            <option />_x000D_
            <option />_x000D_
            <option />_x000D_
        </select>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to turn off word wrapping in HTML?

You need to use the CSS white-space attribute.

In particular, white-space: nowrap and white-space: pre are the most commonly used values. The first one seems to be what you 're after.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

SEVERE: Error listenerStart

This boils down to that a ServletContextListener which is registered by either @WebListener annotation on the class, or by a <listener> declaration in web.xml, has thrown an unhandled exception inside the contextInitialized() method. This is usually caused by a developer's mistake (a bug) and needs to be fixed. For example, a NullPointerException.

The full exception should be visible in webapp-specific startup log as well as the IDE console, before the particular line which you've copypasted. If there is none and you still can't figure the cause of the exception by just looking at the code, put the entire contextInitialized() code in a try-catch wherein you log the exception to a reliable output and then interpret and fix it accordingly.

Using Camera in the Android emulator

Does not seem like it, but android recognises a webcam as a device. Every time I run the emulator my webcam's active light comes on.

How can I flush GPU memory using CUDA (physical reset is unavailable)

on macOS (/ OS X), if someone else is having trouble with the OS apparently leaking memory:

  • https://github.com/phvu/cuda-smi is useful for quickly checking free memory
  • Quitting applications seems to free the memory they use. Quit everything you don't need, or quit applications one-by-one to see how much memory they used.
  • If that doesn't cut it (quitting about 10 applications freed about 500MB / 15% for me), the biggest consumer by far is WindowServer. You can Force quit it, which will also kill all applications you have running and log you out. But it's a bit faster than a restart and got me back to 90% free memory on the cuda device.

Insert picture/table in R Markdown

When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png) can be problematic if PDF output is required.

The knitr function include_graphics knitr::include_graphics('/path/to/image.png') is a more portable alternative that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.

JAX-WS client : what's the correct path to access the local WSDL?

Had the exact same problem that is described herein. No matter what I did, following the above examples, to change the location of my WSDL file (in our case from a web server), it was still referencing the original location embedded within the source tree of the server process.

After MANY hours trying to debug this, I noticed that the Exception was always being thrown from the exact same line (in my case 41). Finally this morning, I decided to just send my source client code to our trade partner so they can at least understand how the code looks, but perhaps build their own. To my shock and horror I found a bunch of class files mixed in with my .java files within my client source tree. How bizarre!! I suspect these were a byproduct of the JAX-WS client builder tool.

Once I zapped those silly .class files and performed a complete clean and rebuild of the client code, everything works perfectly!! Redonculous!!

YMMV, Andrew

How to store and retrieve a dictionary with redis

If you don't know exactly how to organize data in Redis, I did some performance tests, including the results parsing. The dictonary I used (d) had 437.084 keys (md5 format), and the values of this form:

{"path": "G:\tests\2687.3575.json",
 "info": {"f": "foo", "b": "bar"},
 "score": 2.5}

First Test (inserting data into a redis key-value mapping):

conn.hmset('my_dict', d)  # 437.084 keys added in 8.98s

conn.info()['used_memory_human']  # 166.94 Mb

for key in d:
    json.loads(conn.hget('my_dict', key).decode('utf-8').replace("'", '"'))
    #  41.1 s

import ast
for key in d:
    ast.literal_eval(conn.hget('my_dict', key).decode('utf-8'))
    #  1min 3s

conn.delete('my_dict')  # 526 ms

Second Test (inserting data directly into Redis keys):

for key in d:
    conn.hmset(key, d[key])  # 437.084 keys added in 1min 20s

conn.info()['used_memory_human']  # 326.22 Mb

for key in d:
    json.loads(conn.hgetall(key)[b'info'].decode('utf-8').replace("'", '"'))
    #  1min 11s

for key in d:
    conn.delete(key)
    #  37.3s

As you can see, in the second test, only 'info' values have to be parsed, because the hgetall(key) already returns a dict, but not a nested one.

And of course, the best example of using Redis as python's dicts, is the First Test

Loading context in Spring using web.xml

From the spring docs

Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.

The <context-param>:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

You can then use the WebApplicationContext to get a handle on your beans.

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");

See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info

Debug vs Release in CMake

With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt in the root of your project. Then from the root of your project:

mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..
make

And for Debug (again from the root of your project):

mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make

Release / Debug will add the appropriate flags for your compiler. There are also RelWithDebInfo and MinSizeRel build configurations.


You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT variables, e.g.:

set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")

See CMAKE_BUILD_TYPE for more details.


As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.

How to get height of <div> in px dimension

Although they vary slightly as to how they retrieve a height value, i.e some would calculate the whole element including padding, margin, scrollbar, etc and others would just calculate the element in its raw form.
You can try these ones:

javascript:

var myDiv = document.getElementById("myDiv");
myDiv.clientHeight;
myDiv.scrollHeight;
myDiv.offsetHeight;

or in jquery:

$("#myDiv").height();
$("#myDiv").innerHeight();
$("#myDiv").outerHeight();

Is it possible to insert HTML content in XML document?

The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.

'NOT NULL constraint failed' after adding to models.py

@coldmind answer is correct but lacks details.

The 'NOT NULL constraint failed' occurs when something tries to set None to the 'zipcode' property, while it has not been explicitely allowed.

It usually happens when:

1) your field has Null=False by default, so that the value in the database cannot be None (i.e. undefined) when the object is created and saved in the database (this happens after a objects_set.create() call or setting the .zipcode property and doing a .save() call).

For instance, if somewhere in your code an assignement results in:

model.zipcode = None

this error is raised

2) When creating or updating the database, Django is constrained to find a default value to fill the field, because Null=False by default. It does not find any because you haven't defined any. So this error can not only happen during code execution but also when creating the database?

3) Note that the same error would be returned of you define default=None, or if your default value with an incorrect type, for instance default='00000' instead of 00000 for your field (maybe can there be automatic conversion between char and integers, but I would advise against relying on it. Besides, explicit is better than implicit). Most likely an error would also be raised if the default value violates the max_length property, e.g. 123456

So you'll have to define the field by one of the following:

models.IntegerField(_('zipcode'), max_length=5, Null=True,
   blank=True)

models.IntegerField(_('zipcode'), max_length=5, Null=False,
   blank=True, default=00000)

models.IntegerField(_('zipcode'), max_length=5, blank=True,
   default=00000)

and then make a migration (python3 manage.py makemigration ) and then migrate (python3 manage.py migrate).

For safety you can also delete the last failed migration files in <app_name>/migrations/, there are usually named after this pattern:

<NUMBER>_auto_<DATE>_<HOUR>.py

Finally, if you don't set Null=True, make sure that mode.zipcode = None is never done anywhere.

Multiple Python versions on the same machine?

I did this with anaconda navigator. I installed anaconda navigator and created two different development environments with different python versions

and switch between different python versions by switching or activating and deactivating environments.

first install anaconda navigator and then create environments.

see help here on how to manage environments

https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/

Here is the video to do it with conda

https://youtu.be/EGaw6VXV3GI

How can I save an image with PIL?

Try removing the . before the .bmp (it isn't matching BMP as expected). As you can see from the error, the save_handler is upper-casing the format you provided and then looking for a match in SAVE. However the corresponding key in that object is BMP (instead of .BMP).

I don't know a great deal about PIL, but from some quick searching around it seems that it is a problem with the mode of the image. Changing the definition of j to:

j = Image.fromarray(b, mode='RGB')

Seemed to work for me (however note that I have very little knowledge of PIL, so I would suggest using @mmgp's solution as s/he clearly knows what they are doing :) ). For the types of mode, I used this page - hopefully one of the choices there will work for you.

How to list records with date from the last 10 days?

My understanding from my testing (and the PostgreSQL dox) is that the quotes need to be done differently from the other answers, and should also include "day" like this:

SELECT Table.date
  FROM Table 
  WHERE date > current_date - interval '10 day';

Demonstrated here (you should be able to run this on any Postgres db):

SELECT DISTINCT current_date, 
                current_date - interval '10' day, 
                current_date - interval '10 days' 
  FROM pg_language;

Result:

2013-03-01  2013-03-01 00:00:00 2013-02-19 00:00:00

Python assigning multiple variables to same value? list behavior

Yes, that's the expected behavior. a, b and c are all set as labels for the same list. If you want three different lists, you need to assign them individually. You can either repeat the explicit list, or use one of the numerous ways to copy a list:

b = a[:] # this does a shallow copy, which is good enough for this case
import copy
c = copy.deepcopy(a) # this does a deep copy, which matters if the list contains mutable objects

Assignment statements in Python do not copy objects - they bind the name to an object, and an object can have as many labels as you set. In your first edit, changing a[0], you're updating one element of the single list that a, b, and c all refer to. In your second, changing e, you're switching e to be a label for a different object (4 instead of 3).

disable editing default value of text input

How about disabled=disabled:

<input id="price_from" value="price from " disabled="disabled">????????????

Problem is if you don't want user to edit them, why display them in input? You can hide them even if you want to submit a form. And to display information, just use other tag instead.

How can I calculate the number of years between two dates?

This one Help you...

     $("[id$=btnSubmit]").click(function () {
        debugger
        var SDate = $("[id$=txtStartDate]").val().split('-');
        var Smonth = SDate[0];
        var Sday = SDate[1];
        var Syear = SDate[2];
        // alert(Syear); alert(Sday); alert(Smonth);
        var EDate = $("[id$=txtEndDate]").val().split('-');
        var Emonth = EDate[0];
        var Eday = EDate[1];
        var Eyear = EDate[2];
        var y = parseInt(Eyear) - parseInt(Syear);
        var m, d;
        if ((parseInt(Emonth) - parseInt(Smonth)) > 0) {
            m = parseInt(Emonth) - parseInt(Smonth);
        }
        else {
            m = parseInt(Emonth) + 12 - parseInt(Smonth);
            y = y - 1;
        }
        if ((parseInt(Eday) - parseInt(Sday)) > 0) {
            d = parseInt(Eday) - parseInt(Sday);
        }
        else {
            d = parseInt(Eday) + 30 - parseInt(Sday);
            m = m - 1;
        }
        // alert(y + " " + m + " " + d);
        $("[id$=lblAge]").text("your age is " + y + "years  " + m + "month  " + d + "days");
        return false;
    });

Javascript Iframe innerHTML

This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
  Function to display frame from another domain 
*/

function displayFrame()
{
  $webUrl = 'http://[external-web-domain.com]/';

  //Get HTML from the URL
  $content = file_get_contents($webUrl);

  //Add custom JS to returned HTML content
  $customJS = "
  <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
    //Hide Navigation bar
    jQuery(\".navbar\").hide();

  </script>";

  //Append Custom JS with HTML
  $html = $content . $customJS;

  //Return customized HTML
  return $html;
}

Python's equivalent of && (logical-and) in an if-statement

I'm getting an error in the IF conditional. What am I doing wrong?

There reason that you get a SyntaxError is that there is no && operator in Python. Likewise || and ! are not valid Python operators.

Some of the operators you may know from other languages have a different name in Python. The logical operators && and || are actually called and and or. Likewise the logical negation operator ! is called not.

So you could just write:

if len(a) % 2 == 0 and len(b) % 2 == 0:

or even:

if not (len(a) % 2 or len(b) % 2):

Some additional information (that might come in handy):

I summarized the operator "equivalents" in this table:

+------------------------------+---------------------+
|  Operator (other languages)  |  Operator (Python)  |
+==============================+=====================+
|              &&              |         and         |
+------------------------------+---------------------+
|              ||              |         or          |
+------------------------------+---------------------+
|              !               |         not         |
+------------------------------+---------------------+

See also Python documentation: 6.11. Boolean operations.

Besides the logical operators Python also has bitwise/binary operators:

+--------------------+--------------------+
|  Logical operator  |  Bitwise operator  |
+====================+====================+
|        and         |         &          |
+--------------------+--------------------+
|         or         |         |          |
+--------------------+--------------------+

There is no bitwise negation in Python (just the bitwise inverse operator ~ - but that is not equivalent to not).

See also 6.6. Unary arithmetic and bitwise/binary operations and 6.7. Binary arithmetic operations.

The logical operators (like in many other languages) have the advantage that these are short-circuited. That means if the first operand already defines the result, then the second operator isn't evaluated at all.

To show this I use a function that simply takes a value, prints it and returns it again. This is handy to see what is actually evaluated because of the print statements:

>>> def print_and_return(value):
...     print(value)
...     return value

>>> res = print_and_return(False) and print_and_return(True)
False

As you can see only one print statement is executed, so Python really didn't even look at the right operand.

This is not the case for the binary operators. Those always evaluate both operands:

>>> res = print_and_return(False) & print_and_return(True);
False
True

But if the first operand isn't enough then, of course, the second operator is evaluated:

>>> res = print_and_return(True) and print_and_return(False);
True
False

To summarize this here is another Table:

+-----------------+-------------------------+
|   Expression    |  Right side evaluated?  |
+=================+=========================+
| `True` and ...  |           Yes           |
+-----------------+-------------------------+
| `False` and ... |           No            |
+-----------------+-------------------------+
|  `True` or ...  |           No            |
+-----------------+-------------------------+
| `False` or ...  |           Yes           |
+-----------------+-------------------------+

The True and False represent what bool(left-hand-side) returns, they don't have to be True or False, they just need to return True or False when bool is called on them (1).

So in Pseudo-Code(!) the and and or functions work like these:

def and(expr1, expr2):
    left = evaluate(expr1)
    if bool(left):
        return evaluate(expr2)
    else:
        return left

def or(expr1, expr2):
    left = evaluate(expr1)
    if bool(left):
        return left
    else:
        return evaluate(expr2)

Note that this is pseudo-code not Python code. In Python you cannot create functions called and or or because these are keywords. Also you should never use "evaluate" or if bool(...).

Customizing the behavior of your own classes

This implicit bool call can be used to customize how your classes behave with and, or and not.

To show how this can be customized I use this class which again prints something to track what is happening:

class Test(object):
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        print('__bool__ called on {!r}'.format(self))
        return bool(self.value)

    __nonzero__ = __bool__  # Python 2 compatibility

    def __repr__(self):
        return "{self.__class__.__name__}({self.value})".format(self=self)

So let's see what happens with that class in combination with these operators:

>>> if Test(True) and Test(False):
...     pass
__bool__ called on Test(True)
__bool__ called on Test(False)

>>> if Test(False) or Test(False):
...     pass
__bool__ called on Test(False)
__bool__ called on Test(False)

>>> if not Test(True):
...     pass
__bool__ called on Test(True)

If you don't have a __bool__ method then Python also checks if the object has a __len__ method and if it returns a value greater than zero. That might be useful to know in case you create a sequence container.

See also 4.1. Truth Value Testing.

NumPy arrays and subclasses

Probably a bit beyond the scope of the original question but in case you're dealing with NumPy arrays or subclasses (like Pandas Series or DataFrames) then the implicit bool call will raise the dreaded ValueError:

>>> import numpy as np
>>> arr = np.array([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> import pandas as pd
>>> s = pd.Series([1,2,3])
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> s and s
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

In these cases you can use the logical and function from NumPy which performs an element-wise and (or or):

>>> np.logical_and(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([False, False,  True, False])
>>> np.logical_or(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([ True, False,  True,  True])

If you're dealing just with boolean arrays you could also use the binary operators with NumPy, these do perform element-wise (but also binary) comparisons:

>>> np.array([False,False,True,True]) & np.array([True, False, True, False])
array([False, False,  True, False])
>>> np.array([False,False,True,True]) | np.array([True, False, True, False])
array([ True, False,  True,  True])

(1)

That the bool call on the operands has to return True or False isn't completely correct. It's just the first operand that needs to return a boolean in it's __bool__ method:

class Test(object):
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        return self.value

    __nonzero__ = __bool__  # Python 2 compatibility

    def __repr__(self):
        return "{self.__class__.__name__}({self.value})".format(self=self)

>>> x = Test(10) and Test(10)
TypeError: __bool__ should return bool, returned int
>>> x1 = Test(True) and Test(10)
>>> x2 = Test(False) and Test(10)

That's because and actually returns the first operand if the first operand evaluates to False and if it evaluates to True then it returns the second operand:

>>> x1
Test(10)
>>> x2
Test(False)

Similarly for or but just the other way around:

>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)

However if you use them in an if statement the if will also implicitly call bool on the result. So these finer points may not be relevant for you.

SSL Error: unable to get local issuer certificate

If you are a linux user Update node to a later version by running

sudo apt update

 sudo apt install build-essential checkinstall libssl-dev

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash

nvm --version

nvm ls

nvm ls-remote

nvm install [version.number]

this should solve your problem

json parsing error syntax error unexpected end of input

For me the issue was due to single quotes for the name/value pair... data: "{'Name':'AA'}"

Once I changed it to double quotes for the name/value pair it works fine... data: '{"Name":"AA"}' or like this... data: "{\"Name\":\"AA\"}"

Convert String to Calendar Object in Java

Simple method:

public Calendar stringToCalendar(String date, String pattern) throws ParseException {
    String DEFAULT_LOCALE_NAME = "pt";
    String DEFAULT_COUNTRY = "BR";
    Locale DEFAULT_LOCALE = new Locale(DEFAULT_LOCALE_NAME, DEFAULT_COUNTRY);
    SimpleDateFormat format = new SimpleDateFormat(pattern, LocaleUtils.DEFAULT_LOCALE);
    Date d = format.parse(date);
    Calendar c = getCalendar();
    c.setTime(d);
    return c;
}

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Hash string in c#

The fastest way, to get a hash string for password store purposes, is a following code:

    internal static string GetStringSha256Hash(string text)
    {
        if (String.IsNullOrEmpty(text))
            return String.Empty;

        using (var sha = new System.Security.Cryptography.SHA256Managed())
        {
            byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] hash = sha.ComputeHash(textData);
            return BitConverter.ToString(hash).Replace("-", String.Empty);
        }
    }

Remarks:

  • if the method is invoked often, the creation of sha variable should be refactored into a class field;
  • output is presented as encoded hex string;

Laravel-5 'LIKE' equivalent (Eloquent)

$data = DB::table('borrowers')
        ->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
        ->select('borrowers.*', 'loans.*')   
        ->where('loan_officers', 'like', '%' . $officerId . '%')
        ->where('loans.maturity_date', '<', date("Y-m-d"))
        ->get();

What do the different readystates in XMLHttpRequest mean, and how can I use them?

onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:

0: request not initialized

1: server connection established

2: request received

3: processing request

4: request finished and response is ready

status 200: "OK"

404: Page not found

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

The process of generating Entity-Relationship diagram in Oracle SQL Developer has been described in Oracle Magazine by Jeff Smith (link).

Excerpt:

Entity relationship diagram

Entity relationship diagram

Getting Started

To work through the example, you need an Oracle Database instance with the sample HR schema that’s available in the default database installation. You also need version 4.0 of Oracle SQL Developer, in which you access Oracle SQL Developer Data Modeler through the Data Modeler submenu [...] Alternatively, you can use the standalone Oracle SQL Developer Data Modeler. The modeling functionality is identical in the two implementations, and both are available as free downloads from Oracle Technology Network.

In Oracle SQL Developer, select View -> Data Modeler –> Browser. In the Browser panel, select the Relational Models node, right-click, and select New Relational Model to open a blank model diagram panel. You’re now starting at the same place as someone who’s using the standalone Oracle SQL Developer Data Modeler. Importing Your Data Dictionary

Importing Your Data Dictionary

A design in Oracle SQL Developer Data Modeler consists of one logical model and one or more relational and physical models. To begin the process of creating your design, you must import the schema information from your existing database. Select File -> Data Modeler -> Import -> Data Dictionary to open the Data Dictionary Import wizard.

Click Add to open the New -> Select Database Connection dialog box, and connect as the HR user. (For detailed information on creating a connection from Oracle SQL Developer, see “Making Database Connections,” in the May/June 2008 issue of Oracle Magazine.)

Select your connection, and click Next. You see a list of schemas from which you can import. Type HR in the Filter box to narrow the selection list. Select the checkbox next to HR, and click Next.

Read more...

How to get the latest record in each group using GROUP BY?

You need to order them.

SELECT * FROM messages GROUP BY from_id ORDER BY timestamp DESC LIMIT 1

Gaussian fit for Python

After losing hours trying to find my error, the problem is your formula:

sigma = sum(y*(x-mean)**2)/n

This previous formula is wrong, the correct formula is the square root of this!;

sqrt(sum(y*(x-mean)**2)/n)

Hope this helps

How to redirect back to form with input - Laravel 5

You can use the following:

return Redirect::back()->withInput(Input::all());

If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.

Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests:

return redirect()->to($this->getRedirectUrl())
                    ->withInput($request->input())
                    ->withErrors($errors, $this->errorBag());

Comments in .gitignore?

Do git help gitignore

You will get the help page with following line:

A line starting with # serves as a comment.

how to get the last character of a string?

var firstName = "Ada";
var lastLetterOfFirstName = firstName[firstName.length - 1];

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

Please find the actual css from Bootstrap

.container-fluid {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}
.row {
  margin-right: -15px;
  margin-left: -15px;
}

When you add a .container-fluid class, it adds a horizontal padding of 15px, and the same will be removed when you add a .row class as a child element by the negative margin set on row.

How to load all modules in a folder?

I got tired of this problem myself, so I wrote a package called automodinit to fix it. You can get it from http://pypi.python.org/pypi/automodinit/.

Usage is like this:

  1. Include the automodinit package into your setup.py dependencies.
  2. Replace all __init__.py files like this:
__all__ = ["I will get rewritten"]
# Don't modify the line above, or this line!
import automodinit
automodinit.automodinit(__name__, __file__, globals())
del automodinit
# Anything else you want can go after here, it won't get modified.

That's it! From now on importing a module will set __all__ to a list of .py[co] files in the module and will also import each of those files as though you had typed:

for x in __all__: import x

Therefore the effect of "from M import *" matches exactly "import M".

automodinit is happy running from inside ZIP archives and is therefore ZIP safe.

Niall

Start thread with member function

Some users have already given their answer and explained it very well.

I would like to add few more things related to thread.

  1. How to work with functor and thread. Please refer to below example.

  2. The thread will make its own copy of the object while passing the object.

    #include<thread>
    #include<Windows.h>
    #include<iostream>
    
    using namespace std;
    
    class CB
    {
    
    public:
        CB()
        {
            cout << "this=" << this << endl;
        }
        void operator()();
    };
    
    void CB::operator()()
    {
        cout << "this=" << this << endl;
        for (int i = 0; i < 5; i++)
        {
            cout << "CB()=" << i << endl;
            Sleep(1000);
        }
    }
    
    void main()
    {
        CB obj;     // please note the address of obj.
    
        thread t(obj); // here obj will be passed by value 
                       //i.e. thread will make it own local copy of it.
                        // we can confirm it by matching the address of
                        //object printed in the constructor
                        // and address of the obj printed in the function
    
        t.join();
    }
    

Another way of achieving the same thing is like:

void main()
{
    thread t((CB()));

    t.join();
}

But if you want to pass the object by reference then use the below syntax:

void main()
{
    CB obj;
    //thread t(obj);
    thread t(std::ref(obj));
    t.join();
}

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

On bulk, you can always delete the row before the insert. A deletion of a row that doesn't exist doesn't cause an error, so its safely skipped.

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

Return char[]/string from a function

char* charP = createStr();

Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.

Difference between dict.clear() and assigning {} in Python

d = {} will create a new instance for d but all other references will still point to the old contents. d.clear() will reset the contents, but all references to the same instance will still be correct.

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

Be very wary of setting IDENTITY_INSERT to ON. This is a poor practice unless the database is in maintenance mode and set to single user. This affects not only your insert, but those of anyone else trying to access the table.

Why are you trying to put a value into an identity field?

How to convert an Array to a Set in Java

For anyone solving for Android:

Kotlin Collections Solution

The asterisk * is the spread operator. It applies all elements in a collection individually, each passed in order to a vararg method parameter. It is equivalent to:

val myArray = arrayOf("data", "foo")
val mySet = setOf(*myArray)

// Equivalent to
val mySet = setOf("data", "foo")

// Multiple spreads ["data", "foo", "bar", "data", "foo"]
val mySet = setOf(*myArray, "bar", *myArray)

Passing no parameters setOf() results in an empty set.

In addition to setOf, you can also use any of these for a specific hash type:

hashSetOf()
linkedSetOf()
mutableSetOf()
sortableSetOf()

This is how to define the collection item type explicitly.

setOf<String>()
hashSetOf<MyClass>()

How to get all values from python enum class?

This is basically available in a 'protected' attribute of the Enum class:

list(Color._value2member_map_.keys())

find vs find_by vs where

Suppose I have a model User

  1. User.find(id)

Returns a row where primary key = id. The return type will be User object.

  1. User.find_by(email:"[email protected]")

Returns first row with matching attribute or email in this case. Return type will be User object again.

Note :- User.find_by(email: "[email protected]") is similar to User.find_by_email("[email protected]")

  1. User.where(project_id:1)

Returns all users in users table where attribute matches.

Here return type will be ActiveRecord::Relation object. ActiveRecord::Relation class includes Ruby's Enumerable module so you can use it's object like an array and traverse on it.

Job for mysqld.service failed See "systemctl status mysqld.service"

I was also facing same issue .

root@*******:/root >mysql -uroot -password

mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

I found ROOT FS was also full and then I killed below lock session . 
root@**********:/var/lib/mysql >ls -ltr
total 0
-rw------- 1 mysql mysql 0 Sep  9 06:41 mysql.sock.lock

Finally Issue solved .

Java: Identifier expected

Try it like this instead, move your myclass items inside a main method:

    class UserInput {
      public void name() {
        System.out.println("This is a test.");
      }
    }

    public class MyClass {

        public static void main( String args[] )
        {
            UserInput input = new UserInput();
            input.name();
        }

    }

I'm getting Key error in python

A KeyError generally means the key doesn't exist. So, are you sure the path key exists?

From the official python docs:

exception KeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.

For example:

>>> mydict = {'a':'1','b':'2'}
>>> mydict['a']
'1'
>>> mydict['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'
>>>

So, try to print the content of meta_entry and check whether path exists or not.

>>> mydict = {'a':'1','b':'2'}
>>> print mydict
{'a': '1', 'b': '2'}

Or, you can do:

>>> 'a' in mydict
True
>>> 'c' in mydict
False

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

You are allowed to use IDs that start with a digit in your HTML5 documents:

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

But querySelector method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Use a value like b22 for the ID attribute and your code will work.

Since you want to select an element by ID you can also use .getElementById method:

document.getElementById('22')

ASP.NET MVC Html.DropDownList SelectedValue

I managed to get the desired result, but with a slightly different approach. In the Dropdownlist i used the Model and then referenced it. Not sure if this was what you were looking for.

@Html.DropDownList("Example", new SelectList(Model.FeeStructures, "Id", "NameOfFeeStructure", Model.Matters.FeeStructures))

Model.Matters.FeeStructures in above is my id, which could be your value of the item that should be selected.

React onClick function fires on render

Because you are calling that function instead of passing the function to onClick, change that line to this:

<button type="submit" onClick={() => { this.props.removeTaskFunction(todo) }}>Submit</button>

=> called Arrow Function, which was introduced in ES6, and will be supported on React 0.13.3 or upper.

What is a .NET developer?

Generally what's meant by that is a fairly intimate familiarity with one (or probably more) of the .NET languages (C#, VB.NET, etc.) and one (or less probably more) of the .NET stacks (WinForms, ASP.NET, WPF, etc.).

As for a specific "formal definition", I don't think you'll find one beyond that. The job description should be specific about what they're looking for. I wouldn't consider a job listing that asks for a ".NET developer" and provides no more detail than that to be sufficiently descriptive.

MySQL Job failed to start

In my case the problem was the /var/log disk full (check with df -h)

Just deleted some log files and mysql started, no big deal!

Execute curl command within a Python script

You can use below code snippet

import shlex
import subprocess
import json

def call_curl(curl):
    args = shlex.split(curl)
    process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    return json.loads(stdout.decode('utf-8'))


if __name__ == '__main__':
    curl = '''curl - X
    POST - d
    '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
    http: // localhost: 8080 / firewall / rules / 0000000000000001 '''
    output = call_curl(curl)
    print(output)

Datatables on-the-fly resizing

I had the same challenge. When I collapsed some menus I had on the left of my web app, the datatable would not resize. Adding "autoWidth": false duirng initialization worked for me.

$('#dataTable').DataTable({'autoWidth':false, ...});

CSS position absolute full width problem

I have similar situation. In my case, it doesn't have a parent with position:relative. Just paste my solution here for those that might need.

position: fixed;
left: 0;
right: 0;

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Same-origin policy

You can't access an <iframe> with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

Origin is considered different if at least one of the following parts of the address isn't maintained:

protocol://hostname:port/...

Protocol, hostname and port must be the same of your domain if you want to access a frame.

NOTE: Internet Explorer is known to not strictly follow this rule, see here for details.

Examples

Here's what would happen trying to access the following URLs from http://www.example.com/home/index.html

URL                                             RESULT 
http://www.example.com/home/other.html       -> Success 
http://www.example.com/dir/inner/another.php -> Success 
http://www.example.com:80                    -> Success (default port for HTTP) 
http://www.example.com:2251                  -> Failure: different port 
http://data.example.com/dir/other.html       -> Failure: different hostname 
https://www.example.com/home/index.html:80   -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port 
https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname 

Workaround

Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using window.postMessage and its relative message event to send messages between the two pages, like this:

  • In your main page:

    const frame = document.getElementById('your-frame-id');
    frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
    

    The second argument to postMessage() can be '*' to indicate no preference about the origin of the destination. A target origin should always be provided when possible, to avoid disclosing the data you send to any other site.

  • In your <iframe> (contained in the main page):

    window.addEventListener('message', event => {
        // IMPORTANT: check the origin of the data! 
        if (event.origin.startsWith('http://your-first-site.com')) { 
            // The data was sent from your site.
            // Data sent with postMessage is stored in event.data:
            console.log(event.data); 
        } else {
            // The data was NOT sent from your site! 
            // Be careful! Do not use it. This else branch is
            // here just for clarity, you usually shouldn't need it.
            return; 
        } 
    }); 
    

This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.

Disabling same-origin policy in your browser

There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should NEVER be done if you do not know exactly what you are doing (e.g. development purposes).

c# open file with default application and parameters

Please add Settings under Properties for the Project and make use of them this way you have clean and easy configurable settings that can be configured as default

How To: Create a New Setting at Design Time

Update: after comments below

  1. Right + Click on project
  2. Add New Item
  3. Under Visual C# Items -> General
  4. Select Settings File

How to check whether input value is integer or float?

You can use Scanner Class to find whether a given number could be read as Int or Float type.

 import java.util.Scanner;
 public class Test {
     public static void main(String args[] ) throws Exception {

     Scanner sc=new Scanner(System.in);

     if(sc.hasNextInt())
         System.out.println("This input is  of type Integer");
     else if(sc.hasNextFloat())
         System.out.println("This input is  of type Float");
     else
         System.out.println("This is something else");
     }
}

How to force maven update?

If you're unsure what is inside your local repository, I recommend to fire a build with the option:

-Dmaven.repo.local=localrepo

That way you'll ensure to build in a cleanroom environment.

Difference between private, public, and protected inheritance

Private:

The private members of a base class can only be accessed by members of that base class .

Public:

The public members of a base class can be accessed by members of that base class, members of its derived class as well as the members which are outside the base class and derived class.

Protected:

The protected members of a base class can be accessed by members of base class as well as members of its derived class.


In short:

private: base

protected: base + derived

public: base + derived + any other member

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

If there is other content not being shown inside the outer-div (the green box), why not have that content wrapped inside another div, let's call it "content". Have overflow hidden on this new inner-div, but keep overflow visible on the green box.

The only catch is that you will then have to mess around to make sure that the content div doesn't interfere with the positioning of the red box, but it sounds like you should be able to fix that with little headache.

<div id="1" background: #efe; padding: 5px; width: 125px">
    <div id="content" style="overflow: hidden;">
    </div>
    <div id="2" style="position: relative; background: #fee; padding: 2px; width: 100px; height: 100px">
        <div id="3" style="position: absolute; top: 10px; background: #eef; padding: 2px; width: 75px; height: 150px"/>
    </div>
</div>

CSS: Background image and padding

You can achieve your results with two methods:-

First Method define position values:-

HTML

 <ul>
 <li>Hello</li>
 <li>Hello world</li>
 </ul>

CSS

    ul{
    width:100px;    
}

ul li{
    border:1px solid orange;
    background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat 90% 5px;
}


ul li:hover{
    background: yellow url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat 90% 5px;
}

First Demo:- http://jsfiddle.net/QeGAd/18/

Second Method by CSS :before:after Selectors

HTML

<ul>
<li>Hello</li>
<li>Hello world</li>

CSS

    ul{
    width:100px;    
}

ul li{
    border:1px solid orange;
}

ul li:after {
    content: " ";
    padding-right: 16px;
    background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat center right;
}

ul li:hover {
    background:yellow;
}

ul li:hover:after {
    content: " ";
    padding-right: 16px;
    background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat center right;
}

Second Demo:- http://jsfiddle.net/QeGAd/17/

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

check the speling and Upper/Lower case of term ""

when ever we write @RenderSection("name", required: false) make sure that the razor view Contains a section @section name{} so check the speling and Upper/Lower case of term "" Correct in this case is "Scripts"

Xcode 6 Storyboard the wrong size?

Go to Attributes Inspector(right top corner) In the Simulated Metrics, which has Size, Orientation, Status Bar, Top Bar, Bottom Bar properties. For SIZE, change Inferred --> Freeform.

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

jQuery remove special characters from string and more

this will remove all the special character

 str.replace(/[_\W]+/g, "");

this is really helpful and solve my issue. Please run the below code and ensure it works

_x000D_
_x000D_
var str="hello world !#to&you%*()";_x000D_
console.log(str.replace(/[_\W]+/g, ""));
_x000D_
_x000D_
_x000D_

Java/Groovy - simple date reformatting

Your DateFormat pattern does not match you input date String. You could use

new SimpleDateFormat("dd-MMM-yyyy")

How to use the 'main' parameter in package.json?

Just think of it as the "starting point".

In a sense of object-oriented programming, say C#, it's the init() or constructor of the object class, that's what "entry point" meant.

For example

public class IamMain  // when export and require this guy
{
    public IamMain()  // this is "main"
    {...}

    ...   // many others such as function, properties, etc.
}

What is the size of column of int(11) in mysql in bytes?

4294967295 is the answer, because int(11) shows maximum of 11 digits IMO

Error message: "'chromedriver' executable needs to be available in the path"

The best way is maybe to get the current directory and append the remaining address to it. Like this code(Word on windows. On linux you can use something line pwd): webdriveraddress = str(os.popen("cd").read().replace("\n", ''))+'\path\to\webdriver'

Selecting all text in HTML text input when clicked

I was looking for a CSS-only solution and found this works for iOS browsers (tested safari and chrome).

It does not have the same behavior on desktop chrome, but the pain of selecting is not as great there because you have a lot more options as a user (double-click, ctrl-a, etc):

.select-all-on-touch {
    -webkit-user-select: all;
    user-select: all;
}

What is the difference between ng-if and ng-show/ng-hide

Fact, that ng-if directive, unlike ng-show, creates its own scope, leads to interesting practical difference:

_x000D_
_x000D_
angular.module('app', []).controller('ctrl', function($scope){_x000D_
  $scope.delete = function(array, item){_x000D_
    array.splice(array.indexOf(item), 1);_x000D_
  }_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app='app' ng-controller='ctrl'>_x000D_
   <h4>ng-if:</h4>_x000D_
   <ul ng-init='arr1 = [1,2,3]'>_x000D_
      <li ng-repeat='x in arr1'>_x000D_
        {{show}}_x000D_
        <button ng-if='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
        <button ng-if='show' ng-click='delete(arr1, x)'>Yes {{show}}</button>_x000D_
        <button ng-if='show' ng-click='show=!show'>No</button>_x000D_
      </li>_x000D_
   </ul>_x000D_
   _x000D_
   <h4>ng-show:</h4>_x000D_
   <ul ng-init='arr2 = [1,2,3]'>_x000D_
      <li ng-repeat='x in arr2'>_x000D_
        {{show}}_x000D_
        <button ng-show='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
        <button ng-show='show' ng-click='delete(arr2, x)'>Yes {{show}}</button>_x000D_
        <button ng-show='show' ng-click='show=!show'>No</button>_x000D_
      </li>_x000D_
   </ul>_x000D_
   _x000D_
   <h4>ng-if with $parent:</h4>_x000D_
    <ul ng-init='arr3 = [1,2,3]'>_x000D_
      <li ng-repeat='item in arr3'>_x000D_
        {{show}}_x000D_
        <button ng-if='!show' ng-click='$parent.show=!$parent.show'>Delete {{$parent.show}}</button>_x000D_
        <button ng-if='show' ng-click='delete(arr3, x)'>Yes {{$parent.show}}</button>_x000D_
        <button ng-if='show' ng-click='$parent.show=!$parent.show'>No</button>_x000D_
      </li>_x000D_
   </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

At first list, on-click event, show variable, from innner/own scope, is changed, but ng-if is watching on another variable from outer scope with same name, so solution not works. At case of ng-show we have the only one show variable, that is why it works. To fix first attempt, we should reference to show from parent/outer scope via $parent.show.

What's the difference between isset() and array_key_exists()?

The two are not exactly the same. I couldn't remember the exact differences, but they are outlined very well in What's quicker and better to determine if an array key exists in PHP?.

The common consensus seems to be to use isset whenever possible, because it is a language construct and therefore faster. However, the differences should be outlined above.

'setInterval' vs 'setTimeout'

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

Example:

var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.

setTimeout(alert, 1000); // Will alert once, after a second.

Eclipse count lines of code

If on OSX or *NIX use

Get all actual lines of java code from *.java files

find . -name "*.java" -exec grep "[a-zA-Z0-9{}]" {} \; | wc -l

Get all lines from the *.java files, which includes empty lines and comments

find . -name "*.java" -exec cat | wc -l

Get information per File, this will give you [ path to file + "," + number of lines ]

find . -name "*.java" -exec wc -l {} \;

What do column flags mean in MySQL Workbench?

PK - Primary Key

NN - Not Null

BIN - Binary (stores data as binary strings. There is no character set so sorting and comparison is based on the numeric values of the bytes in the values.)

UN - Unsigned (non-negative numbers only. so if the range is -500 to 500, instead its 0 - 1000, the range is the same but it starts at 0)

UQ - Create/remove Unique Key

ZF - Zero-Filled (if the length is 5 like INT(5) then every field is filled with 0’s to the 5th digit. 12 = 00012, 400 = 00400, etc. )

AI - Auto Increment

G - Generated column. i.e. value generated by a formula based on the other columns

How do I find ' % ' with the LIKE operator in SQL Server?

You can use ESCAPE:

WHERE columnName LIKE '%\%%' ESCAPE '\'

Upgrading Node.js to latest version

Install npm =>

sudo apt-get install npm

Install n =>

sudo npm install n -g

latest version of node =>

sudo n latest 

So latest version will be downloaded and installed

Specific version of node you can

List available node versions =>

n ls

Install a specific version =>

sudo n 4.5.0

Is it worth using Python's re.compile?

i'd like to motivate that pre-compiling is both conceptually and 'literately' (as in 'literate programming') advantageous. have a look at this code snippet:

from re import compile as _Re

class TYPO:

  def text_has_foobar( self, text ):
    return self._text_has_foobar_re_search( text ) is not None
  _text_has_foobar_re_search = _Re( r"""(?i)foobar""" ).search

TYPO = TYPO()

in your application, you'd write:

from TYPO import TYPO
print( TYPO.text_has_foobar( 'FOObar ) )

this is about as simple in terms of functionality as it can get. because this is example is so short, i conflated the way to get _text_has_foobar_re_search all in one line. the disadvantage of this code is that it occupies a little memory for whatever the lifetime of the TYPO library object is; the advantage is that when doing a foobar search, you'll get away with two function calls and two class dictionary lookups. how many regexes are cached by re and the overhead of that cache are irrelevant here.

compare this with the more usual style, below:

import re

class Typo:

  def text_has_foobar( self, text ):
    return re.compile( r"""(?i)foobar""" ).search( text ) is not None

In the application:

typo = Typo()
print( typo.text_has_foobar( 'FOObar ) )

I readily admit that my style is highly unusual for python, maybe even debatable. however, in the example that more closely matches how python is mostly used, in order to do a single match, we must instantiate an object, do three instance dictionary lookups, and perform three function calls; additionally, we might get into re caching troubles when using more than 100 regexes. also, the regular expression gets hidden inside the method body, which most of the time is not such a good idea.

be it said that every subset of measures---targeted, aliased import statements; aliased methods where applicable; reduction of function calls and object dictionary lookups---can help reduce computational and conceptual complexity.

IntelliJ: Never use wildcard imports

Like a dum-dum I couldn't figure out why none of these answers were working for my Kotlin files for java.util.*, so if this is happening to you then:

Preferences
> Editor
> Code Style
> **Kotlin**
> Imports
> Packages to Use Import with '*'
-> Remove 'java.util.*'

In Java, can you modify a List while iterating through it?

There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

How to set an button align-right with Bootstrap?

This worked for me:

<div class="text-right">
    <button type="button">Button 1</button>
    <button type="button">Button 2</button>
</div>

How to get file name from file path in android

We can find file name below code:

File file =new File(Path);
String filename=file.getName();

How to check if iframe is loaded or it has a content?

I got a trick working as follows: [have not tested cross-browser!]

Define iframe's onload event handler defined as

_x000D_
_x000D_
$('#myIframe').on('load', function() {_x000D_
    setTimeout(function() {_x000D_
        try {_x000D_
            console.log($('#myIframe')[0].contentWindow.document);_x000D_
        } catch (e) {_x000D_
            console.log(e);_x000D_
            if (e.message.indexOf('Blocked a frame with origin') > -1 || e.message.indexOf('from accessing a cross-origin frame.') > -1) {_x000D_
                alert('Same origin Iframe error found!!!');_x000D_
                //Do fallback handling if you want here_x000D_
            }_x000D_
        }_x000D_
    }, 1000);_x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

Disclaimer: It works only for SAME ORIGIN IFRAME documents.

Filtering Table rows using Jquery

tr:not(:contains(.... work for me

function busca(busca){
    $("#listagem tr:not(:contains('"+busca+"'))").css("display", "none");
    $("#listagem tr:contains('"+busca+"')").css("display", "");
}

SQL Server 2005 Using CHARINDEX() To split a string

Create FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(200), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(10) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 

END**strong text**

Which HTML Parser is the best?

The best I've seen so far is HtmlCleaner:

HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.

With HtmlCleaner you can locate any element using XPath.

For other html parsers see this SO question.

Image inside div has extra space below the image

By default, an image is rendered inline, like a letter so it sits on the same line that a, b, c and d sit on.

There is space below that line for the descenders you find on letters like g, j, p and q.

Demonstration of descenders

You can:

  • adjust the vertical-align of the image to position it elsewhere (e.g. the middle) or
  • change the display so it isn't inline.

_x000D_
_x000D_
div {_x000D_
  border: solid black 1px;_x000D_
  margin-bottom: 10px;_x000D_
}_x000D_
_x000D_
#align-middle img {_x000D_
  vertical-align: middle;_x000D_
}_x000D_
_x000D_
#align-base img {_x000D_
  vertical-align: bottom;_x000D_
}_x000D_
_x000D_
#display img {_x000D_
  display: block;_x000D_
}
_x000D_
<div id="default">_x000D_
<h1>Default</h1>_x000D_
  The quick brown fox jumps over the lazy dog <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt="">_x000D_
</div>_x000D_
_x000D_
<div id="align-middle">_x000D_
<h1>vertical-align: middle</h1>_x000D_
  The quick brown fox jumps over the lazy dog <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt=""> </div>_x000D_
  _x000D_
  <div id="align-base">_x000D_
<h1>vertical-align: bottom</h1>_x000D_
  The quick brown fox jumps over the lazy dog <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt=""> </div>_x000D_
_x000D_
<div id="display">_x000D_
<h1>display: block</h1>_x000D_
  The quick brown fox jumps over the lazy dog <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt="">_x000D_
</div>
_x000D_
_x000D_
_x000D_


The included image is public domain and sourced from Wikimedia Commons

Java HTTP Client Request with defined timeout

This was already mentioned in a comment by benvoliot above. But, I think it's worth a top-level post because it sure had me scratching my head. I'm posting this in case it helps someone else out.

I wrote a simple test client and the CoreConnectionPNames.CONNECTION_TIMEOUT timeout works perfectly in that case. The request gets canceled if the server doesn't respond.

Inside the server code I was actually trying to test however, the identical code never times out.

Changing it to time out on the socket connection activity (CoreConnectionPNames.SO_TIMEOUT) rather than the HTTP connection (CoreConnectionPNames.CONNECTION_TIMEOUT) fixed the problem for me.

Also, read the Apache docs carefully: http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/params/CoreConnectionPNames.html#CONNECTION_TIMEOUT

Note the bit that says

Please note this parameter can only be applied to connections that are bound to a particular local address.

I hope that saves someone else all the head scratching I went through. That will teach me not to read the documentation thoroughly!

hasOwnProperty in JavaScript

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

Make the image go behind the text and keep it in center using CSS

Well, put your image in the background of your website/container and put whatever you want on top of that.

Your container defined in HTML:

<div id="container">
   <input name="box" type="textbox" />
   <input name="box" type="textbox" />
   <input name="submit" type="submit" />
</div>

Your CSS would look like this:

#container {
    background-image:url(yourimage.jpg);
    background-position:center;
    width:700px;
    height:400px;
}

For this to work though, you must have height and width specified to certain values (i.e. no percentages). I could help you more specifically if you wanted, but I'd need more info.

Changing git commit message after push (given that no one pulled from remote)

Command 1.

git commit --amend -m "New and correct message"

Then,

Command 2.

git push origin --force

How to exit from the application and show the home screen?

If you want to end an activity you can simply call finish(). It is however bad practice to have an exit button on the screen.

Squaring all elements in a list

def square(a):
    squares = []
    for i in a:
        squares.append(i**2)
    return squares

so how would i do the square of numbers from 1-20 using the above function

How to display a readable array - Laravel

You can use var_dump or print_r functions on Blade themplate via Controller functions :

class myController{

   public function showView(){
     return view('myView',["myController"=>$this]);
   }
   public function myprint($obj){
     echo "<pre>";
     print_r($obj);
     echo "</pre>";
   }
}

And use your blade themplate :

$myController->myprint($users);

How to calculate time elapsed in bash script?

Following on from Daniel Kamil Kozar's answer, to show hours/minutes/seconds:

echo "Duration: $(($DIFF / 3600 )) hours $((($DIFF % 3600) / 60)) minutes $(($DIFF % 60)) seconds"

So the full script would be:

date1=$(date +"%s")
date2=$(date +"%s")
DIFF=$(($date2-$date1))
echo "Duration: $(($DIFF / 3600 )) hours $((($DIFF % 3600) / 60)) minutes $(($DIFF % 60)) seconds"

How to create a label inside an <input> element?

If you're using HTML5, you can use the placeholder attribute.

<input type="text" name="user" placeholder="Username">

Is generator.next() visible in Python 3?

If your code must run under Python2 and Python3, use the 2to3 six library like this:

import six

six.next(g)  # on PY2K: 'g.next()' and onPY3K: 'next(g)'

What is the difference between bottom-up and top-down?

Dynamic programming problems can be solved using either bottom-up or top-down approaches.

Generally, the bottom-up approach uses the tabulation technique, while the top-down approach uses the recursion (with memorization) technique.

But you can also have bottom-up and top-down approaches using recursion as shown below.

Bottom-Up: Start with the base condition and pass the value calculated until now recursively. Generally, these are tail recursions.

int n = 5;
fibBottomUp(1, 1, 2, n);

private int fibBottomUp(int i, int j, int count, int n) {
    if (count > n) return 1;
    if (count == n) return i + j;
    return fibBottomUp(j, i + j, count + 1, n);
}

Top-Down: Start with the final condition and recursively get the result of its sub-problems.

int n = 5;
fibTopDown(n);

private int fibTopDown(int n) {
    if (n <= 1) return 1;
    return fibTopDown(n - 1) + fibTopDown(n - 2);
}

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

easy replace

sed -i 's/utf8mb4_unicode_520_ci/utf8mb4_unicode_ci/g' your_sql_file.sql

Getting data posted in between two dates

This worked for me:

$this->db->where('RecordDate >=', '2018-08-17 00:00:00');
$this->db->where('RecordDate <=', '2018-10-04 05:32:56');

Android: How to get a custom View's height and width?

I was also lost around getMeasuredWidth() and getMeasuredHeight() getHeight() and getWidth() for a long time.......... later i found onSizeChanged() method to be REALLY helpful.

New Blog Post: how to get width and height dimensions of a customView (extends View) in Android http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html

Map HTML to JSON

I just wrote this function that does what you want; try it out let me know if it doesn't work correctly for you:

// Test with an element.
var initElement = document.getElementsByTagName("html")[0];
var json = mapDOM(initElement, true);
console.log(json);

// Test with a string.
initElement = "<div><span>text</span>Text2</div>";
json = mapDOM(initElement, true);
console.log(json);

function mapDOM(element, json) {
    var treeObject = {};
    
    // If string convert to document Node
    if (typeof element === "string") {
        if (window.DOMParser) {
              parser = new DOMParser();
              docNode = parser.parseFromString(element,"text/xml");
        } else { // Microsoft strikes again
              docNode = new ActiveXObject("Microsoft.XMLDOM");
              docNode.async = false;
              docNode.loadXML(element); 
        } 
        element = docNode.firstChild;
    }
    
    //Recursively loop through DOM elements and assign properties to object
    function treeHTML(element, object) {
        object["type"] = element.nodeName;
        var nodeList = element.childNodes;
        if (nodeList != null) {
            if (nodeList.length) {
                object["content"] = [];
                for (var i = 0; i < nodeList.length; i++) {
                    if (nodeList[i].nodeType == 3) {
                        object["content"].push(nodeList[i].nodeValue);
                    } else {
                        object["content"].push({});
                        treeHTML(nodeList[i], object["content"][object["content"].length -1]);
                    }
                }
            }
        }
        if (element.attributes != null) {
            if (element.attributes.length) {
                object["attributes"] = {};
                for (var i = 0; i < element.attributes.length; i++) {
                    object["attributes"][element.attributes[i].nodeName] = element.attributes[i].nodeValue;
                }
            }
        }
    }
    treeHTML(element, treeObject);
    
    return (json) ? JSON.stringify(treeObject) : treeObject;
}

Working example: http://jsfiddle.net/JUSsf/ (Tested in Chrome, I can't guarantee full browser support - you will have to test this).

?It creates an object that contains the tree structure of the HTML page in the format you requested and then uses JSON.stringify() which is included in most modern browsers (IE8+, Firefox 3+ .etc); If you need to support older browsers you can include json2.js.

It can take either a DOM element or a string containing valid XHTML as an argument (I believe, I'm not sure whether the DOMParser() will choke in certain situations as it is set to "text/xml" or whether it just doesn't provide error handling. Unfortunately "text/html" has poor browser support).

You can easily change the range of this function by passing a different value as element. Whatever value you pass will be the root of your JSON map.

How to create a bash script to check the SSH connection?

You can check this with the return-value ssh gives you:

$ ssh -q user@downhost exit
$ echo $?
255

$ ssh -q user@uphost exit
$ echo $?
0

EDIT: Another approach would be to use nmap (you won't need to have keys or login-stuff):

$ a=`nmap uphost -PN -p ssh | grep open`
$ b=`nmap downhost -PN -p ssh | grep open`

$ echo $a
22/tcp open ssh
$ echo $b
(empty string)

But you'll have to grep the message (nmap does not use the return-value to show if a port was filtered, closed or open).

EDIT2:

If you're interested in the actual state of the ssh-port, you can substitute grep open with egrep 'open|closed|filtered':

$ nmap host -PN -p ssh | egrep 'open|closed|filtered'

Just to be complete.

What do "branch", "tag" and "trunk" mean in Subversion repositories?

Trunk : After the completion of every sprint in agile we come out with a partially shippable product. These releases are kept in trunk.

Branches : All parallel developments codes for each ongoing sprint are kept in branches.

Tags : Every time we release a partially shippable product kind of beta version, we make a tag for it. This gives us the code that was available at that point of time, allowing us to go back at that state if required at some point during development.

Search for a particular string in Oracle clob column

ok, you may use substr in correlation to instr to find the starting position of your string

select 
  dbms_lob.substr(
       product_details, 
       length('NEW.PRODUCT_NO'), --amount
       dbms_lob.instr(product_details,'NEW.PRODUCT_NO') --offset
       ) 
from my_table
where dbms_lob.instr(product_details,'NEW.PRODUCT_NO')>=1;

Is there a code obfuscator for PHP?

Using SourceGuardian is good as it comes with a cool and easy to use GUI.

But be aware:

Pay attention to its -rather funny- licensing terms.

  • You are only allowed to run 1 per machine -so far this is acceptable
  • If you want to run the command line interface on another machine, say your web server, YOU WILL NEED ANOTHER LICENSE (Yes, it's funny and I can hear you laughing too).

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

The one solution that worked on Win 10 flawlessly.

import matplotlib.pyplot as plt

plt.plot(x_data, y_data)

mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.show()

Creating for loop until list.length

The answer depends on what do you need a loop for.

of course you can have a loop similar to Java:

for i in xrange(len(my_list)):

but I never actually used loops like this,

because usually you want to iterate

for obj in my_list

or if you need an index as well

for index, obj in enumerate(my_list)

or you want to produce another collection from a list

map(some_func, my_list)

[somefunc[x] for x in my_list]

also there are itertools module that covers most of iteration related cases

also please take a look at the builtins like any, max, min, all, enumerate

I would say - do not try to write Java-like code in python. There is always a pythonic way to do it.

what does "dead beef" mean?

It is also used for debugging purposes.

Here is a handy list of some of these values:

http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_debug_values

Should C# or C++ be chosen for learning Games Programming (consoles)?

Its always a hard one to say because they were using assembly up until 1993, NBA Jam if anyone remembers that bad boy. Technology is constantly trending so its very difficult to say where it will go, I would recommend learning C and getting a very firm grasp on that then move onto C++. I will say this as a caution if you enjoy playing games you will not enjoy coding games.

How to export data from Excel spreadsheet to Sql Server 2008 table

There are several tools which can import Excel to SQL Server.

I am using DbTransfer (http://www.dbtransfer.com/Products/DbTransfer) to do the job. It's primarily focused on transfering data between databases and excel, xml, etc...

I have tried the openrowset method and the SQL Server Import / Export Assitant before. But I found these methods to be unnecessary complicated and error prone in constrast to doing it with one of the available dedicated tools.

Get value of multiselect box using jQuery or pure JS

According to the widget's page, it should be:

var myDropDownListValues = $("#myDropDownList").multiselect("getChecked").map(function()
{
    return this.value;    
}).get();

It works for me :)

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

None of the solutions here and elsewhere worked for me. Turns out an incompatible 32bit version of mysqlclient is being installed on my 64bit Windows 10 OS because I'm using a 32bit version of Python

I had to uninstall my current Python 3.7 32bit, and reinstalled Python 3.7 64bit and everything is working fine now

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.

The HttpSession#setMaxInactiveInterval() doesn't change much here by the way. It does exactly the same as <session-timeout> in web.xml, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static method).


To play around and experience this yourself, try to set <session-timeout> to 1 minute and create a HttpSessionListener like follows:

@WebListener
public class HttpSessionChecker implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
    }

}

(if you're not on Servlet 3.0 yet and thus can't use @WebListener, then register in web.xml as follows):

<listener>
    <listener-class>com.example.HttpSessionChecker</listener-class>
</listener>

Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.

See also:

Console.WriteLine and generic List

new List<int> { 1, 3, 5 }.ForEach(Console.WriteLine);

Reading data from DataGridView in C#

string[,] myGridData = new string[dataGridView1.Rows.Count,3];

int i = 0;

foreach(DataRow row in dataGridView1.Rows)

{

    myGridData[i][0] = row.Cells[0].Value.ToString();
    myGridData[i][1] = row.Cells[1].Value.ToString();
    myGridData[i][2] = row.Cells[2].Value.ToString();

    i++;
}

Hope this helps....

How to use if, else condition in jsf to display image

Instead of using the "c" tags, you could also do the following:

<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />

<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>

I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?

arranging div one below the other

You don't even need the float:left;

It seems the default behavior is to render one below the other, if it doesn't happen it's because they are inheriting some style from above.

CSS:

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; 
    width:auto;
}
</style>

HTML:

<div id="wrapper">
    <div id="inner1">inner1</div>
    <div id="inner2">inner2</div>
</div>

How do I auto-resize an image to fit a 'div' container?

Make it simple!

Give the container a fixed height and then for the img tag inside it, set width and max-height.

<div style="height: 250px">
     <img src="..." alt=" " style="width: 100%;max-height: 100%" />
</div>

The difference is that you set the width to be 100%, not the max-width.

How to create windows service from java jar?

Another option is winsw: https://github.com/kohsuke/winsw/

Configure an xml file to specify the service name, what to execute, any arguments etc. And use the exe to install. Example xml: https://github.com/kohsuke/winsw/tree/master/examples

I prefer this to nssm, because it is one lightweight exe; and the config xml is easy to share/commit to source code.

PS the service is installed by running your-service.exe install

Pass mouse events through absolutely-positioned element

The reason you are not receiving the event is because the absolutely positioned element is not a child of the element you are wanting to "click" (blue div). The cleanest way I can think of is to put the absolute element as a child of the one you want clicked, but I'm assuming you can't do that or you wouldn't have posted this question here :)

Another option would be to register a click event handler for the absolute element and call the click handler for the blue div, causing them both to flash.

Due to the way events bubble up through the DOM I'm not sure there is a simpler answer for you, but I'm very curious if anyone else has any tricks I don't know about!

How to obtain a Thread id in Python?

I saw examples of thread IDs like this:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...

The threading module docs lists name attribute as well:

...

A thread has a name. 
The name can be passed to the constructor, 
and read or changed through the name attribute.

...

Thread.name

A string used for identification purposes only. 
It has no semantics. Multiple threads may
be given the same name. The initial name is set by the constructor.

Initializing entire 2D array with one value

char grid[row][col];
memset(grid, ' ', sizeof(grid));

That's for initializing char array elements to space characters.

ASP.net page without a code behind

yes on your aspx page include a script tag with runat=server

<script language="c#" runat="server">

public void Page_Load(object sender, EventArgs e)
{
  // some load code
}
</script>

You can also use classic ASP Syntax

<% if (this.MyTextBox.Visible) { %>
<span>Only show when myTextBox is visible</span>
<% } %>

How do I drop table variables in SQL-Server? Should I even do this?

Here is a solution

Declare @tablename varchar(20)
DECLARE @SQL NVARCHAR(MAX)

SET @tablename = '_RJ_TEMPOV4'
SET @SQL = 'DROP TABLE dbo.' + QUOTENAME(@tablename) + '';

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@tablename) AND type in (N'U'))
    EXEC sp_executesql @SQL;

Works fine on SQL Server 2014 Christophe

Reading an Excel file in python using pandas

I think this should satisfy your need:

import pandas as pd

# Read the excel sheet to pandas dataframe
df = pd.read_excel("PATH\FileName.xlsx", sheetname=0)

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>
      <TileColor>#009900</TileColor>
    </tile>
  </msapplication>
</browserconfig>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...
  </div>
</div>

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

<script>
function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;
}
</script>

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

I ran into a merge conflict. How can I abort the merge?

In this particular use case, you don't really want to abort the merge, just resolve the conflict in a particular way.

There is no particular need to reset and perform a merge with a different strategy, either. The conflicts have been correctly highlighted by git and the requirement to accept the other sides changes is only for this one file.

For an unmerged file in a conflict git makes available the common base, local and remote versions of the file in the index. (This is where they are read from for use in a 3-way diff tool by git mergetool.) You can use git show to view them.

# common base:
git show :1:_widget.html.erb

# 'ours'
git show :2:_widget.html.erb

# 'theirs'
git show :3:_widget.html.erb

The simplest way to resolve the conflict to use the remote version verbatim is:

git show :3:_widget.html.erb >_widget.html.erb
git add _widget.html.erb

Or, with git >= 1.6.1:

git checkout --theirs _widget.html.erb

How does Git handle symbolic links?

Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.

When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.

If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.

Negative weights using Dijkstra's Algorithm

you did not use S anywhere in your algorithm (besides modifying it). the idea of dijkstra is once a vertex is on S, it will not be modified ever again. in this case, once B is inside S, you will not reach it again via C.

this fact ensures the complexity of O(E+VlogV) [otherwise, you will repeat edges more then once, and vertices more then once]

in other words, the algorithm you posted, might not be in O(E+VlogV), as promised by dijkstra's algorithm.

JavaScript and getElementById for multiple elements with the same ID

you can use document.document.querySelectorAll("#divId")

adb shell command to make Android package uninstall dialog appear

I assume that you enable developer mode on your android device and you are connected to your device and you have shell access (adb shell).

Once this is done you can uninstall application with this command pm uninstall --user 0 <package.name>. 0 is root id -this way you don't need too root your device.

Here is an example how I did on my Huawei P110 lite

# gain shell access
$ adb shell

# check who you are
$ whoami
shell

# obtain user id
$ id
uid=2000(shell) gid=2000(shell)

# list packages
$ pm list packages | grep google                                                                                                                                                         
package:com.google.android.youtube
package:com.google.android.ext.services
package:com.google.android.googlequicksearchbox
package:com.google.android.onetimeinitializer
package:com.google.android.ext.shared
package:com.google.android.apps.docs.editors.sheets
package:com.google.android.configupdater
package:com.google.android.marvin.talkback
package:com.google.android.apps.tachyon
package:com.google.android.instantapps.supervisor
package:com.google.android.setupwizard
package:com.google.android.music
package:com.google.android.apps.docs
package:com.google.android.apps.maps
package:com.google.android.webview
package:com.google.android.syncadapters.contacts
package:com.google.android.packageinstaller
package:com.google.android.gm
package:com.google.android.gms
package:com.google.android.gsf
package:com.google.android.tts
package:com.google.android.partnersetup
package:com.google.android.videos
package:com.google.android.feedback
package:com.google.android.printservice.recommendation
package:com.google.android.apps.photos
package:com.google.android.syncadapters.calendar
package:com.google.android.gsf.login
package:com.google.android.backuptransport
package:com.google.android.inputmethod.latin

# uninstall gmail app
pm uninstall --user 0 com.google.android.gms

Parsing HTML using Python

I would use EHP

https://github.com/iogf/ehp

Here it is:

from ehp import *

doc = '''<html>
<head>Heading</head>
<body attr1='val1'>
    <div class='container'>
        <div id='class'>Something here</div>
        <div>Something else</div>
    </div>
</body>
</html>
'''

html = Html()
dom = html.feed(doc)
for ind in dom.find('div', ('class', 'container')):
    print ind.text()

Output:

Something here
Something else

How can I clear or empty a StringBuilder?

StringBuilder s = new StringBuilder();
s.append("a");
s.append("a");
// System.out.print(s); is return "aa"
s.delete(0, s.length());
System.out.print(s.length()); // is return 0

is the easy way.

Check for file exists or not in sql server?

Try the following code to verify whether the file exist. You can create a user function and use it in your stored procedure. modify it as you need:

Set NOCOUNT ON

 DECLARE @Filename NVARCHAR(50)
 DECLARE @fileFullPath NVARCHAR(100)

 SELECT @Filename = N'LogiSetup.log'
 SELECT @fileFullPath = N'C:\LogiSetup.log'

create table #dir

(output varchar(2000))

 DECLARE @cmd NVARCHAR(100)
SELECT @cmd = 'dir ' + @fileFullPath     

insert into #dir    

exec master.dbo.xp_cmdshell @cmd

--Select * from #dir

-- This is risky, as the fle path itself might contain the filename
if exists (Select * from #dir where output like '%'+ @Filename +'%')

       begin    
              Print 'File found'    
              --Add code you want to run if file exists    
       end    
else    
       begin    
              Print 'No File Found'    
              --Add code you want to run if file does not exists    
       end

drop table #dir

How can I get date and time formats based on Culture Info?

You can retrieve the format strings from the CultureInfo DateTimeFormat property, which is a DateTimeFormatInfo instance. This in turn has properties like ShortDatePattern and ShortTimePattern, containing the format strings:

CultureInfo us = new CultureInfo("en-US");
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;
string shortUsTimeFormatString = us.DateTimeFormat.ShortTimePattern;

CultureInfo uk = new CultureInfo("en-GB");
string shortUkDateFormatString = uk.DateTimeFormat.ShortDatePattern;
string shortUkTimeFormatString = uk.DateTimeFormat.ShortTimePattern;

If you simply want to format the date/time using the CultureInfo, pass it in as your IFormatter when converting the DateTime to a string, using the ToString method:

string us = myDate.ToString(new CultureInfo("en-US"));
string uk = myDate.ToString(new CultureInfo("en-GB"));

How to make primary key as autoincrement for Room Persistence lib

This works for me:

@Entity(tableName = "note_table")
data class Note(
    @ColumnInfo(name="title") var title: String,
    @ColumnInfo(name="description") var description: String = "",
    @ColumnInfo(name="priority") var priority: Int,
    @PrimaryKey(autoGenerate = true) var id: Int = 0//last so that we don't have to pass an ID value or named arguments
)

Note that the id is last to avoid having to use named arguments when creating the entity, before inserting it into Room. Once it's been added to room, use the id when updating the entity.

Why I've got no crontab entry on OS X when using vim?

Other option is not to use crontab -e at all. Instead I used:

(crontab -l && echo "1 1  * * *  /path/to/my/script.sh") | crontab -

Notice that whatever you print before | crontab - will replace the entire crontab file, so use crontab -l && echo "<your new schedule>" to get the previous content and the new schedule.

Difference between jar and war in Java

War -

distribute Java-based web applications. A WAR has the same file structure as a JAR file, which is a single compressed file that contains multiple files bundled inside it.

Jar -

The .jar files contain libraries, resources and accessories files like property files.

WAR files are used to combine JSPs, servlets, Java class files, XML files, javascript libraries, JAR libraries, static web pages, and any other resources needed to run the application.

How merge two objects array in angularjs?

This works for me :

$scope.array1 = $scope.array1.concat(array2)

In your case it would be :

$scope.actions.data = $scope.actions.data.concat(data)

Expanding a parent <div> to the height of its children

Instead of setting height property, use min-height.

React component not re-rendering on state change

I'd like to add to this the enormously simple, but oh so easily made mistake of writing:

this.state.something = 'changed';

... and then not understanding why it's not rendering and Googling and coming on this page, only to realize that you should have written:

this.setState({something: 'changed'});

React only triggers a re-render if you use setState to update the state.