Programs & Examples On #Vbc

Microsoft's Visual Basic .NET (VB.NET) compiler

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

How to detect if user select cancel InputBox VBA Excel

The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.

For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:

Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
    "Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then  'I also tried with sRange.address and vbNullString
    MsgBox ("Cancel pressed!")
    Exit Sub
End If
    MsgBox ("Your custom range is " & sRange.Address)
End Sub

The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:

Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
    "Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
    MsgBox ("Cancel pressed")
End Sub

So, the question is how to detect either an error or StrPtr()=0 with an If statement?

Line break in SSRS expression

UseEnvironment.NewLine instead of vbcrlf

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

Find specific string in a text file with VBS script

I'd recommend using a regular expressions instead of string operations for this:

Set fso = CreateObject("Scripting.FileSystemObject")

filename = "C:\VBS\filediprova.txt"

newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"

Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global  = False
re.IgnoreCase = True

text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")

The regular expression will match a line feed (\n) followed by a line containing the string Test Case followed by a number (\d), and the replacement will prepend that with the text you want to insert (variable newtext). Setting re.Global = False makes the replacement stop after the first match.

If the line breaks in your text file are encoded as CR-LF (carriage return + line feed) you'll have to change \n into \r\n and vbLf into vbCrLf.

If you have to modify several text files, you could do it in a loop like this:

For Each f In fso.GetFolder("C:\VBS").Files
  If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
    text = f.OpenAsTextStream.ReadAll
    f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
  End If
Next

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

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


Text file in VBA: Open/Find Replace/SaveAs/Close File

Just add this line

sFileName = "C:\someotherfilelocation"

right before this line

Open sFileName For Output As iFileNum

The idea is to open and write to a different file than the one you read earlier (C:\filelocation).

If you want to get fancy and show a real "Save As" dialog box, you could do this instead:

sFileName = Application.GetSaveAsFilename()

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.

equivalent of vbCrLf in c#

You are looking for System.Environment.NewLine.

On Windows, this is equivalent to \r\n though it could be different under another .NET implementation, such as Mono on Linux, for example.

How to find the length of a string in R

You could also use the stringr package:

library(stringr)
str_length("foo")
[1] 3

Converting pixels to dp

kotlin

   fun spToPx(ctx: Context, sp: Float): Float {
    return sp * ctx.resources.displayMetrics.scaledDensity
}

fun pxToDp(context: Context, px: Float): Float {
    return px / context.resources.displayMetrics.density
}

fun dpToPx(context: Context, dp: Float): Float {
    return dp * context.resources.displayMetrics.density
}

java

   public static float spToPx(Context ctx,float sp){
    return sp * ctx.getResources().getDisplayMetrics().scaledDensity;
}

public static float pxToDp(final Context context, final float px) {
    return px / context.getResources().getDisplayMetrics().density;
}

public static float dpToPx(final Context context, final float dp) {
    return dp * context.getResources().getDisplayMetrics().density;
}

How to change the default charset of a MySQL table?

Change table's default charset:

ALTER TABLE etape_prospection
  CHARACTER SET utf8,
  COLLATE utf8_general_ci;

To change string column charset exceute this query:

ALTER TABLE etape_prospection
  CHANGE COLUMN etape_prosp_comment etape_prosp_comment TEXT CHARACTER SET utf8 COLLATE utf8_general_ci;

How do I find the mime-type of a file with php?

I actually got fed up by the lack of standard MIME sniffing methods in PHP. Install fileinfo... Use deprecated functions... Oh these work, but only for images! I got fed up of it, so I did some research and found the WHATWG Mimesniffing spec - I believe this is still a draft spec though.

Anyway, using this specification, I was able to implement a mimesniffer in PHP. Performance is not an issue. In fact on my humble machine, I was able to open and sniff thousands of files before PHP timed out.

Here is the MimeReader class.

require_once("MimeReader.php");

$mime = new MimeReader(<YOUR FILE PATH>);
$mime_type_string = $mime->getType();     // "image/jpeg" etc.

How do you debug PHP scripts?

1) I use print_r(). In TextMate, I have a snippet for 'pre' which expands to this:

echo "<pre>";
print_r();
echo "</pre>";

2) I use Xdebug, but haven't been able to get the GUI to work right on my Mac. It at least prints out a readable version of the stack trace.

How to access iOS simulator camera

It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS version and any Simulator. You will have to use device for testing camera purpose.

Display HTML form values in same page after submit using Ajax

<script type = "text/javascript">
function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>

<!--Insert more code here-->


<input type = "text" id = "textfield">
<input type = "button" onclick = "get('textfield')" value = "submit">

Next time you ask a question here, include more detail and what you have tried.

How to add additional libraries to Visual Studio project?

Without knowing your compiler, no one can give you specific, step by step instructions, but the basic procedure is as follows:

  1. Specify the path which should be searched in order to find the actual library (usually under Library Search Paths, Library Directories, etc. in the properties page)

  2. Under linker options, specify the actual name of the library. In VS, you would write Allegro.lib (or whatever it is), on Linux you usually just write Allegro (prefixes/suffixes are added automatically in most cases). This is usually under "Libraries->Input", just "Libraries", or something similar.

  3. Ensure that you have included the headers for the library and make sure that they can be found (similar process to that listed in step #1 and #2). If it is a static library, you should be good; if it's a DLL, you need to copy it in your project.

  4. Mash the build button.

Tokenizing strings in C

Here's an example of strtok usage, keep in mind that strtok is destructive of its input string (and therefore can't ever be used on a string constant

char *p = strtok(str, " ");
while(p != NULL) {
    printf("%s\n", p);
    p = strtok(NULL, " ");
}

Basically the thing to note is that passing a NULL as the first parameter to strtok tells it to get the next token from the string it was previously tokenizing.

Illegal pattern character 'T' when parsing a date string to java.util.Date

tl;dr

Use java.time.Instant class to parse text in standard ISO 8601 format, representing a moment in UTC.

Instant.parse( "2010-10-02T12:23:23Z" )

ISO 8601

That format is defined by the ISO 8601 standard for date-time string formats.

Both:

…use ISO 8601 formats by default for parsing and generating strings.

You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.

java.time

Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

Instant instant = Instant.parse( "2010-10-02T12:23:23Z" );  // `Instant` is always in UTC.

Convert to the old class.

java.util.Date date = java.util.Date.from( instant );  // Pass an `Instant` to the `from` method.

Time Zone

If needed, you can assign a time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );  // Assign a time zone adjustment from UTC.

Convert.

java.util.Date date = java.util.Date.from( zdt.toInstant() );  // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.

Here is some example code in Joda-Time 2.8.

org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC );  // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.

Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.

java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.

Time Zone

If needed, you can assign a time zone.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Use .htaccess to redirect HTTP to HTTPs

Add this in the WordPress' .htaccess file:

RewriteCond %{HTTP_HOST} ^yoursite.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.yoursite.com [NC]
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [L,R=301,NC]

Therefore the default WordPress' .htaccess file should look like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteCond %{HTTP_HOST} ^yoursite.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.yoursite.com [NC]
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [L,R=301,NC]
</IfModule>

How do you add CSS with Javascript?

Shortest One Liner

_x000D_
_x000D_
// One liner function:
const addCSS = s => document.head.appendChild(document.createElement("style")).innerHTML=s;

// Usage: 
addCSS("body{ background:red; }")
_x000D_
_x000D_
_x000D_

How to get number of entries in a Lua table?

local function CountedTable(x)
    assert(type(x) == 'table', 'bad parameter #1: must be table')

    local new_t = {}
    local mt = {}

    -- `all` will represent the number of both
    local all = 0
    for k, v in pairs(x) do
        all = all + 1
    end

    mt.__newindex = function(t, k, v)
        if v == nil then
            if rawget(x, k) ~= nil then
                all = all - 1
            end
        else
            if rawget(x, k) == nil then
                all = all + 1
            end
        end

        rawset(x, k, v)
    end

    mt.__index = function(t, k)
        if k == 'totalCount' then return all
        else return rawget(x, k) end
    end

    return setmetatable(new_t, mt)
end

local bar = CountedTable { x = 23, y = 43, z = 334, [true] = true }

assert(bar.totalCount == 4)
assert(bar.x == 23)
bar.x = nil
assert(bar.totalCount == 3)
bar.x = nil
assert(bar.totalCount == 3)
bar.x = 24
bar.x = 25
assert(bar.x == 25)
assert(bar.totalCount == 4)

Python: read all text file lines in loop

You can stop the 2-line separation in the output by using

    with open('t.ini') as f:
       for line in f:
           print line.strip()
           if 'str' in line:
              break

Setting default values to null fields when mapping with Jackson

