Programs & Examples On #Ilog

Recently purchased and rebranded by IBM as Websphere JRules, ILog JRules is the former name of a suite of tools used to create and run rule-based applications.

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

You need just to delete your older connector and download new version (mysql-connector-java-5.1.46)

You must add a reference to assembly 'netstandard, Version=2.0.0.0

I experienced this when upgrading .NET Core 1.1 to 2.1.

I followed the instructions outlined here.

Try to remove <RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion> or <NetStandardImplicitPackageVersion> section in the .csproj.

How to use log4net in Asp.net core 2.0

I've figured out what the issue is the namespace is ambigious in the loggerFactory.AddLog4Net(). Here is a brief summary of how I added log4Net to my Asp.Net Core project.

  1. Add the nugget package Microsoft.Extensions.Logging.Log4Net.AspNetCore
  2. Add the log4net.config file in your root application folder

  3. Open the Startup.cs file and change the Configure method to add log4net support with this line loggerFactory.AddLog4Net

First you have to import the package using Microsoft.Extensions.Logging; using the using statement

Here is the entire method, you have to prefix the ILoggerFactory interface with the namespace

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, NorthwindContext context, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();
            ....
        }

How to enable CORS in ASP.net Core WebAPI

below is the settings which works for me: enter image description here

How do I access Configuration in any class in ASP.NET Core?

I'm doing it like this at the moment:

// Requires NuGet package Microsoft.Extensions.Configuration.Json

using Microsoft.Extensions.Configuration;
using System.IO;

namespace ImagesToMssql.AppsettingsJson
{
    public static class AppSettingsJson
    {           
        public static IConfigurationRoot GetAppSettings()
        {
            string applicationExeDirectory = ApplicationExeDirectory();

            var builder = new ConfigurationBuilder()
            .SetBasePath(applicationExeDirectory)
            .AddJsonFile("appsettings.json");

            return builder.Build();
        }

        private static string ApplicationExeDirectory()
        {
            var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var appRoot = Path.GetDirectoryName(location);

            return appRoot;
        }
    }
}

And then I use this where I need to get the data from the appsettings.json file:

var appSettingsJson = AppSettingsJson.GetAppSettings();
// appSettingsJson["keyName"]

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

Override constructor of DbContext Try this :-

public DataContext(DbContextOptions<DataContext> option):base(option) {}

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

I just added custom headers to the Web.config and it worked like a charm.

On configuration - system.webServer:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>

I have the front end app and the backend on the same solution. For this to work, I need to set the web services project (Backend) as the default for this to work.

I was using ReST, haven't tried with anything else.

Position buttons next to each other in the center of page

jsfiddle: http://jsfiddle.net/mgtoz4d3/

I added a container which contains both buttons. Try this:

CSS:

#button1{
    width: 300px;
    height: 40px;
}
#button2{
    width: 300px;
    height: 40px;
}
#container{
    text-align: center;
}

HTML:

<img src="kingstonunilogo.jpg" alt="uni logo" style="width:180px;height:160px">
<br><br>
<div id="container">
    <button type="button home-button" id="button1" >Home</button>
    <button type="button contact-button" id="button2">Contact Us</button>
</div>

Why am I getting a " Traceback (most recent call last):" error?

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

TypeError: 'int' object is not callable

My code for Python 3 is as follows:

# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error

raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: {M_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: {F_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: {G_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: {inches_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    # Printing error in the line below
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

I hope this helps.

how to make window.open pop up Modal?

You can't make window.open modal and I strongly recommend you not to go that way. Instead you can use something like jQuery UI's dialog widget.

UPDATE:

You can use load() method:

$("#dialog").load("resource.php").dialog({options});

This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.

And you can use an IFRAME:

$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});

This is slower, but will submit independently.

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

' << ' operator in verilog

1 << ADDR_WIDTH means 1 will be shifted 8 bits to the left and will be assigned as the value for RAM_DEPTH.

In addition, 1 << ADDR_WIDTH also means 2^ADDR_WIDTH.

Given ADDR_WIDTH = 8, then 2^8 = 256 and that will be the value for RAM_DEPTH

How to change already compiled .class file without decompile?

As far as I've been able to find out, there is no simple way to do it. The easiest way is to not actually convert the class file into an executable, but to wrap an executable launcher around the class file. That is, create an executable file (perhaps an OS-based, executable scripting file) which simply invokes the Java class through the command line.

If you want to actually have a program that does it, you should look into some of the automated installers out there.

Here is a way I've found:

[code]
import java.io.*;
import java.util.jar.*;

class OnlyExt implements FilenameFilter{
String ext;
public OnlyExt(String ext){
this.ext="." + ext;
}

@Override
public boolean accept(File dir,String name){
return name.endsWith(ext);
}
}

public class ExeCreator {
public static int buffer = 10240;
protected void create(File exefile, File[] listFiles) {
try {
byte b[] = new byte[buffer];
FileOutputStream fout = new FileOutputStream(exefile);
JarOutputStream out = new JarOutputStream(fout, new Manifest());
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i] == null || !listFiles[i].exists()|| listFiles[i].isDirectory())
System.out.println("Adding " + listFiles[i].getName());
JarEntry addFiles = new JarEntry(listFiles[i].getName());
addFiles.setTime(listFiles[i].lastModified());
out.putNextEntry(addFiles);

FileInputStream fin = new FileInputStream(listFiles[i]);
while (true) {
int len = fin.read(b, 0, b.length);
if (len <= 0)
break;
out.write(b, 0, len);
}
fin.close();
}
out.close();
fout.close();
System.out.println("Jar File is created successfully.");
} catch (Exception ex) {}
}

public static void main(String[]args){
ExeCreator exe=new ExeCreator();
FilenameFilter ff = new OnlyExt("class");
File folder = new File("./examples");
File[] files = folder.listFiles(ff);
File file=new File("examples.exe");
exe.create(file, files);
}

}


