Programs & Examples On #Dfa

A DFA is a deterministic finite automaton, a simple model of computation. It is one way to model regular languages. Each DFA consists of a finite set of states and a transition function between those states describing how the state of the machine changes in response to new input. DFAs are closely related to regular expressions in the sense that they can be converted into each other. Thus, DFAs are often used to implement regular expression matchers.

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

HTTP URL Address Encoding in Java

The java.net.URI class can help; in the documentation of URL you find

Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use an URI

Use one of the constructors with more than one argument, like:

URI uri = new URI(
    "http", 
    "search.barnesandnoble.com", 
    "/booksearch/first book.pdf",
    null);
URL url = uri.toURL();
//or String request = uri.toString();

(the single-argument constructor of URI does NOT escape illegal characters)


Only illegal characters get escaped by above code - it does NOT escape non-ASCII characters (see fatih's comment).
The toASCIIString method can be used to get a String only with US-ASCII characters:

URI uri = new URI(
    "http", 
    "search.barnesandnoble.com", 
    "/booksearch/é",
    null);
String request = uri.toASCIIString();

For an URL with a query like http://www.google.com/ig/api?weather=São Paulo, use the 5-parameter version of the constructor:

URI uri = new URI(
        "http", 
        "www.google.com", 
        "/ig/api",
        "weather=São Paulo",
        null);
String request = uri.toASCIIString();

php pdo: get the columns name of a table

This is an old question but here's my input

function getColumns($dbhandle, $tableName) {
    $columnsquery = $dbhandle->query("PRAGMA table_info($tableName)");
    $columns = array();
    foreach ($columnsquery as $k) {
        $columns[] = $k['name'];
    }
    return $columns;
}

just put your variable for your pdo object and the tablename. Works for me

Does Java support default parameter values?

Instead of using:

void parameterizedMethod(String param1, int param2) {
    this(param1, param2, false);
}

void parameterizedMethod(String param1, int param2, boolean param3) {
    //use all three parameters here
}

You could utilize java's Optional functionality by having a single method:

void parameterizedMethod(String param1, int param2, @Nullable Boolean param3) {
    param3 = Optional.ofNullable(param3).orElse(false);
    //use all three parameters here
}

The main difference is that you have to use wrapper classes instead of primitive Java types to allow null input.Boolean instead of boolean, Integer instead of int and so on.

Environment variables in Mac OS X

Just open the ~/.profile file, via nano in Terminal and type there :

export PATH=whatever/you/want:$PATH

Save this file (cmd+X and Y). After that please logout/login again or just open a new tab in Terminal and try use your new variable.

PLEASE DON'T forget to add ":$PATH" after whatever/you/want, otherwise you'll erase all paths in PATH variable, which were there before that.

How to clear react-native cache?

If you are using WebStorm, press configuration selection drop down button left of the run button and select edit configurations:

edit configurations

Double click on Start React Native Bundler at bottom in Before launch section:

before launch

Enter --reset-cache to Arguments section:

arguments

drop down list value in asp.net

<asp:DropDownList ID="DdlMonths" runat="server">
    <asp:ListItem Enabled="true" Text="Select Month" Value="-1"></asp:ListItem>
    <asp:ListItem Text="January" Value="1"></asp:ListItem>
    <asp:ListItem Text="February" Value="2"></asp:ListItem>
    ....
    <asp:ListItem Text="December" Value="12"></asp:ListItem>
</asp:DropDownList>

You can even use a RequiredFieldValidator which ignore this item, it considers it as unselected.

<asp:RequiredFieldValidator ID="ReqMonth" runat="server" ControlToValidate="DdlMonths"
    InitialValue="-1">
</asp:RequiredFieldValidator>

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Hidden Features of C#?

Preprocessor Directives can be nifty if you want different behavior between Debug and Release modes.

http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx

Is it correct to use alt tag for an anchor link?

For anchors, you should use title instead. alt is not valid atribute of a. See http://w3schools.com/tags/tag_a.asp

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

Just download and install the latest version of Virtual box, run it then run the emulator and viola, it will be up and running. This one worked for me.

How do you completely remove Ionic and Cordova installation from mac?

Command to remove Cordova and ionic

  • For Window system

    • npm uninstall -g ionic
    • npm uninstall -g cordova
  • For Mac system

    • sudo npm uninstall -g ionic
    • sudo npm uninstall -g cordova
  • For install cordova and ionic

    • npm install -g cordova
    • npm install -g ionic

Note:

  • If you want to install in MAC System use before npm use sudo only.
  • And plan to install specific version of ionic and cordova then use @(version no.).

eg.

sudo npm install -g [email protected]

sudo npm install -g [email protected]

Daemon not running. Starting it now on port 5037

This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.

Loading local JSON file

I can't believe how many times this question has been answered without understanding and/or addressing the problem with the Original Poster's actual code. That said, I'm a beginner myself (only 2 months of coding). My code does work perfectly, but feel free to suggest any changes to it. Here's the solution:

//include the   'async':false   parameter or the object data won't get captured when loading
var json = $.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false});  

//The next line of code will filter out all the unwanted data from the object.
json = JSON.parse(json.responseText); 

//You can now access the json variable's object data like this json.a and json.c
document.write(json.a);
console.log(json);

Here's a shorter way of writing the same code I provided above:

var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);

You can also use $.ajax instead of $.getJSON to write the code exactly the same way:

var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText); 

Finally, the last way to do this is to wrap $.ajax in a function. I can't take credit for this one, but I did modify it a bit. I tested it and it works and produces the same results as my code above. I found this solution here --> load json into variable

var json = function () {
    var jsonTemp = null;
    $.ajax({
        'async': false,
        'url': "http://spoonertuner.com/projects/test/test.json",
        'success': function (data) {
            jsonTemp = data;
        }
    });
    return jsonTemp;
}(); 

document.write(json.a);
console.log(json);

The test.json file you see in my code above is hosted on my server and contains the same json data object that he (the original poster) had posted.

{
    "a" : "b",
    "c" : "d"
}

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

It is recommended to override equals() and hashCode() to work with hash-based collections, including HashMap, HashSet, and Hashtable, So doing this you can easily remove duplicates by initiating HashSet object with Blog list.

List<Blog> blogList = getBlogList();
Set<Blog> noDuplication = new HashSet<Blog>(blogList);

But Thanks to Java 8 which have very cleaner version to do this as you mentioned you can not change code to add equals() and hashCode()

Collection<Blog> uniqueBlogs = getUniqueBlogList(blogList);

private Collection<Blog> getUniqueBlogList(List<Blog> blogList) {
    return blogList.stream()
            .collect(Collectors.toMap(createUniqueKey(), Function.identity(), (blog1, blog2) -> blog1))
            .values();
}
List<Blog> updatedBlogList = new ArrayList<>(uniqueBlogs);

Third parameter of Collectors.toMap() is merge Function (functional interface) used to resolve collisions between values associated with the same key.

Create a CSV File for a user in PHP

Writing your own CSV code is probably a waste of your time, just use a package such as league/csv - it deals with all the difficult stuff for you, the documentation is good and it's very stable / reliable:

http://csv.thephpleague.com/

You'll need to be using composer. If you don't know what composer is I highly recommend you have a look: https://getcomposer.org/

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

What are WSDL, SOAP and REST?

You're not going to "simply" understand something complex.

WSDL is an XML-based language for describing a web service. It describes the messages, operations, and network transport information used by the service. These web services usually use SOAP, but may use other protocols.

A WSDL is readable by a program, and so may be used to generate all, or part of the client code necessary to call the web service. This is what it means to call SOAP-based web services "self-describing".

REST is not related to WSDL at all.

How to change date format using jQuery?

You don't need any date-specific functions for this, it's just string manipulation:

var parts = fecha2.value.split('-');
var newdate = parts[1]+'-'+parts[2]+'-'+(parseInt(parts[0], 10)%100);

JQuery - Storing ajax response into global variable

Just use this. simple and effective:

var y;

function something(x){
return x;
}

$.get(bunch of codes, function (data){

y=something(data);
)}

//anywhere else
console.log(y);

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">

see https://docs.angularjs.org/api/ngRoute

How to pass parameter to function using in addEventListener?

If the this value you want is the just the object that you bound the event handler to, then addEventListener() already does that for you. When you do this:

productLineSelect.addEventListener('change', getSelection, false);

the getSelection function will already be called with this set to the object that the event handler was bound to. It will also be passed an argument that represents the event object which has all sorts of object information about the event.

function getSelection(event) {
    // this will be set to the object that the event handler was bound to
    // event is all the detailed information about the event
}

If the desired this value is some other value than the object you bound the event handler to, you can just do this:

var self = this;
productLineSelect.addEventListener('change',function() {
    getSelection(self)
},false);

By way of explanation:

  1. You save away the value of this into a local variable in your other event handler.
  2. You then create an anonymous function to pass addEventListener.
  3. In that anonymous function, you call your actual function and pass it the saved value of this.

Is it not possible to stringify an Error using JSON.stringify?

You can solve this with a one-liner( errStringified ) in plain javascript:

var error = new Error('simple error message');
var errStringified = (err => JSON.stringify(Object.getOwnPropertyNames(Object.getPrototypeOf(err)).reduce(function(accumulator, currentValue) { return accumulator[currentValue] = err[currentValue], accumulator}, {})))(error);
console.log(errStringified);

It works with DOMExceptions as well.

How to check for a valid Base64 encoded string

Yes, since Base64 encodes binary data into ASCII strings using a limited set of characters, you can simply check it with this regular expression:

/^[A-Za-z0-9\=\+\/\s\n]+$/s

which will assure the string only contains A-Z, a-z, 0-9, '+', '/', '=', and whitespace.

TortoiseSVN icons overlay not showing after updating to Windows 10

Checking "Removable drives" and "Network drives" worked for me.

How can I get color-int from color resource?

For more information on another use-case that may help surface this question in search results, I wanted to apply alpha to a color defined in my resources.

Using @sat's correct answer:

int alpha = ... // 0-255, calculated based on some business logic
int actionBarBackground = getResources().getColor(R.color.actionBarBackground);
int actionBarBackgroundWithAlpha = Color.argb(
        alpha,
        Color.red(actionbarBackground),
        Color.green(actionbarBackground),
        Color.blue(actionbarBackground)
);

Socket send and receive byte array

You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.

This is the easiest case for a known size (100 bytes):

in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);

In this case DataInputStream makes sense as it offers readFully(). If you don't use it, you need to loop yourself until the expected number of bytes is read.

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

I was doing an install of an apk:

adb install /home/me/jones_android-arm.apk

And I was getting an error message telling me that

/data/local/tmp/jones_android-arm.apk