I had a similar problem, but in my case the default value was in database. Below is the solution for that:

 @Configuration
 public class AppConfiguration {
 @Autowired
 private AppConfigDao appConfigDao;

 @Bean
 public Jackson2ObjectMapperBuilder builder() {
   Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
       .deserializerByType(SomeDto.class, 
 new SomeDtoJsonDeserializer(appConfigDao.findDefaultValue()));
   return builder;
 }

Then in SomeDtoJsonDeserializer use ObjectMapper to deserialize the json and set default value if your field/object is null.

Remove or adapt border of frame of legend using matplotlib

One more related question, since it took me forever to find the answer:

How to make the legend background blank (i.e. transparent, not white):

legend = plt.legend()
legend.get_frame().set_facecolor('none')

Warning, you want 'none' (the string). None means the default color instead.

Creating composite primary key in SQL Server

it simple, select columns want to insert primary key and click on Key icon on header and save tablesql composite key

happy coding..,

Usage of __slots__?

Another somewhat obscure use of __slots__ is to add attributes to an object proxy from the ProxyTypes package, formerly part of the PEAK project. Its ObjectWrapper allows you to proxy another object, but intercept all interactions with the proxied object. It is not very commonly used (and no Python 3 support), but we have used it to implement a thread-safe blocking wrapper around an async implementation based on tornado that bounces all access to the proxied object through the ioloop, using thread-safe concurrent.Future objects to synchronise and return results.

By default any attribute access to the proxy object will give you the result from the proxied object. If you need to add an attribute on the proxy object, __slots__ can be used.

from peak.util.proxies import ObjectWrapper

class Original(object):
    def __init__(self):
        self.name = 'The Original'

class ProxyOriginal(ObjectWrapper):

    __slots__ = ['proxy_name']

    def __init__(self, subject, proxy_name):
        # proxy_info attributed added directly to the
        # Original instance, not the ProxyOriginal instance
        self.proxy_info = 'You are proxied by {}'.format(proxy_name)

        # proxy_name added to ProxyOriginal instance, since it is
        # defined in __slots__
        self.proxy_name = proxy_name

        super(ProxyOriginal, self).__init__(subject)

if __name__ == "__main__":
    original = Original()
    proxy = ProxyOriginal(original, 'Proxy Overlord')

    # Both statements print "The Original"
    print "original.name: ", original.name
    print "proxy.name: ", proxy.name

    # Both statements below print 
    # "You are proxied by Proxy Overlord", since the ProxyOriginal
    # __init__ sets it to the original object 
    print "original.proxy_info: ", original.proxy_info
    print "proxy.proxy_info: ", proxy.proxy_info

    # prints "Proxy Overlord"
    print "proxy.proxy_name: ", proxy.proxy_name
    # Raises AttributeError since proxy_name is only set on 
    # the proxy object
    print "original.proxy_name: ", proxy.proxy_name

Ansible: Set variable to file content

You can use fetch module to copy files from remote hosts to local, and lookup module to read the content of fetched files.

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

The best place to demystify this is the source code. The docs are woefully inadequate about explaining this.

dispatchTouchEvent is actually defined on Activity, View and ViewGroup. Think of it as a controller which decides how to route the touch events.

For example, the simplest case is that of View.dispatchTouchEvent which will route the touch event to either OnTouchListener.onTouch if it's defined or to the extension method onTouchEvent.

For ViewGroup.dispatchTouchEvent things are way more complicated. It needs to figure out which one of its child views should get the event (by calling child.dispatchTouchEvent). This is basically a hit testing algorithm where you figure out which child view's bounding rectangle contains the touch point coordinates.

But before it can dispatch the event to the appropriate child view, the parent can spy and/or intercept the event all together. This is what onInterceptTouchEvent is there for. So it calls this method first before doing the hit testing and if the event was hijacked (by returning true from onInterceptTouchEvent) it sends a ACTION_CANCEL to the child views so they can abandon their touch event processing (from previous touch events) and from then onwards all touch events at the parent level are dispatched to onTouchListener.onTouch (if defined) or onTouchEvent(). Also in that case, onInterceptTouchEvent is never called again.

Would you even want to override [Activity|ViewGroup|View].dispatchTouchEvent? Unless you are doing some custom routing you probably should not.

The main extension methods are ViewGroup.onInterceptTouchEvent if you want to spy and/or intercept touch event at the parent level and View.onTouchListener/View.onTouchEvent for main event handling.

All in all its overly complicated design imo but android apis lean more towards flexibility than simplicity.

How to embed HTML into IPython output?

First, the code:

from random import choices

def random_name(length=6):
    return "".join(choices("abcdefghijklmnopqrstuvwxyz", k=length))
# ---

from IPython.display import IFrame, display, HTML
import tempfile
from os import unlink

def display_html_to_frame(html, width=600, height=600):
    name = f"temp_{random_name()}.html"
    with open(name, "w") as f:
        print(html, file=f)
    display(IFrame(name, width, height), metadata=dict(isolated=True))
    # unlink(name)
    
def display_html_inline(html):
    display(HTML(html, metadata=dict(isolated=True)))

h="<html><b>Hello</b></html>"    
display_html_to_iframe(h)
display_html_inline(h)

Some quick notes:

  • You can generally just use inline HTML for simple items. If you are rendering a framework, like a large JavaScript visualization framework, you may need to use an IFrame. Its hard enough for Jupyter to run in a browser without random HTML embedded.
  • The strange parameter, metadata=dict(isolated=True) does not isolate the result in an IFrame, as older documentation suggests. It appears to prevent clear-fix from resetting everything. The flag is no longer documented: I just found using it allowed certain display: grid styles to correctly render.
  • This IFrame solution writes to a temporary file. You could use a data uri as described here but it makes debugging your output difficult. The Jupyter IFrame function does not take a data or srcdoc attribute.
  • The tempfile module creations are not sharable to another process, hence the random_name().
  • If you use the HTML class with an IFrame in it, you get a warning. This may be only once per session.
  • You can use HTML('Hello, <b>world</b>') at top level of cell and its return value will render. Within a function, use display(HTML(...)) as is done above. This also allows you to mix display and print calls freely.
  • Oddly, IFrames are indented slightly more than inline HTML.

How can I force clients to refresh JavaScript files?

The jQuery function getScript can also be used to ensure that a js file is indeed loaded every time the page is loaded.

This is how I did it:

$(document).ready(function(){
    $.getScript("../data/playlist.js", function(data, textStatus, jqxhr){
         startProgram();
    });
});

Check the function at http://api.jquery.com/jQuery.getScript/

By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested.

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

MySQL: Fastest way to count number of rows

Try this:

SELECT
    table_rows "Rows Count"
FROM
    information_schema.tables
WHERE
    table_name="Table_Name"
AND
    table_schema="Database_Name";

how to rotate a bitmap 90 degrees

Just be careful of Bitmap type from java platform call like from comm1x's and Gnzlt's answers, because it might return null. I think it is also more flexible if the parameter can be any Number and use infix for readability, depends on your coding style.

infix fun Bitmap.rotate(degrees: Number): Bitmap? {
    return Bitmap.createBitmap(
        this,
        0,
        0,
        width,
        height,
        Matrix().apply { postRotate(degrees.toFloat()) },
        true
    )
}

How to use?

bitmap rotate 90
// or
bitmap.rotate(90)

' << ' operator in verilog

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

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

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

C# Iterate through Class properties

Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:

public class Record
{
    public string ItemType { get; set; }

    public string this[string propertyName]
    {
        set
        {
            switch (propertyName)
            {
                case "itemType":
                    ItemType = value;
                    break;
                    // etc
            }   
        }
    }
}

Alternatively, as others have mentioned, use reflection.

How to get host name with port from a http or https request

If you use the load balancer & Nginx, config them without modify code.

Nginx:

proxy_set_header       Host $host;  
proxy_set_header  X-Real-IP  $remote_addr;  
proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;  
proxy_set_header X-Forwarded-Proto  $scheme;  

Tomcat's server.xml Engine:

<Valve className="org.apache.catalina.valves.RemoteIpValve"  
remoteIpHeader="X-Forwarded-For"  
protocolHeader="X-Forwarded-Proto"  
protocolHeaderHttpsValue="https"/> 

If only modify Nginx config file, the java code should be:

String XForwardedProto = request.getHeader("X-Forwarded-Proto");

Efficiently getting all divisors of a given number

Here is the Java Implementation of this approach:

public static int countAllFactors(int num)
{
    TreeSet<Integer> tree_set = new TreeSet<Integer>();
    for (int i = 1; i * i <= num; i+=1)
    {
        if (num % i == 0)
        {
            tree_set.add(i);
            tree_set.add(num / i);
        }
    }
    System.out.print(tree_set);
    return tree_set.size();
}

Angular2 handling http response

The service :

import 'rxjs/add/operator/map';

import { Http } from '@angular/http';
import { Observable } from "rxjs/Rx"
import { Injectable } from '@angular/core';

@Injectable()
export class ItemService {
  private api = "your_api_url";

  constructor(private http: Http) {

  }

  toSaveItem(item) {
    return new Promise((resolve, reject) => {
      this.http
        .post(this.api + '/items', { item: item })
        .map(res => res.json())
        // This catch is very powerfull, it can catch all errors
        .catch((err: Response) => {
          // The err.statusText is empty if server down (err.type === 3)
          console.log((err.statusText || "Can't join the server."));
          // Really usefull. The app can't catch this in "(err)" closure
          reject((err.statusText || "Can't join the server."));
          // This return is required to compile but unuseable in your app
          return Observable.throw(err);
        })
        // The (err) => {} param on subscribe can't catch server down error so I keep only the catch
        .subscribe(data => { resolve(data) })
    })
  }
}

In the app :

this.itemService.toSaveItem(item).then(
  (res) => { console.log('success', res) },
  (err) => { console.log('error', err) }
)

Transmitting newline character "\n"

Try using %0A in the URL, just like you've used %20 instead of the space character.

How do I disable text selection with CSS or JavaScript?

<div 
 style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;" 
 unselectable="on"
 onselectstart="return false;" 
 onmousedown="return false;">
    Blabla
</div>

What values for checked and selected are false?

There are no values that will cause the checkbox to be unchecked. If the checked attribute exists, the checkbox will be checked regardless of what value you set it to.

_x000D_
_x000D_
<input type="checkbox" checked />_x000D_
<input type="checkbox" checked="" />_x000D_
<input type="checkbox" checked="checked" />_x000D_
<input type="checkbox" checked="unchecked" />_x000D_
<input type="checkbox" checked="true" />_x000D_
<input type="checkbox" checked="false" />_x000D_
<input type="checkbox" checked="on" />_x000D_
<input type="checkbox" checked="off" />_x000D_
<input type="checkbox" checked="1" />_x000D_
<input type="checkbox" checked="0" />_x000D_
<input type="checkbox" checked="yes" />_x000D_
<input type="checkbox" checked="no" />_x000D_
<input type="checkbox" checked="y" />_x000D_
<input type="checkbox" checked="n" />
_x000D_
_x000D_
_x000D_

Renders everything checked in all modern browsers (FF3.6, Chrome 10, IE8).

FileNotFoundException while getting the InputStream object from HttpURLConnection

FileNotFound in this case means you got a 404 from your server - could it be that the server does not like "POST" requests?

Git says remote ref does not exist when I delete remote branch

For me this worked $ ? git branch -D -r origin/mybranch

Details

$ ? git branch -a | grep mybranch remotes/origin/mybranch

$ ? git branch -r | grep mybranch origin/mybranch

$ ? git branch develop * feature/pre-deployment

$ ? git push origin --delete mybranch error: unable to delete 'mybranch': remote ref does not exist error: failed to push some refs to '[email protected]:config/myrepo.git'

$ ? git branch -D -r origin/mybranch Deleted remote branch origin/mybranch (was 62c7421).

$ ? git branch -a | grep mybranch

$ ? git branch -r | grep mybranch

Relative path to absolute path in C#?

string exactPath = Path.GetFullPath(yourRelativePath);

works

Set cellpadding and cellspacing in CSS?

TBH. For all the fannying around with CSS you might as well just use cellpadding="0" cellspacing="0" since they are not deprecated...

Anyone else suggesting margins on <td>'s obviously has not tried this.

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Basically, you get connections in the Sleep state when :

  • a PHP script connects to MySQL
  • some queries are executed
  • then, the PHP script does some stuff that takes time
    • without disconnecting from the DB
  • and, finally, the PHP script ends
    • which means it disconnects from the MySQL server

So, you generally end up with many processes in a Sleep state when you have a lot of PHP processes that stay connected, without actually doing anything on the database-side.

A basic idea, so : make sure you don't have PHP processes that run for too long -- or force them to disconnect as soon as they don't need to access the database anymore.


Another thing, that I often see when there is some load on the server :

  • There are more and more requests coming to Apache
    • which means many pages to generate
  • Each PHP script, in order to generate a page, connects to the DB and does some queries
  • These queries take more and more time, as the load on the DB server increases
  • Which means more processes keep stacking up

A solution that can help is to reduce the time your queries take -- optimizing the longest ones.

Go to particular revision

One way would be to create all commits ever made to patches. checkout the initial commit and then apply the patches in order after reading.

use git format-patch <initial revision> and then git checkout <initial revision>. you should get a pile of files in your director starting with four digits which are the patches.

when you are done reading your revision just do git apply <filename> which should look like git apply 0001-* and count.

But I really wonder why you wouldn't just want to read the patches itself instead? Please post this in your comments because I'm curious.

the git manual also gives me this:

git show next~10:Documentation/README

Shows the contents of the file Documentation/README as they were current in the 10th last commit of the branch next.

you could also have a look at git blame filename which gives you a listing where each line is associated with a commit hash + author.

How do I change the ID of a HTML element with JavaScript?

It does work in Firefox (including 2.0.0.20). See http://jsbin.com/akili (add /edit to the url to edit):

<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>

The first click changes the id to "two", the second click errors because the element with id="one" now can't be found!

Perhaps you have another element already with id="two" (FYI you can't have more than one element with the same id).

How to get UTC time in Python?

Try this code that uses datetime.utcnow():

from datetime import datetime
datetime.utcnow()

For your purposes when you need to calculate an amount of time spent between two dates all that you need is to substract end and start dates. The results of such substraction is a timedelta object.

From the python docs:

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

And this means that by default you can get any of the fields mentioned in it's definition - days, seconds, microseconds, milliseconds, minutes, hours, weeks. Also timedelta instance has total_seconds() method that:

Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10*6) / 10*6 computed with true division enabled.

Write variable to a file in Ansible

We can directly specify the destination file with the dest option now. In the below example, the output json is stored into the /tmp/repo_version_file

- name: Get repository file repo_version model to set ambari_managed_repositories=false
  uri:
    url: 'http://<server IP>:8080/api/v1/stacks/HDP/versions/3.1/repository_versions/1?fields=operating_systems/*'
    method: GET
    force_basic_auth: yes
    user: xxxxx
    password: xxxxx
    headers:
      "X-Requested-By": "ambari"
      "Content-type": "Application/json"
    status_code: 200
    dest: /tmp/repo_version_file

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

I use this method and it works well:

1- Copy And paste the .jar files under the libs folder.

2- Add compile fileTree(dir: 'libs', include: '*.jar') to dependencies in build.gradle then all the jars in the libs folder will be included..

3- Right click on libs folder and select 'Add as library' option from the list.

How to set a dropdownlist item as selected in ASP.NET?

You can set the SelectedValue to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error.

dropdownlist.ClearSelection();
dropdownlist.SelectedValue = value;

You can also use ListItemCollection.FindByText or ListItemCollection.FindByValue

dropdownlist.ClearSelection();  
dropdownlist.Items.FindByValue(value).Selected = true;

Use the FindByValue method to search the collection for a ListItem with a Value property that contains value specified by the value parameter. This method performs a case-sensitive and culture-insensitive comparison. This method does not do partial searches or wildcard searches. If an item is not found in the collection using this criteria, null is returned, MSDN.

If you expect that you may be looking for text/value that wont be present in DropDownList ListItem collection then you must check if you get the ListItem object or null from FindByText or FindByValue before you access Selected property. If you try to access Selected when null is returned then you will get NullReferenceException.

ListItem listItem = dropdownlist.Items.FindByValue(value);

if(listItem != null) 
{
   dropdownlist.ClearSelection();
   listItem.Selected = true;
}

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

In my case the user could not connect to the database. If will have same issue if the log contains a warning just before the exception:

WARN HHH000342: Could not obtain connection to query metadata : Login failed for user 'my_user'.

Android simple alert dialog

You would simply need to do this in your onClick:

AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
alertDialog.show();

I don't know from where you saw that you need DialogFragment for simply showing an alert.

Hope this helps.

Build tree array from flat array in javascript

This is an old thread but I figured an update never hurts, with ES6 you can do:

_x000D_
_x000D_
const data = [{
    id: 1,
    parent_id: 0
}, {
    id: 2,
    parent_id: 1
}, {
    id: 3,
    parent_id: 1
}, {
    id: 4,
    parent_id: 2
}, {
    id: 5,
    parent_id: 4
}, {
    id: 8,
    parent_id: 7
}, {
    id: 9,
    parent_id: 8
}, {
    id: 10,
    parent_id: 9
}];

const arrayToTree = (items=[], id = null, link = 'parent_id') => items.filter(item => id==null ? !items.some(ele=>ele.id===item[link]) : item[link] === id ).map(item => ({ ...item, children: arrayToTree(items, item.id) }))
const temp1=arrayToTree(data)
console.log(temp1)

const treeToArray = (items=[], key = 'children') => items.reduce((acc, curr) => [...acc, ...treeToArray(curr[key])].map(({ [`${key}`]: child, ...ele }) => ele), items);
const temp2=treeToArray(temp1)

console.log(temp2)
_x000D_
_x000D_
_x000D_

hope it helps someone

configure Git to accept a particular self-signed server certificate for a particular https remote

OSX User adjustments.

Following the steps of the Accepted answer worked for me with a small addition when configuring on OSX.

I put the cert.pem file in a directory under my OSX logged in user and thus caused me to adjust the location for the trusted certificate.

Configure git to trust this certificate:

$ git config --global http.sslCAInfo $HOME/git-certs/cert.pem

Fill Combobox from database

private void StudentForm_Load(object sender, EventArgs e)

{
         string q = @"SELECT [BatchID] FROM [Batch]"; //BatchID column name of Batch table
         SqlDataReader reader = DB.Query(q);

         while (reader.Read())
         {
             cbsb.Items.Add(reader["BatchID"].ToString()); //cbsb is the combobox name
         }
  }

How to concatenate variables into SQL strings

You could make use of Prepared Stements like this.

set @query = concat( "select name from " );
set @query = concat( "table_name"," [where condition] " );

prepare stmt from @like_q;
execute stmt;

Is it possible to return empty in react render function?

Yes you can, but instead of blank, simply return null if you don't want to render anything from component, like this:

return (null);

Another important point is, inside JSX if you are rendering element conditionally, then in case of condition=false, you can return any of these values false, null, undefined, true. As per DOC:

booleans (true/false), null, and undefined are valid children, they will be Ignored means they simply don’t render.

All these JSX expressions will render to the same thing:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

Example:

Only odd values will get rendered, because for even values we are returning null.

_x000D_
_x000D_
const App = ({ number }) => {_x000D_
  if(number%2) {_x000D_
    return (_x000D_
      <div>_x000D_
        Number: {number}_x000D_
      </div>_x000D_
    )_x000D_
  }_x000D_
  _x000D_
  return (null);           //===> notice here, returning null for even values_x000D_
}_x000D_
_x000D_
const data = [1,2,3,4,5,6];_x000D_
_x000D_
ReactDOM.render(_x000D_
  <div>_x000D_
    {data.map(el => <App key={el} number={el} />)}_x000D_
  </div>,_x000D_
  document.getElementById('app')_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='app' />
_x000D_
_x000D_
_x000D_

How do I get the object if it exists, or None if it does not exist?

Here's a variation on the helper function that allows you to optionally pass in a QuerySet instance, in case you want to get the unique object (if present) from a queryset other than the model's all objects queryset (e.g. from a subset of child items belonging to a parent instance):

def get_unique_or_none(model, queryset=None, **kwargs):
    """
        Performs the query on the specified `queryset`
        (defaulting to the `all` queryset of the `model`'s default manager)
        and returns the unique object matching the given
        keyword arguments.  Returns `None` if no match is found.
        Throws a `model.MultipleObjectsReturned` exception
        if more than one match is found.
    """
    if queryset is None:
        queryset = model.objects.all()
    try:
        return queryset.get(**kwargs)
    except model.DoesNotExist:
        return None

This can be used in two ways, e.g.:

  1. obj = get_unique_or_none(Model, **kwargs) as previosuly discussed
  2. obj = get_unique_or_none(Model, parent.children, **kwargs)

split python source code into multiple files?

Sure!

#file  -- test.py --
myvar = 42
def test_func():
    print("Hello!")

Now, this file ("test.py") is in python terminology a "module". We can import it (as long as it can be found in our PYTHONPATH) Note that the current directory is always in PYTHONPATH, so if use_test is being run from the same directory where test.py lives, you're all set:

#file -- use_test.py --
import test
test.test_func()  #prints "Hello!"
print (test.myvar)  #prints 42

from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar)     #Exception (NameError)

from test import *
test_func() #prints "Hello"
print(myvar)      #prints 42

There's a lot more you can do than just that through the use of special __init__.py files which allow you to treat multiple files as a single module), but this answers your question and I suppose we'll leave the rest for another time.

How to split a string to 2 strings in C

If you're open to changing the original string, you can simply replace the delimiter with \0. The original pointer will point to the first string and the pointer to the character after the delimiter will point to the second string. The good thing is you can use both pointers at the same time without allocating any new string buffers.

How do I call a specific Java method on a click/submit event of a specific button in JSP?

<form method="post" action="servletName">   
     <input type="submit" id="btn1" name="btn1"/>
     <input type="submit" id="btn2" name="btn2"/>
</form>  

on pressing it request will go to servlet on the servlet page check which button is pressed and then accordingly call the needed method as objectName.method

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use us jquery function getJson :

$(function(){
    $.getJSON('/api/rest/abc', function(data) {
        console.log(data);
    });
});

php search array key and get value

<?php

// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
  echo $search_array[20120504];
}

// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
  echo $search_array[20120504];
}

// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
  echo $search_array[20120504];
}

?>

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

I usually fix this errore following this msdn blog post Using LocalDB with Full IIS

This requires editing applicationHost.config file which is usually located in C:\Windows\System32\inetsrv\config. Following the instructions from KB 2547655 we should enable both flags for Application Pool ASP.NET v4.0, like this:

<add name="ASP.NET v4.0" autoStart="true" managedRuntimeVersion="v4.0"     managedPipelineMode="Integrated">
    <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</add>

How do you find out which version of GTK+ is installed on Ubuntu?

This will get the version of the GTK+ libraries for GTK+ 2 and GTK+ 3.

dpkg -l | egrep "libgtk(2.0-0|-3-0)"

As major versions are parallel installable, you may have both on your system, which is my case, so the above command returns this on my Ubuntu Trusty system:

ii  libgtk-3-0:amd64                                      3.10.8-0ubuntu1.6                                   amd64        GTK+ graphical user interface library
ii  libgtk2.0-0:amd64                                     2.24.23-0ubuntu1.4                                  amd64        GTK+ graphical user interface library

This means I have GTK+ 2.24.23 and 3.10.8 installed.

If what you want is the version of the development files, use pkg-config --modversion gtk+-3.0 for example for GTK+ 3. To extend that to the different major versions of GTK+, with some sed magic, this gives:

pkg-config --list-all | sed -ne 's/\(gtk+-[0-9]*.0\).*/\1/p' | xargs pkg-config --modversion

How to use SqlClient in ASP.NET Core?

I think you may have missed this part in the tutorial:

Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:

System.Data.Common and System.Data.SqlClient.

Currently this creates dependency in project.json –> aspnetcore50 section to these two libraries.

"aspnetcore50": {
       "dependencies": {
           "System.Runtime": "4.0.20-beta-22523",
           "System.Data.Common": "4.0.0.0-beta-22605",
           "System.Data.SqlClient": "4.0.0.0-beta-22605"
       }
}

Try getting System.Data.Common and System.Data.SqlClient via Nuget and see if this adds the above dependencies for you, but in a nutshell you are missing System.Runtime.

Edit: As per Mozarts answer, if you are using .NET Core 3+, reference Microsoft.Data.SqlClient instead.

Multiline text in JLabel

You can use JTextArea and remove editing capabilities to get normal read-only multiline text.

JTextArea textArea = new JTextArea("line\nline\nline");
textArea.setEditable(false);

JTextArea

setEditable

Codeigniter: does $this->db->last_query(); execute a query?

For me save_queries option was turned off so,

$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;

Ref: Can't get result from $this->db->last_query(); codeigniter

Insert all data of a datagridview to database at once

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ID_Proof;Integrated Security=True");
                        SqlCommand cmd = new SqlCommand("INSERT INTO Restaurant (Customer_Name,Quantity,Price,Category,Subcategory,Item,Room_No,Tax,Service_Charge,Service_Tax,Order_Time) values (@customer,@quantity,@price,@category,@subcategory,@item,@roomno,@tax,@servicecharge,@sertax,@ordertime)", con);
                        cmd.Parameters.AddWithValue("@customer",dataGridView2.Rows[i].Cells[0].Value);
                        cmd.Parameters.AddWithValue("@quantity",dataGridView2.Rows[i].Cells[1].Value);
                        cmd.Parameters.AddWithValue("@price",dataGridView2.Rows[i].Cells[2].Value);
                        cmd.Parameters.AddWithValue("@category",dataGridView2.Rows[i].Cells[3].Value);
                        cmd.Parameters.AddWithValue("@subcategory",dataGridView2.Rows[i].Cells[4].Value);
                        cmd.Parameters.AddWithValue("@item",dataGridView2.Rows[i].Cells[5].Value);
                        cmd.Parameters.AddWithValue("@roomno",dataGridView2.Rows[i].Cells[6].Value);
                        cmd.Parameters.AddWithValue("@tax",dataGridView2.Rows[i].Cells[7].Value);
                        cmd.Parameters.AddWithValue("@servicecharge",dataGridView2.Rows[i].Cells[8].Value);
                        cmd.Parameters.AddWithValue("@sertax",dataGridView2.Rows[i].Cells[9].Value);
                        cmd.Parameters.AddWithValue("@ordertime",dataGridView2.Rows[i].Cells[10].Value);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        MessageBox.Show("Added successfully!");

MVC3 DropDownListFor - a simple example?

I think this will help : In Controller get the list items and selected value

public ActionResult Edit(int id)
{
    ItemsStore item = itemStoreRepository.FindById(id);
    ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(), 
                                        "Id", "Name",item.CategoryId);

    // ViewBag to pass values to View and SelectList
    //(get list of items,valuefield,textfield,selectedValue)

    return View(item);
}

and in View

@Html.DropDownList("CategoryId",String.Empty)

How to force link from iframe to be opened in the parent window

If you are using iframe in your webpage you might encounter a problem while changing the whole page through a HTML hyperlink (anchor tag) from the iframe. There are two solutions to mitigate this problem.

Solution 1. You can use target attribute of anchor tag as given in the following example.

<a target="_parent" href="http://www.kriblog.com">link</a>

Solution 2. You can also open a new page in parent window from iframe with JavaScript.

<a href="#" onclick="window.parent.location.href='http://www.kriblog.com';">

Remember ? target="_parent" has been deprecated in XHTML, but it is still supported in HTML 5.x.

More can be read from following link http://www.kriblog.com/html/link-of-iframe-open-in-the-parent-window.html

Count character occurrences in a string in C++

Pseudocode:

count = 0
For each character c in string s
  Check if c equals '_'
    If yes, increase count

EDIT: C++ example code:

int count_underscores(string s) {
  int count = 0;

  for (int i = 0; i < s.size(); i++)
    if (s[i] == '_') count++;

  return count;
}

Note that this is code to use together with std::string, if you're using char*, replace s.size() with strlen(s).

Also note: I can understand you want something "as small as possible", but I'd suggest you to use this solution instead. As you see you can use a function to encapsulate the code for you so you won't have to write out the for loop everytime, but can just use count_underscores("my_string_") in the rest of your code. Using advanced C++ algorithms is certainly possible here, but I think it's overkill.

how to read a long multiline string line by line in python

What about using .splitlines()?

for line in textData.splitlines():
    print(line)
    lineResult = libLAPFF.parseLine(line)

How to find and replace with regex in excel

As an alternative to Regex, running:

Sub Replacer()
   Dim N As Long, i As Long
   N = Cells(Rows.Count, "A").End(xlUp).Row

   For i = 1 To N
      If Left(Cells(i, "A").Value, 9) = "texts are" Then
         Cells(i, "A").Value = "texts are replaced"
      End If
   Next i
End Sub

will produce:

enter image description here

ImportError: cannot import name NUMPY_MKL

Reinstall numpy-1.11.0_XXX.whl (for your Python) from www.lfd.uci.edu/~gohlke/pythonlibs. This file has the same name and version if compare with the variant downloaded by me earlier 29.03.2016, but its size and content differ from old variant. After re-installation error disappeared.

Second option - return back to scipy 0.17.0 from 0.17.1

P.S. I use Windows 64-bit version of Python 3.5.1, so can't guarantee that numpy for Python 2.7 is already corrected.

No module named pkg_resources

I have seen this error while trying to install rhodecode to a virtualenv on ubuntu 13.10. For me the solution was to run

pip install --upgrade setuptools
pip install --upgrade distribute 

before I run easy_install rhodecode.

Store boolean value in SQLite

But,if you want to store a bunch of them you could bit-shift them and store them all as one int, a little like unix file permissions/modes.

For mode 755 for instance, each digit refers to a different class of users: owner, group, public. Within each digit 4 is read, 2 is write, 1 is execute so 7 is all of them like binary 111. 5 is read and execute so 101. Make up your own encoding scheme.

I'm just writing something for storing TV schedule data from Schedules Direct and I have the binary or yes/no fields: stereo, hdtv, new, ei, close captioned, dolby, sap in Spanish, season premiere. So 7 bits, or an integer with a maximum of 127. One character really.

A C example from what I'm working on now. has() is a function that returns 1 if the 2nd string is in the first one. inp is the input string to this function. misc is an unsigned char initialized to 0.

if (has(inp,"sap='Spanish'") > 0)
  misc += 1;
if (has(inp,"stereo='true'") > 0)
  misc +=2;
if (has(inp,"ei='true'") > 0)
  misc +=4;
if (has(inp,"closeCaptioned='true'") > 0)
  misc += 8;
if (has(inp,"dolby=") > 0)
  misc += 16;
if (has(inp,"new='true'") > 0)
  misc += 32;
if (has(inp,"premier_finale='") > 0)
  misc += 64;
if (has(inp,"hdtv='true'") > 0)
  misc += 128;

So I'm storing 7 booleans in one integer with room for more.

How to determine SSL cert expiration date from a PEM encoded certificate?

One line checking on true/false if cert of domain will be expired in some time later(ex. 15 days):

openssl x509 -checkend $(( 24*3600*15 )) -noout -in <(openssl s_client -showcerts -connect my.domain.com:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
if [ $? -eq 0 ]; then
  echo 'good'
else
  echo 'bad'
fi

Basic Authentication Using JavaScript

Today we use Bearer token more often that Basic Authentication but if you want to have Basic Authentication first to get Bearer token then there is a couple ways:

const request = new XMLHttpRequest();
request.open('GET', url, false, username,password)
request.onreadystatechange = function() {
        // D some business logics here if you receive return
   if(request.readyState === 4 && request.status === 200) {
       console.log(request.responseText);
   }
}
request.send()

Full syntax is here

Second Approach using Ajax:

$.ajax
({
  type: "GET",
  url: "abc.xyz",
  dataType: 'json',
  async: false,
  username: "username",
  password: "password",
  data: '{ "key":"sample" }',
  success: function (){
    alert('Thanks for your up vote!');
  }
});

Hopefully, this provides you a hint where to start API calls with JS. In Frameworks like Angular, React, etc there are more powerful ways to make API call with Basic Authentication or Oauth Authentication. Just explore it.

How to make overlay control above all other controls?

This is a common function of Adorners in WPF. Adorners typically appear above all other controls, but the other answers that mention z-order may fit your case better.

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Try to delete the maven folder at ~/.m2/repository/org/apache/maven and build your project again to force the maven libraries be downloaded. This worked for me the last time I faced this java.lang.NoClassDefFoundError: org/apache/maven/shared/filtering/MavenFilteringException.

Java Map equivalent in C#

Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:

class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}

If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).

SQL update statement in C#