[/code]`

Remove xticks in a matplotlib plot?

Not exactly what the OP was asking for, but a simple way to disable all axes lines, ticks and labels is to simply call:

plt.axis('off')

Verilog generate/genvar in an always block

To put it simply, you don't use generate inside an always process, you use generate to create a parametrized process or instantiate particular modules, where you can combine if-else or case. So you can move this generate and crea a particular process or an instantiation e.g.,

module #(
parameter XLEN = 64,
parameter USEIP = 0
)
(
 input clk,
input rstn,
input [XLEN-1:0] opA,
input [XLEN-1:0] opB,
input [XLEN-1:0] opR,
input en
);

generate 
case(USEIP)
0:begin
always @(posedge clk or negedge rstn)
begin
if(!rstn)
begin
 opR <= '{default:0};
end
else
begin
if(en)
 opR <= opA+opB;
else
opR <= '{default:0};
end
end
end
1:begin
  superAdder #(.XLEN(XLEN)) _adder(.clk(clk),.rstm(rstn), .opA(opA), .opB(opB), .opR(opR), .en(en));
end
endcase

endmodule

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

I am assuming you are using Eclipse as your developing environment.

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

How to save a PNG image server-side, from a base64 data string

based on drew010 example I made a working example for easy understanding.

imagesaver("data:image/jpeg;base64,/9j/4AAQSkZJ"); //use full base64 data 

function imagesaver($image_data){

    list($type, $data) = explode(';', $image_data); // exploding data for later checking and validating 

    if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $type)) {
        $data = substr($data, strpos($data, ',') + 1);
        $type = strtolower($type[1]); // jpg, png, gif

        if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
            throw new \Exception('invalid image type');
        }

        $data = base64_decode($data);

        if ($data === false) {
            throw new \Exception('base64_decode failed');
        }
    } else {
        throw new \Exception('did not match data URI with image data');
    }

    $fullname = time().$type;

    if(file_put_contents($fullname, $data)){
        $result = $fullname;
    }else{
        $result =  "error";
    }
    /* it will return image name if image is saved successfully 
    or it will return error on failing to save image. */
    return $result; 
}

java.lang.ClassNotFoundException: org.apache.log4j.Level

In my environment, I just added the two files to class path. And is work fine.

slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar

How to add a second x-axis in matplotlib

From matplotlib 3.1 onwards you may use ax.secondary_xaxis

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1,13, num=301)
y = (np.sin(x)+1.01)*3000

# Define function and its inverse
f = lambda x: 1/(1+x)
g = lambda x: 1/x-1

fig, ax = plt.subplots()
ax.semilogy(x, y, label='DM')

ax2 = ax.secondary_xaxis("top", functions=(f,g))

ax2.set_xlabel("1/(x+1)")
ax.set_xlabel("x")
plt.show()

Configure Log4Net in web application

You need to call the Configurefunction of the XmlConfigurator

log4net.Config.XmlConfigurator.Configure();

Either call before your first loggin call or in your Global.asax like this:

protected void Application_Start(Object sender, EventArgs e) {
   log4net.Config.XmlConfigurator.Configure();
}

Assign a synthesizable initial value to a reg in Verilog

You can combine the register declaration with initialization.

reg [7:0] data_reg = 8'b10101011;

Or you can use an initial block

reg [7:0] data_reg;
initial data_reg = 8'b10101011;

Raising a number to a power in Java

Too late for the OP of course, but still... Rearranging the expression as:

int bmi = (10000 * weight) / (height * height)

Eliminates all the floating point, and converts a division by a constant to a multiplication, which should execute faster. Integer precision is probably adequate for this application, but if it is not then:

double bmi = (10000.0 * weight) / (height * height)

would still be an improvement.

Correct way of using log4net (logger naming)

My Answer might be coming late, but I think it can help newbie. You shall not see logs executed unless the changes are made as below.

2 Files have to be changes when you implement Log4net.


  1. Add Reference of log4net.dll in the project.
  2. app.config
  3. Class file where you will implement Logs.

Inside [app.config] :

First, under 'configSections', you need to add below piece of code;

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

Then, under 'configuration' block, you need to write below piece of code.(This piece of code is customised as per my need , but it works like charm.)

<log4net debug="true">
    <logger name="log">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="1" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />

      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %C.%M [%line] %-5level - %message %newline %exception %newline" />
      </layout>
    </appender>
</log4net>

Inside Calling Class :

Inside the class where you are going to use this log4net, you need to declare below piece of code.

 ILog log = LogManager.GetLogger("log");

Now, you are ready call log wherever you want in that same class. Below is one of the method you can call while doing operations.

log.Error("message");

Using wire or reg with input or output in Verilog

basically reg is used to store values.For example if you want a counter(which will count and thus will have some value for each count),we will use a reg. On the other hand,if we just have a plain signal with 2 values 0 and 1,we will declare it as wire.Wire can't hold values.So assigning values to wire leads to problems....

Verifying a specific parameter with Moq

I believe that the problem in the fact that Moq will check for equality. And, since XmlElement does not override Equals, it's implementation will check for reference equality.

Can't you use a custom object, so you can override equals?

Export to csv in jQuery

This is my implementation (based in: https://gist.github.com/3782074):

Usage: HTML:

<table class="download">...</table>
<a href="" download="name.csv">DOWNLOAD CSV</a>

JS:

$("a[download]").click(function(){
    $("table.download").toCSV(this);    
});

Code:

jQuery.fn.toCSV = function(link) {
  var $link = $(link);
  var data = $(this).first(); //Only one table
  var csvData = [];
  var tmpArr = [];
  var tmpStr = '';
  data.find("tr").each(function() {
      if($(this).find("th").length) {
          $(this).find("th").each(function() {
            tmpStr = $(this).text().replace(/"/g, '""');
            tmpArr.push('"' + tmpStr + '"');
          });
          csvData.push(tmpArr);
      } else {
          tmpArr = [];
             $(this).find("td").each(function() {
                  if($(this).text().match(/^-{0,1}\d*\.{0,1}\d+$/)) {
                      tmpArr.push(parseFloat($(this).text()));
                  } else {
                      tmpStr = $(this).text().replace(/"/g, '""');
                      tmpArr.push('"' + tmpStr + '"');
                  }
             });
          csvData.push(tmpArr.join(','));
      }
  });
  var output = csvData.join('\n');
  var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(output);
  $link.attr("href", uri);
}

Notes:

  • It uses "th" tags for headings. If they are not present, they are not added.
  • This code detects numbers in the format: -####.## (You will need modify the code in order to accept other formats, e.g. using commas).

UPDATE:

My previous implementation worked fine but it didn't set the csv filename. The code was modified to use a filename but it requires an < a > element. It seems that you can't dynamically generate the < a > element and fire the "click" event (perhaps security reasons?).

DEMO

http://jsfiddle.net/nLj74t0f/

(Unfortunately jsfiddle fails to generate the file and instead it throws an error: 'please use POST request', don't let that error stop you from testing this code in your application).

Log4net does not write the log in the log file

Insert:

 [assembly: log4net.Config.XmlConfigurator(Watch = true)]

at the end of AssemblyInfo.cs file

How to declare and use 1D and 2D byte arrays in Verilog?

In addition to Marty's excellent Answer, the SystemVerilog specification offers the byte data type. The following declares a 4x8-bit variable (4 bytes), assigns each byte a value, then displays all values:

module tb;

byte b [4];

initial begin
    foreach (b[i]) b[i] = 1 << i;
    foreach (b[i]) $display("Address = %0d, Data = %b", i, b[i]);
    $finish;
end

endmodule

This prints out:

Address = 0, Data = 00000001
Address = 1, Data = 00000010
Address = 2, Data = 00000100
Address = 3, Data = 00001000

This is similar in concept to Marty's reg [7:0] a [0:3];. However, byte is a 2-state data type (0 and 1), but reg is 4-state (01xz). Using byte also requires your tool chain (simulator, synthesizer, etc.) to support this SystemVerilog syntax. Note also the more compact foreach (b[i]) loop syntax.

The SystemVerilog specification supports a wide variety of multi-dimensional array types. The LRM can explain them better than I can; refer to IEEE Std 1800-2005, chapter 5.

Where will log4net create this log file?

I was developing for .NET core 2.1 using log4net 2.0.8 and found NealWalters code moans about 0 arguments for XmlConfigurator.Configure(). I found a solution by Matt Watson here

        log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
        var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
        XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

How to remove all ListBox items?

  • VB ListBox2.DataSource = Nothing
  • C# ListBox2.DataSource = null;

What do curly braces mean in Verilog?

The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).

There is a tutorial here*, but it doesn't explain too much more than the above paragraph.

For what it's worth, the nested curly braces around a[15:0] are superfluous.

*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}} should be a {2{2}}.

Where is Python's sys.path initialized from?

"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"

-- http://docs.python.org/library/sys.html#sys.path

Have log4net use application config file for configuration data

Have you tried adding a configsection handler to your app.config? e.g.

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

How do I test which class an object is in Objective-C?

You can also check run time. Put one breakpoint in code and inside (lldb) console write

(lldb) po [yourObject class]

Like this..

enter image description here

Convert char * to LPWSTR

The clean way to use mbstowcs is to call it twice to find the length of the result:

  const char * cs = <your input char*>
  size_t wn = mbsrtowcs(NULL, &cs, 0, NULL);

  // error if wn == size_t(-1)

  wchar_t * buf = new wchar_t[wn + 1]();  // value-initialize to 0 (see below)

  wn = mbsrtowcs(buf, &cs, wn + 1, NULL);

  // error if wn == size_t(-1)

  assert(cs == NULL); // successful conversion

  // result now in buf, return e.g. as std::wstring

  delete[] buf;

Don't forget to call setlocale(LC_CTYPE, ""); at the beginning of your program!

The advantage over the Windows MultiByteToWideChar is that this is entirely standard C, although on Windows you might prefer the Windows API function anyway.

I usually wrap this method, along with the opposite one, in two conversion functions string->wstring and wstring->string. If you also add trivial overloads string->string and wstring->wstring, you can easily write code that compiles with the Winapi TCHAR typedef in any setting.

[Edit:] I added zero-initialization to buf, in case you plan to use the C array directly. I would usually return the result as std::wstring(buf, wn), though, but do beware if you plan on using C-style null-terminated arrays.[/]

In a multithreaded environment you should pass a thread-local conversion state to the function as its final (currently invisible) parameter.

Here is a small rant of mine on this topic.

How to cast ArrayList<> from List<>

Try running the following code:

List<String> listOfString = Arrays.asList("Hello", "World");
ArrayList<String> arrayListOfString = new ArrayList(listOfString);
System.out.println(listOfString.getClass());
System.out.println(arrayListOfString.getClass());

You'll get the following result:

class java.util.Arrays$ArrayList
class java.util.ArrayList

So, that means they're 2 different classes that aren't extending each other. java.util.Arrays$ArrayList signifies the private class named ArrayList (inner class of Arrays class) and java.util.ArrayList signifies the public class named ArrayList. Thus, casting from java.util.Arrays$ArrayList to java.util.ArrayList and vice versa are irrelevant/not available.

How to close Android application?

It's not possible using the framework APIs. It's at the discretion of the operating system (Android) to decide when a process should be removed or remain in memory. This is for efficiency reasons: if the user decides to relaunch the app, then it's already there without it having to be loaded into memory.

So no, it's not only discouraged, it's impossible to do so.

String or binary data would be truncated. The statement has been terminated

Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION

@trackingItems1 TABLE (
item       nvarchar(25)  NULL, -- 25 OR equal size of your item column
warehouse   nvarchar(25) NULL, -- same as above
price int   NULL

) 

Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated

Should ol/ul be inside <p> or outside?

actually you should only put in-line elements inside the p, so in your case ol is better outside

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json; charset=utf-8");
    return headers;
}

You need to add Content-Type to the header.

File tree view in Notepad++

As of Notepad++ 6.9, the new Folder as Workspace feature can be used.

Folder as Workspace opens your folder(s) in a panel so you can browse folder(s) and open any file in Notepad++. Every changement in the folder(s) from outside will be synchronized in the panel. Usage: Simply drop 1 (or more) folder(s) in Notepad++.

Folder as Workspace

This feature has the advantage of not showing your entire file system when just the working directory is needed. It also means you don't need plugins for it to work.

What is the difference between Amazon SNS and Amazon SQS?

Here's a comparison of the two:

Entity Type

  • SQS: Queue (Similar to JMS)
  • SNS: Topic (Pub/Sub system)

Message consumption

  • SQS: Pull Mechanism - Consumers poll and pull messages from SQS
  • SNS: Push Mechanism - SNS Pushes messages to consumers

Use Case

  • SQS: Decoupling two applications and allowing parallel asynchronous processing
  • SNS: Fanout - Processing the same message in multiple ways

Persistence

  • SQS: Messages are persisted for some (configurable) duration if no consumer is available (maximum two weeks), so the consumer does not have to be up when messages are added to queue.
  • SNS: No persistence. Whichever consumer is present at the time of message arrival gets the message and the message is deleted. If no consumers are available then the message is lost after a few retries.

Consumer Type

  • SQS: All the consumers are typically identical and hence process the messages in the exact same way (each message is processed once by one consumer, though in rare cases messages may be resent)
  • SNS: The consumers might process the messages in different ways

Sample applications

  • SQS: Jobs framework: The Jobs are submitted to SQS and the consumers at the other end can process the jobs asynchronously. If the job frequency increases, the number of consumers can simply be increased to achieve better throughput.
  • SNS: Image processing. If someone uploads an image to S3 then watermark that image, create a thumbnail and also send a Thank You email. In that case S3 can publish notifications to an SNS topic with three consumers listening to it. The first one watermarks the image, the second one creates a thumbnail and the third one sends a Thank You email. All of them receive the same message (image URL) and do their processing in parallel.

"Submit is not a function" error in JavaScript

I had the same issue when i was creating a MVC application using with master pages. Tried looking for element with 'submit' as names as mentioned above but it wasn't the case.

For my case it created multiple tags on my page so there were some issues referencing the correct form.

To work around this i'll let the button handle which form object to use:

onclick="return SubmitForm(this.form)"

and with the js:

function SubmitForm(frm) {
    frm.submit();
}

C# - Winforms - Global Variables

public static class MyGlobals
{
  public static string Global1 = "Hello";
  public static string Global2 = "World";
}

public class Foo
{

    private void Method1()
    {
       string example = MyGlobals.Global1;
       //etc
    }
}

XPath to select multiple tags

Why not a/b/(c|d|e)? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work. abc.xml is the doc described by OP.

(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
    #<XdmNode <d>D1</d>>
    #<XdmNode <e>E1</e>>
    #<XdmNode <c>C2</c>>
    #<XdmNode <d>D2</d>>
    #<XdmNode <e>E1</e>>)

How do I mock an open used in a with statement (using the Mock framework in Python)?

Sourced from a github snippet to patch read and write functionality in python.

The source link is over here

import configparser
import pytest

simpleconfig = """[section]\nkey = value\n\n"""

def test_monkeypatch_open_read(mockopen):
    filename = 'somefile.txt'
    mockopen.write(filename, simpleconfig)
 
    parser = configparser.ConfigParser()
    parser.read(filename)
    assert parser.sections() == ['section']
 
def test_monkeypatch_open_write(mockopen):
    parser = configparser.ConfigParser()
    parser.add_section('section')
    parser.set('section', 'key', 'value')
 
    filename = 'somefile.txt'
    parser.write(open(filename, 'wb'))
    assert mockopen.read(filename) == simpleconfig

What is the difference between Task.Run() and Task.Factory.StartNew()

In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.

Difference between pre-increment and post-increment in a loop?

The question is:

Is there a difference in ++i and i++ in a for loop?

The answer is: No.

Why does each and every other answer have to go into detailed explanations about pre and post incrementing when this is not even asked?

This for-loop:

for (int i = 0; // Initialization
     i < 5;     // Condition
     i++)       // Increment
{
   Output(i);
}

Would translate to this code without using loops:

int i = 0; // Initialization

loopStart:
if (i < 5) // Condition
{
   Output(i);

   i++ or ++i; // Increment

   goto loopStart;
}

Now does it matter if you put i++ or ++i as increment here? No it does not as the return value of the increment operation is insignificant. i will be incremented AFTER the code's execution that is inside the for loop body.

How to send string from one activity to another?

You can use the GNLauncher, which is part of a utility library I wrote in cases where a lot of interaction with the Activity is required. With the library, it is almost as simple as calling a function on the Activity object with the required parameters. https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher

How can I format a number into a string with leading zeros?

See String formatting in C# for some example uses of String.Format

Actually a better example of formatting int

String.Format("{0:00000}", 15);          // "00015"

or use String Interpolation:

$"{15:00000}";                           // "00015"

Check if my SSL Certificate is SHA1 or SHA2

Update: The site below is no longer running because, as they say on the site:

As of January 1, 2016, no publicly trusted CA is allowed to issue a SHA-1 certificate. In addition, SHA-1 support was removed by most modern browsers and operating systems in early 2017. Any new certificate you get should automatically use a SHA-2 algorithm for its signature.

Legacy clients will continue to accept SHA-1 certificates, and it is possible to have requested a certificate on December 31, 2015 that is valid for 39 months. So, it is possible to see SHA-1 certificates in the wild that expire in early 2019.

Original answer:

You can also use https://shaaaaaaaaaaaaa.com/ - set up to make this particular task easy. The site has a text box - you type in your site domain name, click the Go button and it then tells you whether the site is using SHA1 or SHA2.

Background

'was not declared in this scope' error

The scope of a variable is always the block it is inside. For example if you do something like

if(...)
{
     int y = 5; //y is created
} //y leaves scope, since the block ends.
else
{
     int y = 8; //y is created
} //y leaves scope, since the block ends.

cout << y << endl; //Gives error since y is not defined.

The solution is to define y outside of the if blocks

int y; //y is created

if(...)
{
     y = 5;
} 
else
{
     y = 8;
} 

cout << y << endl; //Ok

In your program you have to move the definition of y and c out of the if blocks into the higher scope. Your Function then would look like this:

//Using the Gaussian algorithm
int dayofweek(int date, int month, int year )
{
    int y, c;
    int d=date;

    if (month==1||month==2)
    {
         y=((year-1)%100);
         c=(year-1)/100;
    }
    else
    {
         y=year%100;
         c=year/100;
    }
int m=(month+9)%12+1;
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c);
return product%7;
}

Get counts of all tables in a schema

This can be done with a single statement and some XML magic:

select table_name, 
       to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count
from all_tables
where owner = 'FOOBAR'

How do you add a scroll bar to a div?

<head>
<style>
div.scroll
{
background-color:#00FFFF;
width:40%;
height:200PX;
FLOAT: left;
margin-left: 5%;
padding: 1%;
overflow:scroll;
}


</style>
</head>

<body>



<div class="scroll">You can use the overflow property when you want to have better       control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better </div>


</body>
</html>

Check whether a string matches a regex in JS

_x000D_
_x000D_
const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't
_x000D_
_x000D_
_x000D_

Detect if PHP session exists

I use a combined version:

if(session_id() == '' || !isset($_SESSION)) {
    // session isn't started
    session_start();
}

How do I schedule jobs in Jenkins?

The format is as follows:

MINUTE (0-59), HOUR (0-23), DAY (1-31), MONTH (1-12), DAY OF THE WEEK (0-6)

The letter H, representing the word Hash can be inserted instead of any of the values. It will calculate the parameter based on the hash code of you project name.

This is so that if you are building several projects on your build machine at the same time, let’s say midnight each day, they do not all start their build execution at the same time. Each project starts its execution at a different minute depending on its hash code.

You can also specify the value to be between numbers, i.e. H(0,30) will return the hash code of the project where the possible hashes are 0-30.

Examples:

  1. Start build daily at 08:30 in the morning, Monday - Friday: 30 08 * * 1-5

  2. Weekday daily build twice a day, at lunchtime 12:00 and midnight 00:00, Sunday to Thursday: 00 0,12 * * 0-4

  3. Start build daily in the late afternoon between 4:00 p.m. - 4:59 p.m. or 16:00 -16:59 depending on the projects hash: H 16 * * 1-5

  4. Start build at midnight: @midnight or start build at midnight, every Saturday: 59 23 * * 6

  5. Every first of every month between 2:00 a.m. - 02:30 a.m.: H(0,30) 02 01 * *

How to write the Fibonacci Sequence?

Recursion adds time. To eliminate loops, first import math. Then use math.sqrt and golden ratio in a function:

#!/usr/bin/env python3

import math

def fib(n):
    gr = (1 + math.sqrt(5)) / 2
    fib_first = (gr**n - (1 - gr)**n) / math.sqrt(5)
    return int(round(fib_first))

fib_final = fib(100)

print(fib_final)

ref: Fibonacci Numbers in Python

passing 2 $index values within nested ng-repeat

What about using this syntax (take a look in this plunker). I just discovered this and it's pretty awesome.

ng-repeat="(key,value) in data"

Example:

<div ng-repeat="(indexX,object) in data">
    <div ng-repeat="(indexY,value) in object">
       {{indexX}} - {{indexY}} - {{value}}
    </div>
</div>

With this syntax you can give your own name to $index and differentiate the two indexes.

How to read from standard input in the console?

I'm not sure what's wrong with the block

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println(text)

As it works on my machine. However, for the next block you need a pointer to the variables you're assigning the input to. Try replacing fmt.Scanln(text2) with fmt.Scanln(&text2). Don't use Sscanln, because it parses a string already in memory instead of from stdin. If you want to do something like what you were trying to do, replace it with fmt.Scanf("%s", &ln)

If this still doesn't work, your culprit might be some weird system settings or a buggy IDE.

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Android: show/hide status bar/power bar

For Kotlin users

TO SHOW

activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)

TO HIDE

activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)

Reset MySQL root password using ALTER USER statement after install on Mac

If this is NOT your first time setting up the password, try this method:

mysql> UPDATE mysql.user SET Password=PASSWORD('your_new_password')
           WHERE User='root'; 

And if you get the following error, there is a high chance that you have never set your password before:

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement. 

To set up your password for the first time:

mysql> SET PASSWORD = PASSWORD('your_new_password');
Query OK, 0 rows affected, 1 warning (0.01 sec)

Reference: https://dev.mysql.com/doc/refman/5.6/en/alter-user.html

How to display PDF file in HTML?

In html page for pc is easy to implement

<embed src="study/sample.pdf" type="application/pdf"   height="300px" width="100%">

but pdf show in mobile by this code is not possible you must need a plugin

if you have not responsive your site. Then above code pdf not show in mobile but you can put download option after the code

<embed src="study/sample.pdf" type="application/pdf"   height="300px" width="100%" class="responsive">
<a href="study/sample.pdf">download</a>

How to make picturebox transparent?

GameBoard is control of type DataGridView; The image should be type of PNG with transparent alpha channel background;

        Image test = Properties.Resources.checker_black;
        PictureBox b = new PictureBox();
        b.Parent = GameBoard;
        b.Image = test;
        b.Width = test.Width*2;
        b.Height = test.Height*2;
        b.Location = new Point(0, 90);
        b.BackColor = Color.Transparent;
        b.BringToFront();

enter image description here

SQL Server : check if variable is Empty or NULL for WHERE clause

Old post but worth a look for someone who stumbles upon like me

ISNULL(NULLIF(ColumnName, ' '), NULL) IS NOT NULL

ISNULL(NULLIF(ColumnName, ' '), NULL) IS NULL

How to change the status bar background color and text color on iOS 7?

Warning: It does not work anymore with iOS 13 and Xcode 11.

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

I had to try look for other ways. Which does not involve addSubview on window. Because I am moving up the window when keyboard is presented.

Objective-C

- (void)setStatusBarBackgroundColor:(UIColor *)color {

    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

Swift

func setStatusBarBackgroundColor(color: UIColor) {

    guard  let statusBar = UIApplication.sharedApplication().valueForKey("statusBarWindow")?.valueForKey("statusBar") as? UIView else {
        return
    }

    statusBar.backgroundColor = color
}

Swift 3

func setStatusBarBackgroundColor(color: UIColor) {

    guard let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView else { return }

    statusBar.backgroundColor = color
}

Calling this form application:didFinishLaunchingWithOptions worked for me.

N.B. We have an app in the app store with this logic. So I guess it is okay with the app store policy.


Edit:

Use at your own risk. Form the commenter @Sebyddd

I had one app rejected cause of this, while another was accepted just fine. They do consider it private API usage, so you are subject to luck during the reviewing process :) – Sebyddd

onchange event for input type="number"

$(':input').bind('click keyup', function(){
    // do stuff
});

Demo: http://jsfiddle.net/X8cV3/

Switch case: can I use a range instead of a one number

Here is a better and elegant solution for your problem statement.

int mynumbercheck = 1000;
// Your number to be checked
var myswitch = new Dictionary <Func<int,bool>, Action>
            { 
             { x => x < 10 ,    () => //Do this!...  },  
             { x => x < 100 ,    () => //Do this!...  },
             { x => x < 1000 ,    () => //Do this!...  },
             { x => x < 10000 ,   () => //Do this!... } ,
             { x => x < 100000 ,  () => //Do this!... },
             { x => x < 1000000 ,  () => //Do this!... } 
            };

Now to call our conditional switch

   myswitch.First(sw => sw.Key(mynumbercheck)).Value();

Alternate for Switch/ifElse

How to define dimens.xml for every different screen size in android?

I've uploaded a simple java program which takes your project location and the dimension file you want as input. Based on that, it would output the corresponding dimension file in the console. Here's the link to it:

https://github.com/akeshwar/Dimens-for-different-screens-in-Android/blob/master/Main.java

Here's the full code for the reference:

public class Main {


    /**
     * You can change your factors here. The current factors are in accordance with the official documentation.
     */
    private static final double LDPI_FACTOR = 0.375;
    private static final double MDPI_FACTOR = 0.5;
    private static final double HDPI_FACTOR = 0.75;
    private static final double XHDPI_FACTOR = 1.0;
    private static final double XXHDPI_FACTOR = 1.5;
    private static final double XXXHDPI_FACTOR = 2.0;

    private static double factor;

    public static void main(String[] args) throws IOException {


        Scanner in = new Scanner(System.in);
        System.out.println("Enter the location of the project/module");
        String projectPath = in.nextLine();

        System.out.println("Which of the following dimension file do you want?\n1. ldpi \n2. mdpi \n3. hdpi \n4. xhdpi \n5. xxhdpi \n6. xxxhdpi");

        int dimenType = in.nextInt();

        switch (dimenType) {
            case 1: factor = LDPI_FACTOR;
                break;
            case 2: factor = MDPI_FACTOR;
                break;
            case 3: factor = HDPI_FACTOR;
                break;
            case 4: factor = XHDPI_FACTOR;
                break;
            case 5: factor = XXHDPI_FACTOR;
                break;
            case 6: factor = XXXHDPI_FACTOR;
                break;
            default:
                factor = 1.0;
        }

        //full path = "/home/akeshwar/android-sat-bothIncluded-notintegrated/code/tpr-5-5-9/princetonReview/src/main/res/values/dimens.xml"
        //location of the project or module = "/home/akeshwar/android-sat-bothIncluded-notintegrated/code/tpr-5-5-9/princetonReview/"


        /**
         * In case there is some I/O exception with the file, you can directly copy-paste the full path to the file here:
         */
        String fullPath = projectPath + "/src/main/res/values/dimens.xml";

        FileInputStream fstream = new FileInputStream(fullPath);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;

        while ((strLine = br.readLine()) != null)   {
            modifyLine(strLine);
        }
        br.close();

    }

    private static void modifyLine(String line) {

        /**
         * Well, this is how I'm detecting if the line has some dimension value or not.
         */
        if(line.contains("p</")) {
            int endIndex = line.indexOf("p</");

            //since indexOf returns the first instance of the occurring string. And, the actual dimension would follow after the first ">" in the screen
            int begIndex = line.indexOf(">");

            String prefix = line.substring(0, begIndex+1);
            String root = line.substring(begIndex+1, endIndex-1);
            String suffix = line.substring(endIndex-1,line.length());


            /**
             * Now, we have the root. We can use it to create different dimensions. Root is simply the dimension number.
             */

            double dimens = Double.parseDouble(root);
            dimens = dimens*factor*1000;
            dimens = (double)((int)dimens);
            dimens = dimens/1000;
            root = dimens + "";

            System.out.println(prefix + " " +  root + " " + suffix );

        }

        System.out.println(line);
    }
}

Split a String into an array in Swift?

I had a scenario where multiple control characters can be present in the string I want to split. Rather than maintain an array of these, I just let Apple handle that part.

The following works with Swift 3.0.1 on iOS 10:

let myArray = myString.components(separatedBy: .controlCharacters)

What is the simplest way to SSH using Python?

please refer to paramiko.org, its very useful while doing ssh using python.

import paramiko

import time

ssh = paramiko.SSHClient() #SSHClient() is the paramiko object</n>

#Below lines adds the server key automatically to know_hosts file.use anyone one of the below

ssh.load_system_host_keys() 

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:

#Here we are actually connecting to the server.

ssh.connect('10.106.104.24', port=22, username='admin', password='')

time.sleep(5)

#I have mentioned time because some servers or endpoint prints there own information after 
#loggin in e.g. the version, model and uptime information, so its better to give some time 
#before executing the command.

#Here we execute the command, stdin for input, stdout for output, stderr for error

stdin, stdout, stderr = ssh.exec_command('xstatus Time')

#Here we are reading the lines from output.

output = stdout.readlines() 

print(output)


#Below all are the Exception handled by paramiko while ssh. Refer to paramiko.org for more information about exception.


except (BadHostKeyException, AuthenticationException,  
    SSHException, socket.error) as e:           

print(e)

Installing specific package versions with pip

I recently ran into an issue when using pip's -I flag that I wanted to document somewhere:

-I will not uninstall the existing package before proceeding; it will just install it on top of the old one. This means that any files that should be deleted between versions will instead be left in place. This can cause weird behavior if those files share names with other installed modules.

For example, let's say there's a package named package. In one of packages files, they use import datetime. Now, in [email protected], this points to the standard library datetime module, but in [email protected], they added a local datetime.py as a replacement for the standard library version (for whatever reason).

Now lets say I run pip install package==3.0.0, but then later realize that I actually wanted version 2.0.0. If I now run pip install -I package==2.0.0, the old datetime.py file will not be removed, so any calls to import datetime will import the wrong module.

In my case, this manifested with strange syntax errors because the newer version of the package added a file that was only compatible with Python 3, and when I downgraded package versions to support Python 2, I continued importing the Python-3-only module.

Based on this, I would argue that uninstalling the old package is always preferable to using -I when updating installed package versions.

What is the difference between a URI, a URL and a URN?

First of all get your mind out of confusion and take it simple and you will understand.

URI => Uniform Resource Identifier Identifies a complete address of resource i-e location, name or both.

URL => Uniform Resource Locator Identifies location of the resource.

URN => Uniform Resource Name Identifies the name of the resource

Example

We have address https://www.google.com/folder/page.html where,

URI(Uniform Resource Identifier) => https://www.google.com/folder/page.html

URL(Uniform Resource Locator) => https://www.google.com/

URN(Uniform Resource Name) => /folder/page.html

URI => (URL + URN) or URL only or URN only

Undo git update-index --assume-unchanged <file>

To get undo/show dir's/files that are set to assume-unchanged run this:

git update-index --no-assume-unchanged <file>

To get a list of dir's/files that are assume-unchanged run this:

git ls-files -v|grep '^h'

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

class="nav-link {{ \Route::current()->getName() == 'panel' ? 'active' : ''}}"

Vim clear last search highlighting

This will clear the search highlight after updatetime milliseconds of inactivity.

updatetime defaults to 4000ms or 4s but I set mine to 10s. It is important to note that updatetime does more than just this so read the docs before you change it.

function! SearchHlClear()
    let @/ = ''
endfunction
augroup searchhighlight
    autocmd!
    autocmd CursorHold,CursorHoldI * call SearchHlClear()
augroup END

How to solve error: "Clock skew detected"?

I am going to answer my own question.

I added the following lines of code to my Makefile and it fixed the "clock skew" problem:

clean:  
    find . -type f | xargs touch
    rm -rf $(OBJS)

Tracing XML request/responses with JAX-WS

// This solution provides a way programatically add a handler to the web service clien w/o the XML config

// See full doc here: http://docs.oracle.com/cd/E17904_01//web.1111/e13734/handlers.htm#i222476

// Create new class that implements SOAPHandler

public class LogMessageHandler implements SOAPHandler<SOAPMessageContext> {

@Override
public Set<QName> getHeaders() {
    return Collections.EMPTY_SET;
}

@Override
public boolean handleMessage(SOAPMessageContext context) {
    SOAPMessage msg = context.getMessage(); //Line 1
    try {
        msg.writeTo(System.out);  //Line 3
    } catch (Exception ex) {
        Logger.getLogger(LogMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
    } 
    return true;
}

@Override
public boolean handleFault(SOAPMessageContext context) {
    return true;
}

@Override
public void close(MessageContext context) {
}
}

// Programatically add your LogMessageHandler

   com.csd.Service service = null;
    URL url = new URL("https://service.demo.com/ResService.svc?wsdl");

    service = new com.csd.Service(url);

    com.csd.IService port = service.getBasicHttpBindingIService();
    BindingProvider bindingProvider = (BindingProvider)port;
    Binding binding = bindingProvider.getBinding();
    List<Handler> handlerChain = binding.getHandlerChain();
    handlerChain.add(new LogMessageHandler());
    binding.setHandlerChain(handlerChain);

kubectl apply vs kubectl create?

When running in a CI script, you will have trouble with imperative commands as create raises an error if the resource already exists.

What you can do is applying (declarative pattern) the output of your imperative command, by using --dry-run=true and -o yaml options:

kubectl create whatever --dry-run=true -o yaml | kubectl apply -f -

The command above will not raise an error if the resource already exists (and will update the resource if needed).

This is very useful in some cases where you cannot use the declarative pattern (for instance when creating a docker-registry secret).

Run an OLS regression with Pandas Data Frame

B is not statistically significant. The data is not capable of drawing inferences from it. C does influence B probabilities

 df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})

 avg_c=df['C'].mean()
 sumC=df['C'].apply(lambda x: x if x<avg_c else 0).sum()
 countC=df['C'].apply(lambda x: 1 if x<avg_c else None).count()
 avg_c2=sumC/countC
 df['C']=df['C'].apply(lambda x: avg_c2 if x >avg_c else x)
 
 print(df)

 model_ols = smf.ols("A ~ B+C",data=df).fit()

 print(model_ols.summary())

 df[['B','C']].plot()
 plt.show()


 df2=pd.DataFrame()
 df2['B']=np.linspace(10,50,10)
 df2['C']=30

 df3=pd.DataFrame()
 df3['B']=np.linspace(10,50,10)
 df3['C']=100

 predB=model_ols.predict(df2)
 predC=model_ols.predict(df3)
 plt.plot(df2['B'],predB,label='predict B C=30')
 plt.plot(df3['B'],predC,label='predict B C=100')
 plt.legend()
 plt.show()

 print("A change in the probability of C affects the probability of B")

 intercept=model_ols.params.loc['Intercept']
 B_slope=model_ols.params.loc['B']
 C_slope=model_ols.params.loc['C']
 #Intercept    11.874252
 #B             0.760859
 #C            -0.060257

 print("Intercept {}\n B slope{}\n C    slope{}\n".format(intercept,B_slope,C_slope))


 #lower_conf,upper_conf=np.exp(model_ols.conf_int())
 #print(lower_conf,upper_conf)
 #print((1-(lower_conf/upper_conf))*100)

 model_cov=model_ols.cov_params()
 std_errorB = np.sqrt(model_cov.loc['B', 'B'])
 std_errorC = np.sqrt(model_cov.loc['C', 'C'])
 print('SE: ', round(std_errorB, 4),round(std_errorC, 4))
 #check for statistically significant
 print("B z value {} C z value {}".format((B_slope/std_errorB),(C_slope/std_errorC)))
 print("B feature is more statistically significant than C")


 Output:

 A change in the probability of C affects the probability of B
 Intercept 11.874251554067563
 B slope0.7608594144571961
 C slope-0.060256845997223814

 Standard Error:  0.4519 0.0793
 B z value 1.683510336937001 C z value -0.7601036314930376
 B feature is more statistically significant than C

 z>2 is statistically significant     

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

Creating a new directory in C

You can use mkdir:

$ man 2 mkdir

#include <sys/stat.h>
#include <sys/types.h>

int result = mkdir("/home/me/test.txt", 0777);

java.util.Date and getYear()

Don't use Date, use Calendar:

// Beware: months are zero-based and no out of range errors are reported
Calendar date = new GregorianCalendar(2012, 9, 5);
int year = date.get(Calendar.YEAR);  // 2012
int month = date.get(Calendar.MONTH);  // 9 - October!!!
int day = date.get(Calendar.DAY_OF_MONTH);  // 5

It supports time as well:

Calendar dateTime = new GregorianCalendar(2012, 3, 4, 15, 16, 17);
int hour = dateTime.get(Calendar.HOUR_OF_DAY);  // 15
int minute = dateTime.get(Calendar.MINUTE);  // 16
int second = dateTime.get(Calendar.SECOND);  // 17

How to add manifest permission to an application?

Add the below line in your application tag:

 android:usesCleartextTraffic="true"

To be look like below code :

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

And add this above of application tag

<uses-permission android:name="android.permission.INTERNET" />

to be like that :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.themarona.app">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Are SSL certificates bound to the servers ip address?

SSL certificates are bound to a 'common name', which is usually a fully qualified domain name but can be a wildcard name (eg. *.domain.com) or even an IP address, but it usually isn't.

In your case, you are accessing your LDAP server by a hostname and it sounds like your two LDAP servers have different SSL certificates installed. Are you able to view (or download and view) the details of the SSL certificate? Each SSL certificate will have a unique serial numbers and fingerprint which will need to match. I assume the certificate is being rejected as these details don't match with what's in your certificate store.

Your solution will be to ensure that both LDAP servers have the same SSL certificate installed.

BTW - you can normally override DNS entries on your workstation by editing a local 'hosts' file, but I wouldn't recommend this.

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

Print all day-dates between two dates

Using a list comprehension:

from datetime import date, timedelta

d1 = date(2008,8,15)
d2 = date(2008,9,15)

# this will give you a list containing all of the dates
dd = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]

for d in dd:
    print d

# you can't join dates, so if you want to use join, you need to
# cast to a string in the list comprehension:
ddd = [str(d1 + timedelta(days=x)) for x in range((d2-d1).days + 1)]
# now you can join
print "\n".join(ddd)

lambda expression for exists within list

I would look at the Join operator:

from r in list join i in listofIds on r.Id equals i select r

I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.

Edit: Extension method syntax for completeness (now that I've figured it out):

var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);

Jquery change <p> text programmatically

"saving" is something wholly different from changing paragraph content with jquery.

If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").

Judging by your question, this is a topic on which you will have to do MUCH more research.

Input page (input.html):

<form action="/saveMyParagraph.php">
    <input name="pContent" type="text"></input>
</form>

Saving page (saveMyParagraph.php) and Ouput page (output.php):

Inserting Data Into a MySQL Database using PHP

how I can show the sum of in a datagridview column?

Fast and clean way using LINQ

int total = dataGridView1.Rows.Cast<DataGridViewRow>()
                .Sum(t => Convert.ToInt32(t.Cells[1].Value));

verified on VS2013

Min and max value of input in angular4 application

You can write a directive to listen the change event on the input and reset the value to the min value if it is too low. StackBlitz

@HostListener('change') onChange() {
  const min = +this.elementRef.nativeElement.getAttribute('min');

  if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
    this.renderer2.setProperty(
      this.elementRef.nativeElement,
      'value',
      min + ''
    );
  }
}

Also listen for the ngModelChange event to do the same when the form value is set.

@HostListener('ngModelChange', ['$event'])
onModelChange(value: number) {
  const min = +this.elementRef.nativeElement.getAttribute('min');
  if (this.valueIsLessThanMin(min, value)) {
    const formControl = this.formControlName
      ? this.formControlName.control
      : this.formControlDirective.control;

    if (formControl) {
      if (formControl.updateOn === 'change') {
        console.warn(
          `minValueDirective: form control ${this.formControlName.name} is set to update on change
          this can cause issues with min update values.`
        );
      }
      formControl.reset(min);
    }
  }
}

Full code:

import {
  Directive,
  ElementRef,
  HostListener,
  Optional,
  Renderer2,
  Self
} from "@angular/core";
import { FormControlDirective, FormControlName } from "@angular/forms";

@Directive({
  // tslint:disable-next-line: directive-selector
  selector: "input[minValue][min][type=number]"
})
export class MinValueDirective {
  @HostListener("change") onChange() {
    const min = +this.elementRef.nativeElement.getAttribute("min");

    if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
      this.renderer2.setProperty(
        this.elementRef.nativeElement,
        "value",
        min + ""
      );
    }
  }

  // if input is a form control validate on model change
  @HostListener("ngModelChange", ["$event"])
  onModelChange(value: number) {
    const min = +this.elementRef.nativeElement.getAttribute("min");
    if (this.valueIsLessThanMin(min, value)) {
      const formControl = this.formControlName
        ? this.formControlName.control
        : this.formControlDirective.control;

      if (formControl) {
        if (formControl.updateOn === "change") {
          console.warn(
            `minValueDirective: form control ${
              this.formControlName.name
            } is set to update on change
              this can cause issues with min update values.`
          );
        }
        formControl.reset(min);
      }
    }
  }

  constructor(
    private elementRef: ElementRef<HTMLInputElement>,
    private renderer2: Renderer2,
    @Optional() @Self() private formControlName: FormControlName,
    @Optional() @Self() private formControlDirective: FormControlDirective
  ) {}

  private valueIsLessThanMin(min: any, value: number): boolean {
    return typeof min === "number" && value && value < min;
  }
}

Make sure to use this with the form control set to updateOn blur or the user won't be able to enter a +1 digit number if the first digit is below the min value.

 this.formGroup = this.formBuilder.group({
    test: [
      null,
      {
        updateOn: 'blur',
        validators: [Validators.min(5)]
      }
    ]
  });

X close button only using css

-- Simple HTML Solution --

Final result of easy to resize icon:

two close X buttons with different thickness.

JSfiddle demo: https://jsfiddle.net/allenski/yr5gk3cm/

The simple HTML:

<a href="#" class="close" tabindex="0" role="button">close</a>

Note:

  • tabindex attribute is there to help accessibility focus of iOS touch devices.
  • role attribute is to let screen readers users know this is a button.
  • The word close is also intended for screen readers to mention.

The CSS code:

.close {
    position: absolute;
    top: 0;
    right: 0;
    display: block;
    width: 50px;
    height: 50px;
    font-size: 0;
}
.close:before, 
.close:after {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 5px;
    height: 20px;
    background-color: #F0F0F0;
    transform: rotate(45deg) translate(-50%, -50%);
    transform-origin: top left;
    content: '';
}
.close:after {
    transform: rotate(-45deg) translate(-50%, -50%);
}

To adjust thickness of close X icon, change the width property. Example for thinner icon:

.close:before, 
.close:after {
    width: 2px;
}

To adjust length of close X icon, change the height property. Example:

.close:before, 
.close:after {
    height: 33px;
}

Spark: Add column to dataframe conditionally

How about something like this?

val newDF = df.filter($"B" === "").take(1) match {
  case Array() => df
  case _ => df.withColumn("D", $"B" === "")
}

Using take(1) should have a minimal hit

How to determine the screen width in terms of dp or dip at runtime in Android?

You are missing default density value of 160.

    2 px = 3 dip if dpi == 80(ldpi), 320x240 screen
    1 px = 1 dip if dpi == 160(mdpi), 480x320 screen
    3 px = 2 dip if dpi == 240(hdpi), 840x480 screen

In other words, if you design you layout with width equal to 160dip in portrait mode, it will be half of the screen on all ldpi/mdpi/hdpi devices(except tablets, I think)

inline if statement java, why is not working

The ternary operator ? : is to return a value, don't use it when you want to use if for flow control.

if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");

would work good enough.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

history.replaceState() example?

history.pushState pushes the current page state onto the history stack, and changes the URL in the address bar. So, when you go back, that state (the object you passed) are returned to you.

Currently, that is all it does. Any other page action, such as displaying the new page or changing the page title, must be done by you.

The W3C spec you link is just a draft, and browser may implement it differently. Firefox, for example, ignores the title parameter completely.

Here is a simple example of pushState that I use on my website.

(function($){
    // Use AJAX to load the page, and change the title
    function loadPage(sel, p){
        $(sel).load(p + ' #content', function(){
            document.title = $('#pageData').data('title');
        });
    }

    // When a link is clicked, use AJAX to load that page
    // but use pushState to change the URL bar
    $(document).on('click', 'a', function(e){
        e.preventDefault();
        history.pushState({page: this.href}, '', this.href);
        loadPage('#frontPage', this.href);
    });

    // This event is triggered when you visit a page in the history
    // like when yu push the "back" button
    $(window).on('popstate', function(e){
        loadPage('#frontPage', location.pathname);
        console.log(e.originalEvent.state);
    });
}(jQuery));

Java - JPA - @Version annotation

Every time an entity is updated in the database the version field will be increased by one. Every operation that updates the entity in the database will have appended WHERE version = VERSION_THAT_WAS_LOADED_FROM_DATABASE to its query.

In checking affected rows of your operation the jpa framework can make sure there was no concurrent modification between loading and persisting your entity because the query would not find your entity in the database when it's version number has been increased between load and persist.

How to print React component on click of a button?

The solution provided by Emil Ingerslev is working fine, but CSS is not applied to the output. Here I found a good solution given by Andrewlimaza. It prints the contents of a given div, as it uses the window object's print method, the CSS is not lost. And there is no need for an extra iframe also.

var printContents = document.getElementById("divcontents").innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;

Update 1: There is unusual behavior, in chrome/firefox/opera/edge, the print or other buttons stopped working after the execution of this code.

Update 2: The solution given is there on the above link in comments:

.printme { display: none;}
@media print { 
    .no-printme  { display: none;}
    .printme  { display: block;}
}

<h1 class = "no-printme"> do not print this </h1>    
<div class='printme'>
  Print this only 
</div>    
<button onclick={window.print()}>Print only the above div</button>

Show current assembly instruction in GDB

You can switch to assembly layout in GDB:

(gdb) layout asm

See here for more information. The current assembly instruction will be shown in assembler window.

   +---------------------------------------------------------------------------+
   ¦0x7ffff740d756 <__libc_start_main+214>  mov    0x39670b(%rip),%rax        #¦
   ¦0x7ffff740d75d <__libc_start_main+221>  mov    0x8(%rsp),%rsi              ¦
   ¦0x7ffff740d762 <__libc_start_main+226>  mov    0x14(%rsp),%edi             ¦
   ¦0x7ffff740d766 <__libc_start_main+230>  mov    (%rax),%rdx                 ¦
   ¦0x7ffff740d769 <__libc_start_main+233>  callq  *0x18(%rsp)                 ¦
  >¦0x7ffff740d76d <__libc_start_main+237>  mov    %eax,%edi                   ¦
   ¦0x7ffff740d76f <__libc_start_main+239>  callq  0x7ffff7427970 <exit>       ¦
   ¦0x7ffff740d774 <__libc_start_main+244>  xor    %edx,%edx                   ¦
   ¦0x7ffff740d776 <__libc_start_main+246>  jmpq   0x7ffff740d6b9 <__libc_start¦
   ¦0x7ffff740d77b <__libc_start_main+251>  mov    0x39ca2e(%rip),%rax        #¦
   ¦0x7ffff740d782 <__libc_start_main+258>  ror    $0x11,%rax                  ¦
   ¦0x7ffff740d786 <__libc_start_main+262>  xor    %fs:0x30,%rax               ¦
   ¦0x7ffff740d78f <__libc_start_main+271>  callq  *%rax                       ¦
   +---------------------------------------------------------------------------+
multi-thre process 3718 In: __libc_start_main     Line: ??   PC: 0x7ffff740d76d
#3  0x00007ffff7466eb5 in _IO_do_write () from /lib/x86_64-linux-gnu/libc.so.6
#4  0x00007ffff74671ff in _IO_file_overflow ()
   from /lib/x86_64-linux-gnu/libc.so.6
#5  0x0000000000408756 in ?? ()
#6  0x0000000000403980 in ?? ()
#7  0x00007ffff740d76d in __libc_start_main ()
   from /lib/x86_64-linux-gnu/libc.so.6
(gdb)

How do I find which rpm package supplies a file I'm looking for?

You can do this alike here but with your package. In my case, it was lsb_release

Run: yum whatprovides lsb_release

Response:

redhat-lsb-core-4.1-24.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-24.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release`