was too big. Using the sdk tools from r15, and ADT 15 I was able to use the AVD manager to manipulate some of my existing emulator's settings:

Window-> AVD Manager -> (select you virtual machine) -> Edit

then going to the Hardware properties window just below "Skin:" I was able to select with the Hardware: New button 'Ideal size of partition'. I was not, however, able to set the value other than to '0'. Undaunted, I went to my ${HOME}/.android/avd directory There was a 'MyVm.avd' directory. Going into that directory I found a 'config.ini' file. There was the entry :

disk.dataPartition.size=0

I set this to:

disk.dataPartition.size=1024

.. then went back to the AVD Manager, selected MyVm, selected 'Start', opted to wipe user data win the dialog following, and was able to run and install.

Plotting two variables as lines using ggplot2 on the same graph

I am also new to R but trying to understand how ggplot works I think I get another way to do it. I just share probably not as a complete perfect solution but to add some different points of view.

I know ggplot is made to work with dataframes better but maybe it can be also sometimes useful to know that you can directly plot two vectors without using a dataframe.

Loading data. Original date vector length is 100 while var0 and var1 have length 50 so I only plot the available data (first 50 dates).

var0 <- 100 + c(0, cumsum(runif(49, -20, 20)))
var1 <- 150 + c(0, cumsum(runif(49, -10, 10)))
date <- seq(as.Date("2002-01-01"), by="1 month", length.out=50)    

Plotting

ggplot() + geom_line(aes(x=date,y=var0),color='red') + 
           geom_line(aes(x=date,y=var1),color='blue') + 
           ylab('Values')+xlab('date')

enter image description here

However I was not able to add a correct legend using this format. Does anyone know how?

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

maybe a slightly better solution is to bind (with jQuery in my case) the "blur" event on the various input fields.

This because when the keyboard disappear all form fields are blurred. So for my situation this snipped solved the problem.

$('input, textarea').bind('blur', function(e) {

       // Keyboard disappeared
       window.scrollTo(0, 1);

});

hope it helps. Michele

Generate an integer sequence in MySQL

If you happen to be using the MariaDB fork of MySQL, the SEQUENCE engine allows direct generation of number sequences. It does this by using virtual (fake) one column tables.

For example, to generate the sequence of integers from 1 to 1000, do this

     SELECT seq FROM seq_1_to_1000;

For 0 to 11, do this.

     SELECT seq FROM seq_0_to_11;

For a week's worth of consecutive DATE values starting today, do this.

SELECT FROM_DAYS(seq + TO_DAYS(CURDATE)) dateseq FROM seq_0_to_6

For a decade's worth of consecutive DATE values starting with '2010-01-01' do this.

SELECT FROM_DAYS(seq + TO_DAYS('2010-01-01')) dateseq
  FROM seq_0_to_3800
 WHERE FROM_DAYS(seq + TO_DAYS('2010-01-01')) < '2010-01-01' + INTERVAL 10 YEAR

If you don't happen to be using MariaDB, please consider it.

Android: How to create a Dialog without a title?

While using AlertDialog, not using setTitle() makes the title disappear

Sorting object property by values

my solution with sort :

let list = {
    "you": 100, 
    "me": 75, 
    "foo": 116, 
    "bar": 15
};

let sorted = Object.entries(list).sort((a,b) => a[1] - b[1]);

for(let element of sorted) {
    console.log(element[0]+ ": " + element[1]);
}

NHibernate.MappingException: No persister for: XYZ

I have a similar problem but all mentioned requirements are met. In my case I try to save some entity class (Type of OBJEKTE) back to the DB. Other places do work but only in this case it fails and raises this exception.

My solution (HACK) was to re-map the objet of type OBJEKTE again and store it then. Suddenly it works. But don't ask why.

            OBJEKTE t = _mapper.Map<OBJEKTE>(inparam);
            OBJEKTE res = await _objRepo.UpdateAsync(t);

If inparam would go straight to UpdateAsync() it cannot find a matching persistor.

It could be explained by the way NH does this. It derives a proxy from your mapping class and implements the properties with dirty handling included. See this:

t.GetType()
{Name = "OBJEKTE" FullName = "MyComp.Persistence.OBJEKTE"}

inparam.GetType()
{Name = "OBJEKTEProxyForFieldInterceptor" FullName = "OBJEKTEProxyForFieldInterceptor"}

The fun thing though is that the source of inparam is in fact the NH repository itself. Anyways. I stay with this reassign hack for the next time being.

Unsupported major.minor version 52.0 in my app

What no one here is saying is that with Build Tools 24.0.0, Java 8 is required and most people have either 1.6 or 1.7.

So yeah, setting the build tool to 23.x.x would 'solve' the problem but the root cause is the Java version on your system.

On the long term, you might want to upgrade your dev environment to use JDK8 to make use the new language enhancements and the jack compiler.

Reading Excel file using node.js

install exceljs and use the following code,

var Excel = require('exceljs');

var wb = new Excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'sample.xlsx');

wb.xlsx.readFile(filePath).then(function(){

    var sh = wb.getWorksheet("Sheet1");

    sh.getRow(1).getCell(2).value = 32;
    wb.xlsx.writeFile("sample2.xlsx");
    console.log("Row-3 | Cell-2 - "+sh.getRow(3).getCell(2).value);

    console.log(sh.rowCount);
    //Get all the rows data [1st and 2nd column]
    for (i = 1; i <= sh.rowCount; i++) {
        console.log(sh.getRow(i).getCell(1).value);
        console.log(sh.getRow(i).getCell(2).value);
    }
});

jQuery ajax request with json response, how to?

Try this code. You don't require the parse function because your data type is JSON so it is return JSON object.

$.ajax({
    url : base_url+"Login/submit",
    type: "POST",
    dataType: "json",
    data : {
        'username': username,
        'password': password
    },
    success: function(data)
    {
        alert(data.status);
    }
});

MySQL: Get column name or alias from query

Try:

cursor.column_names

mysql connector version:

mysql.connector.__version__
'2.2.9'

SQL How to correctly set a date variable value and use it?

If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

Converting strings to floats in a DataFrame

In a newer version of pandas (0.17 and up), you can use to_numeric function. It allows you to convert the whole dataframe or just individual columns. It also gives you an ability to select how to treat stuff that can't be converted to numeric values:

import pandas as pd
s = pd.Series(['1.0', '2', -3])
pd.to_numeric(s)
s = pd.Series(['apple', '1.0', '2', -3])
pd.to_numeric(s, errors='ignore')
pd.to_numeric(s, errors='coerce')

Early exit from function?

This:

function myfunction()
{
     if (a == 'stop')  // How can I stop working of function here?
     {
         return;
     }
}

How do I escape a single quote in SQL Server?

Single quotes are escaped by doubling them up, just as you've shown us in your example. The following SQL illustrates this functionality. I tested it on SQL Server 2008:

DECLARE @my_table TABLE (
    [value] VARCHAR(200)
)

INSERT INTO @my_table VALUES ('hi, my name''s tim.')

SELECT * FROM @my_table

Results

value
==================
hi, my name's tim.

Better way of getting time in milliseconds in javascript?

I know this is a pretty old thread, but to keep things up to date and more relevant, you can use the more accurate performance.now() functionality to get finer grain timing in javascript.

window.performance = window.performance || {};
performance.now = (function() {
    return performance.now       ||
        performance.mozNow    ||
        performance.msNow     ||
        performance.oNow      ||
        performance.webkitNow ||            
        Date.now  /*none found - fallback to browser default */
})();

javascript object max size limit

you have to put this in web.config :

<system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="50000000" />
      </webServices>
    </scripting>
  </system.web.extensions>

How do you find the row count for all your tables in Postgres

Simple Two Steps:
(Note : No need to change anything - just copy paste)
1. create function

create function 
cnt_rows(schema text, tablename text) returns integer
as
$body$
declare
  result integer;
  query varchar;
begin
  query := 'SELECT count(1) FROM ' || schema || '.' || tablename;
  execute query into result;
  return result;
end;
$body$
language plpgsql;

2. Run this query to get rows count for all the tables

select sum(cnt_rows) as total_no_of_rows from (select 
  cnt_rows(table_schema, table_name)
from information_schema.tables
where 
  table_schema not in ('pg_catalog', 'information_schema') 
  and table_type='BASE TABLE') as subq;

or

To get rows counts tablewise

select
  table_schema,
  table_name, 
  cnt_rows(table_schema, table_name)
from information_schema.tables
where 
  table_schema not in ('pg_catalog', 'information_schema') 
  and table_type='BASE TABLE'
order by 3 desc;

how to make jni.h be found?

Installing the OpenJDK Development Kit (JDK) should fix your problem.

sudo apt-get install openjdk-X-jdk

This should make you able to compile without problems.

How to use local docker images with Minikube?

If anyone is looking to come back to the local environment after setting the minikube env, use following command.

eval $(docker-machine env -u)

Interpreting segfault messages

This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).