string constr = @"Data Source=(LocalDB)\v11.0;Initial Catalog=Bank;Integrated Security=True;Pooling=False";
SqlConnection con = new SqlConnection(constr);
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd = new SqlCommand(" UPDATE Account  SET name = Aleesha, CID = 24 Where name =Areeba and CID =11 )";
cmd.ExecuteNonQuery();

How to sort a list of strings?

It is also worth noting the sorted() function:

for x in sorted(list):
    print x

This returns a new, sorted version of a list without changing the original list.

Tomcat won't stop or restart

I faced the same problem as mentioned below.

PID file found but no matching process was found. Stop aborted.

Solution is to find the free space of the linux machine by using the following command

df -h

The above command shows my home directory was 100% used. Then identified which files to be removed by using the following command

du -h .

After removing, it was able to perform IO operation on the linux machine and the tomcat was able to start.

Easiest way to read from and write to files

using (var file = File.Create("pricequote.txt"))
{
    ...........                        
}

using (var file = File.OpenRead("pricequote.txt"))
{
    ..........
}

Simple, easy and also disposes/cleans up the object once you are done with it.

Open a link in browser with java button?

try {
    Desktop.getDesktop().browse(new URL("http://www.google.com").toURI());
} catch (Exception e) {}

note: you have to include necessary imports from java.net

Looking for a short & simple example of getters/setters in C#

As far as I understand getters and setters are to improve encapsulation. There is nothing complex about them in C#.

You define a property of on object like this:

int m_colorValue = 0;
public int Color 
{
   set { m_colorValue = value; }
   get { return m_colorValue; }
}

This is the most simple use. It basically sets an internal variable or retrieves its value. You use a Property like this:

someObject.Color = 222; // sets a color 222
int color = someObject.Color // gets the color of the object

You could eventually do some processing on the value in the setters or getters like this:

public int Color 
{
   set { m_colorValue = value + 5; }
   get { return m_colorValue  - 30; }
}

if you skip set or get, your property will be read or write only. That's how I understand the stuff.

How to increase IDE memory limit in IntelliJ IDEA on Mac?

I use Mac and Idea 14.1.7. Found idea.vmoptions file here: /Applications/IntelliJ IDEA 14.app/Contents/bin

details

AngularJS - Binding radio buttons to models with boolean values

That's an odd approach with isUserAnswer. Are you really going to send all three choices back to the server where it will loop through each one checking for isUserAnswer == true? If so, you can try this:

http://jsfiddle.net/hgxjv/4/

HTML:

<input type="radio" name="response" value="true" ng-click="setChoiceForQuestion(question1, choice)"/>

JavaScript:

$scope.setChoiceForQuestion = function (q, c) {
    angular.forEach(q.choices, function (c) {
        c.isUserAnswer = false;
    });

    c.isUserAnswer = true;
};

Alternatively, I'd recommend changing your tack:

http://jsfiddle.net/hgxjv/5/

<input type="radio" name="response" value="{{choice.id}}" ng-model="question1.userChoiceId"/>

That way you can just send {{question1.userChoiceId}} back to the server.

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Missing artifact com.sun:tools:jar

None of the other answers did it for me. What did it was to check for "Dependency hierarchy" of the pom.xml in eclipse, where giving a filter 'tools' revealed that I had a real dependency to tools.jar:

Eclipse View

So the culprit for me was this:

<dependency>
    <groupId>com.github.markusbernhardt</groupId>
    <artifactId>robotframework-selenium2library-java</artifactId>
    <version>1.4.0.7</version>
    <scope>test</scope>
</dependency>

Adding an exclusion fixed it:

<dependency>
    <groupId>com.github.markusbernhardt</groupId>
    <artifactId>robotframework-selenium2library-java</artifactId>
    <version>1.4.0.7</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <artifactId>tools</artifactId>
            <groupId>com.sun</groupId>
        </exclusion>
    </exclusions>  
</dependency>

The exclusion doesn't seem to have any downsides to it.

How do I create a basic UIButton programmatically?

In Swift 5 and Xcode 10.2

Basically we have two types of buttons.

1) System type button

2) Custom type button (In custom type button we can set background image for button)

And these two types of buttons has few control states https://developer.apple.com/documentation/uikit/uicontrol/state

Important states are

1) Normal state

2) Selected state

3) Highlighted state

4) Disabled state etc...

//For system type button
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
//  button.backgroundColor = .blue
button.setTitle("Button", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
button.titleLabel?.textAlignment = .center//Text alighment center
button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
button.tag = 1//To assign tag value
button.btnProperties()//Call UIButton properties from extension function
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

//For custom type button (add image to your button)
let button2 = UIButton(type: .custom)
button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
//        button2.backgroundColor = .blue
button2.setImage(UIImage.init(named: "img.png"), for: .normal)
button2.tag = 2
button2.btnProperties()//Call UIButton properties from extension function
button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button2)

@objc func buttonClicked(sender:UIButton) {
    print("Button \(sender.tag) clicked")
}

//You can add UIButton properties using extension
extension UIButton {
    func btnProperties() {
        layer.cornerRadius = 10//Set button corner radious
        clipsToBounds = true
        backgroundColor = .blue//Set background colour
        //titleLabel?.textAlignment = .center//add properties like this
    }
}

How do I open multiple instances of Visual Studio Code?

If you want to open multiple instances of the same folder, then it is not currently supported. Watch and upvote this GitHub issue if you want to see it implemented: Support to open a project folder in multiple Visual Studio Code windows

What's the best CRLF (carriage return, line feed) handling strategy with Git?

Try setting the core.autocrlf configuration option to true. Also have a look at the core.safecrlf option.

Actually it sounds like core.safecrlf might already be set in your repository, because (emphasis mine):

If this is not the case for the current setting of core.autocrlf, git will reject the file.

If this is the case, then you might want to check that your text editor is configured to use line endings consistently. You will likely run into problems if a text file contains a mixture of LF and CRLF line endings.

Finally, I feel that the recommendation to simply "use what you're given" and use LF terminated lines on Windows will cause more problems than it solves. Git has the above options to try to handle line endings in a sensible way, so it makes sense to use them.

mkdir's "-p" option

PATH: Answered long ago, however, it maybe more helpful to think of -p as "Path" (easier to remember), as in this causes mkdir to create every part of the path that isn't already there.

mkdir -p /usr/bin/comm/diff/er/fence

if /usr/bin/comm already exists, it acts like: mkdir /usr/bin/comm/diff mkdir /usr/bin/comm/diff/er mkdir /usr/bin/comm/diff/er/fence

As you can see, it saves you a bit of typing, and thinking, since you don't have to figure out what's already there and what isn't.

How to find the sum of an array of numbers

Recommended (reduce with default value)

Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.

_x000D_
_x000D_
console.log(_x000D_
  [1, 2, 3, 4].reduce((a, b) => a + b, 0)_x000D_
)_x000D_
console.log(_x000D_
  [].reduce((a, b) => a + b, 0)_x000D_
)
_x000D_
_x000D_
_x000D_

Without default value

You get a TypeError

_x000D_
_x000D_
console.log(_x000D_
  [].reduce((a, b) => a + b)_x000D_
)
_x000D_
_x000D_
_x000D_

Prior to ES6's arrow functions

_x000D_
_x000D_
console.log(_x000D_
  [1,2,3].reduce(function(acc, val) { return acc + val; }, 0)_x000D_
)_x000D_
_x000D_
console.log(_x000D_
  [].reduce(function(acc, val) { return acc + val; }, 0)_x000D_
)
_x000D_
_x000D_
_x000D_

Non-number inputs

If non-numbers are possible inputs, you may want to handle that?

_x000D_
_x000D_
console.log(_x000D_
  ["hi", 1, 2, "frog"].reduce((a, b) => a + b)_x000D_
)_x000D_
_x000D_
let numOr0 = n => isNaN(n) ? 0 : n_x000D_
_x000D_
console.log(_x000D_
  ["hi", 1, 2, "frog"].reduce((a, b) => _x000D_
    numOr0(a) + numOr0(b))_x000D_
)
_x000D_
_x000D_
_x000D_

Non-recommended dangerous eval use

We can use eval to execute a string representation of JavaScript code. Using the Array.prototype.join function to convert the array to a string, we change [1,2,3] into "1+2+3", which evaluates to 6.

_x000D_
_x000D_
console.log(_x000D_
  eval([1,2,3].join('+'))_x000D_
)_x000D_
_x000D_
//This way is dangerous if the array is built_x000D_
// from user input as it may be exploited eg: _x000D_
_x000D_
eval([1,"2;alert('Malicious code!')"].join('+'))
_x000D_
_x000D_
_x000D_

Of course displaying an alert isn't the worst thing that could happen. The only reason I have included this is as an answer Ortund's question as I do not think it was clarified.

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

In my case adding Microsoft.AspNet.WebApi.Owin reference via nuget did the trick.

How to load/edit/run/save text files (.py) into an IPython notebook cell?

EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.

A text file can be loaded in a notebook cell with the magic command %load.

If you execute a cell containing:

%load filename.py

the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.

To save the cell content back into a file add the cell-magic %%writefile filename.py at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be silently overwritten.

To see the help for any magic command add a ?: like %load? or %%writefile?.

For general help on magic functions type "%magic" For a list of the available magic functions, use %lsmagic. For a description of any of them, type %magic_name?, e.g. '%cd?'.

See also: Magic functions from the official IPython docs.

How to do SELECT MAX in Django?

Django also has the 'latest(field_name = None)' function that finds the latest (max. value) entry. It not only works with date fields but also with strings and integers.

You can give the field name when calling that function:

max_rated_entry = YourModel.objects.latest('rating')
return max_rated_entry.details

Or you can already give that field name in your models meta data:

from django.db import models

class YourModel(models.Model):
    #your class definition
    class Meta:
        get_latest_by = 'rating'

Now you can call 'latest()' without any parameters:

max_rated_entry = YourModel.objects.latest()
return max_rated_entry.details

Before and After Suite execution hook in jUnit 4.x

The only way I think then to get the functionality you want would be to do something like

import junit.framework.Test;  
import junit.framework.TestResult;  
import junit.framework.TestSuite;  

public class AllTests {  
    public static Test suite() {  
        TestSuite suite = new TestSuite("TestEverything");  
        //$JUnit-BEGIN$  
        suite.addTestSuite(TestOne.class);  
        suite.addTestSuite(TestTwo.class);  
        suite.addTestSuite(TestThree.class);  
        //$JUnit-END$  
     }  

     public static void main(String[] args)  
     {  
        AllTests test = new AllTests();  
        Test testCase = test.suite();  
        TestResult result = new TestResult();  
        setUp();  
        testCase.run(result);  
        tearDown();  
     }  
     public void setUp() {}  
     public void tearDown() {}  
} 

I use something like this in eclipse, so I'm not sure how portable it is outside of that environment

Run Python script at startup in Ubuntu

Put this in /etc/init (Use /etc/systemd in Ubuntu 15.x)

mystartupscript.conf

start on runlevel [2345]
stop on runlevel [!2345]

exec /path/to/script.py

By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.

manual starting/stopping is done with sudo service mystartupscript start and sudo service mystartupscript stop

Django - filtering on foreign key properties

Asset.objects.filter( project__name__contains="Foo" )

How to execute Ant build in command line

Try running all targets individually to check that all are running correct

run ant target name to run a target individually

e.g. ant build-project

Also the default target you specified is

project basedir="." default="build" name="iControlSilk4J"

This will only execute build-subprojects,build-project and init

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

I got this error when I was trying to convert a char (or string) to bytes, the code was something like this with Python 2.7:

# -*- coding: utf-8 -*-
print( bytes('ò') )

This is the way of Python 2.7 when dealing with unicode chars.

This won't work with Python 3.6, since bytes require an extra argument for encoding, but this can be little tricky, since different encoding may output different result:

print( bytes('ò', 'iso_8859_1') ) # prints: b'\xf2'
print( bytes('ò', 'utf-8') ) # prints: b'\xc3\xb2'

In my case I had to use iso_8859_1 when encoding bytes in order to solve the issue.

Hope this helps someone.

How do I exit from a function?

Use the return keyword.

return; //exit this event

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

Variables have a type and a value.

  • $var = "test" is a string that contain "test"
  • $var2 = 24 is an integer vhose value is 24.

When you use these variables (in PHP), sometimes you don't have the good type. For example, if you do

if ($var == 1) {... do something ...}

PHP have to convert ("to cast") $var to integer. In this case, "$var == 1" is true because any non-empty string is casted to 1.

When using ===, you check that the value AND THE TYPE are equal, so "$var === 1" is false.

This is useful, for example, when you have a function that can return false (on error) and 0 (result) :

if(myFunction() == false) { ... error on myFunction ... }

This code is wrong as if myFunction() returns 0, it is casted to false and you seem to have an error. The correct code is :

if(myFunction() === false) { ... error on myFunction ... }

because the test is that the return value "is a boolean and is false" and not "can be casted to false".

How do I use floating-point division in bash?

There are scenarios in wich you cannot use bc becouse it might simply not be present, like in some cut down versions of busybox or embedded systems. In any case limiting outer dependencies is always a good thing to do so you can always add zeroes to the number being divided by (numerator), that is the same as multiplying by a power of 10 (you should choose a power of 10 according to the precision you need), that will make the division output an integer number. Once you have that integer treat it as a string and position the decimal point (moving it from right to left) a number of times equal to the power of ten you multiplied the numerator by. This is a simple way of obtaining float results by using only integer numbers.

python time + timedelta equivalent

This is a bit nasty, but:

from datetime import datetime, timedelta

now = datetime.now().time()
# Just use January the first, 2000
d1 = datetime(2000, 1, 1, now.hour, now.minute, now.second)
d2 = d1 + timedelta(hours=1, minutes=23)
print d2.time()

Auto Generate Database Diagram MySQL

The "Reverse Engineer Database" mode in Workbench is only part of the paid version, not the free one.

Which Protocols are used for PING?

Netscantools Pro Ping can do ICMP, UDP, and TCP.

How do you round a number to two decimal places in C#?

One thing you may want to check is the Rounding Mechanism of Math.Round:

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

Other than that, I recommend the Math.Round(inputNumer, numberOfPlaces) approach over the *100/100 one because it's cleaner.

When to use the different log levels

I've always considered warning the first log level that for sure means there is a problem (for example, perhaps a config file isn't where it should be and we're going to have to run with default settings). An error implies, to me, something that means the main goal of the software is now impossible and we're going to try to shut down cleanly.

How to convert Varchar to Int in sql server 2008?

That is the correct way to convert it to an INT as long as you don't have any alpha characters or NULL values.

If you have any NULL values, use

ISNULL(column1, 0)

Git merge without auto commit

If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too

$ git merge --squash v1.0
$ git commit

How to show math equations in general github's markdown(not github's blog)

Markdown supports inline HTML. Inline HTML can be used for both quick and simple inline equations and, with and external tool, more complex rendering.

Quick and Simple Inline

For quick and simple inline items use HTML ampersand entity codes. An example that combines this idea with subscript text in markdown is: h?(x) = ?o x + ?1x, the code for which follows.

    h<sub>&theta;</sub>(x) = &theta;<sub>o</sub> x + &theta;<sub>1</sub>x

HTML ampersand entity codes for common math symbols can be found here. Codes for Greek letters here.

While this approach has limitations it works in practically all markdown and does not require any external libraries.

Complex Scalable Inline Rendering with LaTeX and Codecogs

If your needs are greater use an external LaTeX renderer like CodeCogs. Create an equation with CodeCogs editor. Choose svg for rendering and HTML for the embed code. Svg renders well on resize. HTML allows LaTeX to be easily read when you are looking at the source. Copy the embed code from the bottom of the page and paste it into your markdown.

<img src="https://latex.codecogs.com/svg.latex?\Large&space;x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}" title="\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}" />