Run to install: yum install redhat-lsb-core

The package name SHOULD be without number and system type so yum packager can choose what is best for him.

Convert string to boolean in C#

I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands

OP, you can convert a string to type Boolean by using any of the methods stated below:

 string sample = "True";
 bool myBool = bool.Parse(sample);

 ///or

 bool myBool = Convert.ToBoolean(sample);

bool.Parse expects one parameter which in this case is sample, .ToBoolean also expects one parameter.

You can use TryParse which is the same as Parse but it doesn't throw any exception :)

  string sample = "false";
  Boolean myBool;

  if (Boolean.TryParse(sample , out myBool))
  {
  }

Please note that you cannot convert any type of string to type Boolean because the value of a Boolean can only be True or False

Hope you understand :)

Import pfx file into particular certificate store from command line

Check these links: http://www.orcsweb.com/blog/james/powershell-ing-on-windows-server-how-to-import-certificates-using-powershell/

Import-Certificate: http://poshcode.org/1937

You can do something like:

dir -Path C:\Certs -Filter *.cer | Import-Certificate -CertFile $_ -StoreNames AuthRoot, Root -LocalMachine -Verbose

How to select rows from a DataFrame based on column values

There are several ways to select rows from a Pandas dataframe:

  1. Boolean indexing (df[df['col'] == value] )
  2. Positional indexing (df.iloc[...])
  3. Label indexing (df.xs(...))
  4. df.query(...) API