If this were a program, not a shared library

Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d (and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.

Since it's a shared library

You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb.

What the error means

Here's the breakdown of the fields:

  • address (after the at) - the location in memory the code is trying to access (it's likely that 10 and 11 are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0)
  • ip - instruction pointer, ie. where the code which is trying to do this lives
  • sp - stack pointer
  • error - An error code for page faults; see below for what this means on x86.

    /*
     * Page fault error code bits:
     *
     *   bit 0 ==    0: no page found       1: protection fault
     *   bit 1 ==    0: read access         1: write access
     *   bit 2 ==    0: kernel-mode access  1: user-mode access
     *   bit 3 ==                           1: use of reserved bit detected
     *   bit 4 ==                           1: fault was an instruction fetch
     */
    

Sass calculate percent minus px

$var:25%;
$foo:5px;
.selector {
    height:unquote("calc( #{$var} - #{$foo} )");
}

Replace comma with newline in sed on MacOS?

Use tr instead:

tr , '\n' < file

jQuery - find table row containing table cell containing specific text

This will search text in all the td's inside each tr and show/hide tr's based on search text

 $.each($(".table tbody").find("tr"), function () {                              

                if ($(this).text().toLowerCase().replace(/\s+/g, '').indexOf(searchText.replace(/\s+/g, '').toLowerCase()) == -1)
                    $(this).hide();
                else
                    $(this).show();
 });

Get records of current month

Check the MySQL Datetime Functions:

Try this:

SELECT * 
FROM tableA 
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND 
      MONTH(columnName) = MONTH(CURRENT_DATE());

Angular 4 - Observable catch error

If you want to use the catch() of the Observable you need to use Observable.throw() method before delegating the error response to a method

_x000D_
_x000D_
import { Injectable } from '@angular/core';_x000D_
import { Headers, Http, ResponseOptions} from '@angular/http';_x000D_
import { AuthHttp } from 'angular2-jwt';_x000D_
_x000D_
import { MEAT_API } from '../app.api';_x000D_
_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/operator/map';_x000D_
import 'rxjs/add/operator/catch';_x000D_
_x000D_
@Injectable()_x000D_
export class CompareNfeService {_x000D_
_x000D_
_x000D_
  constructor(private http: AuthHttp) {}_x000D_
_x000D_
  envirArquivos(order): Observable < any > {_x000D_
    const headers = new Headers();_x000D_
    return this.http.post(`${MEAT_API}compare/arquivo`, order,_x000D_
        new ResponseOptions({_x000D_
          headers: headers_x000D_
        }))_x000D_
      .map(response => response.json())_x000D_
      .catch((e: any) => Observable.throw(this.errorHandler(e)));_x000D_
  }_x000D_
_x000D_
  errorHandler(error: any): void {_x000D_
    console.log(error)_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Using Observable.throw() worked for me

Choosing the best concurrency list in Java

If the size of the list if fixed, then you can use an AtomicReferenceArray. This would allow you to perform indexed updates to a slot. You could write a List view if needed.

How to extract request http headers from a request using NodeJS connect

To see a list of HTTP request headers, you can use :

console.log(JSON.stringify(req.headers));

to return a list in JSON format.

{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}

Display a jpg image on a JPanel

You could also use

ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);

JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);

if your working with a absolut value as layout.

Convert SVG to PNG in Python

Try this: http://cairosvg.org/

The site says:

CairoSVG is written in pure python and only depends on Pycairo. It is known to work on Python 2.6 and 2.7.

Update November 25, 2016:

2.0.0 is a new major version, its changelog includes:

  • Drop Python 2 support

How do I create a random alpha-numeric string in C++?

Mehrdad Afshari's answer would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders:

#include <iostream>
#include <ctime>
#include <unistd.h>

using namespace std;

string gen_random(const int len) {
    
    string tmp_s;
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    
    srand( (unsigned) time(NULL) * getpid());

    tmp_s.reserve(len);

    for (int i = 0; i < len; ++i) 
        tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
    
    
    return tmp_s;
    
}

int main(int argc, char *argv[]) {
    
    cout << gen_random(12) << endl;
    
    return 0;
}

Unity 2d jumping script

The answer above is now obsolete with Unity 5 or newer. Use this instead!

GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);

I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...

    public float playerSpeed;  //allows us to be able to change speed in Unity
public Vector2 jumpHeight;

// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update ()
{
    transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);  //makes player run

    if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
    {
        GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);

This makes it to where you can edit the jump height in Unity itself without having to go back to the script.

Side note - I wanted to comment on the answer above, but I can't because I'm new here. :)

Replace non-ASCII characters with a single space

When we use the ascii() it escapes the non-ascii characters and it doesn't change ascii characters correctly. So my main thought is, it doesn't change the ASCII characters, so I am iterating through the string and checking if the character is changed. If it changed then replacing it with the replacer, what you give.
For example: ' '(a single space) or '?' (with a question mark).

def remove(x, replacer):

     for i in x:
        if f"'{i}'" == ascii(i):
            pass
        else:
            x=x.replace(i,replacer)
     return x
remove('hái',' ')

Result: "h i" (with single space between).

Syntax : remove(str,non_ascii_replacer)
str = Here you will give the string you want to work with.
non_ascii_replacer = Here you will give the replacer which you want to replace all the non ASCII characters with.

get the data of uploaded file in javascript

FileReaderJS can read the files for you. You get the file content inside onLoad(e) event handler as e.target.result.

Using a Glyphicon as an LI bullet point (Bootstrap 3)

I'm using a simplyfied version (just using position relative) based on @SimonEast answer:

li:before {
    content: "\e080";
    font-family: 'Glyphicons Halflings';
    font-size: 9px;
    position: relative;
    margin-right: 10px;
    top: 3px;
    color: #ccc;
}

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

I was parsing JSON from a REST API call and got this error. It turns out the API had become "fussier" (eg about order of parameters etc) and so was returning malformed results. Check that you are getting what you expect :)

How to upgrade docker-compose to latest version

I was trying to install docker-compose on "Ubuntu 16.04.5 LTS" but after installing it like this:

sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

I was getting:

-bash: /usr/local/bin/docker-compose: Permission denied

and while I was using it with sudo I was getting:

sudo: docker-compose: command not found

So here's the steps that I took and solved my problem:

sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.

It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.

Here is some information on intermediate chains:
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR657
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AD146

Intermediate CA Certificates

SVN Repository Search

// Edit: Tool was already mentioned in another answer, so give all credits to Kuryaki.

Just found SupoSE which is a java based command line tool which scans a repository to create an index and afterwards is able to answer certain kinds of queries. We're still evaluating the tool but it looks promising. It's worth to mention that it makes a full index of all revisions including source code files and common office formats.

How can I get the index from a JSON object with value?

Function base solution for get index from a JSON object with value by VanillaJS.

Exemple: https://codepen.io/gmkhussain/pen/mgmEEW

_x000D_
_x000D_
    var data= [{_x000D_
      "name": "placeHolder",_x000D_
      "section": "right"_x000D_
    }, {_x000D_
      "name": "Overview",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "ByFunction",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "Time",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allFit",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allbMatches",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allOffers",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allInterests",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allResponses",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "divChanged",_x000D_
      "section": "right"_x000D_
    }];_x000D_
    _x000D_
    _x000D_
    // create function_x000D_
    function findIndex(jsonData, findThis){_x000D_
      var indexNum = jsonData.findIndex(obj => obj.name==findThis);  _x000D_
_x000D_
    //Output of result_x000D_
          document.querySelector("#output").innerHTML=indexNum;_x000D_
          console.log(" Array Index number: " + indexNum + " , value of " + findThis );_x000D_
    }_x000D_
    _x000D_
    _x000D_
    /* call function */_x000D_
    findIndex(data, "allOffers");
_x000D_
Output of index number : <h1 id="output"></h1>
_x000D_
_x000D_
_x000D_

Setting timezone in Python

You can use pytz as well..

import datetime
import pytz
def utcnow():
    return datetime.datetime.now(tz=pytz.utc)
utcnow()
   datetime.datetime(2020, 8, 15, 14, 45, 19, 182703, tzinfo=<UTC>)
utcnow().isoformat()

'

2020-08-15T14:45:21.982600+00:00'

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

iPhone format strings are in Unicode format. Behind the link is a table explaining what all the letters above mean so you can build your own.

And of course don't forget to release your date formatters when you're done with them. The above code leaks format, now, and inFormat.

How to clear the canvas for redrawing

A simple, but not very readable way is to write this:

var canvas = document.getElementId('canvas');

// after doing some rendering

canvas.width = canvas.width;  // clear the whole canvas

How do I copy items from list to list without foreach?

To add the contents of one list to another list which already exists, you can use:

targetList.AddRange(sourceList);

If you're just wanting to create a new copy of the list, see Lasse's answer.

Working Soap client example

To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             http://www.webservicex.net/uszip.asmx?op=GetInfoByCity


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:GetInfoByCity>
                        <myNamespace:USCity>New York</myNamespace:USCity>
                    </myNamespace:GetInfoByCity>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}

R - Markdown avoiding package loading messages

My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.

{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables
library(xtable)

#data wrangling
library(dplyr)

#text processing
library(stringi)

SyntaxError: missing ; before statement

Looks like you have an extra parenthesis.

The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.

foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
   return '[' + (+$1 + 1) + ']';
})

Unable to connect PostgreSQL to remote database using pgAdmin

If you're using PostgreSQL 8 or above, you may need to modify the listen_addresses setting in /etc/postgresql/8.4/main/postgresql.conf.

Try adding the line:

listen_addresses = *

which will tell PostgreSQL to listen for connections on all network interfaces.

If not explicitly set, this setting defaults to localhost which means it will only accept connections from the same machine.

How to fix request failed on channel 0

This is what which helped me from the various answers provided.

  • Try logging in as root, that will get you in most of the times
  • Try logging in as a different user, it successful, it means that the problem is with a specific account & it implies that there are some process(es) already started by the problematic account which are consuming resources preventing login(most likely no of processes)
  • Increase the limit in /etc/security/limits.d/20-nproc.conf as mentioned by xmduhan above
  • Try to ssh again, it should work

How do I check if an element is hidden in jQuery?

One can simply use the hidden or visible attribute, like:

$('element:hidden')
$('element:visible')

Or you can simplify the same with is as follows.

$(element).is(":visible")

How to clear basic authentication details in chrome

  1. Press the key combination Ctrl+Shift+Delete
  2. You will see popup in chrome enter image description here

  3. Check the above options and click clear data and you are done.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

My issue was that I was creating objects that I wanted to be stored in a NSMutableDictionary but I never initialized the dictionary. Therefore the objects were getting deleted by garbage collection and breaking later. Check that you have at least one strong reference to the objects youre interacting with.

Microsoft Web API: How do you do a Server.MapPath?

Since Server.MapPath() does not exist within a Web Api (Soap or REST), you'll need to denote the local- relative to the web server's context- home directory. The easiest way to do so is with:

string AppContext.BaseDirectory { get;}

You can then use this to concatenate a path string to map the relative path to any file.
NOTE: string paths are \ and not / like they are in mvc.

Ex:

System.IO.File.Exists($"{**AppContext.BaseDirectory**}\\\\Content\\\\pics\\\\{filename}");

returns true- positing that this is a sound path in your example

Maven project version inheritance - do I have to specify the parent version?

The easiest way to update versions IMO:

$ mvn versions:set -DgenerateBackupPoms=false

(do that in your root/parent pom folder).

Your POMs are parsed and you're asked which version to set.

Get current controller in view

You can use any of the below code to get the controller name

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

If you are using MVC 3 you can use

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

Ignore Typescript Errors "property does not exist on value of type"

I know it's now 2020, but I couldn't see an answer that satisfied the "ignore" part of the question. Turns out, you can tell TSLint to do just that using a directive;

// @ts-ignore
this.x = this.x.filter(x => x.someProp !== false);

Normally this would throw an error, stating that 'someProp does not exist on type'. With the comment, that error goes away.

This will stop any errors being thrown when compiling and should also stop your IDE complaining at you.

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

Your listener.ora is misconfigured. There is no orcl service.

Differences between Octave and MATLAB?

The thing makes Matlab so popular and special is its excellent toolboxes in different disciplines. Since your main goal is to learn Matlab, so there is not different at all if you work with Octave or Matlab!

Just going and buying Matlab without any cool toolbox (which basically depends on your major) is not really a reasonable expense!