Expressed in markdown becomes

![\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}](https://latex.codecogs.com/svg.latex?\Large&space;x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}) 

\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}

This combines this answer and this answer.

GitHub support only somtimes worked using the above raw html syntax for readable LaTeX for me. If the above does not work for you another option is to instead choose URL Encoded rendering and use that output to manually create a link like:

\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}

![\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}](https://latex.codecogs.com/svg.latex?x%3D%5Cfrac%7B-b%5Cpm%5Csqrt%7Bb%5E2-4ac%7D%7D%7B2a%7D)

This manually incorporates LaTex in the alt image text and uses an encoded URL for rendering on GitHub.

Multi-line Rendering

If you need multi-line rendering check out this answer.

How can I get a Unicode character's code?

Just convert it to int:

char registered = '®';
int code = (int) registered;

In fact there's an implicit conversion from char to int so you don't have to specify it explicitly as I've done above, but I would do so in this case to make it obvious what you're trying to do.

This will give the UTF-16 code unit - which is the same as the Unicode code point for any character defined in the Basic Multilingual Plane. (And only BMP characters can be represented as char values in Java.) As Andrzej Doyle's answer says, if you want the Unicode code point from an arbitrary string, use Character.codePointAt().

Once you've got the UTF-16 code unit or Unicode code points, but of which are integers, it's up to you what you do with them. If you want a string representation, you need to decide exactly what kind of representation you want. (For example, if you know the value will always be in the BMP, you might want a fixed 4-digit hex representation prefixed with U+, e.g. "U+0020" for space.) That's beyond the scope of this question though, as we don't know what the requirements are.

About .bash_profile, .bashrc, and where should alias be written in?

.bash_profile is loaded for a "login shell". I am not sure what that would be on OS X, but on Linux that is either X11 or a virtual terminal.

.bashrc is loaded every time you run Bash. That is where you should put stuff you want loaded whenever you open a new Terminal.app window.

I personally put everything in .bashrc so that I don't have to restart the application for changes to take effect.

SoapFault exception: Could not connect to host

I am adding my comment for completeness, as the solutions listed here did not help me. On PHP 5.6, SoapClient makes the first call to the specified WSDL URL in SoapClient::SoapClient and after connecting to it and receiving the result, it tries to connect to the WSDL specified in the result in:

<soap:address location="http://"/>

And the call fails with error Could not connect to host if the WSDL is different than the one you specified in SoapClient::SoapClient and is unreachable (my case was SoapUI using http://host.local/).

The behaviour in PHP 5.4 is different and it always uses the WSDL in SoapClient::SoapClient.

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

_x000D_
_x000D_
    var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");_x000D_
    alert(d.toLocaleDateString());
_x000D_
_x000D_
_x000D_

How to enter command with password for git pull?

I did not find the answer to my question after searching Google & stackoverflow for a while so I would like to share my solution here.

git config --global credential.helper "/bin/bash /git_creds.sh"
echo '#!/bin/bash' > /git_creds.sh
echo "sleep 1" >> /git_creds.sh
echo "echo username=$SERVICE_USER" >> /git_creds.sh
echo "echo password=$SERVICE_PASS" >> /git_creds.sh

# to test it
git clone https://my-scm-provider.com/project.git

I did it for Windows too. Full answer here

How to write JUnit test with Spring Autowire?

A JUnit4 test with Autowired and bean mocking (Mockito):

// JUnit starts spring context
@RunWith(SpringRunner.class)
// spring load context configuration from AppConfig class
@ContextConfiguration(classes = AppConfig.class)
// overriding some properties with test values if you need
@TestPropertySource(properties = {
        "spring.someConfigValue=your-test-value",
})
public class PersonServiceTest {

    @MockBean
    private PersonRepository repository;

    @Autowired
    private PersonService personService; // uses PersonRepository    

    @Test
    public void testSomething() {
        // using Mockito
        when(repository.findByName(any())).thenReturn(Collection.emptyList());
        Person person = new Person();
        person.setName(null);

        // when
        boolean found = personService.checkSomething(person);

        // then
        assertTrue(found, "Something is wrong");
    }
}

Detecting a long press with Android

The idea is creating a Runnable for execute long click in a future, but this execution can be canceled because of a click, or move.

You also need to know, when long click was consumed, and when it is canceled because finger moved too much. We use initialTouchX & initialTouchY for checking if the user exit a square area of 10 pixels, 5 each side.

Here is my complete code for delegating Click & LongClick from Cell in ListView to Activity with OnTouchListener:

    ClickDelegate delegate; 
    boolean goneFlag = false;
    float initialTouchX;
    float initialTouchY;
    final Handler handler = new Handler();
    Runnable mLongPressed = new Runnable() {
        public void run() {
            Log.i("TOUCH_EVENT", "Long press!");
            if (delegate != null) {
                goneFlag = delegate.onItemLongClick(index);
            } else {
                goneFlag = true;
            }
        }
    };

    @OnTouch({R.id.layout})
    public boolean onTouch (View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                handler.postDelayed(mLongPressed, ViewConfiguration.getLongPressTimeout());
                initialTouchX = motionEvent.getRawX();
                initialTouchY = motionEvent.getRawY();
                return true;
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_CANCEL:
                if (Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) {
                    handler.removeCallbacks(mLongPressed);
                    return true;
                }
                return false;
            case MotionEvent.ACTION_UP:
                handler.removeCallbacks(mLongPressed);
                if (goneFlag || Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) {
                    goneFlag = false;
                    return true;
                }
                break;
        }
        Log.i("TOUCH_EVENT", "Short press!");
        if (delegate != null) {
            if (delegate.onItemClick(index)) {
                return false;
            }
        }
        return false;
    }

ClickDelegateis an interface for sending click events to the handler class like an Activity

    public interface ClickDelegate {
        boolean onItemClick(int position);
        boolean onItemLongClick(int position);
    }

And all what you need is to implement it in your Activity or parent Viewif you need to delegate the behavior:

public class MyActivity extends Activity implements ClickDelegate {

    //code...
    //in some place of you code like onCreate, 
    //you need to set the delegate like this:
    SomeArrayAdapter.delegate = this;
    //or:
    SomeViewHolder.delegate = this;
    //or:
    SomeCustomView.delegate = this;

    @Override
    public boolean onItemClick(int position) {
        Object obj = list.get(position);
        if (obj) {
            return true; //if you handle click
        } else {
            return false; //if not, it could be another event
        }
    }

    @Override
    public boolean onItemLongClick(int position) {
        Object obj = list.get(position);
        if (obj) {
            return true; //if you handle long click
        } else {
            return false; //if not, it's a click
        }
    }
}

Git - Ignore files during merge

I got over this issue by using git merge command with the --no-commit option and then explicitly removed the staged file and ignore the changes to the file. E.g.: say I want to ignore any changes to myfile.txt I proceed as follows:

git merge --no-ff --no-commit <merge-branch>
git reset HEAD myfile.txt
git checkout -- myfile.txt
git commit -m "merged <merge-branch>"

You can put statements 2 & 3 in a for loop, if you have a list of files to skip.

How do I count unique items in field in Access query?

A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:

SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
  SELECT First([FieldName]) AS [UniqueField]
  FROM TableName
  GROUP BY [FieldName]
  HAVING (((Count([FieldName]))>0))
);

Hope this helps, not the best way I am sure, and Access should have had this built in.

100% width table overflowing div container

Add display: block; and overflow: auto; to .my-table. This will simply cut off anything past the 280px limit you enforced. There's no way to make it "look pretty" with that requirement due to words like pélagosthrough which are wider than 280px.

Pass object to javascript function

Answering normajeans' question about setting default value. Create a defaults object with same properties and merge with the arguments object

If using ES6:

    function yourFunction(args){
        let defaults = {opt1: true, opt2: 'something'};
        let params = {...defaults, ...args}; // right-most object overwrites 
        console.log(params.opt1);
    }

Older Browsers using Object.assign(target, source):

    function yourFunction(args){
        var defaults = {opt1: true, opt2: 'something'};
        var params = Object.assign(defaults, args) // args overwrites as it is source
        console.log(params.opt1);
    }

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

How to get file path in iPhone app

Since it is your files in your app bundle, I think you can use pathForResource:ofType: to get the full pathname of your file.

Here is an example:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"your_file_name" 
                                            ofType:@"the_file_extension"];

How to listen for 'props' changes

I use props and variables computed properties if I need create logic after to receive the changes

export default {
name: 'getObjectDetail',
filters: {},
components: {},
props: {
    objectDetail: {
      type: Object,
      required: true
    }
},
computed: {
    _objectDetail: {
        let value = false
        ...

        if (someValidation)
        ...
    }
}

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

How to use sys.exit() in Python

I think you can use

sys.exit(0)

You may check it here in the python 2.7 doc:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.

Any way to generate ant build.xml file automatically from Eclipse?

I've had the same problem, our work environment is based on Eclipse Java projects, and we needed to build automatically an ANT file so that we could use a continuous integration server (Jenkins, in our case).

We rolled out our own Eclipse Java to Ant tool, which is now available on GitHub:

ant-build-for-java

To use it, call:

java -jar ant-build-for-java.jar <folder with repositories> [<.userlibraries file>]

The first argument is the folder with the repositories. It will search the folder recursively for any .project file. The tool will create a build.xml in the given folder.

Optionally, the second argument can be an exported .userlibraries file, from Eclipse, needed when any of the projects use Eclipse user libraries. The tool was tested only with user libraries using relative paths, it's how we use them in our repo. This implies that JARs and other archives needed by projects are inside an Eclipse project, and referenced from there.

The tool only supports dependencies from other Eclipse projects and from Eclipse user libraries.

pandas dataframe create new columns and fill with calculated values from same df

You can do this easily manually for each column like this:

df['A_perc'] = df['A']/df['sum']

If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):

ds.div(ds['sum'], axis=0)

And if you want this in one step added to the same dataframe:

>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
          A         B         C         D       sum    A_perc    B_perc  \
1  0.151722  0.935917  1.033526  0.941962  3.063127  0.049532  0.305543   
2  0.033761  1.087302  1.110695  1.401260  3.633017  0.009293  0.299283   
3  0.761368  0.484268  0.026837  1.276130  2.548603  0.298739  0.190013   

     C_perc    D_perc  sum_perc  
1  0.337409  0.307517         1  
2  0.305722  0.385701         1  
3  0.010530  0.500718         1  

How to get temporary folder for current user

I have this same requirement - we want to put logs in a specific root directory that should exist within the environment.

public static readonly string DefaultLogFilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

If I want to combine this with a sub-directory, I should be able to use Path.Combine( ... ).

The GetFolderPath method has an overload for special folder options which allows you to control whether the specified path be created or simply verified.

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

Use This its is very useful for your solution:

  1. Start > Control Panel > Administrative Tools > Services
  2. Scroll down to 'Windows Presentation Foundation Font Cache 4.0.0.0' and then right click and select properties
  3. In the window then select 'disabled' in the startup type combo

Count records for every month in a year

This will give you the count per month for 2012;

SELECT MONTH(ARR_DATE) MONTH, COUNT(*) COUNT
FROM table_emp
WHERE YEAR(arr_date)=2012
GROUP BY MONTH(ARR_DATE);

Demo here.

How to get UTC+0 date in Java 8?

In java8, I would use the Instant class which is already in UTC and is convenient to work with.

import java.time.Instant;

Instant ins = Instant.now();
long ts = ins.toEpochMilli();

Instant ins2 = Instant.ofEpochMilli(ts)

Alternatively, you can use the following:

import java.time.*;

Instant ins = Instant.now(); 

OffsetDateTime odt = ins.atOffset(ZoneOffset.UTC);
ZonedDateTime zdt = ins.atZone(ZoneId.of("UTC"));

Back to Instant

Instant ins4 = Instant.from(odt);

Reading Xml with XmlReader in C#

For sub-objects, ReadSubtree() gives you an xml-reader limited to the sub-objects, but I really think that you are doing this the hard way. Unless you have very specific requirements for handling unusual / unpredicatable xml, use XmlSerializer (perhaps coupled with sgen.exe if you really want).

XmlReader is... tricky. Contrast to:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
public class ApplicationPool {
    private readonly List<Account> accounts = new List<Account>();
    public List<Account> Accounts {get{return accounts;}}
}
public class Account {
    public string NameOfKin {get;set;}
    private readonly List<Statement> statements = new List<Statement>();
    public List<Statement> StatementsAvailable {get{return statements;}}
}
public class Statement {}
static class Program {
    static void Main() {
        XmlSerializer ser = new XmlSerializer(typeof(ApplicationPool));
        ser.Serialize(Console.Out, new ApplicationPool {
            Accounts = { new Account { NameOfKin = "Fred",
                StatementsAvailable = { new Statement {}, new Statement {}}}}
        });
    }
}

How do I run a file on localhost?

I'm not really sure what you mean, so I'll start simply:

If the file you're trying to "run" is static content, like HTML or even Javascript, you don't need to run it on "localhost"... you should just be able to open it from wherever it is on your machine in your browser.

If it is a piece of server-side code (ASP[.NET], php, whatever else, uou need to be running either a web server, or if you're using Visual Studio, start the development server for your application (F5 to debug, or CTRL+F5 to start without debugging).

If you're using a web server, you'll need to have a web site configured with the home directory set to the directory the file is in (or, just put the file in whatever home directory is configured).

If you're using Visual Studio, the file just needs to be in your project.

How to access Spring MVC model object in javascript file?

JavaScript is run on the client side. Your model does not exist on the client side, it only exists on the server side while you are rendering your .jsp.

If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.

Update:

A simple example

<%-- SomeJsp.jsp --%>
<script>var paramOne =<c:out value="${paramOne}"/></script>

excel vba getting the row,cell value from selection.address

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

Clear dropdownlist with JQuery

How about storing the new options in a variable, and then using .html(variable) to replace the data in the container?

How is a CSS "display: table-column" supposed to work?

The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html

A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.

"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).

Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.

The table itself is always structured the same way it is in HTML.

In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):

<table ..>
  <col .. />
  <col .. />
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
</table>

Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):

_x000D_
_x000D_
.mytable {_x000D_
  display: table;_x000D_
}_x000D_
.myrow {_x000D_
  display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
  display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
  display: table-column;_x000D_
  background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
  display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 1</div>_x000D_
    <div class="mycell">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 2</div>_x000D_
    <div class="mycell">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_



OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:

_x000D_
_x000D_
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow row1">_x000D_
    <div class="mycell cell1">contents of first cell in row 1</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow row2">_x000D_
    <div class="mycell cell1">contents of first cell in row 2</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.

PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)