Below I show you examples of each, with advice when to use certain techniques. Assume our criterion is column 'A' == 'foo'

(Note on performance: For each base type, we can keep things simple by using the Pandas API or we can venture outside the API, usually into NumPy, and speed things up.)


Setup

The first thing we'll need is to identify a condition that will act as our criterion for selecting rows. We'll start with the OP's case column_name == some_value, and include some other common use cases.

Borrowing from @unutbu:

import pandas as pd, numpy as np

df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})

1. Boolean indexing

... Boolean indexing requires finding the true value of each row's 'A' column being equal to 'foo', then using those truth values to identify which rows to keep. Typically, we'd name this series, an array of truth values, mask. We'll do so here as well.

mask = df['A'] == 'foo'

We can then use this mask to slice or index the data frame

df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

This is one of the simplest ways to accomplish this task and if performance or intuitiveness isn't an issue, this should be your chosen method. However, if performance is a concern, then you might want to consider an alternative way of creating the mask.


2. Positional indexing

Positional indexing (df.iloc[...]) has its use cases, but this isn't one of them. In order to identify where to slice, we first need to perform the same boolean analysis we did above. This leaves us performing one extra step to accomplish the same task.

mask = df['A'] == 'foo'
pos = np.flatnonzero(mask)
df.iloc[pos]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

3. Label indexing

Label indexing can be very handy, but in this case, we are again doing more work for no benefit

df.set_index('A', append=True, drop=False).xs('foo', level=1)

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

4. df.query() API

pd.DataFrame.query is a very elegant/intuitive way to perform this task, but is often slower. However, if you pay attention to the timings below, for large data, the query is very efficient. More so than the standard approach and of similar magnitude as my best suggestion.

df.query('A == "foo"')

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

My preference is to use the Boolean mask

Actual improvements can be made by modifying how we create our Boolean mask.

mask alternative 1 Use the underlying NumPy array and forgo the overhead of creating another pd.Series

mask = df['A'].values == 'foo'

I'll show more complete time tests at the end, but just take a look at the performance gains we get using the sample data frame. First, we look at the difference in creating the mask

%timeit mask = df['A'].values == 'foo'
%timeit mask = df['A'] == 'foo'

5.84 µs ± 195 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
166 µs ± 4.45 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Evaluating the mask with the NumPy array is ~ 30 times faster. This is partly due to NumPy evaluation often being faster. It is also partly due to the lack of overhead necessary to build an index and a corresponding pd.Series object.

Next, we'll look at the timing for slicing with one mask versus the other.

mask = df['A'].values == 'foo'
%timeit df[mask]
mask = df['A'] == 'foo'
%timeit df[mask]

219 µs ± 12.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
239 µs ± 7.03 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

The performance gains aren't as pronounced. We'll see if this holds up over more robust testing.


mask alternative 2 We could have reconstructed the data frame as well. There is a big caveat when reconstructing a dataframe—you must take care of the dtypes when doing so!

Instead of df[mask] we will do this

pd.DataFrame(df.values[mask], df.index[mask], df.columns).astype(df.dtypes)

If the data frame is of mixed type, which our example is, then when we get df.values the resulting array is of dtype object and consequently, all columns of the new data frame will be of dtype object. Thus requiring the astype(df.dtypes) and killing any potential performance gains.

%timeit df[m]
%timeit pd.DataFrame(df.values[mask], df.index[mask], df.columns).astype(df.dtypes)

216 µs ± 10.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.43 ms ± 39.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

However, if the data frame is not of mixed type, this is a very useful way to do it.

Given

np.random.seed([3,1415])
d1 = pd.DataFrame(np.random.randint(10, size=(10, 5)), columns=list('ABCDE'))

d1

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
2  0  2  0  4  9
3  7  3  2  4  3
4  3  6  7  7  4
5  5  3  7  5  9
6  8  7  6  4  7
7  6  2  6  6  5
8  2  8  7  5  8
9  4  7  6  1  5

%%timeit
mask = d1['A'].values == 7
d1[mask]

179 µs ± 8.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Versus

%%timeit
mask = d1['A'].values == 7
pd.DataFrame(d1.values[mask], d1.index[mask], d1.columns)

87 µs ± 5.12 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

We cut the time in half.


mask alternative 3

@unutbu also shows us how to use pd.Series.isin to account for each element of df['A'] being in a set of values. This evaluates to the same thing if our set of values is a set of one value, namely 'foo'. But it also generalizes to include larger sets of values if needed. Turns out, this is still pretty fast even though it is a more general solution. The only real loss is in intuitiveness for those not familiar with the concept.

mask = df['A'].isin(['foo'])
df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

However, as before, we can utilize NumPy to improve performance while sacrificing virtually nothing. We'll use np.in1d

mask = np.in1d(df['A'].values, ['foo'])
df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

Timing

I'll include other concepts mentioned in other posts as well for reference.

Code Below

Each column in this table represents a different length data frame over which we test each function. Each column shows relative time taken, with the fastest function given a base index of 1.0.

res.div(res.min())

                         10        30        100       300       1000      3000      10000     30000
mask_standard         2.156872  1.850663  2.034149  2.166312  2.164541  3.090372  2.981326  3.131151
mask_standard_loc     1.879035  1.782366  1.988823  2.338112  2.361391  3.036131  2.998112  2.990103
mask_with_values      1.010166  1.000000  1.005113  1.026363  1.028698  1.293741  1.007824  1.016919
mask_with_values_loc  1.196843  1.300228  1.000000  1.000000  1.038989  1.219233  1.037020  1.000000
query                 4.997304  4.765554  5.934096  4.500559  2.997924  2.397013  1.680447  1.398190
xs_label              4.124597  4.272363  5.596152  4.295331  4.676591  5.710680  6.032809  8.950255
mask_with_isin        1.674055  1.679935  1.847972  1.724183  1.345111  1.405231  1.253554  1.264760
mask_with_in1d        1.000000  1.083807  1.220493  1.101929  1.000000  1.000000  1.000000  1.144175

You'll notice that the fastest times seem to be shared between mask_with_values and mask_with_in1d.

res.T.plot(loglog=True)

Enter image description here

Functions

def mask_standard(df):
    mask = df['A'] == 'foo'
    return df[mask]

def mask_standard_loc(df):
    mask = df['A'] == 'foo'
    return df.loc[mask]

def mask_with_values(df):
    mask = df['A'].values == 'foo'
    return df[mask]

def mask_with_values_loc(df):
    mask = df['A'].values == 'foo'
    return df.loc[mask]

def query(df):
    return df.query('A == "foo"')

def xs_label(df):
    return df.set_index('A', append=True, drop=False).xs('foo', level=-1)

def mask_with_isin(df):
    mask = df['A'].isin(['foo'])
    return df[mask]

def mask_with_in1d(df):
    mask = np.in1d(df['A'].values, ['foo'])
    return df[mask]

Testing

res = pd.DataFrame(
    index=[
        'mask_standard', 'mask_standard_loc', 'mask_with_values', 'mask_with_values_loc',
        'query', 'xs_label', 'mask_with_isin', 'mask_with_in1d'
    ],
    columns=[10, 30, 100, 300, 1000, 3000, 10000, 30000],
    dtype=float
)

for j in res.columns:
    d = pd.concat([df] * j, ignore_index=True)
    for i in res.index:a
        stmt = '{}(d)'.format(i)
        setp = 'from __main__ import d, {}'.format(i)
        res.at[i, j] = timeit(stmt, setp, number=50)

Special Timing

Looking at the special case when we have a single non-object dtype for the entire data frame.

Code Below

spec.div(spec.min())

                     10        30        100       300       1000      3000      10000     30000
mask_with_values  1.009030  1.000000  1.194276  1.000000  1.236892  1.095343  1.000000  1.000000
mask_with_in1d    1.104638  1.094524  1.156930  1.072094  1.000000  1.000000  1.040043  1.027100
reconstruct       1.000000  1.142838  1.000000  1.355440  1.650270  2.222181  2.294913  3.406735

Turns out, reconstruction isn't worth it past a few hundred rows.

spec.T.plot(loglog=True)

Enter image description here

Functions

np.random.seed([3,1415])
d1 = pd.DataFrame(np.random.randint(10, size=(10, 5)), columns=list('ABCDE'))

def mask_with_values(df):
    mask = df['A'].values == 'foo'
    return df[mask]

def mask_with_in1d(df):
    mask = np.in1d(df['A'].values, ['foo'])
    return df[mask]

def reconstruct(df):
    v = df.values
    mask = np.in1d(df['A'].values, ['foo'])
    return pd.DataFrame(v[mask], df.index[mask], df.columns)

spec = pd.DataFrame(
    index=['mask_with_values', 'mask_with_in1d', 'reconstruct'],
    columns=[10, 30, 100, 300, 1000, 3000, 10000, 30000],
    dtype=float
)

Testing

for j in spec.columns:
    d = pd.concat([df] * j, ignore_index=True)
    for i in spec.index:
        stmt = '{}(d)'.format(i)
        setp = 'from __main__ import d, {}'.format(i)
        spec.at[i, j] = timeit(stmt, setp, number=50)