You can definitely have a good start with Octave, and follow tons of tutorials on Matlab on the internet.

Enable remote connections for SQL Server Express 2012

One More Thing...

Kyralessa provides great information but I have one other thing to add where I was stumped even after this article.

Under SQL Server Network Configuration > Protocols for Server > TCP/IP Enabled. Right Click TCP/IP and choose properties. Under the IP Addresses you need to set Enabled to Yes for each connection type that you are using.

enter image description here

Angular2 router (@angular/router), how to set default route?

I faced same issue apply all possible solution but finally this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

Hope this will help you.

Find methods calls in Eclipse project

Move the cursor to the method name. Right click and select References > Project or References > Workspace from the pop-up menu.

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

Calling a parent window function from an iframe

parent.abc() will only work on same domain due to security purposes. i tried this workaround and mine worked perfectly.

<head>
    <script>
    function abc() {
        alert("sss");
    }

    // window of the iframe
    var innerWindow = document.getElementById('myFrame').contentWindow;
    innerWindow.abc= abc;

    </script>
</head>
<body>
    <iframe id="myFrame">
        <a onclick="abc();" href="#">Click Me</a>
    </iframe>
</body>

Hope this helps. :)

How to create a simple proxy in C#?

If you are just looking to intercept the traffic, you could use the fiddler core to create a proxy...

http://fiddler.wikidot.com/fiddlercore

run fiddler first with the UI to see what it does, it is a proxy that allows you to debug the http/https traffic. It is written in c# and has a core which you can build into your own applications.

Keep in mind FiddlerCore is not free for commercial applications.

How do I divide so I get a decimal value?

In your example, Java is performing integer arithmetic, rounding off the result of the division.

Based on your question, you would like to perform floating-point arithmetic. To do so, at least one of your terms must be specified as (or converted to) floating-point:

Specifying floating point:

3.0/2
3.0/2.0
3/2.0

Converting to floating point:

int a = 2;
int b = 3;
float q = ((float)a)/b;

or

double q = ((double)a)/b;

(See Java Traps: double and Java Floating-Point Number Intricacies for discussions on float and double)

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I also faced the following Error in my system (Mac)

Error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

After doing some random browsing, I came across the link "http://maven.apache.org/install.html" that says "JAVA_HOME" should be set to "/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre".

When I changed "JAVA_HOME" as stated above in ".bash_profile", "mvn" command started working but "javac -version" command stopped working.

When I typed "javac -version" command, I got the following error

Unable to locate an executable at "/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/bin/javac" (-1)

Hence I rolled back my "JAVA_HOME" to "/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home" in ".bash_profile" and added the following line at the top in "mvn" script

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre

Now both "mvn" and "javac" commands worked properly, but after careful observation of the mvn script, I could not make the difference between the following commands

/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java -classpath /Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/boot/plexus-classworlds-2.6.0.jar -Dclassworlds.conf=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/bin/m2.conf -Dmaven.home=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1 -Dlibrary.jansi.path=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/lib/jansi-native -Dmaven.multiModuleProjectDirectory=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/bin org.codehaus.plexus.classworlds.launcher.Launcher

/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/bin/java -classpath /Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/boot/plexus-classworlds-2.6.0.jar -Dclassworlds.conf=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/bin/m2.conf -Dmaven.home=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1 -Dlibrary.jansi.path=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/lib/jansi-native -Dmaven.multiModuleProjectDirectory=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/bin org.codehaus.plexus.classworlds.launcher.Launcher

In the above the first command caused the following error

Error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

while the second command worked fine. Please Note that both the above paths have "java" command while one is from "jre" the other is from "jdk"

Other global variables are as following in ".bash_profile"

export M2_HOME=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1

export PATH=$PATH:$M2_HOME/bin

If file exists then delete the file

fileExists() is a method of FileSystemObject, not a global scope function.

You also have an issue with the delete, DeleteFile() is also a method of FileSystemObject.

Furthermore, it seems you are moving the file and then attempting to deal with the overwrite issue, which is out of order. First you must detect the name collision, so you can choose the rename the file or delete the collision first. I am assuming for some reason you want to keep deleting the new files until you get to the last one, which seemed implied in your question.

So you could use the block:

if NOT fso.FileExists(newname) Then  

    file.move fso.buildpath(OUT_PATH, newname)           

else

    fso.DeleteFile newname
    file.move fso.buildpath(OUT_PATH, newname)  

end if 

Also be careful that your string comparison with the = sign is case sensitive. Use strCmp with vbText compare option for case insensitive string comparison.

Creating a new database and new connection in Oracle SQL Developer

  1. Connect to sys.
  2. Give your password for sys.
  3. Unlock hr user by running following query:

alter user hr identified by hr account unlock;

  1. Then, Click on new connection
  2. Give connection name as HR_ORCL Username: hr Password: hr Connection Type: Basic Role: default Hostname: localhost Port: 1521 SID: xe

  3. Click on test and Connect

Can jQuery check whether input content has changed?

You can also store the initial value in a data attribute and check it against the current value.

<input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" /> 

$("#id_someid").keyup(function() {
    return $(this).val() == $(this).data().initial;
});

Would return true if the initial value has not changed.

How do I get an Excel range using row and column numbers in VSTO / C#?

Facing the same problem I found the quickest solution was to actually scan the rows of the cells I wished to sort, determine the last row with a non-blank element and then select and sort on that grouping.

    Dim lastrow As Integer
lastrow = 0
For r = 3 To 120
   If Cells(r, 2) = "" Then
        Dim rng As Range
        Set rng = Range(Cells(3, 2), Cells(r - 1, 2 + 6))
        rng.Select
        rng.Sort Key1:=Range("h3"), order1:=xlDescending, Header:=xlGuess, DataOption1:=xlSortNormal
        r = 205
    End If
Next r

How to add a new audio (not mixing) into a video using ffmpeg?

mp3 music to wav

ffmpeg -i music.mp3 music.wav

truncate to fit video

ffmpeg -i music.wav -ss 0 -t 37 musicshort.wav

mix music and video

ffmpeg -i musicshort.wav -i movie.avi final_video.avi

HTML / CSS Popup div on text click

DEMO

In the content area you can provide whatever you want to display in it.

_x000D_
_x000D_
.black_overlay {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 0%;_x000D_
  left: 0%;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: black;_x000D_
  z-index: 1001;_x000D_
  -moz-opacity: 0.8;_x000D_
  opacity: .80;_x000D_
  filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
  padding: 16px;_x000D_
  border: 16px solid orange;_x000D_
  background-color: white;_x000D_
  z-index: 1002;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
  </p>_x000D_
  <div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
  </div>_x000D_
  <div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

create a file named logging.properties in WEB-INF/classes with following content:

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler

Better way to find control in ASP.NET

If you're looking for a specific type of control you could use a recursive loop like this one - http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx

Here's an example I made that returns all controls of the given type

/// <summary>
/// Finds all controls of type T stores them in FoundControls
/// </summary>
/// <typeparam name="T"></typeparam>
private class ControlFinder<T> where T : Control 
{
    private readonly List<T> _foundControls = new List<T>();
    public IEnumerable<T> FoundControls
    {
        get { return _foundControls; }
    }    

    public void FindChildControlsRecursive(Control control)
    {
        foreach (Control childControl in control.Controls)
        {
            if (childControl.GetType() == typeof(T))
            {
                _foundControls.Add((T)childControl);
            }
            else
            {
                FindChildControlsRecursive(childControl);
            }
        }
    }
}

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

Go to Start and search for cmd. Right click on it, properties then set the Target path in quotes. This worked fine for me.

Preloading images with JavaScript

Try this I think this is better.

var images = [];
function preload() {
    for (var i = 0; i < arguments.length; i++) {
        images[i] = new Image();
        images[i].src = preload.arguments[i];
    }
}

//-- usage --//
preload(
    "http://domain.tld/gallery/image-001.jpg",
    "http://domain.tld/gallery/image-002.jpg",
    "http://domain.tld/gallery/image-003.jpg"
)

Source: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Could not find an implementation of the query pattern

I had the same error as described by title, but for me it was simply installing Microsoft access 12.0 oledb redistributable to use with LinqToExcel.

How do I apply a diff patch on Windows?

EDIT: Looking at the replies so far, it seems that Tortoise will only do it right if it's a file that's already versioned. That's not the case here. I need to be able to apply a patch to a file that did not come out of an SVN repository. I just tried using Tortoise because I happen to know that SVN uses diffs and has to know how to both create them and apply them.

You can install Cygwin, then use the command-line patch tool to apply the patch. See also this Unix man page, which applies to patch.

How to show alert message in mvc 4 controller?

It is not possible to display alerts from the controller. Because MVC views and controllers are entirely separated from each other. You can only display information in the view only. So it is required to pass the information to be displayed from controller to view by using either ViewBag, ViewData or TempData. If you are trying to display the content stored in TempData["Message"], It is possible to perform in the view page by adding few javascript lines.

<script>
  alert(@TempData["Message"]);
</script>

How to vertically align a html radio button to it's label?

Try this:

input[type="radio"] {
  margin-top: -1px;
  vertical-align: middle;
}

jQuery - What are differences between $(document).ready and $(window).load?

This three function are the same.

$(document).ready(function(){

}) 

and

$(function(){

}); 

and

jQuery(document).ready(function(){

});

here $ is used for define jQuery like $ = jQuery.

Now difference is that

$(document).ready is jQuery event that is fired when DOM is loaded, so it’s fired when the document structure is ready.

$(window).load event is fired after whole content is loaded like page contain images,css etc.

Datatables Select All Checkbox

You can use Checkboxes extension for jQuery Datatables.

var table = $('#example').DataTable({
   'ajax': 'https://api.myjson.com/bins/1us28',
   'columnDefs': [
      {
         'targets': 0,
         'checkboxes': {
            'selectRow': true
         }
      }
   ],
   'select': {
      'style': 'multi'
   },
   'order': [[1, 'asc']]
});

See this example for code and demonstration.

See Checkboxes project page for more examples and documentation.

svn: E155004: ..(path of resource).. is already locked

Inside the folder

TortoiseSVN -> Clean up...

ggplot2 plot without axes, legends, etc

Does this do what you want?

 p <- ggplot(myData, aes(foo, bar)) + geom_whateverGeomYouWant(more = options) +
 p + scale_x_continuous(expand=c(0,0)) + 
 scale_y_continuous(expand=c(0,0)) +
 opts(legend.position = "none")

An existing connection was forcibly closed by the remote host

This error occurred in my application with the CIP-protocol whenever I didn't Send or received data in less than 10s.

This was caused by the use of the forward open method. You can avoid this by working with an other method, or to install an update rate of less the 10s that maintain your forward-open-connection.

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

Execute jar file with multiple classpath libraries from command prompt

Using java 1.7, on UNIX -

java -cp myjar.jar:lib/*:. mypackage.MyClass

On Windows you need to use ';' instead of ':' -

java -cp myjar.jar;lib/*;. mypackage.MyClass

How to insert a SQLite record with a datetime set to 'now' in Android application?

There are a couple options you can use:

  1. You could try using the string "(DATETIME('now'))" instead.
  2. Insert the datetime yourself, ie with System.currentTimeMillis()
  3. When creating the SQLite table, specify a default value for the created_date column as the current date time.
  4. Use SQLiteDatabase.execSQL to insert directly.

Excel VBA Open workbook, perform actions, save as, close

After discussion posting updated answer:

Option Explicit
Sub test()

    Dim wk As String, yr As String
    Dim fname As String, fpath As String
    Dim owb As Workbook

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    wk = ComboBox1.Value
    yr = ComboBox2.Value
    fname = yr & "W" & wk
    fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"

    On Error GoTo ErrorHandler
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)

    'Do Some Stuff

    With owb
        .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
        .Close
    End With

    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
        .EnableEvents = True
    End With

Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

Else: Call Clear

End Sub

Error Handling:

You could try something like this to catch a specific error:

    On Error Resume Next
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    If Err.Number = 1004 Then
    GoTo FileNotFound
    Else
    End If

    ...
    Exit Sub
    FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

    Else: Call Clear

Execute a command line binary with Node.js

Use this lightweight npm package: system-commands

Look at it here.

Import it like this:

const system = require('system-commands')

Run commands like this:

system('ls').then(output => {
    console.log(output)
}).catch(error => {
    console.error(error)
})

How to count the number of lines of a string in javascript

I was testing out the speed of the functions, and I found consistently that this solution that I had written was much faster than matching. We check the new length of the string as compared to the previous length.

const lines = str.length - str.replace(/\n/g, "").length+1;

_x000D_
_x000D_
let str = `Line1
Line2
Line3`;
console.time("LinesTimer")
console.log("Lines: ",str.length - str.replace(/\n/g, "").length+1);
console.timeEnd("LinesTimer")
_x000D_
_x000D_
_x000D_

Compiling LaTex bib source

Just in case it helps someone, since these questions (and answers) helped me really much; I decided to create an alias that runs these 4 commands in a row:

Just add the following line to your ~/.bashrc file (modify the main keyword accordingly to the name of your .tex and .bib files)

alias texbib = 'pdflatex main.tex && bibtex main && pdflatex main.tex && pdflatex main.tex'

And now, by just executing the texbib command (alias), all these commands will be executed sequentially.

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

It seems odd that this directory was not created at install - have you manually changed the path of the socket file in the my.cfg?

Have you tried simply creating this directory yourself, and restarting the service?

mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld

What is the difference between <p> and <div>?

They have semantic difference - a <div> element is designed to describe a container of data whereas a <p> element is designed to describe a paragraph of content.

The semantics make all the difference. HTML is a markup language which means that it is designed to "mark up" content in a way that is meaningful to the consumer of the markup. Most developers believe that the semantics of the document are the default styles and rendering that browsers apply to these elements but that is not the case.

The elements that you choose to mark up your content should describe the content. Don't mark up your document based on how it should look - mark it up based on what it is.

If you need a generic container purely for layout purposes then use a <div>. If you need an element to describe a paragraph of content then use a <p>.

Note: It is important to understand that both <div> and <p> are block-level elements which means that most browsers will treat them in a similar fashion.

What's an easy way to read random line from a file in Unix command line?

Using only vanilla sed and awk, and without using $RANDOM, a simple, space-efficient and reasonably fast "one-liner" for selecting a single line pseudo-randomly from a file named FILENAME is as follows:

sed -n $(awk 'END {srand(); r=rand()*NR; if (r<NR) {sub(/\..*/,"",r); r++;}; print r}' FILENAME)p FILENAME