The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.

Sorting an IList in C#

This question inspired me to write a blog post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/

I think that, ideally, the .NET Framework would include a static sorting method that accepts an IList<T>, but the next best thing is to create your own extension method. It's not too hard to create a couple of methods that will allow you to sort an IList<T> as you would a List<T>. As a bonus you can overload the LINQ OrderBy extension method using the same technique, so that whether you're using List.Sort, IList.Sort, or IEnumerable.OrderBy, you can use the exact same syntax.

public static class SortExtensions
{
    //  Sorts an IList<T> in place.
    public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
    {
        ArrayList.Adapter((IList)list).Sort(new ComparisonComparer<T>(comparison));
    }

    // Sorts in IList<T> in place, when T is IComparable<T>
    public static void Sort<T>(this IList<T> list) where T: IComparable<T>
    {
        Comparison<T> comparison = (l, r) => l.CompareTo(r);
        Sort(list, comparison);

    }

    // Convenience method on IEnumerable<T> to allow passing of a
    // Comparison<T> delegate to the OrderBy method.
    public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, Comparison<T> comparison)
    {
        return list.OrderBy(t => t, new ComparisonComparer<T>(comparison));
    }
}

// Wraps a generic Comparison<T> delegate in an IComparer to make it easy
// to use a lambda expression for methods that take an IComparer or IComparer<T>
public class ComparisonComparer<T> : IComparer<T>, IComparer
{
    private readonly Comparison<T> _comparison;

    public ComparisonComparer(Comparison<T> comparison)
    {
        _comparison = comparison;
    }

    public int Compare(T x, T y)
    {
        return _comparison(x, y);
    }

    public int Compare(object o1, object o2)
    {
        return _comparison((T)o1, (T)o2);
    }
}

With these extensions, sort your IList just like you would a List:

IList<string> iList = new []
{
    "Carlton", "Alison", "Bob", "Eric", "David"
};

// Use the custom extensions:

// Sort in-place, by string length
iList.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));

// Or use OrderBy()
IEnumerable<string> ordered = iList.OrderBy((s1, s2) => s1.Length.CompareTo(s2.Length));

There's more info in the post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/

Vagrant shared and synced folders

shared folders VS synced folders

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

Vagrantfile directory mounted as /vagrant in guest

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

See docs

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

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

Why synced folder is not working

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

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

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

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

output

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

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

How to insert blank lines in PDF?

You can trigger a newline by inserting Chunk.NEWLINE into your document. Here's an example.

public static void main(String args[]) {
    try {
        // create a new document
        Document document = new Document( PageSize.A4, 20, 20, 20, 20 );
        PdfWriter.getInstance( document, new FileOutputStream( "HelloWorld.pdf" ) );

        document.open();

        document.add( new Paragraph( "Hello, World!" ) );
        document.add( new Paragraph( "Hello, World!" ) );

        // add a couple of blank lines
        document.add( Chunk.NEWLINE );
        document.add( Chunk.NEWLINE );

        // add one more line with text
        document.add( new Paragraph( "Hello, World!" ) );

        document.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

Below is a screen shot showing part of the PDF that the code above produces.

Hello PDF with blank lines inserted

How to list the files inside a JAR file?

Code that works for both IDE's and .jar files:

import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;

public class ResourceWalker {
    public static void main(String[] args) throws URISyntaxException, IOException {
        URI uri = ResourceWalker.class.getResource("/resources").toURI();
        Path myPath;
        if (uri.getScheme().equals("jar")) {
            FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap());
            myPath = fileSystem.getPath("/resources");
        } else {
            myPath = Paths.get(uri);
        }
        Stream<Path> walk = Files.walk(myPath, 1);
        for (Iterator<Path> it = walk.iterator(); it.hasNext();){
            System.out.println(it.next());
        }
    }
}

Excel VBA - Sum up a column

I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell. rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:

dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))

or

dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))

The worksheet function sum will correctly ignore blank spaces.

Let me know if this helps!

PHP code to convert a MySQL query to CSV

// Export to CSV
if($_GET['action'] == 'export') {

  $rsSearchResults = mysql_query($sql, $db) or die(mysql_error());

  $out = '';
  $fields = mysql_list_fields('database','table',$db);
  $columns = mysql_num_fields($fields);

  // Put the name of all fields
  for ($i = 0; $i < $columns; $i++) {
    $l=mysql_field_name($fields, $i);
    $out .= '"'.$l.'",';
  }
  $out .="\n";

  // Add all values in the table
  while ($l = mysql_fetch_array($rsSearchResults)) {
    for ($i = 0; $i < $columns; $i++) {
      $out .='"'.$l["$i"].'",';
    }
    $out .="\n";
  }
  // Output to browser with appropriate mime type, you choose ;)
  header("Content-type: text/x-csv");
  //header("Content-type: text/csv");
  //header("Content-type: application/csv");
  header("Content-Disposition: attachment; filename=search_results.csv");
  echo $out;
  exit;
}

svn over HTTP proxy

In /etc/subversion/servers you are setting http-proxy-host, which has nothing to do with svn:// which connects to a different server usually running on port 3690 started by svnserve command.

If you have access to the server, you can setup svn+ssh:// as explained here.

Update: You could also try using connect-tunnel, which uses your HTTPS proxy server to tunnel connections:

connect-tunnel -P proxy.company.com:8080 -T 10234:svn.example.com:3690

Then you would use

svn checkout svn://localhost:10234/path/to/trunk

htaccess Access-Control-Allow-Origin

Make sure you don't have a redirect happening. This can happen if you don't include the trailing slash in the URL.

See this answer for more detail – https://stackoverflow.com/a/27872891/614524

Get OS-level system information

Hey you can do this with java/com integration. By accessing WMI features you can get all the information.

Background thread with QThread in PyQt

In PyQt there are a lot of options for getting asynchronous behavior. For things that need event processing (ie. QtNetwork, etc) you should use the QThread example I provided in my other answer on this thread. But for the vast majority of your threading needs, I think this solution is far superior than the other methods.

The advantage of this is that the QThreadPool schedules your QRunnable instances as tasks. This is similar to the task pattern used in Intel's TBB. It's not quite as elegant as I like but it does pull off excellent asynchronous behavior.

This allows you to utilize most of the threading power of Qt in Python via QRunnable and still take advantage of signals and slots. I use this same code in several applications, some that make hundreds of asynchronous REST calls, some that open files or list directories, and the best part is using this method, Qt task balances the system resources for me.

import time
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import Qt


def async(method, args, uid, readycb, errorcb=None):
    """
    Asynchronously runs a task

    :param func method: the method to run in a thread
    :param object uid: a unique identifier for this task (used for verification)
    :param slot updatecb: the callback when data is receieved cb(uid, data)
    :param slot errorcb: the callback when there is an error cb(uid, errmsg)

    The uid option is useful when the calling code makes multiple async calls
    and the callbacks need some context about what was sent to the async method.
    For example, if you use this method to thread a long running database call
    and the user decides they want to cancel it and start a different one, the
    first one may complete before you have a chance to cancel the task.  In that
    case, the "readycb" will be called with the cancelled task's data.  The uid
    can be used to differentiate those two calls (ie. using the sql query).

    :returns: Request instance
    """
    request = Request(method, args, uid, readycb, errorcb)
    QtCore.QThreadPool.globalInstance().start(request)
    return request


class Request(QtCore.QRunnable):
    """
    A Qt object that represents an asynchronous task

    :param func method: the method to call
    :param list args: list of arguments to pass to method
    :param object uid: a unique identifier (used for verification)
    :param slot readycb: the callback used when data is receieved
    :param slot errorcb: the callback used when there is an error

    The uid param is sent to your error and update callbacks as the
    first argument. It's there to verify the data you're returning

    After created it should be used by invoking:

    .. code-block:: python

       task = Request(...)
       QtCore.QThreadPool.globalInstance().start(task)

    """
    INSTANCES = []
    FINISHED = []
    def __init__(self, method, args, uid, readycb, errorcb=None):
        super(Request, self).__init__()
        self.setAutoDelete(True)
        self.cancelled = False

        self.method = method
        self.args = args
        self.uid = uid
        self.dataReady = readycb
        self.dataError = errorcb

        Request.INSTANCES.append(self)

        # release all of the finished tasks
        Request.FINISHED = []

    def run(self):
        """
        Method automatically called by Qt when the runnable is ready to run.
        This will run in a separate thread.
        """
        # this allows us to "cancel" queued tasks if needed, should be done
        # on shutdown to prevent the app from hanging
        if self.cancelled:
            self.cleanup()
            return

        # runs in a separate thread, for proper async signal/slot behavior
        # the object that emits the signals must be created in this thread.
        # Its not possible to run grabber.moveToThread(QThread.currentThread())
        # so to get this QObject to properly exhibit asynchronous
        # signal and slot behavior it needs to live in the thread that
        # we're running in, creating the object from within this thread
        # is an easy way to do that.
        grabber = Requester()
        grabber.Loaded.connect(self.dataReady, Qt.QueuedConnection)
        if self.dataError is not None:
            grabber.Error.connect(self.dataError, Qt.QueuedConnection)

        try:
            result = self.method(*self.args)
            if self.cancelled:
                # cleanup happens in 'finally' statement
                return
            grabber.Loaded.emit(self.uid, result)
        except Exception as error:
            if self.cancelled:
                # cleanup happens in 'finally' statement
                return
            grabber.Error.emit(self.uid, unicode(error))
        finally:
            # this will run even if one of the above return statements
            # is executed inside of the try/except statement see:
            # https://docs.python.org/2.7/tutorial/errors.html#defining-clean-up-actions
            self.cleanup(grabber)

    def cleanup(self, grabber=None):
        # remove references to any object or method for proper ref counting
        self.method = None
        self.args = None
        self.uid = None
        self.dataReady = None
        self.dataError = None

        if grabber is not None:
            grabber.deleteLater()

        # make sure this python obj gets cleaned up
        self.remove()

    def remove(self):
        try:
            Request.INSTANCES.remove(self)

            # when the next request is created, it will clean this one up
            # this will help us avoid this object being cleaned up
            # when it's still being used
            Request.FINISHED.append(self)
        except ValueError:
            # there might be a race condition on shutdown, when shutdown()
            # is called while the thread is still running and the instance
            # has already been removed from the list
            return

    @staticmethod
    def shutdown():
        for inst in Request.INSTANCES:
            inst.cancelled = True
        Request.INSTANCES = []
        Request.FINISHED = []


class Requester(QtCore.QObject):
    """
    A simple object designed to be used in a separate thread to allow
    for asynchronous data fetching
    """

    #
    # Signals
    #

    Error = QtCore.pyqtSignal(object, unicode)
    """
    Emitted if the fetch fails for any reason

    :param unicode uid: an id to identify this request
    :param unicode error: the error message
    """

    Loaded = QtCore.pyqtSignal(object, object)
    """
    Emitted whenever data comes back successfully

    :param unicode uid: an id to identify this request
    :param list data: the json list returned from the GET
    """

    NetworkConnectionError = QtCore.pyqtSignal(unicode)
    """
    Emitted when the task fails due to a network connection error

    :param unicode message: network connection error message
    """

    def __init__(self, parent=None):
        super(Requester, self).__init__(parent)


class ExampleObject(QtCore.QObject):
    def __init__(self, parent=None):
        super(ExampleObject, self).__init__(parent)
        self.uid = 0
        self.request = None

    def ready_callback(self, uid, result):
        if uid != self.uid:
            return
        print "Data ready from %s: %s" % (uid, result)

    def error_callback(self, uid, error):
        if uid != self.uid:
            return
        print "Data error from %s: %s" % (uid, error)

    def fetch(self):
        if self.request is not None:
            # cancel any pending requests
            self.request.cancelled = True
            self.request = None

        self.uid += 1
        self.request = async(slow_method, ["arg1", "arg2"], self.uid,
                             self.ready_callback,
                             self.error_callback)


def slow_method(arg1, arg2):
    print "Starting slow method"
    time.sleep(1)
    return arg1 + arg2


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)

    obj = ExampleObject()

    dialog = QtGui.QDialog()
    layout = QtGui.QVBoxLayout(dialog)
    button = QtGui.QPushButton("Generate", dialog)
    progress = QtGui.QProgressBar(dialog)
    progress.setRange(0, 0)
    layout.addWidget(button)
    layout.addWidget(progress)
    button.clicked.connect(obj.fetch)
    dialog.show()

    app.exec_()
    app.deleteLater() # avoids some QThread messages in the shell on exit
    # cancel all running tasks avoid QThread/QTimer error messages
    # on exit
    Request.shutdown()

When exiting the application you'll want to make sure you cancel all of the tasks or the application will hang until every scheduled task has completed

How to create a numpy array of all True or all False?

numpy already allows the creation of arrays of all ones or all zeros very easily:

e.g. numpy.ones((2, 2)) or numpy.zeros((2, 2))

Since True and False are represented in Python as 1 and 0, respectively, we have only to specify this array should be boolean using the optional dtype parameter and we are done.

numpy.ones((2, 2), dtype=bool)

returns:

array([[ True,  True],
       [ True,  True]], dtype=bool)

UPDATE: 30 October 2013

Since numpy version 1.8, we can use full to achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):

numpy.full((2, 2), True, dtype=bool)

UPDATE: 16 January 2017

Since at least numpy version 1.12, full automatically casts results to the dtype of the second parameter, so we can just write:

numpy.full((2, 2), True)

How to find and replace all occurrences of a string recursively in a directory tree?

On macOS, none of the answers worked for me. I discovered that was due to differences in how sed works on macOS and other BSD systems compared to GNU.

In particular BSD sed takes the -i option but requires a suffix for the backup (but an empty suffix is permitted)

grep version from this answer.

grep -rl 'foo' ./ | LC_ALL=C xargs sed -i '' 's/foo/bar/g'

find version from this answer.

find . \( ! -regex '.*/\..*' \) -type f | LC_ALL=C xargs sed -i '' 's/foo/bar/g'

Don't omit the Regex to ignore . folders if you're in a Git repo. I realized that the hard way!