How to manually include external aar package using new Gradle Android Build System

With Android Studio 3.4 and Gradle 5 you can simply do it like this

dependencies {
    implementation files('libs/actionbarsherlock.aar')
}

jquery multiple checkboxes array

You can use $.map() (or even the .map() function that operates on a jQuery object) to get an array of checked values. The unary (+) operator will cast the string to a number

var arr = $.map($('input:checkbox:checked'), function(e,i) {
    return +e.value;
});

console.log(arr);

Here's an example

'node' is not recognized as an internal or external command

Make sure nodejs in the PATH is in front of anything that uses node.

Having Django serve downloadable files

Another project to have a look at: http://readthedocs.org/docs/django-private-files/en/latest/usage.html Looks promissing, haven't tested it myself yet tho.

Basically the project abstracts the mod_xsendfile configuration and allows you to do things like:

from django.db import models
from django.contrib.auth.models import User
from private_files import PrivateFileField

def is_owner(request, instance):
    return (not request.user.is_anonymous()) and request.user.is_authenticated and
                   instance.owner.pk = request.user.pk

class FileSubmission(models.Model):
    description = models.CharField("description", max_length = 200)
        owner = models.ForeignKey(User)
    uploaded_file = PrivateFileField("file", upload_to = 'uploads', condition = is_owner)

Groovy built-in REST/HTTP client?

You can take advantage of Groovy features like with(), improvements to URLConnection, and simplified getters/setters:

GET:

String getResult = new URL('http://mytestsite/bloop').text

POST:

String postResult
((HttpURLConnection)new URL('http://mytestsite/bloop').openConnection()).with({
    requestMethod = 'POST'
    doOutput = true
    setRequestProperty('Content-Type', '...') // Set your content type.
    outputStream.withPrintWriter({printWriter ->
        printWriter.write('...') // Your post data. Could also use withWriter() if you don't want to write a String.
    })
    // Can check 'responseCode' here if you like.
    postResult = inputStream.text // Using 'inputStream.text' because 'content' will throw an exception when empty.
})

Note, the POST will start when you try to read a value from the HttpURLConnection, such as responseCode, inputStream.text, or getHeaderField('...').

Does C# support multiple inheritance?

In generally, you can’t do it.

Consider these interfaces and classes:

public class A { }    
public class B { }
public class C { }

public interface IA { }
public interface IB { }

You can inherit multiple interfaces:

class A : B, IA, IB {
  // Inherits any single base class, plus multiple interfaces.
}

But you can’t inherit multiple classes:

class A : B, C, IA, IB {
    // Inherits multiple base classes, plus multiple interfaces.
}

Is there a list of screen resolutions for all Android based phones and tablets?

You can see a lot of screen sizes on this site.

Parsed list of screens:

From http://www.emirweb.com/ScreenDeviceStatistics.php

####################################################################################################
#    Filter out same-sized same-dp screens and width/height swap.
####################################################################################################
Size: 2560 x 1600 px (1280 x 800 dp) xhdpi
Size: 2048 x 1536 px (1024 x 768 dp) xhdpi
Size: 1920 x 1200 px (1442 x 901 dp) tvdpi
Size: 1920 x 1200 px (1280 x 800 dp) hdpi
Size: 1920 x 1200 px (960 x 600 dp) xhdpi
Size: 1920 x 1200 px (640 x 400 dp) xxhdpi
Size: 1920 x 1152 px (640 x 384 dp) xxhdpi
Size: 1920 x 1080 px (1920 x 1080 dp) mdpi
Size: 1920 x 1080 px (1280 x 720 dp) hdpi
Size: 1920 x 1080 px (960 x 540 dp) xhdpi
Size: 1920 x 1080 px (640 x 360 dp) xxhdpi
Size: 1600 x 1200 px (1066 x 800 dp) hdpi
Size: 1600 x 900 px (1600 x 900 dp) mdpi
Size: 1440 x 904 px (960 x 602 dp) hdpi
Size: 1366 x 768 px (1366 x 768 dp) mdpi
Size: 1360 x 768 px (1360 x 768 dp) mdpi
Size: 1280 x 960 px (640 x 480 dp) xhdpi
Size: 1280 x 800 px (1280 x 800 dp) mdpi
Size: 1280 x 800 px (961 x 600 dp) tvdpi
Size: 1280 x 800 px (853 x 533 dp) hdpi
Size: 1280 x 800 px (640 x 400 dp) xhdpi
Size: 1280 x 768 px (1280 x 768 dp) mdpi
Size: 1280 x 768 px (640 x 384 dp) xhdpi
Size: 1280 x 720 px (1280 x 720 dp) mdpi
Size: 1280 x 720 px (961 x 540 dp) tvdpi
Size: 1280 x 720 px (853 x 480 dp) hdpi
Size: 1280 x 720 px (640 x 360 dp) xhdpi
Size: 1279 x 720 px (639 x 360 dp) xhdpi
Size: 1152 x 720 px (1152 x 720 dp) mdpi
Size: 1080 x 607 px (720 x 404 dp) hdpi
Size: 1024 x 960 px (1024 x 960 dp) mdpi
Size: 1024 x 770 px (1024 x 770 dp) mdpi
Size: 1024 x 768 px (1365 x 1024 dp) ldpi
Size: 1024 x 768 px (1024 x 768 dp) mdpi
Size: 1024 x 768 px (512 x 384 dp) xhdpi
Size: 1024 x 600 px (1365 x 800 dp) ldpi
Size: 1024 x 600 px (1024 x 600 dp) mdpi
Size: 1024 x 600 px (682 x 400 dp) hdpi
Size: 960 x 640 px (480 x 320 dp) xhdpi
Size: 960 x 600 px (960 x 600 dp) ldpi
Size: 960 x 540 px (640 x 360 dp) hdpi
Size: 864 x 480 px (576 x 320 dp) hdpi
Size: 854 x 480 px (569 x 320 dp) hdpi
Size: 800 x 600 px (1066 x 800 dp) ldpi
Size: 800 x 480 px (1066 x 640 dp) ldpi
Size: 800 x 480 px (800 x 480 dp) mdpi
Size: 800 x 480 px (600 x 360 dp) tvdpi
Size: 800 x 480 px (533 x 320 dp) hdpi
Size: 800 x 480 px (266 x 160 dp) xxhdpi
Size: 768 x 576 px (768 x 576 dp) mdpi
Size: 640 x 480 px (640 x 480 dp) mdpi
Size: 640 x 360 px (426 x 240 dp) hdpi
Size: 480 x 320 px (480 x 320 dp) mdpi
Size: 480 x 320 px (320 x 213 dp) hdpi
Size: 432 x 240 px (576 x 320 dp) ldpi
Size: 400 x 240 px (533 x 320 dp) ldpi
Size: 320 x 240 px (426 x 320 dp) ldpi
Size: 280 x 280 px (186 x 186 dp) hdpi

####################################################################################################
#    Sorted by smallest width.
####################################################################################################
sw800dp:
Size: 1920 x 1080 px (1920 x 1080 dp) mdpi
Size: 1024 x 768 px (1365 x 1024 dp) ldpi
Size: 1024 x 960 px (1024 x 960 dp) mdpi
Size: 1920 x 1200 px (1442 x 901 dp) tvdpi
Size: 1600 x 900 px (1600 x 900 dp) mdpi
Size: 800 x 600 px (1066 x 800 dp) ldpi
Size: 1920 x 1200 px (1280 x 800 dp) hdpi
Size: 1024 x 600 px (1365 x 800 dp) ldpi
Size: 2560 x 1600 px (1280 x 800 dp) xhdpi
Size: 1280 x 800 px (1280 x 800 dp) mdpi
Size: 1600 x 1200 px (1066 x 800 dp) hdpi

sw720dp:
Size: 1024 x 770 px (1024 x 770 dp) mdpi
Size: 1366 x 768 px (1366 x 768 dp) mdpi
Size: 1280 x 768 px (1280 x 768 dp) mdpi
Size: 2048 x 1536 px (1024 x 768 dp) xhdpi
Size: 1360 x 768 px (1360 x 768 dp) mdpi
Size: 1024 x 768 px (1024 x 768 dp) mdpi
Size: 1152 x 720 px (1152 x 720 dp) mdpi
Size: 1280 x 720 px (1280 x 720 dp) mdpi
Size: 1920 x 1080 px (1280 x 720 dp) hdpi

sw600dp:
Size: 800 x 480 px (1066 x 640 dp) ldpi
Size: 1440 x 904 px (960 x 602 dp) hdpi
Size: 960 x 600 px (960 x 600 dp) ldpi
Size: 1280 x 800 px (961 x 600 dp) tvdpi
Size: 1024 x 600 px (1024 x 600 dp) mdpi
Size: 1920 x 1200 px (960 x 600 dp) xhdpi

sw480dp:
Size: 768 x 576 px (768 x 576 dp) mdpi
Size: 1920 x 1080 px (960 x 540 dp) xhdpi
Size: 1280 x 720 px (961 x 540 dp) tvdpi
Size: 1280 x 800 px (853 x 533 dp) hdpi
Size: 1280 x 720 px (853 x 480 dp) hdpi
Size: 800 x 480 px (800 x 480 dp) mdpi
Size: 1280 x 960 px (640 x 480 dp) xhdpi
Size: 640 x 480 px (640 x 480 dp) mdpi

sw320dp:
Size: 1080 x 607 px (720 x 404 dp) hdpi
Size: 1024 x 600 px (682 x 400 dp) hdpi
Size: 1280 x 800 px (640 x 400 dp) xhdpi
Size: 1920 x 1200 px (640 x 400 dp) xxhdpi
Size: 1280 x 768 px (640 x 384 dp) xhdpi
Size: 1024 x 768 px (512 x 384 dp) xhdpi
Size: 1920 x 1152 px (640 x 384 dp) xxhdpi
Size: 1279 x 720 px (639 x 360 dp) xhdpi
Size: 800 x 480 px (600 x 360 dp) tvdpi
Size: 960 x 540 px (640 x 360 dp) hdpi
Size: 1920 x 1080 px (640 x 360 dp) xxhdpi
Size: 1280 x 720 px (640 x 360 dp) xhdpi
Size: 432 x 240 px (576 x 320 dp) ldpi
Size: 800 x 480 px (533 x 320 dp) hdpi
Size: 960 x 640 px (480 x 320 dp) xhdpi
Size: 864 x 480 px (576 x 320 dp) hdpi
Size: 854 x 480 px (569 x 320 dp) hdpi
Size: 480 x 320 px (480 x 320 dp) mdpi
Size: 400 x 240 px (533 x 320 dp) ldpi
Size: 320 x 240 px (426 x 320 dp) ldpi

sw240dp:
Size: 640 x 360 px (426 x 240 dp) hdpi

lower:
Size: 480 x 320 px (320 x 213 dp) hdpi
Size: 280 x 280 px (186 x 186 dp) hdpi
Size: 800 x 480 px (266 x 160 dp) xxhdpi

####################################################################################################
#    Different size in px only.
####################################################################################################
2560 x 1600 px
2048 x 1536 px
1920 x 1200 px
1920 x 1152 px
1920 x 1080 px
1600 x 1200 px
1600 x 900 px
1440 x 904 px
1366 x 768 px
1360 x 768 px
1280 x 960 px
1280 x 800 px
1280 x 768 px
1280 x 720 px
1279 x 720 px
1152 x 720 px
1080 x 607 px
1024 x 960 px
1024 x 770 px
1024 x 768 px
1024 x 600 px
960 x 640 px
960 x 600 px
960 x 540 px
864 x 480 px
854 x 480 px
800 x 600 px
800 x 480 px
768 x 576 px
640 x 480 px
640 x 360 px
480 x 320 px
432 x 240 px
400 x 240 px
320 x 240 px
280 x 280 px

####################################################################################################
#    Different size in dp only.
####################################################################################################
1920 x 1080 dp
1600 x 900 dp
1442 x 901 dp
1366 x 768 dp
1365 x 1024 dp
1365 x 800 dp
1360 x 768 dp
1280 x 800 dp
1280 x 768 dp
1280 x 720 dp
1152 x 720 dp
1066 x 800 dp
1066 x 640 dp
1024 x 960 dp
1024 x 770 dp
1024 x 768 dp
1024 x 600 dp
961 x 600 dp
961 x 540 dp
960 x 602 dp
960 x 600 dp
960 x 540 dp
853 x 533 dp
853 x 480 dp
800 x 480 dp
768 x 576 dp
720 x 404 dp
682 x 400 dp
640 x 480 dp
640 x 400 dp
640 x 384 dp
640 x 360 dp
639 x 360 dp
600 x 360 dp
576 x 320 dp
569 x 320 dp
533 x 320 dp
512 x 384 dp
480 x 320 dp
426 x 320 dp
426 x 240 dp
320 x 213 dp
266 x 160 dp
186 x 186 dp

I drop a lot of same-sized same-dp screens, ignore height/width swap and include some sorting results.

How to extract this specific substring in SQL Server?

select substring(your_field, CHARINDEX(';',your_field)+1 ,CHARINDEX('[',your_field)-CHARINDEX(';',your_field)-1) from your_table

Can't get the others to work. I believe you just want what is in between ';' and '[' in all cases regardless of how long the string in between is. After specifying the field in the substring function, the second argument is the starting location of what you will extract. That is, where the ';' is + 1 (fourth position - the c), because you don't want to include ';'. The next argument takes the location of the '[' (position 14) and subtracts the location of the spot after the ';' (fourth position - this is why I now subtract 1 in the query). This basically says substring(field,location I want substring to begin, how long I want substring to be). I've used this same function in other cases. If some of the fields don't have ';' and '[', you'll want to filter those out in the "where" clause, but that's a little different than the question. If your ';' was say... ';;;', you would use 3 instead of 1 in the example. Hope this helps!

How to squash commits in git after they have been pushed?

On a branch I was able to do it like this (for the last 4 commits)

git checkout my_branch
git reset --soft HEAD~4
git commit
git push --force origin my_branch

I do not want to inherit the child opacity from the parent in CSS

If you have to use an image as the transparent background, you might be able to work around it using a pseudo element:

html

<div class="wrap"> 
   <p>I have 100% opacity</p>  
</div>

css

.wrap, .wrap > * {
  position: relative;
}
.wrap:before {
  content: " ";
  opacity: 0.2;
  background: url("http://placehold.it/100x100/FF0000") repeat;     
  position: absolute;
  width: 100%;
  height: 100%;
}

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

There are some problems with your code. First I advise to use parametrized queries so you avoid SQL Injection attacks and also parameter types are discovered by framework:

var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);

Second, as you are interested only in one value getting returned from the query, it is better to use ExecuteScalar:

var name = cmd.ExecuteScalar();

if (name != null)
{
   position = name.ToString();
   Response.Write("User Registration successful");
}
else
{
    Console.WriteLine("No Employee found.");
}

The last thing is to wrap SqlConnection and SqlCommand into using so any resources used by those will be disposed of:

string position;

using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
  con.Open();

  using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con))
  {
    cmd.Parameters.AddWithValue("@id", id.Text);
  
    var name = cmd.ExecuteScalar();
  
    if (name != null)
    {
       position = name.ToString();
       Response.Write("User Registration successful");
    }
    else
    {
        Console.WriteLine("No Employee found.");
    }
  }
}

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

I prefer (a != null) so that the syntax matches reference types.

jQuery append text inside of an existing paragraph tag

I have just discovered a way to append text and its working fine at least.

 var text = 'Put any text here';
 $('#text').append(text);

You can change text according to your need.

Hope this helps.

How to make a section of an image a clickable link