(This works even if FILENAME is empty, in which case no line is emitted.)

One possible advantage of this approach is that it only calls rand() once.

As pointed out by @AdamKatz in the comments, another possibility would be to call rand() for each line:

awk 'rand() * NR < 1 { line = $0 } END { print line }' FILENAME

(A simple proof of correctness can be given based on induction.)

Caveat about rand()

"In most awk implementations, including gawk, rand() starts generating numbers from the same starting number, or seed, each time you run awk."

-- https://www.gnu.org/software/gawk/manual/html_node/Numeric-Functions.html

Find empty or NaN entry in Pandas Dataframe

To obtain all the rows that contains an empty cell in in a particular column.

DF_new_row=DF_raw.loc[DF_raw['columnname']=='']

This will give the subset of DF_raw, which satisfy the checking condition.

Javascript Print iframe contents only

Use this code for IE9 and above:

window.frames["printf"].focus();
window.frames["printf"].print();

For IE8:

window.frames[0].focus();
window.frames[0].print();

How do I find which application is using up my port?

To see which ports are available on your machine run:

C:>  netstat -an |find /i "listening"

How to specify a min but no max decimal using the range data annotation attribute?

It seems there's no choice but to put in the max value manually. I was hoping there was some type of overload where you didn't need to specify one.

[Range(typeof(decimal), "0", "79228162514264337593543950335")]
public decimal Price { get; set; }

How to Remove Line Break in String

None of the other answers (with one exception, see my edit) handle the case where there are multiple trailing carriage returns. If the goal is to make a function similar to "Trim" that removes carriage returns as well as spaces, you'll probably want it to be robust enough to remove as many as there are and not just one. Also, I'd recommend avoiding the use of the "Left" or "Right" functions in VBA since they do not exist in VB.Net. It may be necessary at some point to convert an Office VBA Macro to a VSTO COM Add-In so it's a good habit to avoid the use of functions that only exist in VBA.

Function RemoveTrailingWhiteSpace(s As String) As String
    RemoveTrailingWhiteSpace = s
    Dim StrLen As Long
    StrLen = Len(RemoveTrailingWhiteSpace)
    While (StrLen > 0 And (Mid(RemoveTrailingWhiteSpace, StrLen) = vbCr Or Mid(RemoveTrailingWhiteSpace, StrLen) = vbLf) Or Mid(RemoveTrailingWhiteSpace, StrLen) = " ")
        RemoveTrailingWhiteSpace = Mid(RemoveTrailingWhiteSpace, 1, StrLen - 1)
        StrLen = Len(RemoveTrailingWhiteSpace)
    Wend
End Function

Edit: I should clarify that there is another answer listed here that trims carriage returns and white space from both ends of the string, but it looked far more convoluted. This can be done fairly concisely.

To the power of in C?

you can use pow(base, exponent) from #include <math.h>

or create your own:

int myPow(int x,int n)
{
    int i; /* Variable used in loop counter */
    int number = 1;

    for (i = 0; i < n; ++i)
        number *= x;

    return(number);
}

What's NSLocalizedString equivalent in Swift?

When you are developing an SDK. You need some extra operation.

1) create Localizable.strings as usual in YourLocalizeDemoSDK.

2) create the same Localizable.strings in YourLocalizeDemo.

3) find your Bundle Path of YourLocalizeDemoSDK.

Swift4:

// if you use NSLocalizeString in NSObject, you can use it like this
let value = NSLocalizedString("key", tableName: nil, bundle: Bundle(for: type(of: self)), value: "", comment: "")

Bundle(for: type(of: self)) helps you to find the bundle in YourLocalizeDemoSDK. If you use Bundle.main instead, you will get a wrong value(in fact it will be the same string with the key).

But if you want to use the String extension mentioned by dr OX. You need to do some more. The origin extension looks like this.

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
    }
}

As we know, we are developing an SDK, Bundle.main will get the bundle of YourLocalizeDemo's bundle. That's not what we want. We need the bundle in YourLocalizeDemoSDK. This is a trick to find it quickly.

Run the code below in a NSObject instance in YourLocalizeDemoSDK. And you will get the URL of YourLocalizeDemoSDK.

let bundleURLOfSDK = Bundle(for: type(of: self)).bundleURL
let mainBundleURL = Bundle.main.bundleURL

Print both of the two url, you will find that we can build bundleURLofSDK base on mainBundleURL. In this case, it will be:

let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main

And the String extension will be:

extension String {
    var localized: String {
        let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
        return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")
    }
}

Hope it helps.

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

1) "Squared" instructions for making 24-hours became 12-hours:

var hours24 = new Date().getHours(); // retrieve current hours (in 24 mode)
var dayMode = hours24 < 12 ? "am" : "pm"; // if it's less than 12 then "am"
var hours12 = hours24 <= 12 ? (hours24 == 0 ? 12 : hours24) : hours24 - 12;
// "0" in 24-mode now becames "12 am" in 12-mode – thanks to user @Cristian
document.write(hours12 + " " + dayMode); // printing out the result of code

2) In a single line (same result with slightly different algorythm):

var str12 = (h24 = new Date().getHours()) && (h24 - ((h24 == 0)? -12 : (h24 <= 12)? 0 : 12)) + (h24 < 12 ? " am" : " pm");

Both options return string, like "5 pm" or "10 am" etc.

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

How to convert strings into integers in Python?

You can do something like this:

T1 = (('13', '17', '18', '21', '32'),  
     ('07', '11', '13', '14', '28'),  
     ('01', '05', '06', '08', '15', '16'))  
new_list = list(list(int(a) for a in b if a.isdigit()) for b in T1)  
print(new_list)  

Can't draw Histogram, 'x' must be numeric

Because of the thousand separator, the data will have been read as 'non-numeric'. So you need to convert it:

 we <- gsub(",", "", we)   # remove comma
 we <- as.numeric(we)      # turn into numbers

and now you can do

 hist(we)

and other numeric operations.

How to set tbody height with overflow scroll

It is simple way to use scroll bar to table body

_x000D_
_x000D_
/* It is simple way to use scroll bar to table body*/

table tbody {
  display: block;
  max-height: 300px;
  overflow-y: scroll;
}

table thead, table tbody tr {
  display: table;
  width: 100%;
  table-layout: fixed;
}
_x000D_
<table>
  <thead>
    <th>Invoice Number</th>
    <th>Purchaser</th>
    <th>Invoice Amount</th>
    <th>Invoice Date</th>
  </thead>
  <tbody>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
    <tr>
      <td>INV-1233</td>
      <td>Dinesh Vaitage</td>
      <td>$300</td>
      <td>01/12/2017</td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Convert objective-c typedef to its string equivalent

I like the #define way of doing this:

// Place this in your .h file, outside the @interface block