That LC_ALL=C option is to avoid getting sed: RE error: illegal byte sequence if sed finds a byte sequence that is not a valid UTF-8 character. That's another difference between BSD and GNU. Depending on the kind of files you are dealing with, you may not need it.

For some reason that is not clear to me, the grep version found more occurrences than the find one, which is why I recommend to use grep.

ADB Android Device Unauthorized

Steps that worked for me:
1. Disconnect phone from usb cable
2. Revoke USB Debugging on phone
3. Restart the device
4. Reconnect the device

The most important part was rebooting the device. Didn't work without it .

Formatting ISODate from Mongodb

// from MongoDate object to Javascript Date object

var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");
    dt.setSeconds(MongoDate.sec);

Remove specific characters from a string in Python

My method I'd use probably wouldn't work as efficiently, but it is massively simple. I can remove multiple characters at different positions all at once, using slicing and formatting. Here's an example:

words = "things"
removed = "%s%s" % (words[:3], words[-1:])

This will result in 'removed' holding the word 'this'.

Formatting can be very helpful for printing variables midway through a print string. It can insert any data type using a % followed by the variable's data type; all data types can use %s, and floats (aka decimals) and integers can use %d.

Slicing can be used for intricate control over strings. When I put words[:3], it allows me to select all the characters in the string from the beginning (the colon is before the number, this will mean 'from the beginning to') to the 4th character (it includes the 4th character). The reason 3 equals till the 4th position is because Python starts at 0. Then, when I put word[-1:], it means the 2nd last character to the end (the colon is behind the number). Putting -1 will make Python count from the last character, rather than the first. Again, Python will start at 0. So, word[-1:] basically means 'from the second last character to the end of the string.

So, by cutting off the characters before the character I want to remove and the characters after and sandwiching them together, I can remove the unwanted character. Think of it like a sausage. In the middle it's dirty, so I want to get rid of it. I simply cut off the two ends I want then put them together without the unwanted part in the middle.

If I want to remove multiple consecutive characters, I simply shift the numbers around in the [] (slicing part). Or if I want to remove multiple characters from different positions, I can simply sandwich together multiple slices at once.

Examples:

 words = "control"
 removed = "%s%s" % (words[:2], words[-2:])

removed equals 'cool'.

words = "impacts"
removed = "%s%s%s" % (words[1], words[3:5], words[-1])

removed equals 'macs'.

In this case, [3:5] means character at position 3 through character at position 5 (excluding the character at the final position).

Remember, Python starts counting at 0, so you will need to as well.

Combining a class selector and an attribute selector with jQuery

This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

Java 1.7 makes our lives much easier thanks to the try-with-resources statement.

try (Connection connection = dataSource.getConnection();
    Statement statement = connection.createStatement()) {
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do stuff with the result set.
    }
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do more stuff with the second result set.
    }
}

This syntax is quite brief and elegant. And connection will indeed be closed even when the statement couldn't be created.

Combining INSERT INTO and WITH/CTE

Yep:

WITH tab (
  bla bla
)

INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (  BatchID,                                                        AccountNo,
APartyNo,
SourceRowID)    

SELECT * FROM tab

Note that this is for SQL Server, which supports multiple CTEs:

WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y

Teradata allows only one CTE and the syntax is as your example.

Foreign keys in mongo?

Short answer: You should to use "weak references" between collections, using ObjectId properties:

References store the relationships between data by including links or references from one document to another. Applications can resolve these references to access the related data. Broadly, these are normalized data models.

https://docs.mongodb.com/manual/core/data-modeling-introduction/#references

This will of course not check any referential integrity. You need to handle "dead links" on your side (application level).

CSV with comma or semicolon?

In Windows it is dependent on the "Regional and Language Options" customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.

Of course this only has effect in Windows applications, for example Excel will not automatically split data into columns if the file is not using the above mentioned separator. All applications that use Windows regional settings will have this behavior.

If you are writing a program for Windows that will require importing the CSV in other applications and you know that the list separator set for your target machines is ,, then go for it, otherwise I prefer ; since it causes less problems with decimal points, digit grouping and does not appear in much text.

how to run a winform from console application?

Its totally depends upon your choice, that how you are implementing.
a. Attached process , ex: input on form and print on console
b. Independent process, ex: start a timer, don't close even if console exit.

for a,

Application.Run(new Form1());
//or -------------
Form1 f = new Form1();
f.ShowDialog();

for b, Use thread, or task anything, How to open win form independently?

How to select specified node within Xpath node sets by index with Selenium?

There is no i in xpath is not entirely true. You can still use the count() to find the index.

Consider the following page

_x000D_
_x000D_
<html>_x000D_
_x000D_
 <head>_x000D_
  <title>HTML Sample table</title>_x000D_
 </head>_x000D_
_x000D_
 <style>_x000D_
 table, td, th {_x000D_
  border: 1px solid black;_x000D_
  font-size: 15px;_x000D_
  font-family: Trebuchet MS, sans-serif;_x000D_
 }_x000D_
 table {_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
 }_x000D_
_x000D_
 th, td {_x000D_
  text-align: left;_x000D_
  padding: 8px;_x000D_
 }_x000D_
_x000D_
 tr:nth-child(even){background-color: #f2f2f2}_x000D_
_x000D_
 th {_x000D_
  background-color: #4CAF50;_x000D_
  color: white;_x000D_
 }_x000D_
 </style>_x000D_
_x000D_
 <body>_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 1</th>_x000D_
    <th>Heading 2</th>_x000D_
    <th>Heading 3</th>_x000D_
    <th>Heading 4</th>_x000D_
    <th>Heading 5</th>_x000D_
    <th>Heading 6</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </br>_x000D_
_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 7</th>_x000D_
    <th>Heading 8</th>_x000D_
    <th>Heading 9</th>_x000D_
    <th>Heading 10</th>_x000D_
    <th>Heading 11</th>_x000D_
    <th>Heading 12</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The page has 2 tables and has 6 columns each with unique column names and 6 rows with variable data. The last row has the Modify button in both the tables.

Assuming that the user has to select the 4th Modify button from the first table based on the heading

Use the xpath //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

The count() operator comes in handy in situations like these.

Logic:

  1. Find the header for the Modify button using //th[.='Heading 4']
  2. Find the index of the header column using count(//tr/th[.='Heading 4']/preceding-sibling::th)+1

Note: Index starts at 0

  1. Get the rows for the corresponding header using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]

  2. Get the Modify button from the extracted node list using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

Insert a new row into DataTable

In c# following code insert data into datatable on specified position

DataTable dt = new DataTable();
dt.Columns.Add("SL");
dt.Columns.Add("Amount");

dt.rows.add(1, 1000)
dt.rows.add(2, 2000)

dt.Rows.InsertAt(dt.NewRow(), 3);

var rowPosition = 3;
dt.Rows[rowPosition][dt.Columns.IndexOf("SL")] = 3;
dt.Rows[rowPosition][dt.Columns.IndexOf("Amount")] = 3000;

How to run a JAR file

To run jar, first u have to create

executable jar

then

java -jar xyz.jar

command will work

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

You could do a Select Into, which would create the table structure on the fly based on the fields you select, but I don't think it will create an identity field for you.

Where does MySQL store database files on Windows and what are the names of the files?

I have a default my-default.ini file in the root and there is one server configuration:

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES 

So that does not tell me the path.

The best way is to connect to the database and run this query:

SHOW VARIABLES WHERE Variable_Name LIKE "%dir" ;

Here's the result of that:

basedir                     C:\Program Files (x86)\MySQL\MySQL Server 5.6\
character_sets_dir          C:\Program Files (x86)\MySQL\MySQL Server 5.6\share\charsets\

datadir                     C:\ProgramData\MySQL\MySQL Server 5.6\Data\
innodb_data_home_dir    
innodb_log_group_home_dir   .\
lc_messages_dir             C:\Program Files (x86)\MySQL\MySQL Server 5.6\share\

plugin_dir                  C:\Program Files (x86)\MySQL\MySQL Server 5.6\lib\plugin\

slave_load_tmpdir           C:\Windows\SERVIC~2\NETWOR~1\AppData\Local\Temp
tmpdir                      C:\Windows\SERVIC~2\NETWOR~1\AppData\Local\Temp

If you want to see all the parameters configured for the database execute this:

SHOW VARIABLES;

The storage_engine variable will tell you if you're using InnoDb or MyISAM.

How to simulate a click by using x,y coordinates in JavaScript?

This is just torazaburo's answer, updated to use a MouseEvent object.

function click(x, y)
{
    var ev = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true,
        'screenX': x,
        'screenY': y
    });

    var el = document.elementFromPoint(x, y);

    el.dispatchEvent(ev);
}

How to disable an input type=text?

You can also by jquery:

$('#foo')[0].disabled = true;

Working example:

_x000D_
_x000D_
$('#foo')[0].disabled = true;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input id="foo" placeholder="placeholder" value="value" />
_x000D_
_x000D_
_x000D_

Adding Only Untracked Files

git ls-files lists the files in the current directory. If you want to list untracked files from anywhere in the tree, this might work better:

git ls-files -o --exclude-standard $(git rev-parse --show-toplevel)

To add all untracked files in the tree:

git ls-files -o --exclude-standard $(git rev-parse --show-toplevel) | xargs git add

JQuery - Get select value

var nationality = $("#dancerCountry").val(); should work. Are you sure that the element selector is working properly? Perhaps you should try:

var nationality = $('select[name="dancerCountry"]').val();

How to access my localhost from another PC in LAN?

IP can be any LAN or WAN IP address. But you'll want to set your firewall connection allow it.

Device connection with webserver pc can be by LAN or WAN (i.e by wifi, connectify, adhoc, cable, mypublic wifi etc)

You should follow these steps:

  1. Go to the control panel
  2. Inbound rules > new rules
  3. Click port > next > specific local port > enter 8080 > next > allow the connection>
  4. Next > tick all (domain, private, public) > specify any name
  5. Now you can access your localhost by any device (laptop, mobile, desktop, etc).
  6. Enter ip address in browser url as 123.23.xx.xx:8080 to access localhost by any device.

This IP will be of that device which has the web server.

Better way to sort array in descending order

Yes, you can pass predicate to sort. That would be your reverse implementation.

What's a good, free serial port monitor for reverse-engineering?

I've been down this road and eventually opted for a hardware data scope that does non-instrusive in-line monitoring. The software solutions that I tried didn't work for me. If you had a spare PC you could probably build one, albeit rather bulky. This software data scope may work, as might this, but I haven't tried either.

Where does Jenkins store configuration files for the jobs it runs?

For the sake of completeness: macOS High Sierra, Jenkins 2.x, installation via Homebrew
~/.jenkins/jobs/{project_name}/config.xml

Complete overview about jenkins home: https://wiki.jenkins.io/display/JENKINS/Administering+Jenkins

C++ static virtual members?

Like others have said, there are 2 important pieces of information:

  1. there is no this pointer when making a static function call and
  2. the this pointer points to the structure where the virtual table, or thunk, are used to look up which runtime method to call.

A static function is determined at compile time.

I showed this code example in C++ static members in class; it shows that you can call a static method given a null pointer:

struct Foo
{
    static int boo() { return 2; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo* pFoo = NULL;
    int b = pFoo->boo(); // b will now have the value 2
    return 0;
}

Memory address of an object in C#

Here's a simple way I came up with that doesn't involve unsafe code or pinning the object. Also works in reverse (object from address):

public static class AddressHelper
{
    private static object mutualObject;
    private static ObjectReinterpreter reinterpreter;

    static AddressHelper()
    {
        AddressHelper.mutualObject = new object();
        AddressHelper.reinterpreter = new ObjectReinterpreter();
        AddressHelper.reinterpreter.AsObject = new ObjectWrapper();
    }

    public static IntPtr GetAddress(object obj)
    {
        lock (AddressHelper.mutualObject)
        {
            AddressHelper.reinterpreter.AsObject.Object = obj;
            IntPtr address = AddressHelper.reinterpreter.AsIntPtr.Value;
            AddressHelper.reinterpreter.AsObject.Object = null;
            return address;
        }
    }

    public static T GetInstance<T>(IntPtr address)
    {
        lock (AddressHelper.mutualObject)
        {
            AddressHelper.reinterpreter.AsIntPtr.Value = address;
            return (T)AddressHelper.reinterpreter.AsObject.Object;
        }
    }

    // I bet you thought C# was type-safe.
    [StructLayout(LayoutKind.Explicit)]
    private struct ObjectReinterpreter
    {
        [FieldOffset(0)] public ObjectWrapper AsObject;
        [FieldOffset(0)] public IntPtrWrapper AsIntPtr;
    }

    private class ObjectWrapper
    {
        public object Object;
    }

    private class IntPtrWrapper
    {
        public IntPtr Value;
    }
}

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

For ASPNET MVC, we did the following:

  1. By default, set SessionStateBehavior.ReadOnly on all controller's action by overriding DefaultControllerFactory
  2. On controller actions that need writing to session state, mark with attribute to set it to SessionStateBehavior.Required

Create custom ControllerFactory and override GetControllerSessionBehavior.