The easiest way is to make the "button image" as a separate image. Then place it over the main image (using "style="position: absolute;". Assign the URL link to "button image". and smile :)

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

<div class="modal show">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">     

    <h4 class="modal-title">Modal title</h4>
     </div>
     <div class="modal-body">
      <p>One fine body&hellip;</p>
  </div>

  </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

i think this codepen can help you prevent modal close css and bootstrap

Get last 30 day records from today date in SQL Server

you can use this to get the data of the last 30 days based on a column.

WHERE DATEDIFF(dateColumn,CURRENT_TIMESTAMP) BETWEEN 0 AND 30

JavaScript OR (||) variable assignment explanation

It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.

var x = '';
var y = 'bob';
var z = x || y;
alert(z);

Will output 'bob';

onclick="javascript:history.go(-1)" not working in Chrome

Try this:

<a href="www.mypage.com" onclick="history.go(-1); return false;"> Link </a>

Best timestamp format for CSV/Excel?

The earlier suggestion to use "yyyy-MM-dd HH:mm:ss" is fine, though I believe Excel has much finer time resolution than that. I find this post rather credible (follow the thread and you'll see lots of arithmetic and experimenting with Excel), and if it's correct, you'll have your milliseconds. You can just tack on decimal places at the end, i.e. "yyyy-mm-dd hh:mm:ss.000".

You should be aware that Excel may not necessarily format the data (without human intervention) in such a way that you will see all of that precision. On my computer at work, when I set up a CSV with "yyyy-mm-dd hh:mm:ss.000" data (by hand using Notepad), I get "mm:ss.0" in the cell and "m/d/yyyy  hh:mm:ss AM/PM" in the formula bar.

For maximum information[1] conveyed in the cells without human intervention, you may want to split up your timestamp into a date portion and a time portion, with the time portion only to the second. It looks to me like Excel wants to give you at most three visible "levels" (where fractions of a second are their own level) in any given cell, and you want seven: years, months, days, hours, minutes, seconds, and fractions of a second.

Or, if you don't need the timestamp to be human-readable but you want it to be as accurate as possible, you might prefer just to store a big number (internally, Excel is just using the number of days, including fractional days, since an "epoch" date).


[1]That is, numeric information. If you want to see as much information as possible but don't care about doing calculations with it, you could make up some format which Excel will definitely parse as a string, and thus leave alone; e.g. "yyyymmdd.hhmmss.000".

change Oracle user account status from EXPIRE(GRACE) to OPEN

Step-1 Need to find user details by using below query

SQL> select username, account_status from dba_users where username='BOB';

USERNAME                       ACCOUNT_STATUS
------------------------------ --------------------------------
BOB                            EXPIRED

Step-2 Get users password by using below query.

SQL>SELECT 'ALTER USER '|| name ||' IDENTIFIED BY VALUES '''|| spare4 ||';'|| password ||''';' FROM sys.user$ WHERE name='BOB';

ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';

Step -3 Run Above alter query

SQL> ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
User altered.

Step-4 :Check users account status

SQL> select username, account_status from dba_users where username='BOB';
USERNAME                       ACCOUNT_STATUS
------------------------------ --------------------------------
BOB                            OPEN

VBA test if cell is in a range

If the two ranges to be tested (your given cell and your given range) are not in the same Worksheet, then Application.Intersect throws an error. Thus, a way to avoid it is with something like

Sub test_inters(rng1 As Range, rng2 As Range)
    If (rng1.Parent.Name = rng2.Parent.Name) Then
        Dim ints As Range
        Set ints = Application.Intersect(rng1, rng2)
        If (Not (ints Is Nothing)) Then
            ' Do your job
        End If
    End If
End Sub

How to cast from List<Double> to double[] in Java?

With , you can do it this way.

double[] arr = frameList.stream().mapToDouble(Double::doubleValue).toArray(); //via method reference
double[] arr = frameList.stream().mapToDouble(d -> d).toArray(); //identity function, Java unboxes automatically to get the double value

What it does is :

  • get the Stream<Double> from the list
  • map each double instance to its primitive value, resulting in a DoubleStream
  • call toArray() to get the array.

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

An optional parameter is just tagged with an attribute. This attribute tells the compiler to insert the default value for that parameter at the call-site.

The call obj2.TestMethod(); is replaced by obj2.TestMethod(false); when the C# code gets compiled to IL, and not at JIT-time.

So in a way it's always the caller providing the default value with optional parameters. This also has consequences on binary versioning: If you change the default value but don't recompile the calling code it will continue to use the old default value.

On the other hand, this disconnect means you can't always use the concrete class and the interface interchangeably.

You already can't do that if the interface method was implemented explicitly.

Override valueof() and toString() in Java enum

You still have an option to implement in your enum this:

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name){...}

How to remove all whitespace from a string?

I just learned about the "stringr" package to remove white space from the beginning and end of a string with str_trim( , side="both") but it also has a replacement function so that:

a <- " xx yy 11 22 33 " 
str_replace_all(string=a, pattern=" ", repl="")

[1] "xxyy112233"

Remove Identity from a column in a table

You cannot remove an IDENTITY specification once set.

To remove the entire column:

ALTER TABLE yourTable
DROP COLUMN yourCOlumn;

Information about ALTER TABLE here

If you need to keep the data, but remove the IDENTITY column, you will need to:

  • Create a new column
  • Transfer the data from the existing IDENTITY column to the new column
  • Drop the existing IDENTITY column.
  • Rename the new column to the original column name

How can I Convert HTML to Text in C#?

Here is the short sweet answer using HtmlAgilityPack. You can run this in LinqPad.

var html = "<div>..whatever html</div>";
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var plainText = doc.DocumentNode.InnerText;

I simply use HtmlAgilityPack in any .NET project that needs HTML parsing. It's simple, reliable, and fast.

Checking for an empty file in C++

Ok, so this piece of code should work for you. I changed the names to match your parameter.

inFile.seekg(0, ios::end);  
if (inFile.tellg() == 0) {    
  // ...do something with empty file...  
}

How to instantiate a javascript class in another js file?

You can export your methods to access from other files like this:

file1.js

var name = "Jhon";
exports.getName = function() {
  return name;
}

file2.js

var instance = require('./file1.js');
var name = instance.getName();

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I finally found the problem. The error was not the good one.

Apparently, Ole DB source have a bug that might make it crash and throw that error. I replaced the OLE DB destination with a OLE DB Command with the insert statement in it and it fixed it.

The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

Strange Bug, Hope it will help other people.

Using Service to run background and create notification

The question is relatively old, but I hope this post still might be relevant for others.

TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;

What this test-application(and instruction) is about:

Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.

When should you use it:

Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.

What to do:

  1. First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
        <Button
            android:id="@+id/sendNotifications"
            android:onClick="onSendNotificationsButtonClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start Sending Notifications Every 2 Hours!" />
    </RelativeLayout>
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void onSendNotificationsButtonClick(View view) {
            NotificationEventReceiver.setupAlarm(getApplicationContext());
        }   
    }
    

    and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.

  2. Then let's create WakefulBroadcastReceiver broadcast receiver, I called NotificationEventReceiver in code above.

    Here, we'll set up AlarmManager to fire PendingIntent every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive() method. In our case - wakefully start IntentService, which we'll specify in the later steps. This IntentService would generate notifications for us.

    Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later

    NB1! As I'm using WakefulBroadcastReceiver, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />

    NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.

    NotificationEventReceiver.java

    public class NotificationEventReceiver extends WakefulBroadcastReceiver {
    
        private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
        private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
        private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    
        public static void setupAlarm(Context context) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent alarmIntent = getStartPendingIntent(context);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    getTriggerAt(new Date()),
                    NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
                    alarmIntent);
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Intent serviceIntent = null;
            if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
                serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
            } else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
                serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
            }
    
            if (serviceIntent != null) {
                startWakefulService(context, serviceIntent);
            }
        }
    
        private static long getTriggerAt(Date now) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
            return calendar.getTimeInMillis();
        }
    
        private static PendingIntent getStartPendingIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    
        public static PendingIntent getDeleteIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_DELETE_NOTIFICATION);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    }
    
  3. Now let's create an IntentService to actually create notifications.

    There, we specify onHandleIntent() which is responses on NotificationEventReceiver's intent we passed in startWakefulService method.

    If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder we're composing new notification and showing it by NotificationManager.notify. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.

    NotificationIntentService.java

    public class NotificationIntentService extends IntentService {
    
        private static final int NOTIFICATION_ID = 1;
        private static final String ACTION_START = "ACTION_START";
        private static final String ACTION_DELETE = "ACTION_DELETE";
    
        public NotificationIntentService() {
            super(NotificationIntentService.class.getSimpleName());
        }
    
        public static Intent createIntentStartNotificationService(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_START);
            return intent;
        }
    
        public static Intent createIntentDeleteNotification(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_DELETE);
            return intent;
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
            try {
                String action = intent.getAction();
                if (ACTION_START.equals(action)) {
                    processStartNotification();
                }
                if (ACTION_DELETE.equals(action)) {
                    processDeleteNotification(intent);
                }
            } finally {
                WakefulBroadcastReceiver.completeWakefulIntent(intent);
            }
        }
    
        private void processDeleteNotification(Intent intent) {
            // Log something?
        }
    
        private void processStartNotification() {
            // Do something. For example, fetch fresh data from backend to create a rich notification?
    
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setContentTitle("Scheduled Notification")
                    .setAutoCancel(true)
                    .setColor(getResources().getColor(R.color.colorAccent))
                    .setContentText("This notification has been triggered by Notification Service")
                    .setSmallIcon(R.drawable.notification_icon);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    NOTIFICATION_ID,
                    new Intent(this, NotificationActivity.class),
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
            builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
    
            final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(NOTIFICATION_ID, builder.build());
        }
    }
    
  4. Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).

    NotificationServiceStarterReceiver.java

    public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationEventReceiver.setupAlarm(context);
        }
    }
    
  5. We need to also register all our services, broadcast receivers in AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="klogi.com.notificationbyschedule">
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <service
                android:name=".notifications.NotificationIntentService"
                android:enabled="true"
                android:exported="false" />
    
            <receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
            <receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.TIMEZONE_CHANGED" />
                    <action android:name="android.intent.action.TIME_SET" />
                </intent-filter>
            </receiver>
    
            <activity
                android:name=".NotificationActivity"
                android:label="@string/title_activity_notification"
                android:theme="@style/AppTheme.NoActionBar"/>
        </application>
    
    </manifest>
    

That's it!

The source code for this project you can find here. I hope, you will find this post helpful.

retrieve links from web page using python and BeautifulSoup

There can be many duplicate links together with both external and internal links. To differentiate between the two and just get unique links using sets:

# Python 3.
import urllib    
from bs4 import BeautifulSoup

url = "http://www.espncricinfo.com/"
resp = urllib.request.urlopen(url)
# Get server encoding per recommendation of Martijn Pieters.
soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))  
external_links = set()
internal_links = set()
for line in soup.find_all('a'):
    link = line.get('href')
    if not link:
        continue
    if link.startswith('http'):
        external_links.add(link)
    else:
        internal_links.add(link)

# Depending on usage, full internal links may be preferred.
full_internal_links = {
    urllib.parse.urljoin(url, internal_link) 
    for internal_link in internal_links
}

# Print all unique external and full internal links.
for link in external_links.union(full_internal_links):
    print(link)

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

var list = new List<string> { "One", "Two", "Three" };

Essentially the syntax is:

new List<Type> { Instance1, Instance2, Instance3 };

Which is translated by the compiler as

List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");

How to extract one column of a csv file

Many answers for this questions are great and some have even looked into the corner cases. I would like to add a simple answer that can be of daily use... where you mostly get into those corner cases (like having escaped commas or commas in quotes etc.,).

FS (Field Separator) is the variable whose value is dafaulted to space. So awk by default splits at space for any line.

So using BEGIN (Execute before taking input) we can set this field to anything we want...

awk 'BEGIN {FS = ","}; {print $3}'

The above code will print the 3rd column in a csv file.

Postgresql SELECT if string contains

In addition to the solution with 'aaaaaaaa' LIKE '%' || tag_name || '%' there are position (reversed order of args) and strpos.

SELECT id FROM TAG_TABLE WHERE strpos('aaaaaaaa', tag_name) > 0

Besides what is more efficient (LIKE looks less efficient, but an index might change things), there is a very minor issue with LIKE: tag_name of course should not contain % and especially _ (single char wildcard), to give no false positives.

HTML-encoding lost when attribute read from input field

Underscore provides _.escape() and _.unescape() methods that do this.

> _.unescape( "chalk &amp; cheese" );
  "chalk & cheese"

> _.escape( "chalk & cheese" );
  "chalk &amp; cheese"

How to use vertical align in bootstrap

.parent {
    display: table;
    table-layout: fixed;
}

.child {
    display:table-cell;
    vertical-align:middle;
    text-align:center;
}

table-layout: fixed prevents breaking the functionality of the col-* classes.

In C#, how to check if a TCP port is available?

To answer the exact question of finding a free port (which is what I needed in my unit tests) in dotnet core 3.1 I came up this

public static int GetAvailablePort(IPAddress ip) {
        TcpListener l = new TcpListener(ip, 0);
        l.Start();
        int port = ((IPEndPoint)l.LocalEndpoint).Port;
        l.Stop();
        Log.Info($"Available port found: {port}");
        return port;
    }

note: based the comment by @user207421 about port zero I searched and found this and slightly modified it.

Where to declare variable in react js

Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.

Android basics: running code in the UI thread

If you need to use in Fragment you should use

private Context context;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }


    ((MainActivity)context).runOnUiThread(new Runnable() {
        public void run() {
            Log.d("UI thread", "I am the UI thread");
        }
    });

instead of

getActivity().runOnUiThread(new Runnable() {
    public void run() {
        Log.d("UI thread", "I am the UI thread");
    }
});

Because There will be null pointer exception in some situation like pager fragment

Mongoose.js: Find user by username LIKE value

Here my code with expressJS:

router.route('/wordslike/:word')
    .get(function(request, response) {
            var word = request.params.word;       
            Word.find({'sentence' : new RegExp(word, 'i')}, function(err, words){
               if (err) {response.send(err);}
               response.json(words);
            });
         });

bash string compare to multiple correct values

Maybe you should better use a case for such lists:

case "$cms" in
  wordpress|meganto|typo3)
    do_your_else_case
    ;;
  *)
    do_your_then_case
    ;;
esac

I think for long such lists this is better readable.

If you still prefer the if you can do it with single brackets in two ways:

if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then

or

if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then

curl Failed to connect to localhost port 80

In my case, the file ~/.curlrc had a wrong proxy configured.

Play/pause HTML 5 video using JQuery

I use FancyBox and jQuery to embedd a video. Give it an ID.

Perhaps not the BEST solution could toggle play/pause differently - but easy for me and IT WORKS! :)

In the

`

<input type="hidden" id="current_video_playing">

<input type="hidden" id="current_video_status" value="playing">

<video id="video-1523" autobuffer="false" src="movie.mp4"></video>

<script>

// Play Pause with spacebar

$(document).keypress(function(e) { 

    theVideo = document.getElementById('current_video_playing').value

    if (e.which == 32) {

        if (document.getElementById('current_video_status').value == 'playing') {

            document.getElementById(theVideo).pause();

            document.getElementById('current_video_status').value = 'paused'

        } else {

            document.getElementById('current_video_status').value = 'playing'

            document.getElementById(theVideo).play();

        }

    }

});

</script>`

bootstrap datepicker today as default

Its simple

$(function() {
        $("#datePicker").datetimepicker({
            defaultDate:'now'

        });
    });

This will set today as default

Get bytes from std::string in C++

If you just need read-only access, then c_str() will do it:

char const *c = myString.c_str();

If you need read/write access, then you can copy the string into a vector. vectors manage dynamic memory for you. You don't have to mess with allocation/deallocation then:

std::vector<char> bytes(myString.begin(), myString.end());
bytes.push_back('\0');
char *c = &bytes[0];

There is already an open DataReader associated with this Command which must be closed first

I dont know whether this is duplicate answer or not. If it is I am sorry. I just want to let the needy know how I solved my issue using ToList().

In my case I got same exception for below query.

int id = adjustmentContext.InformationRequestOrderLinks.Where(
             item => item.OrderNumber == irOrderLinkVO.OrderNumber 
                  && item.InformationRequestId == irOrderLinkVO.InformationRequestId)
             .Max(item => item.Id);

I solved like below

List<Entities.InformationRequestOrderLink> links = 
      adjustmentContext.InformationRequestOrderLinks
           .Where(item => item.OrderNumber == irOrderLinkVO.OrderNumber 
                       && item.InformationRequestId == irOrderLinkVO.InformationRequestId)
           .ToList();

int id = 0;

if (links.Any())
{
  id = links.Max(x => x.Id);
}
if (id == 0)
{
//do something here
}

SQL query for finding records where count > 1

Use the HAVING clause and GROUP By the fields that make the row unique

The below will find

all users that have more than one payment per day with the same account number

SELECT 
 user_id ,
 COUNT(*) count
FROM 
 PAYMENT
GROUP BY
 account,
 user_id ,
 date
HAVING
COUNT(*) > 1

Update If you want to only include those that have a distinct ZIP you can get a distinct set first and then perform you HAVING/GROUP BY

 SELECT 
    user_id,
    account_no , 
    date,
        COUNT(*)
 FROM
    (SELECT DISTINCT
            user_id,
            account_no , 
            zip, 
            date
         FROM
            payment 
    
        ) 
        payment
 GROUP BY
    
    user_id,
    account_no , 
    
    date
HAVING COUNT(*) > 1

Server unable to read htaccess file, denying access to be safe

Just my solution. I had extracted a file, had some minor changes, and got the error above. Deleted everything, uploaded and extracted again, and normal business.

How do I get Fiddler to stop ignoring traffic to localhost?

Windows XP:

Be sure to set to click the settings button for each of the items in the "Dial-up and Virtual Private Network settings" listbox in the "Connections" tab of the "Internet Options" control panel applet.

I noticed that Fiddler would stop using the "LAN settings" configuration once I connected to my VPN. Even if the traffic wasn't going through the VPN.

How to read input with multiple lines in Java

This is good for taking multiple line input

import java.util.Scanner;
public class JavaApp {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String line;
        while(true){
            line = scanner.nextLine();
            System.out.println(line);
            if(line.equals("")){
                break;
            }
        }
    }  
}

PostgreSQL: Show tables in PostgreSQL

  1. In PostgreSQL command-line interface after login, type the following command to connect with the desired database.

        \c [database_name]
    

Then you will see this message You are now connected to database "[database_name]"

  1. Type the following command to list all the tables.

        \dt
    

How can I open two pages from a single click without using JavaScript?

If you have the authority to edit the pages to be opened, you can href to 'A' page and in the A page you can put link to B page in onpageload attribute of body tag.

How can I escape white space in a bash loop list?

Here is a simple solution which handles tabs and/or whitespaces in the filename. If you have to deal with other strange characters in the filename like newlines, pick another answer.

The test directory

ls -F test
Baltimore/  Cherry Hill/  Edison/  New York City/  Philadelphia/  cities.txt

The code to go into the directories

find test -type d | while read f ; do
  echo "$f"
done

The filename must be quoted ("$f") if used as argument. Without quotes, the spaces act as argument separator and multiple arguments are given to the invoked command.

And the output:

test/Baltimore
test/Cherry Hill
test/Edison
test/New York City
test/Philadelphia

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

How do I get currency exchange rates via an API such as Google Finance?

You can try geoplugin

Beside the geolocation done by IP (but the IP is the provider IP, so not so accurate), they return currencies also and have a currency converter: see examples.

They have 111 currencies updated.

How to create an XML document using XmlDocument?

What about:

#region Using Statements
using System;
using System.Xml;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XmlDocument doc = new XmlDocument( );

        //(1) the xml declaration is recommended, but not mandatory
        XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore( xmlDeclaration, root );

        //(2) string.Empty makes cleaner code
        XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
        doc.AppendChild( element1 );

        XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
        element1.AppendChild( element2 );

        XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text1 = doc.CreateTextNode( "text" );
        element3.AppendChild( text1 );
        element2.AppendChild( element3 );

        XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text2 = doc.CreateTextNode( "other text" );
        element4.AppendChild( text2 );
        element2.AppendChild( element4 );

        doc.Save( "D:\\document.xml" );
    }
}

(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?


The result is:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

But I recommend you to use LINQ to XML which is simpler and more readable like here:

#region Using Statements
using System;
using System.Xml.Linq;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XDocument doc = new XDocument( new XElement( "body", 
                                           new XElement( "level1", 
                                               new XElement( "level2", "text" ), 
                                               new XElement( "level2", "other text" ) ) ) );
        doc.Save( "D:\\document.xml" );
    }
}

Apache shows PHP code instead of executing it

Run Xampp (apache) as administrator. In google chrome type:

localhost/<insert folder name here>/<insert file name>

i.e. if folder you created is "LearnPhp", file is "chapter1.php" then type

localhost/LearnPhp/chapter1.php

I created this folder in the xampp folder in the htdocs folder which gets created when you download xampp.

How do I compare two string variables in an 'if' statement in Bash?

I don't have access to a Linux box right now, but [ is actually a program (and a Bash builtin), so I think you have to put a space between [ and the first parameter.

Also note that the string equality operator seems to be a single =.

How can I use goto in Javascript?

const
    start = 0,
    more = 1,
    pass = 2,
    loop = 3,
    skip = 4,
    done = 5;

var label = start;


while (true){
    var goTo = null;
    switch (label){
        case start:
            console.log('start');
        case more:
            console.log('more');
        case pass:
            console.log('pass');
        case loop:
            console.log('loop');
            goTo = pass; break;
        case skip:
            console.log('skip');
        case done:
            console.log('done');

    }
    if (goTo == null) break;
    label = goTo;
}

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

How to install SQL Server 2005 Express in Windows 8

Microsoft SQL Server 2005 Express Edition Service Pack 4 on Windows Server 2012 R2

Those steps are based on previous howto from https://stackoverflow.com/users/2385/eduardo-molteni

  1. download SQLEXPR.EXE
  2. run SQLEXPR.EXE
  3. copy c:\generated_installation_dir to inst.bak
  4. quit install
  5. run inst.bak/setuip/sqlncli_x64.msi
  6. run SQLEXPR.EXE
  7. enjoy!

This works with Microsoft SQL Server 2005 Express Edition Service Pack 4 http://www.microsoft.com/en-us/download/details.aspx?id=184

How do I use HTML as the view engine in Express?

to server html pages through routing, I have done this.

var hbs = require('express-hbs');
app.engine('hbs', hbs.express4({
  partialsDir: __dirname + '/views/partials'
}));
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');

and renamed my .html files to .hbs files - handlebars support plain html

Can Android Studio be used to run standard Java projects?

Tested in Android Studio 0.8.14:
I was able to get a standard project running with minimal steps in this way:

  • In an open Android Studio project, click File > New Module.
  • Click More Modules > Java Library > Next, then fill in whatever you prefer for the names.
  • A new module will appear as a folder on the same level as your "app" folder in the Project Structure. Open it and open the new Java class file.

    You can then add your code, and choose Build > Run 'YourClassName'. Presto, your code is running with no Android device!

  • When do you use map vs flatMap in RxJava?

    I just wanted to add that with flatMap, you don't really need to use your own custom Observable inside the function and you can rely on standard factory methods/operators:

    Observable.from(jsonFile).flatMap(new Func1<File, Observable<String>>() {
        @Override public Observable<String> call(final File file) {
            try {
                String json = new Gson().toJson(new FileReader(file), Object.class);
                return Observable.just(json);
            } catch (FileNotFoundException ex) {
                return Observable.<String>error(ex);
            }
        }
    });
    

    Generally, you should avoid throwing (Runtime-) exceptions from onXXX methods and callbacks if possible, even though we placed as many safeguards as we could in RxJava.

    Return positions of a regex match() in Javascript?

    exec returns an object with a index property:

    _x000D_
    _x000D_
    var match = /bar/.exec("foobar");_x000D_
    if (match) {_x000D_
        console.log("match found at " + match.index);_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    And for multiple matches:

    _x000D_
    _x000D_
    var re = /bar/g,_x000D_
        str = "foobarfoobar";_x000D_
    while ((match = re.exec(str)) != null) {_x000D_
        console.log("match found at " + match.index);_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    How to store a command in a variable in a shell script?

    Be Careful registering an order with the: X=$(Command)

    This one is still executed Even before being called. To check and confirm this, you cand do:

    echo test;
    X=$(for ((c=0; c<=5; c++)); do
    sleep 2;
    done);
    echo note the 5 seconds elapsed
    

    Setting Android Theme background color

    <resources>
    
        <!-- Base application theme. -->
        <style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
            <item name="android:windowBackground">@android:color/black</item>
        </style>
    
    </resources>
    

    What does "connection reset by peer" mean?

    It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:

    "Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.

    How to use target in location.href

    If you go with the solution by @qiao, perhaps you would want to remove the appended child since the tab remains open and subsequent clicks would add more elements to the DOM.

    // Code by @qiao
    var a = document.createElement('a')
    a.href = 'http://www.google.com'
    a.target = '_blank'
    document.body.appendChild(a)
    a.click()
    // Added code
    document.body.removeChild(a)
    

    Maybe someone could post a comment to his post, because I cannot.

    How to use Macro argument as string literal?

    You want to use the stringizing operator:

    #define STRING(s) #s
    
    int main()
    {
        const char * cstr = STRING(abc); //cstr == "abc"
    }
    

    Make code in LaTeX look *nice*

    The listings package is quite nice and very flexible (e.g. different sizes for comments and code).

    Remove x-axis label/text in chart.js

    Faced this issue of removing the labels in Chartjs now. Looks like the documentation is improved. http://www.chartjs.org/docs/#getting-started-global-chart-configuration

    Chart.defaults.global.legend.display = false;
    

    this global settings prevents legends from being shown in all Charts. Since this was enough for me, I used it. I am not sure to how to avoid legends for individual charts.

    CSS hide scroll bar, but have element scrollable

    if you use sass, you can try this

    &::-webkit-scrollbar { 
    
    }
    

    Editing dictionary values in a foreach loop

    How about just doing some linq queries against your dictionary, and then binding your graph to the results of those?...

    var under = colStates.Where(c => (decimal)c.Value / (decimal)totalCount < .05M);
    var over = colStates.Where(c => (decimal)c.Value / (decimal)totalCount >= .05M);
    var newColStates = over.Union(new Dictionary<string, int>() { { "Other", under.Sum(c => c.Value) } });
    
    foreach (var item in newColStates)
    {
        Console.WriteLine("{0}:{1}", item.Key, item.Value);
    }
    

    Creating a new column based on if-elif-else condition

    For this particular relationship, you could use np.sign:

    >>> df["C"] = np.sign(df.A - df.B)
    >>> df
       A  B  C
    a  2  2  0
    b  3  1  1
    c  1  3 -1
    

    How to convert a string of numbers to an array of numbers?

    My 2 cents for golfers:

    b="1,2,3,4".split`,`.map(x=>+x)
    

    backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(','). The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x (which is even shorter than the Number function (5 chars instead of 6)) is equivalent to :

    function(x){return parseInt(x,10)}// version from techfoobar
    (x)=>{return parseInt(x)}         // lambda are shorter and parseInt default is 10
    (x)=>{return +x}                  // diff. with parseInt in SO but + is better in this case
    x=>+x                             // no multiple args, just 1 function call
    

    I hope it is a bit more clear.

    Overloading operators in typedef structs (c++)

    1. bool operator==(pos a) const{ - this method doesn't change object's elements.
    2. bool operator==(pos a) { - it may change object's elements.

    T-SQL How to select only Second row from a table?

    Use TOP 2 in the SELECT to get the desired number of rows in output. This would return in the sequence the data was created. If you have a date option you could order by the date along with TOP n Clause.

    To get the top 2 rows;

    SELECT TOP 2 [Id] FROM table 
    

    To get the top 2 rows order by some field

    SELECT TOP 2 [ID] FROM table ORDER BY <YourColumn> ASC/DESC
    

    To Get only 2nd Row;

    WITH Resulttable AS 
    ( 
      SELECT TOP 2 
        *, ROW_NUMBER() OVER(ORDER BY YourColumn) AS RowNumber 
      FROM @Table 
    )  
    SELECT *
    FROM Resultstable
    WHERE RowNumber = 2
    

    correct way to use super (argument passing)

    If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

    class First(object):
        def __init__(self, *args, **kwargs):
            self.first_arg = kwargs.pop('first_arg')
            super(First, self).__init__(*args, **kwargs)
    
    class Second(First):
        def __init__(self, *args, **kwargs):
            self.second_arg = kwargs.pop('second_arg')
            super(Second, self).__init__(*args, **kwargs)
    
    class Third(Second):
        def __init__(self, *args, **kwargs):
            self.third_arg = kwargs.pop('third_arg')
            super(Third, self).__init__(*args, **kwargs)
    

    This is the simplest way to solve those kind of problems.

    third = Third(first_arg=1, second_arg=2, third_arg=3)
    

    Why is division in Ruby returning an integer instead of decimal value?

    It’s doing integer division. You can make one of the numbers a Float by adding .0:

    9.0 / 5  #=> 1.8
    9 / 5.0  #=> 1.8
    

    jQuery, checkboxes and .is(":checked")

    $( "#checkbox" ).change(function() {
        if($(this).is(":checked")){
            alert('hi');
        }
    
    });
    

    How to increase code font size in IntelliJ?

    It's as simple as Ctrl + mouse wheel. If this doesn't work for you, enable File ? Settings ? Editor ? General ? (checked) Change font size (Zoom) with Ctrl+Mouse Wheel.

    how to inherit Constructor from super class to sub class

    Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass.

    Here is an example of how this works:

    class Foo {
        Foo(String str) { }
    }
    
    class Bar extends Foo {
        Bar(String str) {
            // Here I am explicitly calling the superclass 
            // constructor - since constructors are not inherited
            // you must chain them like this.
            super(str);
        }
    }
    

    Aborting a stash pop in Git

    I'm posting here hoping that others my find my answer helpful. I had a similar problem when I tried to do a stash pop on a different branch than the one I had stashed from. On my case I had no files that were uncommitted or in the index but still got into the merge conflicts case (same case as @pid). As others pointed out previously, the failed git stash pop did indeed retain my stash, then A quick git reset HEAD plus going back to my original branch and doing the stash from there did resolve my problem.

    Bash script processing limited number of commands in parallel

    See parallel. Its syntax is similar to xargs, but it runs the commands in parallel.

    In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

    1. Final • Final is used to apply restrictions on class, method and variable. • Final class can't be inherited, final method can't be overridden and final variable value can't be changed. • Final variables are initialized at the time of creation except in case of blank final variable which is initialized in Constructor. • Final is a keyword.

    2. Finally • Finally is used for exception handling along with try and catch. • It will be executed whether exception is handled or not. • This block is used to close the resources like database connection, I/O resources. • Finally is a block.

    3. Finalize • Finalize is called by Garbage collection thread just before collecting eligible objects to perform clean up processing. • This is the last chance for object to perform any clean-up but since it’s not guaranteed that whether finalize () will be called, its bad practice to keep resource till finalize call. • Finalize is a method.

    Matching an optional substring in a regex

    (\d+)\s+(\(.*?\))?\s?Z
    

    Note the escaped parentheses, and the ? (zero or once) quantifiers. Any of the groups you don't want to capture can be (?: non-capture groups).

    I agree about the spaces. \s is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^ at the front and a $ at the end).

    How to set a default row for a query that returns no rows?

    Do you want to return a full row? Does the default row need to have default values or can it be an empty row? Do you want the default row to have the same column structure as the table in question?

    Depending on your requirements, you might do something like this:

    1) run the query and put results in a temp table (or table variable) 2) check to see if the temp table has results 3) if not, return an empty row by performing a select statement similar to this (in SQL Server):

    select '' as columnA, '' as columnB, '' as columnC from #tempTable
    

    Where columnA, columnB and columnC are your actual column names.

    Importing a Maven project into Eclipse from Git

    Here's my workaround, this is a solution to these issues:

    • You can't install m2e-egit (I get an error in Juno)
    • Converting a general project (connected to your Git repository) to a Maven project isn't working for you (The Import Maven Projects step seems essential)
    • Importing Maven Projects from your repository on the filesystem isn't showing the project connected to Git.

    1. Setup your Git repository in the Git Repository Exploring perspective.
      • Switch to the Java perspective, Import > Existing Maven Projects
      • Browse to your Git checkout in the filesystem, select the directory containing the pom.xml file. Finish the import; you'll notice these projects aren't connected to Git. :-(
      • Delete these projects, but DO NOT DELETE FROM FILESYSTEM. We don't want our clone deleted; this task also leaves the .project file behind so that we can import in the next step.
    2. Go back to the Git Repository Exploring perspective.
      • Right-click your repository, Import Projects...
      • Select Import existing projects
      • In the explorer below, browse to and select the directory containing the pom.xml (and .project file) , then click next.
      • Continue through the wizard.

    Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

    You are mixing mysqli and mysql extensions, which will not work.

    You need to use

    $myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql"); 
    
    mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");   
    

    mysqli has many improvements over the original mysql extension, so it is recommended that you use mysqli.

    Check if a given time lies between two times regardless of date

    Sounds to me that your problem is an OR situation... You want to check if time1 > 20:11:13 OR time1 < 14:49:00.

    There will never be a time greater to 20:11:13 that exceeds your range through the other end (14:49:00) and viceversa. Think of it as if you are checking that a time is NOT between a properly ordered couple of timestamps.

    Fuzzy matching using T-SQL

    In addition to the other good info here, you might want to consider using the Double Metaphone phonetic algorithm which is generally considered to be better than SOUNDEX.

    Tim Pfeiffer details an implementation in SQL in his article Double Metaphone Sounds Great Convert the C++ Double Metaphone algorithm to T-SQL (originally in SQL Mag & then in SQL Server Pro).

    That will assist in matching names with slight misspellings, e.g., Carl vs. Karl.

    Update: The actual downloadable code seems to be gone, but here's an implementation found on a github repo that appears to have cloned the original code

    Uncaught SyntaxError: Unexpected token with JSON.parse

    Why you need JSON.parse? It's already in array of object format.

    Better use JSON.stringify as below : var b = JSON.stringify(products);

    This may help you.

    jQuery onclick event for <li> tags

    I'm not really sure what your question is, but to get the text of the li element you can use:

    $(this).text();

    And to get the id of an element you can use .attr('id');. Once you have a reference to the element you want (e.g. $(this)) you can perform any jQuery function on it.

    How to update specific key's value in an associative array in PHP?

    PHP array_walk() function is specifically for altering array.

    Try this:

    array_walk ( $data, function (&$key) { 
        $key["transaction_date"] = date('d/m/Y',$key["transaction_date"]); 
    });
    

    How to undo a successful "git cherry-pick"?

    To undo your last commit, simply do git reset --hard HEAD~.

    Edit: this answer applied to an earlier version of the question that did not mention preserving local changes; the accepted answer from Tim is indeed the correct one. Thanks to qwertzguy for the heads up.

    Regex using javascript to return just numbers

    If you want dot/comma separated numbers also, then:

    \d*\.?\d*
    

    or

    [0-9]*\.?[0-9]*
    

    You can use https://regex101.com/ to test your regexes.

    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 generate entire DDL of an Oracle schema (scriptable)?

    To generate the DDL script for an entire SCHEMA i.e. a USER, you could use dbms_metadata.get_ddl.

    Execute the following script in SQL*Plus created by Tim Hall:

    Provide the username when prompted.

    set long 20000 longchunksize 20000 pagesize 0 linesize 1000 feedback off verify off trimspool on
    column ddl format a1000
    
    begin
       dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'SQLTERMINATOR', true);
       dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'PRETTY', true);
    end;
    /
    
    variable v_username VARCHAR2(30);
    
    exec:v_username := upper('&1');
    
    select dbms_metadata.get_ddl('USER', u.username) AS ddl
    from   dba_users u
    where  u.username = :v_username
    union all
    select dbms_metadata.get_granted_ddl('TABLESPACE_QUOTA', tq.username) AS ddl
    from   dba_ts_quotas tq
    where  tq.username = :v_username
    and    rownum = 1
    union all
    select dbms_metadata.get_granted_ddl('ROLE_GRANT', rp.grantee) AS ddl
    from   dba_role_privs rp
    where  rp.grantee = :v_username
    and    rownum = 1
    union all
    select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', sp.grantee) AS ddl
    from   dba_sys_privs sp
    where  sp.grantee = :v_username
    and    rownum = 1
    union all
    select dbms_metadata.get_granted_ddl('OBJECT_GRANT', tp.grantee) AS ddl
    from   dba_tab_privs tp
    where  tp.grantee = :v_username
    and    rownum = 1
    union all
    select dbms_metadata.get_granted_ddl('DEFAULT_ROLE', rp.grantee) AS ddl
    from   dba_role_privs rp
    where  rp.grantee = :v_username
    and    rp.default_role = 'YES'
    and    rownum = 1
    union all
    select to_clob('/* Start profile creation script in case they are missing') AS ddl
    from   dba_users u
    where  u.username = :v_username
    and    u.profile <> 'DEFAULT'
    and    rownum = 1
    union all
    select dbms_metadata.get_ddl('PROFILE', u.profile) AS ddl
    from   dba_users u
    where  u.username = :v_username
    and    u.profile <> 'DEFAULT'
    union all
    select to_clob('End profile creation script */') AS ddl
    from   dba_users u
    where  u.username = :v_username
    and    u.profile <> 'DEFAULT'
    and    rownum = 1
    /
    
    set linesize 80 pagesize 14 feedback on trimspool on verify on
    

    What does \u003C mean?

    It is a unicode char \u003C = <

    Reading a cell value in Excel vba and write in another Cell

    I have this function for this case ..

    Function GetValue(r As Range, Tag As String) As Integer
    Dim c, nRet As String
    Dim n, x As Integer
    Dim bNum As Boolean
    
    c = r.Value
    n = InStr(c, Tag)
    For x = n + 1 To Len(c)
      Select Case Mid(c, x, 1)
        Case ":":    bNum = True
        Case " ": Exit For
        Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
      End Select
    Next
    GetValue = val(nRet)
    End Function
    

    To fill cell BC .. (assumed that you check cell A1)

    Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")
    

    Getting value of HTML Checkbox from onclick/onchange events

    For React.js, you can do this with more readable code. Hope it helps.

    handleCheckboxChange(e) {
      console.log('value of checkbox : ', e.target.checked);
    }
    render() {
      return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
    }
    

    How to get default gateway in Mac OSX

    I would use something along these lines...

     netstat -rn | grep "default" | awk '{print $2}'
    

    No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

    in addition,if you try to use CustomActionBarTheme,make sure there is

    <application android:theme="@style/CustomActionBarTheme" ... />
    

    in AndroidManifest.xml

    not

    <application android:theme="@android:style/CustomActionBarTheme" ... />
    

    How can I loop through a List<T> and grab each item?

    Just for completeness, there is also the LINQ/Lambda way:

    myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));
    

    How to link external javascript file onclick of button

    I have to agree with the comments above, that you can't call a file, but you could load a JS file like this, I'm unsure if it answers your question but it may help... oh and I've used a link instead of a button in my example...

    <a href='linkhref.html' id='mylink'>click me</a>
    
    <script type="text/javascript">
    
    var myLink = document.getElementById('mylink');
    
    myLink.onclick = function(){
    
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "Public/Scripts/filename.js."; 
        document.getElementsByTagName("head")[0].appendChild(script);
        return false;
    
    }
    
    
    </script>
    

    Excel Create Collapsible Indented Row Hierarchies

    A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

    Static methods in Python?

    You don't really need to use the @staticmethod decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)

    Mostly, you just use functions though...

    Difference between InvariantCulture and Ordinal string comparison

    Although the question is about equality, for quick visual reference, here the order of some strings sorted using a couple of cultures illustrating some of the idiosyncrasies out there.

    Ordinal          0 9 A Ab a aB aa ab ss Ä Äb ß ä äb ? ? ? ? ? A
    IgnoreCase       0 9 a A aa ab Ab aB ss ä Ä äb Äb ß ? ? ? ? ? A
    --------------------------------------------------------------------
    InvariantCulture 0 9 a A A ä Ä aa ab aB Ab äb Äb ss ß ? ? ? ? ?
    IgnoreCase       0 9 A a A Ä ä aa Ab aB ab Äb äb ß ss ? ? ? ? ?
    --------------------------------------------------------------------
    da-DK            0 9 a A A ab aB Ab ss ß ä Ä äb Äb aa ? ? ? ? ?
    IgnoreCase       0 9 A a A Ab aB ab ß ss Ä ä Äb äb aa ? ? ? ? ?
    --------------------------------------------------------------------
    de-DE            0 9 a A A ä Ä aa ab aB Ab äb Äb ß ss ? ? ? ? ?
    IgnoreCase       0 9 A a A Ä ä aa Ab aB ab Äb äb ss ß ? ? ? ? ?
    --------------------------------------------------------------------
    en-US            0 9 a A A ä Ä aa ab aB Ab äb Äb ß ss ? ? ? ? ?
    IgnoreCase       0 9 A a A Ä ä aa Ab aB ab Äb äb ss ß ? ? ? ? ?
    --------------------------------------------------------------------
    ja-JP            0 9 a A A ä Ä aa ab aB Ab äb Äb ß ss ? ? ? ? ?
    IgnoreCase       0 9 A a A Ä ä aa Ab aB ab Äb äb ss ß ? ? ? ? ?
    

    Observations:

    • de-DE, ja-JP, and en-US sort the same way
    • Invariant only sorts ss and ß differently from the above three cultures
    • da-DK sorts quite differently
    • the IgnoreCase flag matters for all sampled cultures

    The code used to generate above table:

    var l = new List<string>
        { "0", "9", "A", "Ab", "a", "aB", "aa", "ab", "ss", "ß",
          "Ä", "Äb", "ä", "äb", "?", "?", "?", "?", "A", "?" };
    
    foreach (var comparer in new[]
    {
        StringComparer.Ordinal,
        StringComparer.OrdinalIgnoreCase,
        StringComparer.InvariantCulture,
        StringComparer.InvariantCultureIgnoreCase,
        StringComparer.Create(new CultureInfo("da-DK"), false),
        StringComparer.Create(new CultureInfo("da-DK"), true),
        StringComparer.Create(new CultureInfo("de-DE"), false),
        StringComparer.Create(new CultureInfo("de-DE"), true),
        StringComparer.Create(new CultureInfo("en-US"), false),
        StringComparer.Create(new CultureInfo("en-US"), true),
        StringComparer.Create(new CultureInfo("ja-JP"), false),
        StringComparer.Create(new CultureInfo("ja-JP"), true),
    })
    {
        l.Sort(comparer);
        Console.WriteLine(string.Join(" ", l));
    }
    

    Decoding UTF-8 strings in Python

    You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

    Because you do not provide any context or code for your question it is not possible to give a direct answer.

    I suggest you study how unicode and character encoding is done in Python:

    http://docs.python.org/2/howto/unicode.html

    C++ compile error: has initializer but incomplete type

    You need this include:

    #include <sstream>
    

    Remove all the children DOM elements in div

    In Dojo 1.7 or newer, use domConstruct.empty(String|DomNode):

    require(["dojo/dom-construct"], function(domConstruct){
      // Empty node's children byId:
      domConstruct.empty("someId");
    });
    

    In older Dojo, use dojo.empty(String|DomNode) (deprecated at Dojo 1.8):

    dojo.empty( id or DOM node );
    

    Each of these empty methods safely removes all children of the node.

    Chrome extension: accessing localStorage in content script

    Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:

    • store information from your content script without the need for message passing between content script and extension;
    • store your data as JavaScript objects without serializing them to JSON (localStorage only stores strings).

    Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.

    content_script.js

    (function () {
        var visited = window.location.href;
        var time = +new Date();
        chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
            console.log("Just visited",visited)
        });
    })();
    

    popup.js

    (function () {
        chrome.storage.onChanged.addListener(function (changes,areaName) {
            console.log("New item in storage",changes.visitedPages.newValue);
        })
    })();
    

    "Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.

    Remember to declare storage permission in manifest.json.

    manifest.json

    ...
    "permissions": [
        "storage"
     ],
    ...
    

    How do I install imagemagick with homebrew?

    The quickest fix for me was doing the following:

    cd /usr/local
    git reset --hard FETCH_HEAD
    

    Then I retried brew install imagemagick and it correctly pulled the package from the new mirror, instead of adamv.

    If that does not work, ensure that /Library/Caches/Homebrew does not contain any imagemagick files or folders. Delete them if it does.

    Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

    I had this error, I follwed below three steps to solve,

    1). check proxy settings in settings.xml refer,

    2). .m2 diretory to release cached files causing problems

    3) Point your eclipse to correct JDK installation. Refer No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? to know how

    Div table-cell vertical align not working

    see this bin: http://jsbin.com/yacom/2/edit

    should set parent element to

    display:table-cell;
    vertical-align:middle;
    text-align:center;
    

    MySQL my.ini location

    Open your run console type: services.msc look for: mysql right click properties where is written "path to executable", click and move the cursor to the right until you see the directory of my.ini, it's written "defaults-file-". to reach it manually on your explore folders you have to enable the visualization of hidden elements (explore folder>top menu>visualize>visualize hidden elements)

    as explained by this video

    https://www.youtube.com/watch?v=SvCAa2XuQhg

    Create a 3D matrix

    I use Octave, but Matlab has the same syntax.

    Create 3d matrix:

    octave:3> m = ones(2,3,2)
    m =
    
    ans(:,:,1) =
    
       1   1   1
       1   1   1
    
    ans(:,:,2) =
    
       1   1   1
       1   1   1
    

    Now, say I have a 2D matrix that I want to expand in a new dimension:

    octave:4> Two_D = ones(2,3)
    Two_D =
       1   1   1
       1   1   1
    

    I can expand it by creating a 3D matrix, setting the first 2D in it to my old (here I have size two of the third dimension):

    octave:11> Three_D = zeros(2,3,2)
    Three_D =
    
    ans(:,:,1) =
    
       0   0   0
       0   0   0
    
    ans(:,:,2) =
    
       0   0   0
       0   0   0
    
    
    
    octave:12> Three_D(:,:,1) = Two_D
    Three_D =
    
    ans(:,:,1) =
    
       1   1   1
       1   1   1
    
    ans(:,:,2) =
    
       0   0   0
       0   0   0
    

    How to Query an NTP Server using C#?

    This is a optimized version of the function which removes dependency on BitConverter function and makes it compatible with NETMF (.NET Micro Framework)

    public static DateTime GetNetworkTime()
    {
        const string ntpServer = "pool.ntp.org";
        var ntpData = new byte[48];
        ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)
    
        var addresses = Dns.GetHostEntry(ntpServer).AddressList;
        var ipEndPoint = new IPEndPoint(addresses[0], 123);
        var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    
        socket.Connect(ipEndPoint);
        socket.Send(ntpData);
        socket.Receive(ntpData);
        socket.Close();
    
        ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
        ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];
    
        var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
        var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
    
        return networkDateTime;
    }
    

    Finding all possible combinations of numbers to reach a given sum

    This is similar to a coin change problem

    public class CoinCount 
    {   
    public static void main(String[] args)
    {
        int[] coins={1,4,6,2,3,5};
        int count=0;
    
        for (int i=0;i<coins.length;i++)
        {
            count=count+Count(9,coins,i,0);
        }
        System.out.println(count);
    }
    
    public static int Count(int Sum,int[] coins,int index,int curSum)
    {
        int count=0;
    
        if (index>=coins.length)
            return 0;
    
        int sumNow=curSum+coins[index];
        if (sumNow>Sum)
            return 0;
        if (sumNow==Sum)
            return 1;
    
        for (int i= index+1;i<coins.length;i++)
            count+=Count(Sum,coins,i,sumNow);
    
        return count;       
    }
    }
    

    (change) vs (ngModelChange) in angular

    As I have found and wrote in another topic - this applies to angular < 7 (not sure how it is in 7+)

    Just for the future

    we need to observe that [(ngModel)]="hero.name" is just a short-cut that can be de-sugared to: [ngModel]="hero.name" (ngModelChange)="hero.name = $event".

    So if we de-sugar code we would end up with:

    <select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event">

    or

    <[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()">

    If you inspect the above code you will notice that we end up with 2 ngModelChange events and those need to be executed in some order.

    Summing up: If you place ngModelChange before ngModel, you get the $event as the new value, but your model object still holds previous value. If you place it after ngModel, the model will already have the new value.

    SOURCE

    Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

    I got the same error after a Java version update. I just edited the line after "-vm" in the eclipse.ini file, which was pointing to the older and no more existing jre path, and everything worked fine.

    C#: what is the easiest way to subtract time?

    Hi if you are going to subtract only Integer value from DateTime then you have to write code like this

    DateTime.Now.AddHours(-2)
    

    Here I am subtracting 2 hours from the current date and time

    Is it better to use C void arguments "void foo(void)" or not "void foo()"?

    Besides syntactical differences, many people also prefer using void function(void) for pracitical reasons:

    If you're using the search function and want to find the implementation of the function, you can search for function(void), and it will return the prototype as well as the implementation.

    If you omit the void, you have to search for function() and will therefore also find all function calls, making it more difficult to find the actual implementation.