typedef enum {
    JPG,
    PNG,
    GIF,
    PVR
} kImageType;
#define kImageTypeArray @"JPEG", @"PNG", @"GIF", @"PowerVR", nil

// Place this in the .m file, inside the @implementation block
// A method to convert an enum to string
-(NSString*) imageTypeEnumToString:(kImageType)enumVal
{
    NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
    return [imageTypeArray objectAtIndex:enumVal];
}

source (source no longer available)

is there something like isset of php in javascript/jQuery?

You can just:

if(variable||variable===0){
    //Yes it is set
    //do something
}
else {
    //No it is not set
    //Or its null
    //do something else 
}

Connection Strings for Entity Framework

Instead of using config files you can use a configuration database with a scoped systemConfig table and add all your settings there.

CREATE TABLE [dbo].[SystemConfig]  
    (  
      [Id] [int] IDENTITY(1, 1)  
                 NOT NULL ,  
      [AppName] [varchar](128) NULL ,  
      [ScopeName] [varchar](128) NOT NULL ,  
      [Key] [varchar](256) NOT NULL ,  
      [Value] [varchar](MAX) NOT NULL ,  
      CONSTRAINT [PK_SystemConfig_ID] PRIMARY KEY NONCLUSTERED ( [Id] ASC )  
        WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  
               IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,  
               ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]  
    )  
ON  [PRIMARY]  

GO  

SET ANSI_PADDING OFF  
GO  

ALTER TABLE [dbo].[SystemConfig] ADD  CONSTRAINT [DF_SystemConfig_ScopeName]  DEFAULT ('SystemConfig') FOR [ScopeName]  
GO 

With such configuration table you can create rows like such: enter image description here

Then from your your application dal(s) wrapping EF you can easily retrieve the scoped configuration.
If you are not using dal(s) and working in the wire directly with EF, you can make an Entity from the SystemConfig table and use the value depending on the application you are on.

How do I check if a cookie exists?

/// ************************************************ cookie_exists

/// global entry point, export to global namespace

/// <synopsis>
///   cookie_exists ( name );
///
/// <summary>
///   determines if a cookie with name exists
///
/// <param name="name">
///   string containing the name of the cookie to test for 
//    existence
///
/// <returns>
///   true, if the cookie exists; otherwise, false
///
/// <example>
///   if ( cookie_exists ( name ) );
///     {
///     // do something with the existing cookie
///     }
///   else
///     {
///     // cookies does not exist, do something else 
///     }

function cookie_exists ( name )
  {
  var exists = false;

  if ( document.cookie )
    {
    if ( document.cookie.length > 0 )
      {
                                    // trim name
      if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
        {
        var cookies = document.cookie.split ( ";" );
        var name_with_equal = name + "=";

        for ( var i = 0; ( i < cookies.length ); i++ )
          {
                                    // trim cookie
          var cookie = cookies [ i ].replace ( /^\s*/, "" );

          if ( cookie.indexOf ( name_with_equal ) === 0 )
            {
            exists = true;
            break;
            }
          }
        }
      }
    }

  return ( exists );

  } // cookie_exists

Using filesystem in node.js with async / await

You can use the simple and lightweight module https://github.com/nacholibre/nwc-l it supports both async and sync methods.

Note: this module was created by me.

Filter Pyspark dataframe column with None value

None/Null is a data type of the class NoneType in pyspark/python so, Below will not work as you are trying to compare NoneType object with string object

Wrong way of filreting

df[df.dt_mvmt == None].count() 0 df[df.dt_mvmt != None].count() 0

correct

df=df.where(col("dt_mvmt").isNotNull()) returns all records with dt_mvmt as None/Null

Django TemplateDoesNotExist?

For the django version 1.9,I added

'DIRS': [os.path.join(BASE_DIR, 'templates')], 

line to the Templates block in settings.py And it worked well

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
  <li>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
  </li>
<% end %>

This way you are using the locales for the error messages.

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.

To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:

var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');

depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.

Can you style html form buttons with css?

write the below style into same html file head section or write into a .css file

<style type="text/css">
.submit input
    {
    color: #000;
    background: #ffa20f;
    border: 2px outset #d7b9c9
    }
</style>

<input type="submit" class="submit"/>

.submit - in css . means class , so i created submit class with set of attributes
and applied that class to the submit tag, using class attribute

Run a script in Dockerfile

Try to create script with ADD command and specification of working directory Like this("script" is the name of script and /root/script.sh is where you want it in the container, it can be different path:

ADD script.sh /root/script.sh

In this case ADD has to come before CMD, if you have one BTW it's cool way to import scripts to any location in container from host machine

In CMD place [./script]

It should automatically execute your script

You can also specify WORKDIR as /root, then you'l be automatically placed in root, upon starting a container

Difference between float and decimal data type

I found this useful:

Generally, Float values are good for scientific Calculations, but should not be used for Financial/Monetary Values. For Business Oriented Math, always use Decimal.

Source: http://code.rohitink.com/2013/06/12/mysql-integer-float-decimal-data-types-differences/

Difference between UTF-8 and UTF-16?

This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow.

static byte[] toBytes(String s){
        byte[] b=new byte[s.length()*2];
        ByteBuffer.wrap(b).asCharBuffer().put(s);
        return b;
    }

How to retrieve the current value of an oracle sequence without increment it?

The follows is often used:

select field_SQ.nextval from dual;
select field_SQ.currval from DUAL;

However the following is able to change the sequence to what you expected. The 1 can be an integer (negative or positive)

alter sequence field_SQ increment by 1 minvalue 0

How can you test if an object has a specific property?

For identifying which of the objects in an array have a property

$HasProperty = $ArrayOfObjects | Where-Object {$_.MyProperty}

Call Activity method from adapter

In Kotlin there is now a cleaner way by using lambda functions, no need for interfaces:

class MyAdapter(val adapterOnClick: (Any) -> Unit) {
    fun setItem(item: Any) {
        myButton.setOnClickListener { adapterOnClick(item) }
    }
}

class MyActivity {
    override fun onCreate(savedInstanceState: Bundle?) {
        var myAdapter = MyAdapter { item -> doOnClick(item) }
    }


    fun doOnClick(item: Any) {

    }
}

Git: How to remove proxy

Did you already check your proxys here?

git config --global --list

or

git config --local --list

Checking if output of a command contains a certain string in a shell script

Test the return value of grep:

./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
   echo "matched"
fi

which is done idiomatically like so:

if ./somecommand | grep -q 'string'; then
   echo "matched"
fi

and also:

./somecommand | grep -q 'string' && echo 'matched'

How to create a data file for gnuplot?

Either as most people answered: the file doesn't exist / you're not specifying the path correctly.

Or, you're simply writing the syntax wrong (which you can't know unless you know what it should be like, right?, especially when in the "help" itself, it's wrong).

For gnuplot 4.6.0 on windows 7, terminal type set to windows

Make sure you specify the file's whole path to avoid looking for it where it's not (default seems to be "documents")

Make sure you use this syntax:

plot 'path\path\desireddatafile.txt'

NOT

plot "< path\path\desireddatafile.txt>"

NOR

plot "path\path\desireddatafile.txt"

also make sure your file is in the right format, like for .txt file format ANSI, not Unicode and such.

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

Closing JFrame with button click

It appears to me that you have two issues here. One is that JFrame does not have a close method, which has been addressed in the other answers.

The other is that you're having trouble referencing your JFrame. Within actionPerformed, super refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super instead (you should also be able to use MyExtendedJFrame.this, as I see no reason why you'd want to override the behaviour of dispose or setVisible).

CSS Font Border?

I created a comparison of all the solutions mentioned here to have a quick overview:

<h1>with mixin</h1>
<h2>with text-shadow</h2>
<h3>with css text-stroke-width</h3>

https://codepen.io/Grienauer/pen/GRRdRJr

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

I was compiling my application targeting any CPU and main problem turned out that adobe reader was installed older v10.x needs to upgrade v11.x, this is the way how I get to resolve this issue.

Java out.println() how is this possible?

you can see this also in sockets ...

PrintWriter out = new PrintWriter(socket.getOutputStream());

out.println("hello");

How can I turn a DataTable to a CSV?

Try changing sb.Append(Environment.NewLine); to sb.AppendLine();.

StringBuilder sb = new StringBuilder();          
foreach (DataColumn col in dt.Columns)         
{             
    sb.Append(col.ColumnName + ',');         
}          

sb.Remove(sb.Length - 1, 1);         
sb.AppendLine();          

foreach (DataRow row in dt.Rows)         
{             
    for (int i = 0; i < dt.Columns.Count; i++)             
    {                 
        sb.Append(row[i].ToString() + ",");             
    }              

    sb.AppendLine();         
}          

File.WriteAllText("test.csv", sb.ToString());

Generating random numbers in Objective-C

Same as C, you would do

#include <time.h>
#include <stdlib.h>
...
srand(time(NULL));
int r = rand() % 74;

(assuming you meant including 0 but excluding 74, which is what your Java example does)

Edit: Feel free to substitute random() or arc4random() for rand() (which is, as others have pointed out, quite sucky).

Why catch and rethrow an exception in C#?

Most of answers talking about scenario catch-log-rethrow.

Instead of writing it in your code consider to use AOP, in particular Postsharp.Diagnostic.Toolkit with OnExceptionOptions IncludeParameterValue and IncludeThisArgument

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

With argc (argument count) and argv (argument vector) you can get the number and the values of passed arguments when your application has been launched.

This way you can use parameters (such as -version) when your application is started to act a different way.

But you can also use int main(void) as a prototype in C.

There is a third (less known and nonstandard) prototype with a third argument which is envp. It contains environment variables.


Resources:

How to make matrices in Python?

If you don't want to use numpy, you could use the list of lists concept. To create any 2D array, just use the following syntax:

  mat = [[input() for i in range (col)] for j in range (row)]

and then enter the values you want.

Correct way to detach from a container without stopping it