    protected override SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, Type controllerType)
    {
        var DefaultSessionStateBehaviour = SessionStateBehaviour.ReadOnly;

        if (controllerType == null)
            return DefaultSessionStateBehaviour;

        var isRequireSessionWrite =
            controllerType.GetCustomAttributes<AcquireSessionLock>(inherit: true).FirstOrDefault() != null;

        if (isRequireSessionWrite)
            return SessionStateBehavior.Required;

        var actionName = requestContext.RouteData.Values["action"].ToString();
        MethodInfo actionMethodInfo;

        try
        {
            actionMethodInfo = controllerType.GetMethod(actionName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
        }
        catch (AmbiguousMatchException)
        {
            var httpRequestTypeAttr = GetHttpRequestTypeAttr(requestContext.HttpContext.Request.HttpMethod);

            actionMethodInfo =
                controllerType.GetMethods().FirstOrDefault(
                    mi => mi.Name.Equals(actionName, StringComparison.CurrentCultureIgnoreCase) && mi.GetCustomAttributes(httpRequestTypeAttr, false).Length > 0);
        }

        if (actionMethodInfo == null)
            return DefaultSessionStateBehaviour;

        isRequireSessionWrite = actionMethodInfo.GetCustomAttributes<AcquireSessionLock>(inherit: false).FirstOrDefault() != null;

         return isRequireSessionWrite ? SessionStateBehavior.Required : DefaultSessionStateBehaviour;
    }

    private static Type GetHttpRequestTypeAttr(string httpMethod) 
    {
        switch (httpMethod)
        {
            case "GET":
                return typeof(HttpGetAttribute);
            case "POST":
                return typeof(HttpPostAttribute);
            case "PUT":
                return typeof(HttpPutAttribute);
            case "DELETE":
                return typeof(HttpDeleteAttribute);
            case "HEAD":
                return typeof(HttpHeadAttribute);
            case "PATCH":
                return typeof(HttpPatchAttribute);
            case "OPTIONS":
                return typeof(HttpOptionsAttribute);
        }

        throw new NotSupportedException("unable to determine http method");
    }

AcquireSessionLockAttribute

[AttributeUsage(AttributeTargets.Method)]
public sealed class AcquireSessionLock : Attribute
{ }

Hook up the created controller factory in global.asax.cs

ControllerBuilder.Current.SetControllerFactory(typeof(DefaultReadOnlySessionStateControllerFactory));

Now, we can have both read-only and read-write session state in a single Controller.

public class TestController : Controller 
{
    [AcquireSessionLock]
    public ActionResult WriteSession()
    {
        var timeNow = DateTimeOffset.UtcNow.ToString();
        Session["key"] = timeNow;
        return Json(timeNow, JsonRequestBehavior.AllowGet);
    }

    public ActionResult ReadSession()
    {
        var timeNow = Session["key"];
        return Json(timeNow ?? "empty", JsonRequestBehavior.AllowGet);
    }
}

Note: ASPNET session state can still be written to even in readonly mode and will not throw any form of exception (It just doesn't lock to guarantee consistency) so we have to be careful to mark AcquireSessionLock in controller's actions that require writing session state.

What is the role of "Flatten" in Keras?

It is rule of thumb that the first layer in your network should be the same shape as your data. For example our data is 28x28 images, and 28 layers of 28 neurons would be infeasible, so it makes more sense to 'flatten' that 28,28 into a 784x1. Instead of wriitng all the code to handle that ourselves, we add the Flatten() layer at the begining, and when the arrays are loaded into the model later, they'll automatically be flattened for us.

BigDecimal to string

The BigDecimal can not be a double. you can use Int number. if you want to display exactly own number, you can use the String constructor of BigDecimal .

like this:

BigDecimal bd1 = new BigDecimal("10.0001");

now, you can display bd1 as 10.0001

So simple. GOOD LUCK.

How to select multiple files with <input type="file">?

Thats easy ...

<input type='file' multiple>
$('#file').on('change',function(){
     _readFileDataUrl(this,function(err,files){
           if(err){return}
           console.log(files)//contains base64 encoded string array holding the 
           image data 
     });
});
var _readFileDataUrl=function(input,callback){
    var len=input.files.length,_files=[],res=[];
    var readFile=function(filePos){
        if(!filePos){
            callback(false,res);
        }else{
            var reader=new FileReader();
            reader.onload=function(e){              
                res.push(e.target.result);
                readFile(_files.shift());
            };
            reader.readAsDataURL(filePos);
        }
    };
    for(var x=0;x<len;x++){
        _files.push(input.files[x]);
    }
    readFile(_files.shift());
};

Importing a CSV file into a sqlite3 database table using Python

Creating an sqlite connection to a file on disk is left as an exercise for the reader ... but there is now a two-liner made possible by the pandas library

df = pandas.read_csv(csvfile)
df.to_sql(table_name, conn, if_exists='append', index=False)

Gson: How to exclude specific fields from Serialization without annotations

After reading all available answers I found out, that most flexible, in my case, was to use custom @Exclude annotation. So, I implemented simple strategy for this (I didn't want to mark all fields using @Expose nor I wanted to use transient which conflicted with in app Serializable serialization) :

Annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Exclude {
}

Strategy:

public class AnnotationExclusionStrategy implements ExclusionStrategy {

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return f.getAnnotation(Exclude.class) != null;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}

Usage:

new GsonBuilder().setExclusionStrategies(new AnnotationExclusionStrategy()).create();

How to check if a registry value exists using C#?

string keyName=@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\services\pcmcia";
string valueName="Start";
if (Registry.GetValue(keyName, valueName, null) == null)
{
     //code if key Not Exist
}
else
{
     //code if key Exist
}

How do I remove the top margin in a web page?

I have been having a similar issue. I wanted a percentage height and top-margin for my container div, but the body would take on the margin of the container div. I think I figured out a solution.

Here is my original (problem) code:

html {
    height:100%;
}

body {
    height:100%;                    
    margin-top:0%;
    padding:0%; 
}

#pageContainer {
    position:relative;
    width:96%;                  /* 100% - (margin * 2) */
    height:96%;                 /* 100% - (margin * 2) */           
    margin:2% auto 0% auto;
    padding:0%;
}

My solution was to set the height of the body the same as the height of the container.
html { height:100%; }

body {
    height:96%;     /* 100% * (pageContainer*2) */
    margin-top:0%;
    padding:0%; 
}

#pageContainer {
    position:relative;
    width:96%;                  /* 100% - (margin * 2) */
    height:96%;                 /* 100% - (margin * 2) */           
    margin:2% auto 0% auto;
    padding:0%;
}

I haven't tested it in every browser, but this seems to work.

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

A workaround for CONTAINS: If you don't want to create a full text Index on the column, and performance is not one of your priorities you could use the LIKE statement which doesn't need any prior configuration:

Example: find all Products that contains the letter Q:

SELECT ID, ProductName
FROM [ProductsDB].[dbo].[Products]
WHERE [ProductsDB].[dbo].[Products].ProductName LIKE '%Q%'

Delete files older than 3 months old in a directory using .NET

i have try this code and it works very well, hope this answered

namespace EraseJunkFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\yourdirectory\");
            foreach (FileInfo file in yourRootDir.GetFiles())
                if (file.LastWriteTime < DateTime.Now.AddDays(-90))
                    file.Delete();
        }
    }
}

OSError [Errno 22] invalid argument when use open() in Python

I had the same problem It happens because files can't contain special characters like ":", "?", ">" and etc. You should replace these files by using replace() function:

filename = filename.replace("special character to replace", "-")

linux execute command remotely

I think this article explains well:

Running Commands on a Remote Linux / UNIX Host

Google is your best friend ;-)

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

I could not understand those 3 rules in the specs too well -- hope to have something that is more plain English -- but here is what I gathered from JavaScript: The Definitive Guide, 6th Edition, David Flanagan, O'Reilly, 2011:

Quote:

JavaScript does not treat every line break as a semicolon: it usually treats line breaks as semicolons only if it can’t parse the code without the semicolons.

Another quote: for the code

var a
a
=
3 console.log(a)

JavaScript does not treat the second line break as a semicolon because it can continue parsing the longer statement a = 3;

and:

two exceptions to the general rule that JavaScript interprets line breaks as semicolons when it cannot parse the second line as a continuation of the statement on the first line. The first exception involves the return, break, and continue statements

... If a line break appears after any of these words ... JavaScript will always interpret that line break as a semicolon.

... The second exception involves the ++ and -- operators ... If you want to use either of these operators as postfix operators, they must appear on the same line as the expression they apply to. Otherwise, the line break will be treated as a semicolon, and the ++ or -- will be parsed as a prefix operator applied to the code that follows. Consider this code, for example:

x 
++ 
y

It is parsed as x; ++y;, not as x++; y

So I think to simplify it, that means:

In general, JavaScript will treat it as continuation of code as long as it makes sense -- except 2 cases: (1) after some keywords like return, break, continue, and (2) if it sees ++ or -- on a new line, then it will add the ; at the end of the previous line.

The part about "treat it as continuation of code as long as it makes sense" makes it feel like regular expression's greedy matching.

With the above said, that means for return with a line break, the JavaScript interpreter will insert a ;

(quoted again: If a line break appears after any of these words [such as return] ... JavaScript will always interpret that line break as a semicolon)

and due to this reason, the classic example of

return
{ 
  foo: 1
}

will not work as expected, because the JavaScript interpreter will treat it as:

return;   // returning nothing
{
  foo: 1
}

There has to be no line-break immediately after the return:

return { 
  foo: 1
}

for it to work properly. And you may insert a ; yourself if you were to follow the rule of using a ; after any statement:

return { 
  foo: 1
};

Stop a youtube video with jquery?

I got this to work on all modern browsers, including IE9|IE8|IE7. The following code will open your YouTube video in a jQuery UI dialog modal, autoplay the video from 0:00 on dialog open, and stop video on dialog close.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>    

<script type="text/javascript">

    google.load("swfobject", "2.1");

    function _run() {
        /* YouTube player embed for modal dialog */
        // The video to load.
        var videoID = "INSERT YOUR YOUTUBE VIDEO ID HERE"
        // Lets Flash from another domain call JavaScript
        var params = { allowScriptAccess: "always" };
        // The element id of the Flash embed
        var atts = { id: "ytPlayer" };
        // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
        swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "?version=3&enablejsapi=1&playerapiid=player1&autoplay=1",
                       "videoDiv", "879", "520", "9", null, null, params, atts);
    }
    google.setOnLoadCallback(_run);

    $(function () {
        $("#big-video").dialog({
            autoOpen: false,
            close: function (event, ui) {
                ytPlayer.stopVideo() // stops video/audio on dialog close
            },
            modal: true,
            open: function (event, ui) {
                ytPlayer.seekTo(0) // resets playback to beginning of video and then plays video
            }
        });

        $("#big-video-opener").click(function () {
            $("#big-video").dialog("open");
            return false;
        });

    });
</script>

<div id="big-video" title="Video">
    <div id="videoDiv">Loading...</div>
</div>

<a id="big-video-opener" class="button" href="#">Watch the short video</a>

Unsupported method: BaseConfig.getApplicationIdSuffix()

For Android Studio 3 I need to update two files to fix the error:--

1. app/build.gradle

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

2. app/gradle/wrapper/gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

Bootstrap 3 Multi-column within a single ul not floating properly

You should try using the Grid Template.

Here's what I've used for a two Column Layout of a <ul>

<ul class="list-group row">
     <li class="list-group-item col-xs-6">Row1</li>
     <li class="list-group-item col-xs-6">Row2</li>
     <li class="list-group-item col-xs-6">Row3</li>
     <li class="list-group-item col-xs-6">Row4</li>
     <li class="list-group-item col-xs-6">Row5</li>
</ul>

This worked for me.

Properties file in python (similar to Java Properties)

This is not exactly properties but Python does have a nice library for parsing configuration files. Also see this recipe: A python replacement for java.util.Properties.

How to add a custom button to the toolbar that calls a JavaScript function?

In case anybody is interested, I wrote a solution for this using Prototype. In order to get the button to appear correctly, I had to specify extraPlugins: 'ajaxsave' from inside the CKEDITOR.replace() method call.

Here is the plugin.js:

CKEDITOR.plugins.add('ajaxsave',
{
    init: function(editor)
    {
    var pluginName = 'ajaxsave';

    editor.addCommand( pluginName,
    {
        exec : function( editor )
        {
            new Ajax.Request('ajaxsave.php',
            {
                method:     "POST",
                parameters: { filename: 'index.html', editor: editor.getData() },
                onFailure:  function() { ThrowError("Error: The server has returned an unknown error"); },
                on0:        function() { ThrowError('Error: The server is not responding. Please try again.'); },
                onSuccess:  function(transport) {

                    var resp = transport.responseText;

                    //Successful processing by ckprocess.php should return simply 'OK'. 
                    if(resp == "OK") {
                        //This is a custom function I wrote to display messages. Nicer than alert() 
                        ShowPageMessage('Changes have been saved successfully!');
                    } else {
                        ShowPageMessage(resp,'10');
                    }
                }
            });
        },

        canUndo : true
    });

    editor.ui.addButton('ajaxsave',
    {
        label: 'Save',
        command: pluginName,
        className : 'cke_button_save'
    });
    }
});

React setState not updating state

I had the same situation with some convoluted code, and nothing from the existing suggestions worked for me.

My problem was that setState was happening from callback func, issued by one of the components. And my suspicious is that the call was occurring synchronously, which prevented setState from setting state at all.

Simply put I have something like this:

render() {
    <Control
        ref={_ => this.control = _}
        onChange={this.handleChange}
        onUpdated={this.handleUpdate} />
}

handleChange() {
    this.control.doUpdate();
}

handleUpdate() {
    this.setState({...});
}

The way I had to "fix" it was to put doUpdate() into setTimeout like this:

handleChange() {
    setTimeout(() => { this.control.doUpdate(); }, 10);
}

Not ideal, but otherwise it would be a significant refactoring.

Detect enter press in JTextField

Just use this code:

SwingUtilities.getRootPane(myButton).setDefaultButton(myButton);

UICollectionView Set number of columns

This answer is for swift 3.0 -->

first conform to the protocol :

 UICollectionViewDelegateFlowLayout

then add these methods :

    //this method is for the size of items      
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.width/3
        let height : CGFloat = 160.0
        return CGSize(width: width, height: height)
    }
    //these methods are to configure the spacing between items

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0,0,0,0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

Loop through the rows of a particular DataTable

For Each row As DataRow In dtDataTable.Rows
    strDetail = row.Item("Detail")
Next row

There's also a shorthand:

For Each row As DataRow In dtDataTable.Rows
    strDetail = row("Detail")
Next row

Note that Microsoft's style guidelines for .Net now specifically recommend against using hungarian type prefixes for variables. Instead of "strDetail", for example, you should just use "Detail".

Best XML Parser for PHP

Have a look at PHP's available XML extensions.

The main difference between XML Parser and SimpleXML is that the latter is not a pull parser. SimpleXML is built on top of the DOM extensions and will load the entire XML file into memory. XML Parser like XMLReader will only load the current node into memory. You define handlers for specific nodes which will get triggered when the Parser encounters it. That is faster and saves on memory. You pay for that with not being able to use XPath.

Personally, I find SimpleXml quite limiting (hence simple) in what it offers over DOM. You can switch between DOM and SimpleXml easily though, but I usually dont bother and go the DOM route directly. DOM is an implementation of the W3C DOM API, so you might be familiar with it from other languages, for instance JavaScript.

jQuery click not working for dynamically created items

$("#container").delegate("span", "click", function (){
    alert(11);
});

Setting table row height

try setting the attribute for td so:

.topic td{ height: 14px };