You can use the --detach-keys option when you run docker attach to override the default CTRL+P, CTRL + Q sequence (that doesn't always work).

For example, when you run docker attach --detach-keys="ctrl-a" test and you press CTRL+A you will exit the container, without killing it.

Other examples:

  • docker attach --detach-keys="ctrl-a,x" test - press CTRL+A and then X to exit
  • docker attach --detach-keys="a,b,c" test - press A, then B, then C to exit

Extract from the official documentation:

If you want, you can configure an override the Docker key sequence for detach. This is useful if the Docker default sequence conflicts with key sequence you use for other applications. There are two ways to define your own detach key sequence, as a per-container override or as a configuration property on your entire configuration.

To override the sequence for an individual container, use the --detach-keys="<sequence>" flag with the docker attach command. The format of the <sequence> is either a letter [a-Z], or the ctrl- combined with any of the following:

  • a-z (a single lowercase alpha character )
  • @ (at sign)
  • [ (left bracket)
  • \ (two backward slashes)
  • _ (underscore)
  • ^ (caret)

These a, ctrl-a, X, or ctrl-\\ values are all examples of valid key sequences. To configure a different configuration default key sequence for all containers, see Configuration file section.

Note: This works since docker version 1.10+ (at the time of this answer, the current version is 18.03)

Remove duplicates from a List<T> in C#

Here's an extension method for removing adjacent duplicates in-situ. Call Sort() first and pass in the same IComparer. This should be more efficient than Lasse V. Karlsen's version which calls RemoveAt repeatedly (resulting in multiple block memory moves).

public static void RemoveAdjacentDuplicates<T>(this List<T> List, IComparer<T> Comparer)
{
    int NumUnique = 0;
    for (int i = 0; i < List.Count; i++)
        if ((i == 0) || (Comparer.Compare(List[NumUnique - 1], List[i]) != 0))
            List[NumUnique++] = List[i];
    List.RemoveRange(NumUnique, List.Count - NumUnique);
}

How to access elements of a JArray (or iterate over them)

Update - I verified the below works. Maybe the creation of your JArray isn't quite right.

[TestMethod]
    public void TestJson()
    {
        var jsonString = @"{""trends"": [
              {
                ""name"": ""Croke Park II"",
                ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                ""promoted_content"": null,
                ""query"": ""%22Croke+Park+II%22"",
                ""events"": null
              },
              {
                ""name"": ""Siptu"",
                ""url"": ""http://twitter.com/search?q=Siptu"",
                ""promoted_content"": null,
                ""query"": ""Siptu"",
                ""events"": null
              },
              {
                ""name"": ""#HNCJ"",
                ""url"": ""http://twitter.com/search?q=%23HNCJ"",
                ""promoted_content"": null,
                ""query"": ""%23HNCJ"",
                ""events"": null
              },
              {
                ""name"": ""Boston"",
                ""url"": ""http://twitter.com/search?q=Boston"",
                ""promoted_content"": null,
                ""query"": ""Boston"",
                ""events"": null
              },
              {
                ""name"": ""#prayforboston"",
                ""url"": ""http://twitter.com/search?q=%23prayforboston"",
                ""promoted_content"": null,
                ""query"": ""%23prayforboston"",
                ""events"": null
              },
              {
                ""name"": ""#TheMrsCarterShow"",
                ""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
                ""promoted_content"": null,
                ""query"": ""%23TheMrsCarterShow"",
                ""events"": null
              },
              {
                ""name"": ""#Raw"",
                ""url"": ""http://twitter.com/search?q=%23Raw"",
                ""promoted_content"": null,
                ""query"": ""%23Raw"",
                ""events"": null
              },
              {
                ""name"": ""Iran"",
                ""url"": ""http://twitter.com/search?q=Iran"",
                ""promoted_content"": null,
                ""query"": ""Iran"",
                ""events"": null
              },
              {
                ""name"": ""#gaa"",
                ""url"": ""http://twitter.com/search?q=%23gaa"",
                ""promoted_content"": null,
                ""query"": ""gaa"",
                ""events"": null
              },
              {
                ""name"": ""Facebook"",
                ""url"": ""http://twitter.com/search?q=Facebook"",
                ""promoted_content"": null,
                ""query"": ""Facebook"",
                ""events"": null
              }]}";

        var twitterObject = JToken.Parse(jsonString);
        var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;


        foreach (var item in trendsArray.Children())
        {
            var itemProperties = item.Children<JProperty>();
            //you could do a foreach or a linq here depending on what you need to do exactly with the value
            var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
            var myElementValue = myElement.Value; ////This is a JValue type
        }
    }

So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.

foreach(var item in yourJArray.Children())
{
    var itemProperties = item.Children<JProperty>();
    //you could do a foreach or a linq here depending on what you need to do exactly with the value
    var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
    var myElementValue = myElement.Value; ////This is a JValue type
}

How to pass an event object to a function in Javascript?

  1. Modify the definition of the function check_me as::

     function check_me(ev) {
    
  2. Now you can access the methods and parameters of the event, in your case:

     ev.preventDefault();
    
  3. Then, you have to pass the parameter on the onclick in the inline call::

     <button type="button" onclick="check_me(event);">Click Me!</button>
    

A useful link to understand this.


Full example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
    </script>
  </head>
  <body>
    <button type="button" onclick="check_me(event);">Click Me!</button>
  </body>
</html>









Alternatives (best practices):

Although the above is the direct answer to the question (passing an event object to an inline event), there are other ways of handling events that keep the logic separated from the presentation

A. Using addEventListener:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
      
      <!-- add the event to the button identified #my_button -->
      document.getElementById("my_button").addEventListener("click", check_me);
    </script>
  </body>
</html>

B. Isolating Javascript:

Both of the above solutions are fine for a small project, or a hackish quick and dirty solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.

Just put this two files in the same folder:

  • example.html:
<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript" src="example.js"></script>
  </body>
</html>
  • example.js:
function check_me(ev) {
    ev.preventDefault();
    alert("Hello World!")
}
document.getElementById("my_button").addEventListener("click", check_me);

Easiest way to compare arrays in C#

For unit tests, you can use CollectionAssert.AreEqual instead of Assert.AreEqual.

It is probably the easiest way.

VBA paste range

This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:

'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Sub CopyLayout(TargetRange As Range, typee As Integer)
    Application.ScreenUpdating = False
        Dim ncolumn As Integer
        Dim nrow As Integer

        SheetLayout.Activate
    If (typee = 1) Then 'is installation
        Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    ElseIf (typee = 2) Then 'is package
        Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    End If

    Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@

    If typee = 1 Then
       nrow = SheetLayout.Range("installationlayout").Rows.Count
       ncolumn = SheetLayout.Range("installationlayout").Columns.Count

       Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    ElseIf typee = 2 Then
       nrow = SheetLayout.Range("PackageLayout").Rows.Count
       ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
       Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    End If
    Range("A1").Select 'Deselect the created table

    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
    Dim R As Long, C As Long

    For R = 1 To RowCount
        PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
        If R >= 2 And R < RowCount Then
            PastedTable.Rows(R).Group 'Main group of the table
        End If
        If R = 2 Then
            PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
        ElseIf (R = 4 And typee = 1) Then
            PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
        End If
    Next R

    For C = 1 To ColumnCount
        PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
    Next C
End Function



Sub test ()
    Call CopyLayout(Sheet2.Range("A18"), 2)
end sub

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

You need to start the Apache Tomcat services.

Win+R --> sevices.msc

Then, search for Apache Tomcat and right click on it and click on Start. This will start the service and then you'll be able to see Apache Tomcat homepage on the localhost .

UNION with WHERE clause

You need to look at the explain plans, but unless there is an INDEX or PARTITION on COL_A, you are looking at a FULL TABLE SCAN on both tables.

With that in mind, your first example is throwing out some of the data as it does the FULL TABLE SCAN. That result is being sorted by the UNION, then duplicate data is dropped. This gives you your result set.

In the second example, you are pulling the full contents of both tables. That result is likely to be larger. So the UNION is sorting more data, then dropping the duplicate stuff. Then the filter is being applied to give you the result set you are after.

As a general rule, the earlier you filter away data, the smaller the data set, and the faster you will get your results. As always, your milage may vary.

What are enums and why are they useful?

You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: "permanent", "temp", "apprentice"), or flags ("execute now", "defer execution").

If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.

BTW, overuse of enums might mean that your methods do too much (it's often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go.

As an example, which is better?

/** Counts number of foobangs.
 * @param type Type of foobangs to count. Can be 1=green foobangs,
 * 2=wrinkled foobangs, 3=sweet foobangs, 0=all types.
 * @return number of foobangs of type
 */
public int countFoobangs(int type)

versus

/** Types of foobangs. */
public enum FB_TYPE {
 GREEN, WRINKLED, SWEET, 
 /** special type for all types combined */
 ALL;
}

/** Counts number of foobangs.
 * @param type Type of foobangs to count
 * @return number of foobangs of type
 */
public int countFoobangs(FB_TYPE type)

A method call like:

int sweetFoobangCount = countFoobangs(3);

then becomes:

int sweetFoobangCount = countFoobangs(FB_TYPE.SWEET);

In the second example, it's immediately clear which types are allowed, docs and implementation cannot go out of sync, and the compiler can enforce this. Also, an invalid call like

int sweetFoobangCount = countFoobangs(99);

is no longer possible.

How to use JavaScript to change div backgroundColor

It's very simple just use a function on javaScript and call it onclick

   <script type="text/javascript">
            function change()
            {
            document.getElementById("catestory").style.backgroundColor="#666666";
            }
            </script>

    <a href="#" onclick="change()">Change Bacckground Color</a>

Run a single test method with maven

This command works !! mvn "-DTest=JoinTeamTestCases#validateJoinTeam" test Note that "-DTest" starts with UPPER CASE 'T'.

How to add a button dynamically in Android?

If you want to add dynamically buttons try this:

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    for (int i = 1; i <= 5; i++) {
        LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout);
        layout.setOrientation(LinearLayout.VERTICAL);
        Button btn = new Button(this);
        btn.setText("    ");
        layout.addView(btn);
    }

}

How to properly stop the Thread in Java?

I didn't get the interrupt to work in Android, so I used this method, works perfectly:

boolean shouldCheckUpdates = true;

private void startupCheckForUpdatesEveryFewSeconds() {
    threadCheckChat = new Thread(new CheckUpdates());
    threadCheckChat.start();
}

private class CheckUpdates implements Runnable{
    public void run() {
        while (shouldCheckUpdates){
            System.out.println("Do your thing here");
        }
    }
}

 public void stop(){
        shouldCheckUpdates = false;
 }

Install python 2.6 in CentOS

When I've run into similar situations, I generally avoid the package manager, especially if it would be embarrassing to break something, i.e. a production server. Instead, I would go to Activestate and download their binary package:

https://www.activestate.com/activepython/downloads/

This is installed by running a script which places everything into a folder and does not touch any system files. In fact, you don't even need root permissions to set it up. Then I change the name of the binary to something like apy26, add that folder to the end of the PATH and start coding. If you install packages with apy26 setup.py installor if you use virtualenv and easyinstall, then you have just as flexible a python environment as you need without touching the system standard python.

Edits... Recently I've done some work to build a portable Python binary for Linux that should run on any distro with no external dependencies. This means that any binary shared libraries needed by the portable Python module are part of the build, included in the tarball and installed in Python's private directory structure. This way you can install Python for your application without interfering with the system installed Python.

My github site has a build script which has been thoroughly tested on Ubuntu Lucid 10.04 LTS both 32 and 64 bit installs. I've also built it on Debian Etch but that was a while ago and I can't guarantee that I haven't changed something. The easiest way to do this is you just put your choice of Ubuntu Lucid in a virtual machine, checkout the script with git clone git://github.com/wavetossed/pybuild.git and then run the script.

Once you have it built, use the tarball on any recent Linux distro. There is one little wrinkle with moving it to a directory other than /data1/packages/python272 which is that you have to run the included patchelf to set the interpreter path BEFORE you move the directory. This affects any binaries in /data1/packages/python272/bin

All of this is based on building with RUNPATH and copying the dependent shared libraries. Even though the script is in several files, it is effectively one long shell script arranged in the style of /etc/rc.d directories.

Plot a legend outside of the plotting area in base graphics?

Sorry for resurrecting an old thread, but I was with the same problem today. The simplest way that I have found is the following:

# Expand right side of clipping rect to make room for the legend
par(xpd=T, mar=par()$mar+c(0,0,0,6))

# Plot graph normally
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")

# Plot legend where you want
legend(3.2,1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

# Restore default clipping rect
par(mar=c(5, 4, 4, 2) + 0.1)

Found here: http://www.harding.edu/fmccown/R/

How to convert hex to ASCII characters in the Linux shell?

echo -n 5a | perl -pe 's/([0-9a-f]{2})/chr hex $1/gie'

Note that this won't skip non-hex characters. If you want just the hex (no whitespace from the original string etc):

echo 5a | perl -ne 's/([0-9a-f]{2})/print chr hex $1/gie'

Also, zsh and bash support this natively in echo:

echo -e '\x5a'

How to remove the focus from a TextBox in WinForms?

The way I get around it is to place all my winform controls. I make all labels and non-selecting winform controls as tab order 0, then my first control as tab order 2 and then increment each selectable control's order by 1, so 3, 4, 5 etc...

This way, when my Winforms start up, the first TextBox doesn't have focus!

Unfamiliar symbol in algorithm: what does ? mean?

Can be read, "For all s such that s does not equal s[start]"

pull/push from multiple remote locations

For updating the remotes (i.e. the pull case), things have become easier.

The statement of Linus

Sadly, there's not even any way to fake this out with a git alias.

in the referenced entry at the Git mailing list in elliottcable's answer is no longer true.

git fetch learned the --all parameter somewhere in the past allowing to fetch all remotes in one go.

If not all are requested, one could use the --multiple switch in order to specify multiple remotes or a group.

top -c command in linux to filter processes listed based on processname

It can be done interactively

After running top -c , hit o and write a filter on a column, e.g. to show rows where COMMAND column contains the string foo, write COMMAND=foo

If you just want some basic output this might be enough:

top -bc |grep name_of_process

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

In my case, I commited a spell mistake in @Named("beanName"), it was suppose to be "beanName", but I wrote "beanNam", for example.

C# refresh DataGridView when updating or inserted on another form

For datagridview in C#, use this code

con.Open();
MySqlDataAdapter MyDA = new MySqlDataAdapter();
string sqlSelectAll = "SELECT * from dailyprice";
MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, con);

DataTable table = new DataTable();
MyDA.Fill(table);

BindingSource bSource = new BindingSource();
bSource.DataSource = table;


dataGridView1.DataSource = bSource;
con.Close();

It works for show new records in the datagridview.

What does "Use of unassigned local variable" mean?

There are many paths through your code whereby your variables are not initialized, which is why the compiler complains.

Specifically, you are not validating the user input for creditPlan - if the user enters a value of anything else than "0","1","2" or "3", then none of the branches indicated will be executed (and creditPlan will not be defaulted to zero as per your user prompt).

As others have mentioned, the compiler error can be avoided by either a default initialization of all derived variables before the branches are checked, OR ensuring that at least one of the branches is executed (viz, mutual exclusivity of the branches, with a fall through else statement).

I would however like to point out other potential improvements:

  • Validate user input before you trust it for use in your code.
  • Model the parameters as a whole - there are several properties and calculations applicable to each plan.
  • Use more appropriate types for data. e.g. CreditPlan appears to have a finite domain and is better suited to an enumeration or Dictionary than a string. Financial data and percentages should always be modelled as decimal, not double to avoid rounding issues, and 'status' appears to be a boolean.
  • DRY up repetitive code. The calculation, monthlyCharge = balance * annualRate * (1/12)) is common to more than one branch. For maintenance reasons, do not duplicate this code.
  • Possibly more advanced, but note that Functions are now first class citizens of C#, so you can assign a function or lambda as a property, field or parameter!.

e.g. here is an alternative representation of your model:

    // Keep all Credit Plan parameters together in a model
    public class CreditPlan
    {
        public Func<decimal, decimal, decimal> MonthlyCharge { get; set; }
        public decimal AnnualRate { get; set; }
        public Func<bool, Decimal> LateFee { get; set; }
    }

    // DRY up repeated calculations
    static private decimal StandardMonthlyCharge(decimal balance, decimal annualRate)
    { 
       return balance * annualRate / 12;
    }

    public static Dictionary<int, CreditPlan> CreditPlans = new Dictionary<int, CreditPlan>
    {
        { 0, new CreditPlan
            {
                AnnualRate = .35M, 
                LateFee = _ => 0.0M, 
                MonthlyCharge = StandardMonthlyCharge
            }
        },
        { 1, new CreditPlan
            {
                AnnualRate = .30M, 
                LateFee = late => late ? 0 : 25.0M,
                MonthlyCharge = StandardMonthlyCharge
            }
        },
        { 2, new CreditPlan
            {
                AnnualRate = .20M, 
                LateFee = late => late ? 0 : 35.0M,
                MonthlyCharge = (balance, annualRate) => balance > 100 
                    ? balance * annualRate / 12
                    : 0
            }
        },
        { 3, new CreditPlan
            {
                AnnualRate = .15M, 
                LateFee = _ => 0.0M,
                MonthlyCharge = (balance, annualRate) => balance > 500 
                    ? (balance - 500) * annualRate / 12
                    : 0
            }
        }
    };

SQL Server error on update command - "A severe error occurred on the current command"

This seems to happen when there's a generic problem with your data source that it isn't handling.

In my case I had inserted a bunch of data, the indexes had become corrupt on the table, they needed rebuilding. I found a script to rebuild them all, seemed to fix it. To find the error I ran the same query on the database - one that had worked 100+ times previously.

Emulate Samsung Galaxy Tab

I don't know if it is help. Create an AVD for a tablet-type device: Set the target to "Android 3.0" and the skin to "WXGA" (the default skin). You can check this site. http://developer.android.com/guide/practices/optimizing-for-3.0.html

Git submodule push

A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )

$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"

Leader Not Available Kafka in Console Producer

I have been witnessing this same issue in the last 2 weeks while working with Kafka and have been reading this Stackoverflow's post ever since.

After 2 weeks of analysis i have deduced that in my case this happens when trying to produce messages to a topic that doesn't exist.

The outcome in my case is that Kafka sends an error message back but creates, at the same time, the topic that did not exist before. So if I try to produce any message again to that topic after this event, the error will not appear anymore as the topic as been created.

PLEASE NOTE: It could be that my particular Kafka installation was configured to automatically create the topic when the same does not exist; that should explain why in my case I can see the issue only once for every topic after resetting the topics: your configuration might be different and in that case you would keep receiving the same error over and over.

Regards,

Luca Tampellini

Flattening a shallow list in Python

This version is a generator.Tweak it if you want a list.

def list_or_tuple(l):
    return isinstance(l,(list,tuple))
## predicate will select the container  to be flattened
## write your own as required
## this one flattens every list/tuple


def flatten(seq,predicate=list_or_tuple):        
    ## recursive generator 
    for i in seq:
        if predicate(seq):
            for j in flatten(i):
                yield j
        else:
            yield i

You can add a predicate ,if want to flatten those which satisfy a condition

Taken from python cookbook

Running vbscript from batch file

You can use %~dp0 to get the path of the currently running batch file.

Edited to change directory to the VBS location before running

If you want the VBS to synchronously run in the same window, then

@echo off
pushd %~dp0
cscript necdaily.vbs

If you want the VBS to synchronously run in a new window, then

@echo off
pushd %~dp0
start /wait "" cmd /c cscript necdaily.vbs

If you want the VBS to asynchronously run in the same window, then

@echo off
pushd %~dp0
start /b "" cscript necdaily.vbs

If you want the VBS to asynchronously run in a new window, then

@echo off
pushd %~dp0
start "" cmd /c cscript necdaily.vbs

PHP - cannot use a scalar as an array warning

The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:

$data = [
"rs" => null
]

this above will work absolutely fine when used like:

$data["rs"] =  5;

But the below will throw a warning ::

$data = [
    "rs" => [
       "rs1" => null;
       ]
    ]
..

$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array

How to list npm user-installed packages?

I prefer tools with some friendly gui!

I used npm-gui which gives you list of local and global packages

The package is at https://www.npmjs.com/package/npm-gui and https://github.com/q-nick/npm-gui

//Once
npm install -g npm-gui

cd c:\your-prject-folder
npm-gui localhost:9000

At your browser http:\\localhost:9000

npm-gui

Is Python strongly typed?

It's already been answered a few times, but Python is a strongly typed language:

>>> x = 3
>>> y = '4'
>>> print(x+y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The following in JavaScript:

var x = 3    
var y = '4'
alert(x + y) //Produces "34"

That's the difference between weak typing and strong typing. Weak types automatically try to convert from one type to another, depending on context (e.g. Perl). Strong types never convert implicitly.

Your confusion lies in a misunderstanding of how Python binds values to names (commonly referred to as variables).

In Python, names have no types, so you can do things like:

bob = 1
bob = "bob"
bob = "An Ex-Parrot!"

And names can be bound to anything:

>>> def spam():
...     print("Spam, spam, spam, spam")
...
>>> spam_on_eggs = spam
>>> spam_on_eggs()
Spam, spam, spam, spam

For further reading:

https://en.wikipedia.org/wiki/Dynamic_dispatch

and the slightly related but more advanced:

http://effbot.org/zone/call-by-object.htm

.Net System.Mail.Message adding multiple "To" addresses

Thanks for spotting this I was about to add strings thinking the same as you that they'd get added to end of collection. It appears the params are:

msg.to.Add(<MailAddress>) adds MailAddress to the end of the collection
msg.to.Add(<string>) add a list of emails to the collection

Slightly different actions depending on param type, I think this is pretty bad form i'd have prefered split methods AddStringList of something.