Programs & Examples On #Ikimageview

How to send an HTTP request with a header parameter?

With your own Code and a Slight Change withou jQuery,

function testingAPI(){ 
    var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
    var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
    console.log(httpGet(url,key)); 
}


function httpGet(url,key){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank You

How could I put a border on my grid control in WPF?

This is a later answer that works for me, if it may be of use to anyone in the future. I wanted a simple border around all four sides of the grid and I achieved it like so...

<DataGrid x:Name="dgDisplay" Margin="5" BorderBrush="#1266a7" BorderThickness="1"...

In Swift how to call method with parameters on GCD main thread?

Don't forget to weakify self if you are using self inside of the closure.

dispatch_async(dispatch_get_main_queue(),{ [weak self] () -> () in
    if let strongSelf = self {
        self?.doSomething()
    }
})

Start service in Android

Java code for start service:

Start service from Activity:

startService(new Intent(MyActivity.this, MyService.class));

Start service from Fragment:

getActivity().startService(new Intent(getActivity(), MyService.class));

MyService.java:

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

    private static String TAG = "MyService";
    private Handler handler;
    private Runnable runnable;
    private final int runTime = 5000;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");

        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {

                handler.postDelayed(runnable, runTime);
            }
        };
        handler.post(runnable);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, "onStart");
    }

}

Define this Service into Project's Manifest File:

Add below tag in Manifest file:

<service android:enabled="true" android:name="com.my.packagename.MyService" />

Done

Why am I getting the error "connection refused" in Python? (Sockets)

host = socket.gethostname()  # Get the local machine name
port = 12397                 # Reserve a port for your service
s.bind((host,port))          # Bind to the port

I think this error may related to the DNS resolution. This sentence host = socket.gethostname() get the host name, but if the operating system can not resolve the host name to local address, you would get the error. Linux operating system can modify the /etc/hosts file, add one line in it. It looks like below( 'hostname' is which socket.gethostname() got).

127.0.0.1   hostname

How to manually install an artifact in Maven 2?

According to maven's Guide to installing 3rd party JARs, the command is:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

You need indeed the packaging option. This answers the original question.

Now, in your context, you are fighting with a jar provided by Sun. You should read the Coping with Sun JARs page too. There, you'll learn how to help maven to provide you better information about Sun jars location and how to add Java.net Maven 2 repository which contains jta-1.0.1B.jar. Add this in your settings.xml (not portable) or pom.xml (portable):

  <repositories>
    <repository>
      <id>maven2-repository.dev.java.net</id>
      <name>Java.net Repository for Maven</name>
      <url>http://download.java.net/maven/2/</url>
      <layout>default</layout>
    </repository>
  </repositories>

React router nav bar example

Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:

<Router>
  <Route path="/" component={App}>
    <Route path="page1" component={Page1} />
    <Route path="page2" component={Page2} />
  </Route>
  <Route path="/login" component={Login} />
</Router>

And the other components would look something like this:

var NavBar = React.createClass({
  render() {
    return (
      <div>
        <ul>
          <a onClick={() => history.push('page1') }>Page 1</a>
          <a onClick={() => history.push('page2') }>Page 2</a>
        </ul>
      </div>
    )
  }
});

var App = React.createClass({
  render() {
    return (
      <div>
        <NavBar />
        <div>Other Content</div>
        {this.props.children}
      </div>
    )
  }
});

Linux / Bash, using ps -o to get process by specific name?

Sorry, much late to the party, but I'll add here that if you wanted to capture processes with names identical to your search string, you could do

pgrep -x PROCESS_NAME

-x          Require an exact match of the process name, or argument list if -f is given.
             The default is to match any substring.

This is extremely useful if your original process created child processes (possibly zombie when you query) which prefix the original process' name in their own name and you are trying to exclude them from your results. There are many UNIX daemons which do this. My go-to example is ninja-dev-sync.

How to use sed to remove the last n lines of a file

I prefer this solution;

head -$(gcalctool -s $(cat file | wc -l)-N) file

where N is the number of lines to remove.

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

Make sure you've set your target API (different from the target SDK) in the Project Properties (not the manifest) to be at least 4.0/API 14.

jQuery UI Sortable, then write order into a database

You're in luck, I use the exact thing in my CMS

When you want to store the order, just call the JavaScript method saveOrder(). It will make an AJAX POST request to saveorder.php, but of course you could always post it as a regular form.

<script type="text/javascript">
function saveOrder() {
    var articleorder="";
    $("#sortable li").each(function(i) {
        if (articleorder=='')
            articleorder = $(this).attr('data-article-id');
        else
            articleorder += "," + $(this).attr('data-article-id');
    });
            //articleorder now contains a comma separated list of the ID's of the articles in the correct order.
    $.post('/saveorder.php', { order: articleorder })
        .success(function(data) {
            alert('saved');
        })
        .error(function(data) { 
            alert('Error: ' + data); 
        }); 
}
</script>
<ul id="sortable">
<?php
//my way to get all the articles, but you should of course use your own method.
$articles = Page::Articles();
foreach($articles as $article) {
    ?>
    <li data-article-id='<?=$article->Id()?>'><?=$article->Title()?></li>
    <?
}               
?>   
</ul>
   <input type='button' value='Save order' onclick='saveOrder();'/>

In saveorder.php; Keep in mind I removed all verification and checking.

<?php
$orderlist = explode(',', $_POST['order']);
foreach ($orderlist as $k=>$order) {
  echo 'Id for position ' . $k . ' = ' . $order . '<br>';
}     
?>

How to make/get a multi size .ico file?

This can be done for free using GIMP.

It uses the ability of GIMP to have each layer a different size.

I created the following layers sized correctly.

  • 256x256 will be saved as 32bpp 8bit alpha
  • 48x48 will be saved as 32bpp 8bit alpha
  • 48x48 will be saved as 8bpp 1bit alpha
  • 32x32 will be saved as 32bpp 8bit alpha
  • 32x32 will be saved as 8bpp 1bit alpha
  • 32x32 will be saved as 4bpp 1bit alpha
  • 16x16 will be saved as 32bpp 8bit alpha
  • 16x16 will be saved as 8bpp 1bit alpha
  • 16x16 will be saved as 4bpp 1bit alpha

Notes

  • You may need to check other resources to confirm to yourself that this is a sensible list of resolutions and colour depths.
  • Make sure you use transparency round the outside of your image, and anti-aliased edges. You should see the grey checkerboard effect round the outside of your layers to indicate they are transparent
  • The 16x16 icons will need to be heavily edited by hand using a 1 pixel wide pencil and the eyedropper tool to make them look any good.
  • Do not change colour depth / Mode in GIMP. Leave it as RGB
  • You change the colour depths when you save as an .ico - GIMP pops up a special dialog box for changing the colour settings for each layer

Aren't Python strings immutable? Then why does a + " " + b work?

First a pointed to the string "Dog". Then you changed the variable a to point at a new string "Dog eats treats". You didn't actually mutate the string "Dog". Strings are immutable, variables can point at whatever they want.

How can I create directory tree in C++/Linux?

If you don't have C++17 yet and look for a platform agnostic solution, use ghc::filesystem. The header-ony code is compatible to C++17 (in fact a backport) and easy to migrate later on.

When is a CDATA section necessary within a script tag?

When browsers treat the markup as XML:

<script>
<![CDATA[
    ...code...
]]>
</script>

When browsers treat the markup as HTML:

<script>
    ...code...
</script>

When browsers treat the markup as HTML and you want your XHTML 1.0 markup (for example) to validate.

<script>
//<![CDATA[
    ...code...
//]]>
</script>

How do I make a dotted/dashed line in Android?

Without java code:

drawable/dotted.xml:

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

    <stroke
       android:color="#FF00FF"
       android:dashWidth="10px"
       android:dashGap="10px"
       android:width="1dp"/>
</shape>

view.xml:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:src="@drawable/dotted"
    android:layerType="software" />

Effect: enter image description here

Exporting the values in List to excel

the one easy way to do it is to open Excel create sheet containing test data you want to export then say to excel save as xml open the xml see the xml format excel is expecting and generate it by head replacing the test data with export data

SpreadsheetML Markup Spec

@lan this is xml fo a simle execel file with one column value i genereted with office 2003 this format is for office 2003 and above

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Author>Dancho</Author>
  <LastAuthor>Dancho</LastAuthor>
  <Created>2010-02-05T10:15:54Z</Created>
  <Company>cc</Company>
  <Version>11.9999</Version>
 </DocumentProperties>
 <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
  <WindowHeight>13800</WindowHeight>
  <WindowWidth>24795</WindowWidth>
  <WindowTopX>480</WindowTopX>
  <WindowTopY>105</WindowTopY>
  <ProtectStructure>False</ProtectStructure>
  <ProtectWindows>False</ProtectWindows>
 </ExcelWorkbook>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
 </Styles>
 <Worksheet ss:Name="Sheet1">
  <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="6" x:FullColumns="1"
   x:FullRows="1">
   <Row>
    <Cell><Data ss:Type="String">Value1</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value2</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value3</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value4</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value5</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value6</Data></Cell>
   </Row>
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <Selected/>
   <Panes>
    <Pane>
     <Number>3</Number>
     <ActiveRow>5</ActiveRow>
    </Pane>
   </Panes>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet2">
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet3">
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
</Workbook>

How to negate specific word in regex?

Just thought of something else that could be done. It's very different from my first answer, as it doesn't use regular expressions, so I decided to make a second answer post.

Use your language of choice's split() method equivalent on the string with the word to negate as the argument for what to split on. An example using Python:

>>> text = 'barbarasdbarbar 1234egb ar bar32 sdfbaraadf'
>>> text.split('bar')
['', '', 'asd', '', ' 1234egb ar ', '32 sdf', 'aadf']

The nice thing about doing it this way, in Python at least (I don't remember if the functionality would be the same in, say, Visual Basic or Java), is that it lets you know indirectly when "bar" was repeated in the string due to the fact that the empty strings between "bar"s are included in the list of results (though the empty string at the beginning is due to there being a "bar" at the beginning of the string). If you don't want that, you can simply remove the empty strings from the list.

Quadratic and cubic regression in Excel

The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.

CSS Inset Borders

You can do this:

.thing {
  border: 2px solid transparent;
}
.thing:hover {
  border: 2px solid green;
}

How to write to the Output window in Visual Studio?

OutputDebugString function will do it.

example code

    void CClass::Output(const char* szFormat, ...)
{
    char szBuff[1024];
    va_list arg;
    va_start(arg, szFormat);
    _vsnprintf(szBuff, sizeof(szBuff), szFormat, arg);
    va_end(arg);

    OutputDebugString(szBuff);
}

Run Function After Delay

$(document).ready(function() {

  // place this within dom ready function
  function showpanel() {     
    $(".navigation").hide();
    $(".page").children(".panel").fadeIn(1000);
 }

 // use setTimeout() to execute
 setTimeout(showpanel, 1000)

});

For more see here

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

(For those who read all answers). My case was simply the fact that I created a SQL expression using the format Forms!Table!Control. That format is Ok within a query, but DAO doesn't recognize it. I'm surprised that nobody commented this.

This doesn't work:

Dim rs As DAO.Recordset, strSQL As String
strSQL = "SELECT * FROM Table1 WHERE Name = Forms!Table!Control;"
Set rs = CurrentDb.OpenRecordset(strSQL)

This is Ok:

Dim rs As DAO.Recordset, strSQL, val As String
val = Forms!Table!Control
strSQL = "SELECT * FROM Table1 WHERE Name = '" & val & "';"
Set rs = CurrentDb.OpenRecordset(strSQL)

Count frequency of words in a list and sort by frequency

You can use

from collections import Counter

It supports Python 2.7,read more information here

1.

>>>c = Counter('abracadabra')
>>>c.most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

use dict

>>>d={1:'one', 2:'one', 3:'two'}
>>>c = Counter(d.values())
[('one', 2), ('two', 1)]

But, You have to read the file first, and converted to dict.

2. it's the python docs example,use re and Counter

# Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

.rar, .zip files MIME Type

I see many answer reporting for zip and rar the Media Types application/zip and application/x-rar-compressed, respectively.

While the former matching is correct, for the latter IANA reports here https://www.iana.org/assignments/media-types/application/vnd.rar that for rar application/x-rar-compressed is a deprecated alias name and instead application/vnd.rar is the official one. So, right Media Types from IANA in 2020 are:

  1. zip: application/zip
  2. rar: application/vnd.rar

Get all dates between two dates in SQL Server

Just saying...here is a more simple approach to this:

declare @sdate date = '2017-06-25'
    , @edate date = '2017-07-24';

with dates_CTE (date) as (
    select @sdate 
    Union ALL
    select DATEADD(day, 1, date)
    from dates_CTE
    where date < @edate
)
select *
from dates_CTE;

Can I limit the length of an array in JavaScript?

arr.length = Math.min(arr.length, 5)

Skipping Incompatible Libraries at compile

Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.

So, you need to look to see whether /dvlpmnt/libPI-Http.a is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32 option. Then you need to establish whether there is an alternative libPI-Http.a or libPI-Http.so file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.

To establish what is in that library, you may need to do:

mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk

The 'file' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.

How to take character input in java

you can use a Scanner to read from input :

Scanner scanner = new Scanner(System.in); 
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

"This project is incompatible with the current version of Visual Studio"

This issue might be caused when using VS 2015 with Update 3 installed on one PC and without update 3 installed on another. This was the problem in my case.

How do I change the UUID of a virtual disk?

The following worked for me:

  1. run VBoxManage internalcommands sethduuid "VDI/VMDK file" twice (the first time is just to conveniently generate an UUID, you could use any other UUID generation method instead)

  2. open the .vbox file in a text editor

  3. replace the UUID found in Machine uuid="{...}" with the UUID you got when you ran sethduuid the first time

  4. replace the UUID found in HardDisk uuid="{...}" and in Image uuid="{}" (towards the end) with the UUID you got when you ran sethduuid the second time

Change header text of columns in a GridView

Better to find cells from gridview instead of static/fix index so it will not generate any problem whenever you will add/remove any columns on gridview.

ASPX:

<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" >
    <Columns>
        <asp:BoundField HeaderText="Date" DataField="CreatedDate" />
    </Columns>
</asp:GridView>

CS:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            if (string.Compare(e.Row.Cells[i].Text, "Date", true) == 0)
            {
                e.Row.Cells[i].Text = "Created Date";
            }
        }
    }
}

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

How to parse XML to R data frame

Use xpath more directly for both performance and clarity.

time_path <- "//start-valid-time"
temp_path <- "//temperature[@type='hourly']/value"

df <- data.frame(
    latitude=data[["number(//point/@latitude)"]],
    longitude=data[["number(//point/@longitude)"]],
    start_valid_time=sapply(data[time_path], xmlValue),
    hourly_temperature=as.integer(sapply(data[temp_path], as, "integer"))

leading to

> head(df, 2)
  latitude longitude          start_valid_time hourly_temperature
1    29.81    -82.42 2014-02-14T18:00:00-05:00                 60
2    29.81    -82.42 2014-02-14T19:00:00-05:00                 55

Mailto links do nothing in Chrome but work in Firefox?

You can use like this also,

<a href="javascript:void(0);" onclick="javascript:window.location.href='mailto:[email protected]'; return false;">[email protected]</a>

I think this is best way to resolved for chrome issues.

Thanks..

MySQL - Get row number on select

Take a look at this.

Change your query to:

SET @rank=0;
SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
  FROM orders
  GROUP BY itemID
  ORDER BY ordercount DESC;
SELECT @rank;

The last select is your count.

How to convert an Instant to a date format?

Instant i = Instant.ofEpochSecond(cal.getTime);

Read more here and here

Eclipse jump to closing brace

I found that if the chosen perspective doesn't match the type of the current file, then "go to matching brace" doesn't work. However, changing perspectives makes it work again. So, for example, when I have a PHP file open, but, say, the Java perspective active, pressing Ctrl + Shift + P does nothing. For the same file with the PHP perspective active, pressing Ctrl + Shift + P does exactly what you'd expect and puts my cursor beside the closing brace relative to the one it started at.

iOS / Android cross platform development

If you've ever used LUA, you might try Corona SDK can create apps that run on IOS and Android

https://coronalabs.com/

I've downloaded it and messed around some, I find LUA a very easy to learn scripting language without the usual scripting language hassles/limitations....

How do I set the figure title and axes labels font size in Matplotlib?

Place right_ax before set_ylabel()

ax.right_ax.set_ylabel('AB scale')

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I got this problem because I uninstalled VS 2012, I don't want to reinstall it back, so I downloaded the AspNetMVC4Setup.exe from Microsoft.com and fixed my problem.

https://www.microsoft.com/en-us/download/details.aspx?id=30683

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

Anyone who has this error, especially on Azure, try adding "tcp:" to the db-server-name in your connection string in your application. This forces the sql client to communicate with the db using tcp. I'm assuming the connection is UDP by default and there can be intermittent connection issues

jQuery append and remove dynamic table row

live view Link Jsfiddle

vary simple way you can solve it ..... take a look my new collected code.

 $(document).ready(function(){
            $(".add-row").click(function(){
                var name = $("#name").val();
                var email = $("#email").val();
                var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
                $("table tbody").append(markup);
            });

            // Find and remove selected table rows
            $(".delete-row").click(function(){
                $("table tbody").find('input[name="record"]').each(function(){
                    if($(this).is(":checked")){
                        $(this).parents("tr").remove();
                    }
                });
            });
        });   

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".add-row").click(function() {_x000D_
    var name = $("#name").val();_x000D_
    var email = $("#email").val();_x000D_
    var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";_x000D_
    $("table tbody").append(markup);_x000D_
  });_x000D_
_x000D_
  // Find and remove selected table rows_x000D_
  $(".delete-row").click(function() {_x000D_
    $("table tbody").find('input[name="record"]').each(function() {_x000D_
      if ($(this).is(":checked")) {_x000D_
        $(this).parents("tr").remove();_x000D_
      }_x000D_
    });_x000D_
  });_x000D_
});
_x000D_
form {_x000D_
  margin: 20px 0;_x000D_
}_x000D_
form input,_x000D_
button {_x000D_
  padding: 6px;_x000D_
  font-size: 18px;_x000D_
}_x000D_
table {_x000D_
  width: 100%;_x000D_
  margin-bottom: 20px;_x000D_
  border-collapse: collapse;_x000D_
  background: #fff;_x000D_
}_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #cdcdcd;_x000D_
}_x000D_
table th,_x000D_
table td {_x000D_
  padding: 10px;_x000D_
  text-align: left;_x000D_
}_x000D_
body {_x000D_
  background: #ccc;_x000D_
}_x000D_
.add-row,_x000D_
.delete-row {_x000D_
  font-size: 16px;_x000D_
  font-weight: 600;_x000D_
  padding: 8px 16px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <input type="text" id="name" placeholder="Name">_x000D_
  <input type="text" id="email" placeholder="Email">_x000D_
  <input type="button" class="add-row" value="Add Row">_x000D_
</form>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Select</th>_x000D_
      <th>Name</th>_x000D_
      <th>Email</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <input type="checkbox" name="record">_x000D_
      </td>_x000D_
      <td>Peter Parker</td>_x000D_
      <td>[email protected]</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<button type="button" class="delete-row">Delete Row</button>
_x000D_
_x000D_
_x000D_

How do I align a label and a textarea?

Just wrap the textarea with the label and set the textarea style to

vertical-align: middle;

Here is some magic for all textareas on the page:)

<style>
    label textarea{
        vertical-align: middle;
    }
</style>

<label>Blah blah blah Description: <textarea>dura bura</textarea></label>

Align DIV to bottom of the page

Nathan Lee's answer is perfect. I just wanted to add something about position:absolute;. If you wanted to use position:absolute; like you had in your code, you have to think of it as pushing it away from one side of the page.

For example, if you wanted your div to be somewhere in the bottom, you would have to use position:absolute; top:500px;. That would push your div 500px from the top of the page. Same rule applies for all other directions.

DEMO

Why doesn't JUnit provide assertNotEquals methods?

I'd argue that the absence of assertNotEqual is indeed an asymmetry and makes JUnit a bit less learnable. Mind that this is a neat case when adding a method would diminish the complexity of the API, at least for me: Symmetry helps ruling the bigger space. My guess is that the reason for the omission may be that there are too few people calling for the method. Yet, I remember a time when even assertFalse did not exist; hence, I have a positive expectation that the method might eventually be added, given that it is not a difficult one; even though I acknowledge that there are numerous workarounds, even elegant ones.

How can I monitor the thread count of a process on linux?

try

ps huH p <PID_OF_U_PROCESS> | wc -l

or htop

PreparedStatement with list of parameters in a IN clause

You might want to check this link:

http://www.javaranch.com/journal/200510/Journal200510.jsp#a2

It explains the pros and cons of different methods of creating PreparedStatement with in clause.

EDIT:

An obvious approach is to dynamically generate the '?' part at runtime, but I don't want to merely suggest just this approach because depending on the way you use it, it might be inefficient (since the PreparedStatement will need to be 'compiled' every time it gets used)

How to split a dos path into its components in Python

It works for me:

>>> a=r"d:\stuff\morestuff\furtherdown\THEFILE.txt"
>>> a.split("\\")
['d:', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']

Sure you might need to also strip out the colon from the first component, but keeping it makes it possible to re-assemble the path.

The r modifier marks the string literal as "raw"; notice how embedded backslashes are not doubled.

How do I get cURL to not show the progress bar?

On MacOS 10.13.6 (High Sierra), the '-ss' option works. It is especially useful inside perl, in a command like curl -ss --get {someURL}, which frankly is a whole lot more simple than any of the LWP or HTTP wrappers, for just getting a website or webpage's contents.

Define make variable at rule execution time

Another possibility is to use separate lines to set up Make variables when a rule fires.

For example, here is a makefile with two rules. If a rule fires, it creates a temp dir and sets TMP to the temp dir name.

PHONY = ruleA ruleB display

all: ruleA

ruleA: TMP = $(shell mktemp -d testruleA_XXXX)
ruleA: display

ruleB: TMP = $(shell mktemp -d testruleB_XXXX)
ruleB: display

display:
    echo ${TMP}

Running the code produces the expected result:

$ ls
Makefile
$ make ruleB
echo testruleB_Y4Ow
testruleB_Y4Ow
$ ls
Makefile  testruleB_Y4Ow

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

The usual rules should apply for how you send the request. If the request is to retrieve information (e.g. a partial search 'hint' result, or a new page to be displayed, etc...) you can use GET. If the data being sent is part of a request to change something (update a database, delete a record, etc..) then use POST.

Server-side, there's no reason to use the raw input, unless you want to grab the entire post/get data block in a single go. You can retrieve the specific information you want via the _GET/_POST arrays as usual. AJAX libraries such as MooTools/jQuery will handle the hard part of doing the actual AJAX calls and encoding form data into appropriate formats for you.

Steps to send a https request to a rest service in Node js

just use the core https module with the https.request function. Example for a POST request (GET would be similar):

var https = require('https');

var options = {
  host: 'www.google.com',
  port: 443,
  path: '/upload',
  method: 'POST'
};

var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

Android Whatsapp/Chat Examples

If you are looking to create an instant messenger for Android, this code should get you started somewhere.

Excerpt from the source :

This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.

EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.

There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!

*UPDATE : * Scringo services will be closed down on 15 February, 2015.

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

I used this command and it worked fine with me:

>git push -f origin master

But notice, that may delete some files you already have on the remote repo. That came in handy with me as the scenario was different; I was pushing my local project to the remote repo which was empty but the READ.ME

How do I set a column value to NULL in SQL Server Management Studio?

If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl+0.

How do you decompile a swf file

Usually 'lost' is a euphemism for "We stopped paying the developer and now he wont give us the source code."

That being said, I own a copy of Burak's ActionScript Viewer, and it works pretty well. A simple google search will find you many other SWF decompilers.

Mongoose limit/offset and count query

I suggest you to use 2 queries:

  1. db.collection.count() will return total number of items. This value is stored somewhere in Mongo and it is not calculated.

  2. db.collection.find().skip(20).limit(10) here I assume you could use a sort by some field, so do not forget to add an index on this field. This query will be fast too.

I think that you shouldn't query all items and than perform skip and take, cause later when you have big data you will have problems with data transferring and processing.

React.js, wait for setState to finish before triggering a function?

setState takes new state and optional callback function which is called after the state has been updated.

this.setState(
  {newState: 'whatever'},
  () => {/*do something after the state has been updated*/}
)

How to install maven on redhat linux

Sometimes you may get "Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/classworlds/Launcher" even after setting M2_HOME and PATH parameters correctly.

This exception is because your JDK/Java version need to be updated/installed.

jQuery’s .bind() vs. .on()

As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.

jQuery API documentation for .bind()

How to dump a dict to a json file?

If you're using Path:

example_path = Path('/tmp/test.json')
example_dict = {'x': 24, 'y': 25}
json_str = json.dumps(example_dict, indent=4) + '\n'
example_path.write_text(json_str, encoding='utf-8')

In Tkinter is there any way to make a widget not visible?

One option, as explained in another answer, is to use pack_forget or grid_forget. Another option is to use lift and lower. This changes the stacking order of widgets. The net effect is that you can hide widgets behind sibling widgets (or descendants of siblings). When you want them to be visible you lift them, and when you want them to be invisible you lower them.

The advantage (or disadvantage...) is that they still take up space in their master. If you "forget" a widget, the other widgets might readjust their size or orientation, but if you raise or lower them they will not.

Here is a simple example:

import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.frame = tk.Frame(self)
        self.frame.pack(side="top", fill="both", expand=True)
        self.label = tk.Label(self, text="Hello, world")
        button1 = tk.Button(self, text="Click to hide label",
                           command=self.hide_label)
        button2 = tk.Button(self, text="Click to show label",
                            command=self.show_label)
        self.label.pack(in_=self.frame)
        button1.pack(in_=self.frame)
        button2.pack(in_=self.frame)

    def show_label(self, event=None):
        self.label.lift(self.frame)

    def hide_label(self, event=None):
        self.label.lower(self.frame)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

AngularJS - Create a directive that uses ng-model

I wouldn't set the ngmodel via an attribute, you can specify it right in the template:

template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',

plunker: http://plnkr.co/edit/9vtmnw?p=preview

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

How to parse JSON in Scala using standard Scala classes?

I like @huynhjl's answer, it led me down the right path. However, it isn't great at handling error conditions. If the desired node does not exist, you get a cast exception. I've adapted this slightly to make use of Option to better handle this.

class CC[T] {
  def unapply(a:Option[Any]):Option[T] = if (a.isEmpty) {
    None
  } else {
    Some(a.get.asInstanceOf[T])
  }
}

object M extends CC[Map[String, Any]]
object L extends CC[List[Any]]
object S extends CC[String]
object D extends CC[Double]
object B extends CC[Boolean]

for {
  M(map) <- List(JSON.parseFull(jsonString))
  L(languages) = map.get("languages")
  language <- languages
  M(lang) = Some(language)
  S(name) = lang.get("name")
  B(active) = lang.get("is_active")
  D(completeness) = lang.get("completeness")
} yield {
  (name, active, completeness)
}

Of course, this doesn't handle errors so much as avoid them. This will yield an empty list if any of the json nodes are missing. You can use a match to check for the presence of a node before acting...

for {
  M(map) <- Some(JSON.parseFull(jsonString))
} yield {
  map.get("languages") match {
    case L(languages) => {
      for {
        language <- languages
        M(lang) = Some(language)
        S(name) = lang.get("name")
        B(active) = lang.get("is_active")
        D(completeness) = lang.get("completeness")
      } yield {
        (name, active, completeness)
      }        
    }
    case None => "bad json"
  }
}

How to see what privileges are granted to schema of another user

Use example with from the post of Szilágyi Donát.

I use two querys, one to know what roles I have, excluding connect grant:

SELECT * FROM USER_ROLE_PRIVS WHERE GRANTED_ROLE != 'CONNECT'; -- Roles of the actual Oracle Schema

Know I like to find what privileges/roles my schema/user have; examples of my roles ROLE_VIEW_PAYMENTS & ROLE_OPS_CUSTOMERS. But to find the tables/objecst of an specific role I used:

SELECT * FROM ALL_TAB_PRIVS WHERE GRANTEE='ROLE_OPS_CUSTOMERS'; -- Objects granted at role.

The owner schema for this example could be PRD_CUSTOMERS_OWNER (or the role/schema inself).

Regards.

node.js require() cache - possible to invalidate?

requireUncached with relative path:

const requireUncached = require => module => {
  delete require.cache[require.resolve(module)];
  return require(module);
};

module.exports = requireUncached;

invoke requireUncached with relative path:

const requireUncached = require('../helpers/require_uncached')(require);
const myModule = requireUncached('./myModule');

Pattern matching using a wildcard

glob2rx() converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.

If you want to match "blue*" where * has the usual wildcard, not regular expression, meaning we use glob2rx() to convert the wildcard pattern into a useful regular expression:

> glob2rx("blue*")
[1] "^blue"

The returned object is a regular expression.

Given your data:

x <- c('red','blue1','blue2', 'red2')

we can pattern match using grep() or similar tools:

> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE  TRUE  TRUE FALSE

As for the selecting rows problem you posted

> a <- data.frame(x =  c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2

or via subset():

> with(a, subset(a, subset = grepl(grx, x)))
      x
2 blue1
3 blue2

Hope that explains what grob2rx() does and how to use it?

GitHub relative link in Markdown file

As of January 31, 2013 Github markdown supports relative links to files.

[a relative link](markdown_file.md)

However, there are a few deficiencies that have been discussed in this comment thread.

As an alternative, you can use Gitdown to construct full URLs to the repository and even make them branch aware, e.g.

{"gitdown": "gitinfo", "name": "url"} // https://github.com/gajus/gitdown
{"gitdown": "gitinfo", "name": "branch"} // master

Gitdown is a GitHub markdown preprocessor. It streamlines common tasks associated with maintaining a documentation page for a GitHub repository, e.g. generating table of contents, including variables, generating URLs and getting information about the repository itself at the time of processing the input. Gitdown seamlessly integrates with your building scripts.

I am the author of the Gitdown library.

Refreshing all the pivot tables in my excel workbook with a macro

Yes.

ThisWorkbook.RefreshAll

Or, if your Excel version is old enough,

Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

"Sub or Function not defined" when trying to run a VBA script in Outlook

I think you need to update your libraries so that your VBA code works, your using ms outlook

There has been an error processing your request, Error log record number

Go to magento/var/report and open the file with the Error log record number name i.e 673618173351 in your case. In that file you can find the complete description of the error.

For log files like system.log and exception.log, go to magento/var/log/.

Not Able To Debug App In Android Studio

I tested all ways and non of them worked !!!

finally had to change the adb port and it worked. first kill adb server like below:

adb kill-server

then restart it using another port

adb -P 5038 start-server

How can I pass a member function where a free function is expected?

If you actually don't need to use the instance a (i.e. you can make it static like @mathengineer 's answer) you can simply pass in a non-capture lambda. (which decay to function pointer)


#include <iostream>

class aClass
{
public:
   void aTest(int a, int b)
   {
      printf("%d + %d = %d", a, b, a + b);
   }
};

void function1(void (*function)(int, int))
{
    function(1, 1);
}

int main()
{
   //note: you don't need the `+`
   function1(+[](int a,int b){return aClass{}.aTest(a,b);}); 
}

Wandbox


note: if aClass is costly to construct or has side effect, this may not be a good way.

Tab space instead of multiple non-breaking spaces ("nbsp")?

Well, if one needs a long whitespace in the beginning of one line only out of the whole paragraph, then this may be a solution:

<span style='display:inline-block;height:1em;width:4em;'>&nbsp;</span>

If that is too much to write or one needs such tabs in many places, then you can do this

<span class='tab'>&nbsp;</span>

Then include this into CSS:

span.tab {display:inline-block;height:1em;width:4em;}

How to mark-up phone numbers?

The best bet is to start off with tel: which works on all mobiles

Then put in this code, which will only run when on a desktop, and only when a link is clicked.

I'm using http://detectmobilebrowsers.com/ to detect mobile browsers, you can use whatever method you prefer

if (!jQuery.browser.mobile) {
    jQuery('body').on('click', 'a[href^="tel:"]', function() {
            jQuery(this).attr('href', 
                jQuery(this).attr('href').replace(/^tel:/, 'callto:'));
    });
}

So basically you cover all your bases.

tel: works on all phones to open the dialer with the number

callto: works on your computer to connect to skype from firefox, chrome

Where is the web server root directory in WAMP?

this is the path to the web root directory c:\wamp\www

you can create different projects by adding different folders to this directory and call them like:

localhost/project1 from browser

this will run the index.html or index.php, lying inside project1

How many threads is too many?

I think this is a bit of a dodge to your question, but why not fork them into processes? My understanding of networking (from the hazy days of yore, I don't really code networks at all) was that each incoming connection can be handled as a separate process, because then if someone does something nasty in your process, it doesn't nuke the entire program.

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

How to print Boolean flag in NSLog?

Booleans are nothing but integers only, they are just type casted values like...

typedef signed char     BOOL; 

#define YES (BOOL)1
#define NO (BOOL)0

BOOL value = YES; 
NSLog(@"Bool value: %d",value);

If output is 1,YES otherwise NO

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny is actually a good name):

def getAny(dic, keys, default=None):
    return (keys or default) and dic.get(keys[0], 
                                         getAny( dic, keys[1:], default=default))

or even better, without recursion and more clear:

def getAny(dic, keys, default=None):
    for k in keys: 
        if k in dic:
           return dic[k]
    return default

Then that could be used in a way similar to the dict.get method, like:

getAny(myDict, keySet)

and even have a default result in case of no keys found at all:

getAny(myDict, keySet, "not found")

Using Mysql WHERE IN clause in codeigniter

Try this one:

$this->db->select("*");
$this->db->where_in("(SELECT trans_id FROM myTable WHERE code = 'B')");
$this->db->where('code !=', 'B');
$this->db->get('myTable');

Note: $this->db->select("*"); is optional when you are selecting all columns from table

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

I was having same problem. I was getting error when i tried to run in my android device not emulator.

sudo ionic run android 

I am able to fix this by running

adb uninstall com.mypackage.name

Capturing console output from a .NET application (C#)

Use ProcessInfo.RedirectStandardOutput to redirect the output when creating your console process.

Then you can use Process.StandardOutput to read the program output.

The second link has a sample code how to do it.

How to fix the error "Windows SDK version 8.1" was not found?

Grep the folder tree's *.vcxproj files. Replace <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion> with <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion> or whatever SDK version you get when you update one of the projects.

How can I style the border and title bar of a window in WPF?

Those are "non-client" areas and are controlled by Windows. Here is the MSDN docs on the subject (the pertinent info is at the top).

Basically, you set your Window's WindowStyle="None", then build your own window interface. (similar question on SO)

How do I break out of a loop in Scala?

Clever use of find method for collection will do the trick for you.

var largest = 0
lazy val ij =
  for (i <- 999 to 1 by -1; j <- i to 1 by -1) yield (i, j)

val largest_ij = ij.find { case(i,j) =>
  val product = i * j
  if (product.toString == product.toString.reverse)
    largest = largest max product
  largest > product
}

println(largest_ij.get)
println(largest)

Showing the same file in both columns of a Sublime Text window

View -> Layout -> Choose one option or use shortcut

Layout        Shortcut

Single        Alt + Shift + 1
Columns: 2    Alt + Shift + 2
Columns: 3    Alt + Shift + 3
Columns: 4    Alt + Shift + 4
Rows: 2       Alt + Shift + 8
Rows: 3       Alt + Shift + 9
Grid: 4       Alt + Shift + 5

enter image description here

Remove all line breaks from a long string of text

Another option is regex:

>>> import re
>>> re.sub("\n|\r", "", "Foo\n\rbar\n\rbaz\n\r")
'Foobarbaz'

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Just add the column names, yes you can use Null instead but is is a very bad idea to not use column names in any insert, ever.

How do you change the text in the Titlebar in Windows Forms?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        //private void Form1_Load(object sender, EventArgs e)
        //{

        //    // Instantiate a new instance of Form1.
        //    Form1 f1 = new Form1();
        //    f1.Text = "zzzzzzz";

        //}
    }

    class MainApplication
    {
        public static void Main()
        {
            // Instantiate a new instance of Form1.
            Form1 f1 = new Form1();
            // Display a messagebox. This shows the application 
            // is running, yet there is nothing shown to the user. 
            // This is the point at which you customize your form.
            System.Windows.Forms.MessageBox.Show("The application "
               + "is running now, but no forms have been shown.");
            // Customize the form.
            f1.Text = "Running Form";
            // Show the instance of the form modally.
            f1.ShowDialog();
        }
    }

}

Android open camera from button

I have created a libray for pick image from camera or galley and cropping also

Try this,

ImagePro.Java

public class ImagePro
{
    public static String TAG = "ImagePro";
    Activity activity;
    Uri mImageCaptureUri;
    public static int CAMERA_CODE = 64;
    public static int GALLERY_CODE = 74;
    public static int CROPPING_CODE = 84;
    private final static int REQUEST_PERMISSION_REQ_CODE = 704;

    public ImagePro(Activity activity) {

        this.activity = activity;
        this.outPutFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_REQ_CODE);
        }
    }

    private void LogToast(String message) {

        try {
            Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.d(TAG, message);
    }

    private void Toast(String message) {

        try {
            Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void Log(String message) {

        Log.d(TAG, message);
    }

    /**
     * This function return captured image path
     *
     * @param requestCode on activity result requestCode
     * @param resultCode on activity result resultCode
     * @param intent on activity result intent
     * @return ImageDetails values
     */
    public ImageDetails getImagePath(int requestCode, int resultCode, Intent intent) {

        ImageDetails imageDetails = new ImageDetails();

        if(resultCode == Activity.RESULT_OK) {

            if(requestCode == CAMERA_CODE) {
                imageDetails.setUri(mImageCaptureUri);
                imageDetails.setPath(mImageCaptureUri.getPath());
                Bitmap bitmap = null;

                try {
                    bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), mImageCaptureUri);
                } catch (IOException e) {
                    LogToast(e.getMessage());
                    e.printStackTrace();
                }
                imageDetails.setBitmap(bitmap);
                imageDetails.setFile(new File(mImageCaptureUri.getPath()));

            } else if(requestCode == GALLERY_CODE) {

                Uri uri = intent.getData();

                imageDetails.setUri(uri);
                Bitmap bitmap = null;

                try {
                    bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
                } catch (IOException e) {
                    LogToast(e.getMessage());
                    e.printStackTrace();
                }

                imageDetails.setBitmap(bitmap);
                imageDetails.setFile(new File(uri.getPath()));
                imageDetails.setPath(uri.getPath());

            } else if(requestCode == CROPPING_CODE) {
                try {
                    if(outPutFile.exists()){

                        imageDetails.setUri(Uri.fromFile(outPutFile));
                        imageDetails.setFile(outPutFile);
                        imageDetails.setPath(outPutFile.getPath());
                        Bitmap photo = decodeFile(outPutFile);
                        imageDetails.setBitmap(photo);
                    }
                    else {
                        LogToast("Error while save image");
                    }
                } catch (Exception e) {

                    e.printStackTrace();
                    LogToast(e.getMessage());
                }
            }

        } else {
            LogToast("user cancelled.");
        }

        return imageDetails;
    }

    /**
     * Open image pick dialog.<br/>
     * CAMERA_CODE</br>
     * GALLERY_CODE
     */
    public void openImagePickOption() {

        final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {

                if (items[item].equals("Capture Photo")) {

                    captureImage();

                } else if (items[item].equals("Choose from Gallery")) {

                    pickImage();

                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    /**
     * decode from file to bitmap
     * @param f file
     * @return Bitmap data
     */
    private Bitmap decodeFile(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 512;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {

            Log(e.getMessage());
        }
        return null;
    }

    /**
     * Capture image using camera <br/>
     * REQUEST_CODE = ImagePro.CAMERA_CODE
     */
    public void captureImage() {

        if(activity != null) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
            mImageCaptureUri = Uri.fromFile(f);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
            activity.startActivityForResult(intent, CAMERA_CODE);

        } else {

            LogToast("Activity not assigned");
        }
    }

    /**
     * pick image from gallery
     */
    public void pickImage() {

        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        activity.startActivityForResult(i, GALLERY_CODE);
    }

    /**
     * cropping the uri image
     * @param uri - open cropping dialog using the uri data
     */
    public void croppingImage(Uri uri) {

        CroppingIMG(uri);
    }

    int CROP_IMG_X=512;
    int CROP_IMG_Y=512;

    public void croppingImage(Uri uri, int cropX, int cropY) {

        CROP_IMG_X = cropX;
        CROP_IMG_Y = cropY;

        CroppingIMG(uri);
    }

    File outPutFile=null;

    private void CroppingIMG(Uri uri) {

        final ArrayList<CroppingOption> cropOptions = new ArrayList<>();

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");

        List<ResolveInfo> list = activity.getPackageManager().queryIntentActivities( intent, 0 );
        int size = list.size();
        if (size == 0) {
            LogToast("Can't find image croping app");
        } else {
            intent.setData(uri);
            intent.putExtra("outputX", CROP_IMG_X);
            intent.putExtra("outputY", CROP_IMG_Y);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);

            //Create output file here
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile));

            if (size == 1) {
                Intent i   = new Intent(intent);
                ResolveInfo res = list.get(0);

                i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                activity.startActivityForResult(i, CROPPING_CODE);
            } else {
                for (ResolveInfo res : list) {
                    final CroppingOption co = new CroppingOption();

                    co.title = activity.getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                    co.icon = activity.getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                    co.appIntent = new Intent(intent);
                    co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                    cropOptions.add(co);
                }

                CropingOptionAdapter adapter = new CropingOptionAdapter(activity.getApplicationContext(), cropOptions);

                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setTitle("Choose Cropping App");
                builder.setCancelable(false);
                builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
                    public void onClick( DialogInterface dialog, int item ) {
                        activity.startActivityForResult( cropOptions.get(item).appIntent, CROPPING_CODE);
                    }
                });

                builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel( DialogInterface dialog ) {

                        if (mImageCaptureUri != null ) {
                            activity.getContentResolver().delete(mImageCaptureUri, null, null );
                            mImageCaptureUri = null;
                        }
                    }
                } );

                AlertDialog alert = builder.create();
                alert.show();
            }
        }
    }

    /**
     * Capture image using camera<br/>
     * REQUEST_CODE = User defined code<br/>
     * <br/>
     * @param iRequestCode User defined code
     */
    public void captureImage(int iRequestCode) {

        CAMERA_CODE = iRequestCode;
        captureImage();
    }

    /**
     * get path, bitmap, file and uri from image details object
     */
    public class ImageDetails {

        String path="";
        Bitmap bitmap=null;
        File file=null;
        Uri uri=null;

        public Uri getUri() {
            return uri;
        }

        public void setUri(Uri uri) {
            this.uri = uri;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public Bitmap getBitmap() {
            return bitmap;
        }

        public void setBitmap(Bitmap bitmap) {
            this.bitmap = bitmap;
        }

        public File getFile() {
            return file;
        }

        public void setFile(File file) {
            this.file = file;
        }
    }

    /**
     * Created by DP on 7/12/2016.
     */
    public class CroppingOption {
        public CharSequence title;
        public Drawable icon;
        public Intent appIntent;
    }

    public class CropingOptionAdapter extends ArrayAdapter {
        private ArrayList<CroppingOption> mOptions;
        private LayoutInflater mInflater;

        public CropingOptionAdapter(Context context, ArrayList<CroppingOption> options) {

            super(context, R.layout.croping_selector, options);
            mOptions  = options;
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup group) {
            if (convertView == null)
                convertView = mInflater.inflate(R.layout.croping_selector, null);

            CroppingOption item = mOptions.get(position);

            if (item != null) {
                ((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon);
                ((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title);

                return convertView;
            }

            return null;
        }
    }
}

MainActivity.java

ImagePro imagePro;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imagePro = new ImagePro(this);
    }

    public void onClickUploadImageButton(View view) {

        imagePro.openImagePickOption();
    }

onActivityResult

if(requestCode == CAMERA_CODE && resultCode == RESULT_OK) {

            imageDetails = imagePro.getImagePath(CAMERA_CODE, RESULT_OK, data);
            ivCrop.setImageBitmap(imageDetails.getBitmap());
//imageDetails.getPath(), imageDetails.getBitmap(), imageDetails.getUri(), imageDetails.getFile
        }

How to add an Access-Control-Allow-Origin header

According to the official docs, browsers do not like it when you use the

Access-Control-Allow-Origin: "*"

header if you're also using the

Access-Control-Allow-Credentials: "true"

header. Instead, they want you to allow their origin specifically. If you still want to allow all origins, you can do some simple Apache magic to get it to work (make sure you have mod_headers enabled):

Header set Access-Control-Allow-Origin "%{HTTP_ORIGIN}e" env=HTTP_ORIGIN

Browsers are required to send the Origin header on all cross-domain requests. The docs specifically state that you need to echo this header back in the Access-Control-Allow-Origin header if you are accepting/planning on accepting the request. That's what this Header directive is doing.

How to pass a form input value into a JavaScript function

It might be cleaner to take out your inline click handler and do it like this:

$(document).ready(function() {
    $('#button-id').click(function() {
      foo($('#formValueId').val());
    });
});

Find a pair of elements from an array whose sum equals a given number

Implementation in Java : Using codaddict's algorithm (Maybe slightly different)

import java.util.HashMap;

public class ArrayPairSum {


public static void main(String[] args) {        

    int []a = {2,45,7,3,5,1,8,9};
    printSumPairs(a,10);        

}


public static void printSumPairs(int []input, int k){
    Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();

    for(int i=0;i<input.length;i++){

        if(pairs.containsKey(input[i]))
            System.out.println(input[i] +", "+ pairs.get(input[i]));
        else
            pairs.put(k-input[i], input[i]);
    }

}
}

For input = {2,45,7,3,5,1,8,9} and if Sum is 10

Output pairs:

3,7 
8,2
9,1

Some notes about the solution :

  • We iterate only once through the array --> O(n) time
  • Insertion and lookup time in Hash is O(1).
  • Overall time is O(n), although it uses extra space in terms of hash.

How to stop creating .DS_Store on Mac?

the function

find ~/ -name '.DS_Store' -delete

, removed the .DS store files temporarily. But am not sure , whether the files will came back on the Mac. Also i noticed something peculiar, the "DS_Store" start coming to the Mac after installing 'ATOM'. So guys please make it sure to scan properly your third party software before installing them. Best

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

These strange errors occured recently on my OSX machine.

I could help myself the quick & dirty way by running:

sudo chmod -R 777 /usr/local/lib/node_modules/

Something seemed to have messed up the access rights of all global node modules.

cannot find module "lodash"

I got the error above and after fixing it I got an error for lodash/merge, then I got an error for 'license-check-and-add' then I realized that according to https://accessibilityinsights.io if I ran the below command, it installs all the missing pacakages at once! Then running the yarn build command worked smoothly with a --force parameter with yarn build.

yarn install

yarn build --force

enter image description here

Yarn build --force execution: enter image description here

Newline in markdown table?

When you're exporting to HTML, using <br> works. However, if you're using pandoc to export to LaTeX/PDF as well, you should use grid tables:

+---------------+---------------+--------------------+
| Fruit         | Price         | Advantages         |
+===============+===============+====================+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+

VMware Workstation and Device/Credential Guard are not compatible

To make it super easy:

  1. Just download this script directly from Microsoft.

  2. Run your Powershell as an admin and then execute following commands:

    • To Verify if DG/CG is enabled DG_Readiness.ps1 -Ready
    • To Disable DG/CG. DG_Readiness.ps1 -Disable

Wamp Server not goes to green color

I found something I did wrong, install the Apache and MySQL services. Click on the WAMP logo, goto Apache -> Service -> Install Service, after that Apache -> Service -> Start/Resume Service. Do the same for MySQL and it will turn green.

How to run a single test with Mocha?

If you are using npm test (using package.json scripts) use an extra -- to pass the param through to mocha

e.g. npm test -- --grep "my second test"

EDIT: Looks like --grep can be a little fussy (probably depending on the other arguments). You can:

Modify the package.json:

"test:mocha": "mocha --grep \"<DealsList />\" .",

Or alternatively use --bail which seems to be less fussy

npm test -- --bail

Summarizing multiple columns with dplyr?

For completeness: with dplyr v0.2 ddply with colwise will also do this:

> ddply(df, .(grp), colwise(mean))
  grp        a    b        c        d
1   1 4.333333 4.00 1.000000 2.000000
2   2 2.000000 2.75 2.750000 2.750000
3   3 3.000000 4.00 4.333333 3.666667

but it is slower, at least in this case:

> microbenchmark(ddply(df, .(grp), colwise(mean)), 
                  df %>% group_by(grp) %>% summarise_each(funs(mean)))
Unit: milliseconds
                                            expr      min       lq     mean
                ddply(df, .(grp), colwise(mean))     3.278002 3.331744 3.533835
 df %>% group_by(grp) %>% summarise_each(funs(mean)) 1.001789 1.031528 1.109337

   median       uq      max neval
 3.353633 3.378089 7.592209   100
 1.121954 1.133428 2.292216   100

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

I had a similar error and fixed it by following steps: 1. Under Servers project (which gets created itself when you add Apache Tomcat Server in Eclipse), open server.xml 2. Comment out the line

<Context docBase=... />

How to change color in markdown cells ipython/jupyter notebook?

Similarly to Jakob's answer, you can use HTML tags. Just a note that the color attribute of font (<font color=...>) is deprecated in HTML5. The following syntax would be HTML5-compliant:

This <span style="color:red">word</span> is not black.

Same caution that Jakob made probably still applies:

Be aware that this will not survive a conversion of the notebook to latex.

When and where to use GetType() or typeof()?

typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

Example where compile-time and run-time types are equal

string s = "hello";

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2 ==> true

Example where compile-time and run-time types are different

object obj = "hello";

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type of the object referenced by obj.


Testing types

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

if (mycontrol is TextBox)

Note that this is not completely equivalent to

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

If you have the following test followed by a cast and T is nullable ...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

Starting with C# 7.0 you can simplify the code by using pattern matching:

if (obj is T t) {
    // t is a variable of type T having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

if (o is int? ni) ===> does NOT compile!

This is because either the value is null or it is an int. This works for int? o as well as for object o = new Nullable<int>(x);:

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Value property.

Very Simple, Very Smooth, JavaScript Marquee

The following works:

http://jsfiddle.net/xAGRJ/4/

The problem with your original code was you are calling scrollticker() by passing a string to setInterval, where you should just pass the function name and treat it as a variable:

lefttime = setInterval(scrollticker, 50);

instead of

lefttime = setInterval("scrollticker()", 50);

How to parse JSON array in jQuery?

I am trying to parse JSON data returned from an ajax call, and the following is working for me:

Sample PHP code

$portfolio_array= Array('desc'=>'This is test description1','item1'=>'1.jpg','item2'=>'2.jpg');

echo json_encode($portfolio_array);

And in the .js, i am parsing like this:

var req=$.post("json.php", { id: "" + id + ""},
function(data) {
    data=$.parseJSON(data);
    alert(data.desc);
    $.each(data, function(i,item){
    alert(item);
    });
})
.success(function(){})
.error(function(){alert('There was problem loading portfolio details.');})
.complete(function(){});

If you have multidimensional array like below

$portfolio_array= Array('desc'=>'This is test description 1','items'=> array('item1'=>'1.jpg','item2'=>'2.jpg'));
echo json_encode($portfolio_array);

Then the code below should work:

var req=$.post("json.php", { id: "" + id + 
    function(data) {
    data=$.parseJSON(data);
    alert(data.desc);
    $.each(data.items, function(i,item){
    alert(item);
    });
})
.success(function(){})
.error(function(){alert('There was problem loading portfolio details.');})
.complete(function(){});

Please note the sub array key here is items, and suppose if you have xyz then in place of data.items use data.xyz

How to stop a goroutine

EDIT: I wrote this answer up in haste, before realizing that your question is about sending values to a chan inside a goroutine. The approach below can be used either with an additional chan as suggested above, or using the fact that the chan you have already is bi-directional, you can use just the one...

If your goroutine exists solely to process the items coming out of the chan, you can make use of the "close" builtin and the special receive form for channels.

That is, once you're done sending items on the chan, you close it. Then inside your goroutine you get an extra parameter to the receive operator that shows whether the channel has been closed.

Here is a complete example (the waitgroup is used to make sure that the process continues until the goroutine completes):

package main

import "sync"
func main() {
    var wg sync.WaitGroup
    wg.Add(1)

    ch := make(chan int)
    go func() {
        for {
            foo, ok := <- ch
            if !ok {
                println("done")
                wg.Done()
                return
            }
            println(foo)
        }
    }()
    ch <- 1
    ch <- 2
    ch <- 3
    close(ch)

    wg.Wait()
}

Solr vs. ElasticSearch

I see some of the above answers are now a bit out of date. From my perspective, and I work with both Solr(Cloud and non-Cloud) and ElasticSearch on a daily basis, here are some interesting differences:

  • Community: Solr has a bigger, more mature user, dev, and contributor community. ES has a smaller, but active community of users and a growing community of contributors
  • Maturity: Solr is more mature, but ES has grown rapidly and I consider it stable
  • Performance: hard to judge. I/we have not done direct performance benchmarks. A person at LinkedIn did compare Solr vs. ES vs. Sensei once, but the initial results should be ignored because they used non-expert setup for both Solr and ES.
  • Design: People love Solr. The Java API is somewhat verbose, but people like how it's put together. Solr code is unfortunately not always very pretty. Also, ES has sharding, real-time replication, document and routing built-in. While some of this exists in Solr, too, it feels a bit like an after-thought.
  • Support: there are companies providing tech and consulting support for both Solr and ElasticSearch. I think the only company that provides support for both is Sematext (disclosure: I'm Sematext founder)
  • Scalability: both can be scaled to very large clusters. ES is easier to scale than pre-Solr 4.0 version of Solr, but with Solr 4.0 that's no longer the case.

For more thorough coverage of Solr vs. ElasticSearch topic have a look at https://sematext.com/blog/solr-vs-elasticsearch-part-1-overview/ . This is the first post in the series of posts from Sematext doing direct and neutral Solr vs. ElasticSearch comparison. Disclosure: I work at Sematext.

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

Change content of div - jQuery

Try this to Change content of div using jQuery.

See more @ Change content of div using jQuery

$(document).ready(function(){
    $("#Textarea").keyup(function(){
        // Getting the current value of textarea
        var currentText = $(this).val();

        // Setting the Div content
        $(".output").text(currentText);
    });
});

Vue 2 - Mutating props vue-warn

Adding to the best answer,

Vue.component('task', {
    template: '#task-template',
    props: ['list'],
    data: function () {
        return {
            mutableList: JSON.parse(this.list);
        }
    }
});

Setting props by an array is meant for dev/prototyping, in production make sure to set prop types(https://vuejs.org/v2/guide/components-props.html) and set a default value in case the prop has not been populated by the parent, as so.

Vue.component('task', {
    template: '#task-template',
    props: {
      list: {
        type: String,
        default() {
          return '{}'
        }
      }
    },
    data: function () {
        return {
            mutableList: JSON.parse(this.list);
        }
    }
});

This way you atleast get an empty object in mutableList instead of a JSON.parse error if it is undefined.

How do I remove background-image in css?

Doesn't this work:

.clear-background{
background-image: none;
}

Might have problems on older browsers...

Attributes / member variables in interfaces?

Java 8 introduced default methods for interfaces using which you can body to the methods. According to OOPs interfaces should act as contract between two systems/parties.

But still i found a way to achieve storing properties in the interface. I admit it is kinda ugly implementation.

   import java.util.Map;
   import java.util.WeakHashMap;

interface Rectangle
{

class Storage
{
    private static final Map<Rectangle, Integer> heightMap = new WeakHashMap<>();
    private static final Map<Rectangle, Integer> widthMap = new WeakHashMap<>();
}

default public int getHeight()
{
    return Storage.heightMap.get(this);
}

default public int getWidth()
{
    return Storage.widthMap.get(this);
}

default public void setHeight(int height)
{
    Storage.heightMap.put(this, height);
}

default public void setWidth(int width)
{
    Storage.widthMap.put(this, width);
}
}

This interface is ugly. For storing simple property it needed two hashmaps and each hashmap by default creates 16 entries by default. Additionally when real object is dereferenced JVM additionally need to remove this weak reference.

Render HTML to PDF in Django site

You can use iReport editor to define the layout, and publish the report in jasper reports server. After publish you can invoke the rest api to get the results.

Here is the test of the functionality:

from django.test import TestCase
from x_reports_jasper.models import JasperServerClient

"""
    to try integraction with jasper server through rest
"""
class TestJasperServerClient(TestCase):

    # define required objects for tests
    def setUp(self):

        # load the connection to remote server
        try:

            self.j_url = "http://127.0.0.1:8080/jasperserver"
            self.j_user = "jasperadmin"
            self.j_pass = "jasperadmin"

            self.client = JasperServerClient.create_client(self.j_url,self.j_user,self.j_pass)

        except Exception, e:
            # if errors could not execute test given prerrequisites
            raise

    # test exception when server data is invalid
    def test_login_to_invalid_address_should_raise(self):
        self.assertRaises(Exception,JasperServerClient.create_client, "http://127.0.0.1:9090/jasperserver",self.j_user,self.j_pass)

    # test execute existent report in server
    def test_get_report(self):

        r_resource_path = "/reports/<PathToPublishedReport>"
        r_format = "pdf"
        r_params = {'PARAM_TO_REPORT':"1",}

        #resource_meta = client.load_resource_metadata( rep_resource_path )

        [uuid,out_mime,out_data] = self.client.generate_report(r_resource_path,r_format,r_params)
        self.assertIsNotNone(uuid)

And here is an example of the invocation implementation:

from django.db import models
import requests
import sys
from xml.etree import ElementTree
import logging 

# module logger definition
logger = logging.getLogger(__name__)

# Create your models here.
class JasperServerClient(models.Manager):

    def __handle_exception(self, exception_root, exception_id, exec_info ):
        type, value, traceback = exec_info
        raise JasperServerClientError(exception_root, exception_id), None, traceback

    # 01: REPORT-METADATA 
    #   get resource description to generate the report
    def __handle_report_metadata(self, rep_resourcepath):

        l_path_base_resource = "/rest/resource"
        l_path = self.j_url + l_path_base_resource
        logger.info( "metadata (begin) [path=%s%s]"  %( l_path ,rep_resourcepath) )

        resource_response = None
        try:
            resource_response = requests.get( "%s%s" %( l_path ,rep_resourcepath) , cookies = self.login_response.cookies)

        except Exception, e:
            self.__handle_exception(e, "REPORT_METADATA:CALL_ERROR", sys.exc_info())

        resource_response_dom = None
        try:
            # parse to dom and set parameters
            logger.debug( " - response [data=%s]"  %( resource_response.text) )
            resource_response_dom = ElementTree.fromstring(resource_response.text)

            datum = "" 
            for node in resource_response_dom.getiterator():
                datum = "%s<br />%s - %s" % (datum, node.tag, node.text)
            logger.debug( " - response [xml=%s]"  %( datum ) )

            #
            self.resource_response_payload= resource_response.text
            logger.info( "metadata (end) ")
        except Exception, e:
            logger.error( "metadata (error) [%s]" % (e))
            self.__handle_exception(e, "REPORT_METADATA:PARSE_ERROR", sys.exc_info())


    # 02: REPORT-PARAMS 
    def __add_report_params(self, metadata_text, params ):
        if(type(params) != dict):
            raise TypeError("Invalid parameters to report")
        else:
            logger.info( "add-params (begin) []" )
            #copy parameters
            l_params = {}
            for k,v in params.items():
                l_params[k]=v
            # get the payload metadata
            metadata_dom = ElementTree.fromstring(metadata_text)
            # add attributes to payload metadata
            root = metadata_dom #('report'):

            for k,v in l_params.items():
                param_dom_element = ElementTree.Element('parameter')
                param_dom_element.attrib["name"] = k
                param_dom_element.text = v
                root.append(param_dom_element)

            #
            metadata_modified_text =ElementTree.tostring(metadata_dom, encoding='utf8', method='xml')
            logger.info( "add-params (end) [payload-xml=%s]" %( metadata_modified_text )  )
            return metadata_modified_text



    # 03: REPORT-REQUEST-CALL 
    #   call to generate the report
    def __handle_report_request(self, rep_resourcepath, rep_format, rep_params):

        # add parameters
        self.resource_response_payload = self.__add_report_params(self.resource_response_payload,rep_params)

        # send report request

        l_path_base_genreport = "/rest/report"
        l_path = self.j_url + l_path_base_genreport
        logger.info( "report-request (begin) [path=%s%s]"  %( l_path ,rep_resourcepath) )

        genreport_response = None
        try:
            genreport_response = requests.put( "%s%s?RUN_OUTPUT_FORMAT=%s" %(l_path,rep_resourcepath,rep_format),data=self.resource_response_payload, cookies = self.login_response.cookies )
            logger.info( " - send-operation-result [value=%s]"  %( genreport_response.text) )
        except Exception,e:
            self.__handle_exception(e, "REPORT_REQUEST:CALL_ERROR", sys.exc_info())


        # parse the uuid of the requested report
        genreport_response_dom = None

        try:
            genreport_response_dom = ElementTree.fromstring(genreport_response.text)

            for node in genreport_response_dom.findall("uuid"):
                datum = "%s" % (node.text)

            genreport_uuid = datum      

            for node in genreport_response_dom.findall("file/[@type]"):
                datum = "%s" % (node.text)
            genreport_mime = datum

            logger.info( "report-request (end) [uuid=%s,mime=%s]"  %( genreport_uuid, genreport_mime) )

            return [genreport_uuid,genreport_mime]
        except Exception,e:
            self.__handle_exception(e, "REPORT_REQUEST:PARSE_ERROR", sys.exc_info())

    # 04: REPORT-RETRIEVE RESULTS 
    def __handle_report_reply(self, genreport_uuid ):


        l_path_base_getresult = "/rest/report"
        l_path = self.j_url + l_path_base_getresult 
        logger.info( "report-reply (begin) [uuid=%s,path=%s]"  %( genreport_uuid,l_path) )

        getresult_response = requests.get( "%s%s/%s?file=report" %(self.j_url,l_path_base_getresult,genreport_uuid),data=self.resource_response_payload, cookies = self.login_response.cookies )
        l_result_header_mime =getresult_response.headers['Content-Type']

        logger.info( "report-reply (end) [uuid=%s,mime=%s]"  %( genreport_uuid, l_result_header_mime) )
        return [l_result_header_mime, getresult_response.content]

    # public methods ---------------------------------------    

    # tries the authentication with jasperserver throug rest
    def login(self, j_url, j_user,j_pass):
        self.j_url= j_url

        l_path_base_auth = "/rest/login"
        l_path = self.j_url + l_path_base_auth

        logger.info( "login (begin) [path=%s]"  %( l_path) )

        try:
            self.login_response = requests.post(l_path , params = {
                    'j_username':j_user,
                    'j_password':j_pass
                })                  

            if( requests.codes.ok != self.login_response.status_code ):
                self.login_response.raise_for_status()

            logger.info( "login (end)" )
            return True
            # see http://blog.ianbicking.org/2007/09/12/re-raising-exceptions/

        except Exception, e:
            logger.error("login (error) [e=%s]" % e )
            self.__handle_exception(e, "LOGIN:CALL_ERROR",sys.exc_info())
            #raise

    def generate_report(self, rep_resourcepath,rep_format,rep_params):
        self.__handle_report_metadata(rep_resourcepath)
        [uuid,mime] = self.__handle_report_request(rep_resourcepath, rep_format,rep_params)
        # TODO: how to handle async?
        [out_mime,out_data] = self.__handle_report_reply(uuid)
        return [uuid,out_mime,out_data]

    @staticmethod
    def create_client(j_url, j_user, j_pass):
        client = JasperServerClient()
        login_res = client.login( j_url, j_user, j_pass )
        return client


class JasperServerClientError(Exception):

    def __init__(self,exception_root,reason_id,reason_message=None):
        super(JasperServerClientError, self).__init__(str(reason_message))
        self.code = reason_id 
        self.description = str(exception_root) + " " + str(reason_message)
    def __str__(self):
        return self.code + " " + self.description

Why does a base64 encoded string have an = sign at the end

1: No.

2: As a short answer: The 65th character ("=" sign) is used only as a complement in the final process of encoding a message.

You will not have a '=' sign if your string has a multiple of 3 characters number, because Base64 encoding takes each three bytes (8 bits) and represents them as four printable characters in the ASCII standard.

Details:

(a) If you want to encode

ABCDEFG <=> [ABC] [DEF] [G

Base64 will deal with the first block (producing 4 characters) and the second (as they are complete). But for the third it will add a double == in the output in order to complete the 4 needed characters. Thus, the result will be QUJD REVG Rw== (without spaces).

(b) If you want to encode

ABCDEFGH <=> [ABC] [DEF] [GH

similarly, it will add just a single = in the end of the output to get 4 characters.

The result will be QUJD REVG R0g= (without spaces).

Why is it said that "HTTP is a stateless protocol"?

Modern HTTP is stateful. Old timey HTTP was stateless.

Before Netscape invented cookies and HTTPS in 1994 http could be considered stateless. As time progressed more and more stateful aspects were added for a myriad of reasons, including performance and security.

While HTTP 1 originally sought out to be stateless many HTTP/2 components are the very definition of stateful. HTTP/2 abandoned stateless goals.

No reasonable person can read the HTTP/2 RFC and think it is stateless. The errant "HTTP is stateless" old time dogma is false and far from the current reality of stateful HTTP.

Here's a limited, and not exhaustive list, of stateful HTTP/1 and HTTP/2 components:

  • Cookies, named "HTTP State Management Mechanism" by the RFC.
  • HTTPS, which stores keys thus state.
  • HTTP authentication requires state.
  • Web Storage.
  • HTTP caching is stateful.
  • The very purpose of the stream identifier is state. It's even in the name of the RFC section, "Stream States".
  • Header blocks, which establish stream identifiers, are stateful.
  • Frames which reference stream identifiers are stateful.
  • Header Compression, which the HTTP RFC explicitly says is stateful, is stateful.
  • Opportunistic encryption is stateful.

Section 5.1 of the HTTP/2 RFC is a great example of stateful mechanisms defined by the HTTP/2 standard.

Is it safe for web applications to consider HTTP/2 as a stateless protocol?

HTTP/2 is a stateful protocol, but that doesn't mean your HTTP/2 application can't be stateless. You can choose to not use certain stateful features for stateless HTTP/2 applications by using only a subset of HTTP/2 features.

Cookies and some other stateful mechanisms, or less obvious stateful mechanisms, are later HTTP additions. HTTP 1 is said to be stateless although in practice we use standardized stateful mechanisms, like cookies, TLS, and caching. Unlike HTTP/1, HTTP/2 defines stateful components in its standard from the very beginning. A particular HTTP/2 application can use a subset of HTTP/2 features to maintain statelessness, but the protocol itself anticipate state to be the norm, not the exception.

Existing applications, even HTTP 1 applications, needing state will break if trying to use them statelessly. It can be impossible to log into some HTTP/1.1 websites if cookies are disabled, thus breaking the application. It may not be safe to assume that a particular HTTP 1 application does not use state. This is no different for HTTP/2.

Say it with me one last time:

HTTP/2 is a stateful protocol.

What do the crossed style properties in Google Chrome devtools mean?

There is some cases when you copy and paste the CSS code in somewhere and it breaks the format so Chrome show the yellow warning. You should try to reformat the CSS code again and it should be fine.

Callback when DOM is loaded in react.js

I applied componentDidUpdate to table to have all columns same height. it works same as on $(window).load() in jquery.

eg:

componentDidUpdate: function() {
        $(".tbl-tr").height($(".tbl-tr ").height());
    }

Package php5 have no installation candidate (Ubuntu 16.04)

You must use prefix "php5.6-" instead of "php5-" as in ubuntu 14.04 and olders:

sudo apt-get install php5.6 php5.6-mcrypt

JavaFX 2.1 TableView refresh items

I suppose this thread has a very good description of the problem with table refresh.

Unused arguments in R

One approach (which I can't imagine is good programming practice) is to add the ... which is traditionally used to pass arguments specified in one function to another.

> multiply <- function(a,b) a*b
> multiply(a = 2,b = 4,c = 8)
Error in multiply(a = 2, b = 4, c = 8) : unused argument(s) (c = 8)
> multiply2 <- function(a,b,...) a*b
> multiply2(a = 2,b = 4,c = 8)
[1] 8

You can read more about ... is intended to be used here

Sending credentials with cross-domain posts?

In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:

$.ajax(
        'https://foo.bar.com,
        {
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: successFunc
        }
    );

The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:

An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT

Make new column in Panda dataframe by adding values from other columns

As of Pandas version 0.16.0 you can use assign as follows:

df = pd.DataFrame({"A": [1,2,3], "B": [4,6,9]})
df.assign(C = df.A + df.B)

# Out[383]: 
#    A  B   C
# 0  1  4   5
# 1  2  6   8
# 2  3  9  12

You can add multiple columns this way as follows:

df.assign(C = df.A + df.B,
          Diff = df.B - df.A,
          Mult = df.A * df.B)
# Out[379]: 
#    A  B   C  Diff  Mult
# 0  1  4   5     3     4
# 1  2  6   8     4    12
# 2  3  9  12     6    27

Parse an URL in JavaScript

One liner:

location.search.replace('?','').split('&').reduce(function(s,c){var t=c.split('=');s[t[0]]=t[1];return s;},{})

How to identify object types in java

You can compare class tokens to each other, so you could use value.getClass() == Integer.class. However, the simpler and more canonical way is to use instanceof :

    if (value instanceof Integer) {
        System.out.println("This is an Integer");
    } else if(value instanceof String) {
        System.out.println("This is a String");
    } else if(value instanceof Float) {
        System.out.println("This is a Float");
    }

Notes:

  • the only difference between the two is that comparing class tokens detects exact matches only, while instanceof C matches for subclasses of C too. However, in this case all the classes listed are final, so they have no subclasses. Thus instanceof is probably fine here.
  • as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.

    System.out.println("This is a(n) " + value.getClass().getSimpleName());
    

Pythonic way to print list items

OP's question is: does something like following exists, if not then why

print(p) for p in myList # doesn't work, OP's intuition

answer is, it does exist which is:

[p for p in myList] #works perfectly

Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this

Export HTML table to pdf using jspdf

Here is working example:

in head

<script type="text/javascript" src="jspdf.debug.js"></script>

script:

<script type="text/javascript">
        function demoFromHTML() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            // source can be HTML-formatted string, or a reference
            // to an actual DOM element from which the text will be scraped.
            source = $('#customers')[0];

            // we support special element handlers. Register them with jQuery-style 
            // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
            // There is no support for any other type of selectors 
            // (class, of compound) at this time.
            specialElementHandlers = {
                // element with id of "bypass" - jQuery style selector
                '#bypassme': function(element, renderer) {
                    // true = "handled elsewhere, bypass text extraction"
                    return true
                }
            };
            margins = {
                top: 80,
                bottom: 60,
                left: 40,
                width: 522
            };
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
            pdf.fromHTML(
                    source, // HTML string or DOM elem ref.
                    margins.left, // x coord
                    margins.top, {// y coord
                        'width': margins.width, // max width of content on PDF
                        'elementHandlers': specialElementHandlers
                    },
            function(dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            }
            , margins);
        }
    </script>

and table:

<div id="customers">
        <table id="tab_customers" class="table table-striped" >
            <colgroup>
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <col width="20%">
            </colgroup>
            <thead>         
                <tr class='warning'>
                    <th>Country</th>
                    <th>Population</th>
                    <th>Date</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Chinna</td>
                    <td>1,363,480,000</td>
                    <td>March 24, 2014</td>
                    <td>19.1</td>
                </tr>
                <tr>
                    <td>India</td>
                    <td>1,241,900,000</td>
                    <td>March 24, 2014</td>
                    <td>17.4</td>
                </tr>
                <tr>
                    <td>United States</td>
                    <td>317,746,000</td>
                    <td>March 24, 2014</td>
                    <td>4.44</td>
                </tr>
                <tr>
                    <td>Indonesia</td>
                    <td>249,866,000</td>
                    <td>July 1, 2013</td>
                    <td>3.49</td>
                </tr>
                <tr>
                    <td>Brazil</td>
                    <td>201,032,714</td>
                    <td>July 1, 2013</td>
                    <td>2.81</td>
                </tr>
            </tbody>
        </table> 
    </div>

and button to run:

<button onclick="javascript:demoFromHTML()">PDF</button>

and working example online:

tabel to pdf jspdf

or try this: HTML Table Export

Capture Signature using HTML5 and iPad

Here's another canvas based version with variable width (based on drawing velocity) curves: demo at http://szimek.github.io/signature_pad and code at https://github.com/szimek/signature_pad.

signature sample

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

If you are using eclipse, you should modify the context.xml, from the server project created in your eclipse package explorer. When using tomcat in eclipse it is the only one valid, the others are ignored or overwriten

Font-awesome, input type 'submit'

Well, technically it's not possible to get :before and :after pseudo elements work on input elements

From W3C:

12.1 The :before and :after pseudo-elements

Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.


So I had a project where I had submit buttons in the form of input tags and for some reason the other developers restricted me to use <button> tags instead of the usual input submit buttons, so I came up with another solution, of wrapping the buttons inside a span set to position: relative; and then absolutely positioning the icon using :after pseudo.

Note: The demo fiddle uses the content code for FontAwesome 3.2.1 so you may need to change the value of content property accordingly.

HTML

<span><input type="submit" value="Send" class="btn btn-default" /></span>

CSS

input[type="submit"] {
    margin: 10px;
    padding-right: 30px;
}

span {
    position: relative;
}

span:after {
    font-family: FontAwesome;
    content: "\f004"; /* Value may need to be changed in newer version of font awesome*/
    font-size: 13px;
    position: absolute;
    right: 20px;
    top: 1px;
    pointer-events: none;
}

Demo

Now here everything is self explanatory here, about one property i.e pointer-events: none;, I've used that because on hovering over the :after pseudo generated content, your button won't click, so using the value of none will force the click action to go pass through that content.

From Mozilla Developer Network :

In addition to indicating that the element is not the target of mouse events, the value none instructs the mouse event to go "through" the element and target whatever is "underneath" that element instead.

Hover the heart font/icon Demo and see what happens if you DON'T use pointer-events: none;

Separators for Navigation

For those using Sass, I have written a mixin for this purpose:

@mixin addSeparator($element, $separator, $padding) {
    #{$element+'+'+$element}:before {
        content: $separator;
        padding: 0 $padding;
    }
}

Example:

@include addSeparator('li', '|', 1em);

Which will give you this:

li+li:before {
  content: "|";
  padding: 0 1em;
}

RESTful web service - how to authenticate requests from other services?

I would use have an application redirect a user to your site with an application id parameter, once the user approves the request generate a unique token that is used by the other app for authentication. This way the other applications are not handling user credentials and other applications can be added, removed and managed by users. Foursquare and a few other sites authenticate this way and its very easy to implement as the other application.

How to put labels over geom_bar in R with ggplot2

As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:

dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))

So that the x variable matches the corresponding variable in df, and so on. Then you simply include it using geom_text:

ggplot(df) + geom_bar(aes(x,fill=x)) + 
    geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
    opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),legend.title=theme_blank(),
        axis.title.y=theme_blank())

This example will plot just the percentages, but you can paste together the counts as well via something like this:

dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")

Note that in the current version of ggplot2, opts is deprecated, so we would use theme and element_blank now.

this.getClass().getClassLoader().getResource("...") and NullPointerException

I had the same issue with the following conditions:

  • The resource files are in the same package as the java source files, in the java source folder (src/test/java).
  • I build the project with maven on the command line and the build failed on the tests with the NullPointerException.
  • The command line build did not copy the resource files to the test-classes folder, which explained the build failure.
  • When going to eclipse after the command line build and rerun the tests in eclipse I also got the NullPointerException in eclipse.
  • When I cleaned the project (deleted the content of the target folder) and rebuild the project in Eclipse the test did run correctly. This explains why it runs when you start with a clean project.

I fixed this by placing the resource files in the resources folder in test: src/test/resources using the same package structure as the source class.

BTW I used getClass().getResource(...)

delete all from table

There is a mySQL bug report from 2004 that still seems to have some validity. It seems that in 4.x, this was fastest:

DROP table_name
CREATE TABLE table_name

TRUNCATE table_name was DELETE FROM internally back then, providing no performance gain.

This seems to have changed, but only in 5.0.3 and younger. From the bug report:

[11 Jan 2005 16:10] Marko Mäkelä

I've now implemented fast TRUNCATE TABLE, which will hopefully be included in MySQL 5.0.3.

How can I echo a newline in a batch file?

You can use @echo ( @echo + [space] + [insecable space] )

Note: The insecable space can be obtained with Alt+0160

Hope it helps :)

[edit] Hmm you're right, I needed it in a Makefile, it works perfectly in there. I guess my answer is not adapted for batch files... My bad.

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

Scrolling the page to the near by point mentioned in the exception did the trick for me. Below is code snippet:

$wd_host = 'http://localhost:4444/wd/hub';
$capabilities =
    [
        \WebDriverCapabilityType::BROWSER_NAME => 'chrome',
        \WebDriverCapabilityType::PROXY => [
            'proxyType' => 'manual',
            'httpProxy' => PROXY_DOMAIN.':'.PROXY_PORT,
            'sslProxy' => PROXY_DOMAIN.':'.PROXY_PORT,
            'noProxy' =>  PROXY_EXCEPTION // to run locally
        ],
    ];
$webDriver = \RemoteWebDriver::create($wd_host, $capabilities, 250000, 250000);
...........
...........
// Wait for 3 seconds
$webDriver->wait(3);
// Scrolls the page vertically by 70 pixels 
$webDriver->executeScript("window.scrollTo(0, 70);");

NOTE: I use Facebook php webdriver

What is JavaScript garbage collection?

Good quote taken from a blog

The DOM component is "garbage collected", as is the JScript component, which means that if you create an object within either component, and then lose track of that object, it will eventually be cleaned up.

For example:

function makeABigObject() {
var bigArray = new Array(20000);
}

When you call that function, the JScript component creates an object (named bigArray) that is accessible within the function. As soon as the function returns, though, you "lose track" of bigArray because there's no way to refer to it anymore. Well, the JScript component realizes that you've lost track of it, and so bigArray is cleaned up--its memory is reclaimed. The same sort of thing works in the DOM component. If you say document.createElement('div'), or something similar, then the DOM component creates an object for you. Once you lose track of that object somehow, the DOM component will clean up the related.

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

var img = $('<img />', { 
  id: 'Myid',
  src: 'MySrc.gif',
  alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));

How do I run a terminal inside of Vim?

This question is rather old, but for those finding it, there's a new possible solution: Neovim contains a full-fledged, first-class terminal emulator, which does exactly what ConqueTerm tried to. Simply run :term <your command here>.

<C-\><C-n> will exit term mode back to normal-mode. If you're like me and prefer that escape still exit term mode, you can add this to your nvimrc:

tnoremap <ESC><ESC> <C-\><C-N>

And then hitting ESC twice will exit terminal mode back to normal-mode, so you can manipulate the buffer that the still-running command is writing to.

Though keep in mind, as nvim is under heavy development at the time I'm posting this answer, another way to exit terminal mode may be added. As Ctrl+\Ctrl+n switches to normal mode from almost any mode, I don't expect that this answer will become wrong, but be aware that if it doesn't work, this answer might be out of date.

https://github.com/neovim/neovim

Is there a way to make mv create the directory to be moved to if it doesn't exist?

Sillier, but working way:

mkdir -p $2
rmdir $2
mv $1 $2

Make the directory with mkdir -p including a temporary directory that is shares the destination file name, then remove that file name directory with a simple rmdir, then move your file to its new destination. I think answer using dirname is probably the best though.

Remove all items from RecyclerView

For my case adding an empty list did the job.

List<Object> data = new ArrayList<>();
adapter.setData(data);
adapter.notifyDataSetChanged();

How to create <input type=“text”/> dynamically

Maybe the method document.createElement(); is what you're looking for.

Python: split a list based on a condition?

good.append(x) if x in goodvals else bad.append(x)

This elegant and concise answer by @dansalmo showed up buried in the comments, so I'm just reposting it here as an answer so it can get the prominence it deserves, especially for new readers.

Complete example:

good, bad = [], []
for x in my_list:
    good.append(x) if x in goodvals else bad.append(x)

Scraping html tables into R data frames using the XML package

…or a shorter try:

library(XML)
library(RCurl)
library(rlist)
theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))

the picked table is the longest one on the page

tables[[which.max(n.rows)]]

Entity Framework: There is already an open DataReader associated with this Command

Alternatively to using MARS (MultipleActiveResultSets) you can write your code so you dont open multiple result sets.

What you can do is to retrieve the data to memory, that way you will not have the reader open. It is often caused by iterating through a resultset while trying to open another result set.

Sample Code:

public class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

public class Blog
{
    public int BlogID { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostID { get; set; }
    public virtual Blog Blog { get; set; }
    public string Text { get; set; }
}

Lets say you are doing a lookup in your database containing these:

var context = new MyContext();

//here we have one resultset
var largeBlogs = context.Blogs.Where(b => b.Posts.Count > 5); 

foreach (var blog in largeBlogs) //we use the result set here
{
     //here we try to get another result set while we are still reading the above set.
    var postsWithImportantText = blog.Posts.Where(p=>p.Text.Contains("Important Text"));
}

We can do a simple solution to this by adding .ToList() like this:

var largeBlogs = context.Blogs.Where(b => b.Posts.Count > 5).ToList();

This forces entityframework to load the list into memory, thus when we iterate though it in the foreach loop it is no longer using the data reader to open the list, it is instead in memory.

I realize that this might not be desired if you want to lazyload some properties for example. This is mostly an example that hopefully explains how/why you might get this problem, so you can make decisions accordingly

flow 2 columns of text automatically with CSS

Here is an example of a simple Two-column class:

.two-col {
       -moz-column-count: 2;
       -moz-column-gap: 20px;
       -webkit-column-count: 2;
       -webkit-column-gap: 20px;
}

Of which you would apply to a block of text like so:

<p class="two-col">Text</p>

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

There are subtle and not-so-subtle differences between generic and non-generic collections. They merely use different underlying data structures. For example, Hashtable guarantees one-writer-many-readers without sync. Dictionary does not.

Maven skip tests

I have another approach for Intellij users, and it is working very fine for me:

  1. Click on the "Skip Test" button

enter image description here

  1. Hold the "CTRL" button
  2. Select "clean" and "install"

enter image description here

  1. Click on the "Run" button in the maven pannel

enter image description here

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

Me too faced the same issue. But the problem was I forgot to list the module in the list of modules the ng-app depends on.

Split a string into array in Perl

You already have multiple answers to your question, but I would like to add another minor one here that might help to add something.

To view data structures in Perl you can use Data::Dumper. To print a string you can use say, which adds a newline character "\n" after every call instead of adding it explicitly.

I usually use \s which matches a whitespace character. If you add + it matches one or more whitespace characters. You can read more about it here perlre.

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

use feature 'say';

my $line = "file1.gz file2.gz file3.gz";
my @abc  = split /\s+/, $line;

print Dumper \@abc;
say for @abc;

Remove numbers from string sql server

This one works for me

CREATE Function [dbo].[RemoveNumericCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @NumRange as varchar(50) = '%[0-9]%'
    While PatIndex(@NumRange, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@NumRange, @Temp), 1, '')

    Return @Temp
End

and you can use it like so

SELECT dbo.[RemoveNumericCharacters](Name) FROM TARGET_TABLE

java.io.IOException: Server returned HTTP response code: 500

This Status Code 500 is an Internal Server Error. This code indicates that a part of the server (for example, a CGI program) has crashed or encountered a configuration error.

i think the problem does'nt lie on your side, but rather on the side of the Http server. the resources you used to access may have been moved or get corrupted, or its configuration just may have altered or spoiled

Difference between onCreate() and onStart()?

Take a look on life cycle of Activity enter image description here

Where

***onCreate()***

Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().

***onStart()***

Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

And you can write your simple class to take a look when these methods call

public class TestActivity extends Activity {
    /** Called when the activity is first created. */

    private final static String TAG = "TestActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.i(TAG, "On Create .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onDestroy()
    */
    @Override
    protected void onDestroy() { 
        super.onDestroy();
        Log.i(TAG, "On Destroy .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onPause()
    */
    @Override
    protected void onPause() { 
        super.onPause();
        Log.i(TAG, "On Pause .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onRestart()
    */
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "On Restart .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onResume()
    */
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "On Resume .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onStart()
    */
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "On Start .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onStop()
    */
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "On Stop .....");
    }
}

Hope this will clear your confusion.

And take a look here for details.

Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.

How can I check for an empty/undefined/null string in JavaScript?

You can easily add it to native String object in JavaScript and reuse it over and over...
Something simple like below code can do the job for you if you want to check '' empty strings:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
  return !(!!this.length);
}

Otherwise if you'd like to check both '' empty string and ' ' with space, you can do that by just adding trim(), something like the code below:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
   return !(!!this.trim().length);
}

and you can call it this way:

''.isEmpty(); //return true
'alireza'.isEmpty(); //return false

How do I see what character set a MySQL database / table / column is?

I always just look at SHOW CREATE TABLE mydatabase.mytable.

For the database, it appears you need to look at SELECT DEFAULT_CHARACTER_SET_NAME FROM information_schema.SCHEMATA.

Alternating Row Colors in Bootstrap 3 - No Table

There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type (or :nth-child -- either would work in this case.)

Smallest viewport:

@media (max-width:$smallest-breakpoint) {

  .row div {
     background: #eee;
   }

  .row div:nth-of-type(2n) {
     background: #fff;
   }

}

Medium viewport:

@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
    background: #fff;
  }

}

Largest viewport:

@media (min-width:$mid-breakpoint) and (max-width:9999px) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(6n+4), 
  .row div:nth-of-type(6n+5), 
  .row div:nth-of-type(6n+6) {
      background: #fff;
  }
}

Working fiddle here

How to concatenate int values in java?

How about not using strings at all...

This should work for any number of digits...

int[] nums = {1, 0, 2, 2, 1};

int retval = 0;

for (int digit : nums)
{
    retval *= 10;
    retval += digit;
}

System.out.println("Return value is: " + retval);

Serialize Property as Xml Attribute in Element

You will need wrapper classes:

public class SomeIntInfo
{
    [XmlAttribute]
    public int Value { get; set; }
}

public class SomeStringInfo
{
    [XmlAttribute]
    public string Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeStringInfo SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeIntInfo SomeInfo { get; set; }
}

or a more generic approach if you prefer:

public class SomeInfo<T>
{
    [XmlAttribute]
    public T Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeInfo<string> SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeInfo<int> SomeInfo { get; set; }
}

And then:

class Program
{
    static void Main()
    {
        var model = new SomeModel
        {
            SomeString = new SomeInfo<string> { Value = "testData" },
            SomeInfo = new SomeInfo<int> { Value = 5 }
        };
        var serializer = new XmlSerializer(model.GetType());
        serializer.Serialize(Console.Out, model);
    }
}

will produce:

<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomeStringElementName Value="testData" />
  <SomeInfoElementName Value="5" />
</SomeModel>

How can I set a UITableView to grouped style

For set grouped style in ui itself:-Select the TableView then change the "style"(in attribute inspector)) from plain to Grouped.

How to send HTML email using linux command line

With heirloom-mailx you can change sendmail program to your hook script, replace headers there and then use sendmail.

The script I use (~/bin/sendmail-hook):

#!/bin/bash

sed '1,/^$/{
s,^\(Content-Type: \).*$,\1text/html; charset=utf-8,g
s,^\(Content-Transfer-Encoding: \).*$,\18bit,g
}' | sendmail $@

This script changes the values in the mail header as follows:

  • Content-Type: to text/html; charset=utf-8
  • Content-Transfer-Encoding: to 8bit (not sure if this is really needed).

To send HTML email:

mail -Ssendmail='~/bin/sendmail-hook' \
    -s "Built notification" [email protected] < /var/www/report.csv

Convert INT to VARCHAR SQL

SELECT cast(CAST([field_name] AS bigint) as nvarchar(255)) FROM table_name

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

Multiple Approch can be applied:

  • Class Based Approch: use local state and define existing field with default value:
constructor(props) {
    super(props);
    this.state = {
      value:''
    }
  }
<input type='text'
                  name='firstName'
                  value={this.state.value}
                  className="col-12"
                  onChange={this.onChange}
                  placeholder='Enter First name' />

  • Using Hooks React > 16.8 in functional style components:
[value, setValue] = useState('');
<input type='text'
                  name='firstName'
                  value={value}
                  className="col-12"
                  onChange={this.onChange}
                  placeholder='Enter First name' />

  • If Using propTypes and providing Default Value for propTypes in case of HOC component in functional style.
 HOC.propTypes = {
    value       : PropTypes.string
  }
  HOC.efaultProps = {
    value: ''
  }

function HOC (){

  return (<input type='text'
                  name='firstName'
                  value={this.props.value}
                  className="col-12"
                  onChange={this.onChange}
                  placeholder='Enter First name' />)

}


Show ImageView programmatically

How to export data to an excel file using PHPExcel

Try the below complete example for the same

<?php
  $objPHPExcel = new PHPExcel();
  $query1 = "SELECT * FROM employee";
  $exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
  $serialnumber=0;
  //Set header with temp array
  $tmparray =array("Sr.Number","Employee Login","Employee Name");
  //take new main array and set header array in it.
  $sheet =array($tmparray);

  while ($res1 = mysql_fetch_array($exec1))
  {
    $tmparray =array();
    $serialnumber = $serialnumber + 1;
    array_push($tmparray,$serialnumber);
    $employeelogin = $res1['employeelogin'];
    array_push($tmparray,$employeelogin);
    $employeename = $res1['employeename'];
    array_push($tmparray,$employeename);   
    array_push($sheet,$tmparray);
  }
   header('Content-type: application/vnd.ms-excel');
   header('Content-Disposition: attachment; filename="name.xlsx"');
  $worksheet = $objPHPExcel->getActiveSheet();
  foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
  }

  //make first row bold
  $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
  $objPHPExcel->setActiveSheetIndex(0);
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>

Make HTML5 video poster be same size as video itself

I had a similar issue and just fixed it by creating an image with the same aspect ratio as my video (16:9). My width is set to 100% on the video tag and now the image (320 x 180) fits perfectly. Hope that helps!

Initialize a byte array to a certain value, other than the default null?

If you need to initialise a small array you can use:

byte[] smallArray = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };

If you have a larger array, then you could use:

byte[] bitBiggerArray Enumerable.Repeat(0x20, 7000).ToArray();

Which is simple, and easy for the next guy/girl to read. And will be fast enough 99.9% of the time. (Normally will be the BestOption™)

However if you really really need super speed, calling out to the optimized memset method, using P/invoke, is for you: (Here wrapped up in a nice to use class)

public static class Superfast
{
    [DllImport("msvcrt.dll",
              EntryPoint = "memset",
              CallingConvention = CallingConvention.Cdecl,
              SetLastError = false)]
    private static extern IntPtr MemSet(IntPtr dest, int c, int count);

    //If you need super speed, calling out to M$ memset optimized method using P/invoke
    public static byte[] InitByteArray(byte fillWith, int size)
    {
        byte[] arrayBytes = new byte[size];
        GCHandle gch = GCHandle.Alloc(arrayBytes, GCHandleType.Pinned);
        MemSet(gch.AddrOfPinnedObject(), fillWith, arrayBytes.Length);
        gch.Free();
        return arrayBytes;
    }
}

Usage:

byte[] oneofManyBigArrays =  Superfast.InitByteArray(0x20,700000);

DateTime vs DateTimeOffset

There's a few places where DateTimeOffset makes sense. One is when you're dealing with recurring events and daylight savings time. Let's say I want to set an alarm to go off at 9am every day. If I use the "store as UTC, display as local time" rule, then the alarm will be going off at a different time when daylight savings time is in effect.

There are probably others, but the above example is actually one that I've run into in the past (this was before the addition of DateTimeOffset to the BCL - my solution at the time was to explicitly store the time in the local timezone, and save the timezone information along side it: basically what DateTimeOffset does internally).

Is there a Social Security Number reserved for testing/examples?

Please look at this document

http://www.socialsecurity.gov/employer/randomization.html

The SSA is instituting a new policy the where all previously unused sequences are will be available for use.

Goes into affect June 25, 2011.

Taken from the new FAQ:

What changes will result from randomization?

The SSA will eliminate the geographical significance of the first three digits of the SSN, currently referred to as the area number, by no longer allocating the area numbers for assignment to individuals in specific states. The significance of the highest group number (the fourth and fifth digits of the SSN) for validation purposes will be eliminated. Randomization will also introduce previously unassigned area numbers for assignment excluding area numbers 000, 666 and 900-999. Top

Will SSN randomization assign group number (the fourth and fifth digits of the SSN) 00 or serial number (the last four digits of the SSN) 0000?

SSN randomization will not assign group number 00 or serial number 0000. SSNs containing group number 00 or serial number 0000 will continue to be invalid.

How to check type of object in Python?

What type() means:

I think your question is a bit more general than I originally thought. type() with one argument returns the type or class of the object. So if you have a = 'abc' and use type(a) this returns str because the variable a is a string. If b = 10, type(b) returns int.

See also python documentation on type().


For comparisons:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference (to check if it is a h5py.h5r.Reference instance).

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference) but then also subclasses will evaluate to True.

If you want to print the class use print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v) or isinstance(v, other_v.__class__).

Disabling buttons on react native

TouchableOpacity extents TouchableWithoutFeedback, so you can just use the disabled property :

<TouchableOpacity disabled={true}>
  <Text>I'm disabled</Text>
</TouchableOpacity>

React Native TouchableWithoutFeedback #disabled documentation

The new Pressable API has a disabled option too :

<Pressable disable={true}>
  {({ pressed }) => (
    <Text>I'm disabled</Text>
  )}
</Pressable>

Disabling Chrome Autofill

Pure HTML solution:

(No javascript needed, no css needed and no hidden inputs needed)

<form autoComplete="new-password" ... >
        <input name="myInput" type="text" autoComplete="off" id="myInput" placeholder="Search field" />
</form>

Notes:

  • form does not necessarily need to be the direct parent of the input element
  • input needs a name attribute

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

is soft link of

/etc/ssl/openssl.cnf

You can see that using long list (ls -l) on the /usr/local/ssl/ directory where you will find

lrwxrwxrwx 1 root root 20 Mar 1 05:15 openssl.cnf -> /etc/ssl/openssl.cnf

String variable interpolation Java

You can use Kotlin, the Super (cede of) Java for JVM, it has a nice way of interpolating strings like those of ES5, Ruby and Python.

class Client(val firstName: String, val lastName: String) {
    val fullName = "$firstName $lastName"
}

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

This error occurs because you are using a normal string as a path. You can use one of the three following solutions to fix your problem:

1: Just put r before your normal string it converts normal string to raw string:

pandas.read_csv(r"C:\Users\DeePak\Desktop\myac.csv")

2:

pandas.read_csv("C:/Users/DeePak/Desktop/myac.csv")

3:

pandas.read_csv("C:\\Users\\DeePak\\Desktop\\myac.csv")

Where does Console.WriteLine go in ASP.NET?

There simply is no console listening by default. Running in debug mode there is a console attached, but in a production environment it is as you suspected, the message just doesn't go anywhere because nothing is listening.

How to convert WebResponse.GetResponseStream return into a string?

As @Heinzi mentioned the character set of the response should be used.

var encoding = response.CharacterSet == ""
    ? Encoding.UTF8
    : Encoding.GetEncoding(response.CharacterSet);

using (var stream = response.GetResponseStream())
{
    var reader = new StreamReader(stream, encoding);
    var responseString = reader.ReadToEnd();
}

Thymeleaf: Concatenation - Could not parse as expression

You can concat many kind of expression by sorrounding your simple/complex expression between || characters:

<p th:text="|${bean.field} ! ${bean.field}|">Static content</p>

What are invalid characters in XML

In summary, valid characters in the text are:

  • tab, line-feed and carriage-return.
  • all non-control characters are valid except & and <.
  • > is not valid if following ]].

Sections 2.2 and 2.4 of the XML specification provide the answer in detail:

Characters

Legal characters are tab, carriage return, line feed, and the legal characters of Unicode and ISO/IEC 10646

Character data

The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " & " and " < " respectively. The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, be escaped using either " > " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.

can't multiply sequence by non-int of type 'float'

In this line:

fund = fund * (1 + 0.01 * growthRates) + depositPerYear

I think you mean this:

fund = fund * (1 + 0.01 * i) + depositPerYear

When you try to multiply a float by growthRates (which is a list), you get that error.

Cloning an Object in Node.js

Simple and the fastest way to clone an Object in NodeJS is to use Object.keys( obj ) method

var a = {"a": "a11", "b": "avc"};
var b;

for(var keys = Object.keys(a), l = keys.length; l; --l)
{
   b[ keys[l-1] ] = a[ keys[l-1] ];
}
b.a = 0;

console.log("a: " + JSON.stringify(a)); // LOG: a: {"a":"a11","b":"avc"} 
console.log("b: " + JSON.stringify(b)); // LOG: b: {"a":0,"b":"avc"}

The method Object.keys requires JavaScript 1.8.5; nodeJS v0.4.11 supports this method

but of course for nested objects need to implement recursive func


Other solution is to use native JSON (Implemented in JavaScript 1.7), but it's much slower (~10 times slower) than previous one

var a = {"a": i, "b": i*i};
var b = JSON.parse(JSON.stringify(a));
b.a = 0;

Bootstrap full responsive navbar with logo or brand name text

I checked and it worked for me.

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" style="margin-top:100px;"><!--style with margin-top according to your need-->
        <ul class="nav navbar-nav navbar-right">
            <li><a href="#">About</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </div>

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use a simple regex like this:

public static string StripHTML(string input)
{
   return Regex.Replace(input, "<.*?>", String.Empty);
}

Be aware that this solution has its own flaw. See Remove HTML tags in String for more information (especially the comments of @mehaase)

Another solution would be to use the HTML Agility Pack.
You can find an example using the library here: HTML agility pack - removing unwanted tags without removing content?

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

I agree that setting a system setting may be a bit much, but the shortcut requiring a hardcoded path is not ideal. A bat file actually solves the problem nicely

RunMyPowershellScript.bat

 start powershell -command "& '.\MyPowershellScript.ps1' -MyArguments blah"

This batch file can now be double clicked on, shortcuts can be easily created to the batch file, and the script can be deployed to any folder.

jQuery won't parse my JSON from AJAX query

If jQuery's error handler is being called and the XHR object contains "parser error", that's probably a parser error coming back from the server.

Is your multiple result scenario when you call the service without a parameter, but it's breaking when you try to supply a parameter to retrieve the single record?

What backend are you returning this from?

On ASMX services, for example, that's often the case when parameters are supplied to jQuery as a JSON object instead of a JSON string. If you provide jQuery an actual JSON object for its "data" parameter, it will serialize that into standard & delimited k,v pairs instead of sending it as JSON.

How to set tint for an image view programmatically in android?

Beginning in Lollipop, there is a method called ImageView#setImageTintList() that you can use... the advantage being that it takes a ColorStateList as opposed to just a single color, thus making the image's tint state-aware.

On pre-Lollipop devices, you can get the same behavior by tinting the drawable and then setting it as the ImageView's image drawable:

ColorStateList csl = AppCompatResources.getColorStateList(context, R.color.my_clr_selector);
Drawable drawable = DrawableCompat.wrap(imageView.getDrawable());
DrawableCompat.setTintList(drawable, csl);
imageView.setImageDrawable(drawable);

How do I get monitor resolution in Python?

To get bits per pixel:

import ctypes
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32

screensize = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
print "screensize =%s"%(str(screensize))
dc = user32.GetDC(None);

screensize = (gdi32.GetDeviceCaps(dc,8), gdi32.GetDeviceCaps(dc,10), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))
screensize = (gdi32.GetDeviceCaps(dc,118), gdi32.GetDeviceCaps(dc,117), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))

parameters in gdi32:

#/// Vertical height of entire desktop in pixels
#DESKTOPVERTRES = 117,
#/// Horizontal width of entire desktop in pixels
#DESKTOPHORZRES = 118,
#/// Horizontal width in pixels
#HORZRES = 8,
#/// Vertical height in pixels
#VERTRES = 10,
#/// Number of bits per pixel
#BITSPIXEL = 12,

How to see the proxy settings on windows?

You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:

netstat

and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.

[see also https://stackoverflow.com/a/8161865/3195477]

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player);     // I get the error here.

void showInventory(player& obj) {   // By Johnny :D

this means that player is an datatype and showInventory expect an referance to an variable of type player.

so the correct code will be

  void showInventory(player& obj) {   // By Johnny :D
    for(int i = 0; i < 20; i++) {
        std::cout << "\nINVENTORY:\n" + obj.getItem(i);
        i++;
        std::cout << "\t\t\t" + obj.getItem(i) + "\n";
        i++;
    }
    }

players myPlayers[10];

    std::string toDo() //BY KEATON
    {
    std::string commands[5] =   // This is the valid list of commands.
        {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return NULL;
    }
    else if(ans == commands[1]) {
        showInventory(myPlayers[0]);     // or any other index,also is not necessary to have an array
        return NULL;
    }

}

How to set a value of a variable inside a template code?

This is not a good idea in general. Do all the logic in python and pass the data to template for displaying. Template should be as simple as possible to ensure those working on the design can focus on design rather than worry about the logic.

To give an example, if you need some derived information within a template, it is better to get it into a variable in the python code and then pass it along to the template.

Test if string begins with a string?

The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.

The expensive regex method and the css attribute selector with starts with ^ operator

Option Explicit

Public Sub test()

    Debug.Print StartWithSubString("ab", "abc,d")

End Sub

Regex:

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft VBScript Regular Expressions
    Dim re As VBScript_RegExp_55.RegExp
    Set re = New VBScript_RegExp_55.RegExp

    re.Pattern = "^" & substring

    StartWithSubString = re.test(testString)

End Function

Css attribute selector with starts with operator

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft HTML Object Library
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument

    html.body.innerHTML = "<div test=""" & testString & """></div>"

    StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0

End Function

What are all possible pos tags of NLTK?

The tag set depends on the corpus that was used to train the tagger. The default tagger of nltk.pos_tag() uses the Penn Treebank Tag Set.

In NLTK 2, you could check which tagger is the default tagger as follows:

import nltk
nltk.tag._POS_TAGGER
>>> 'taggers/maxent_treebank_pos_tagger/english.pickle'

That means that it's a Maximum Entropy tagger trained on the Treebank corpus.

nltk.tag._POS_TAGGER does not exist anymore in NLTK 3 but the documentation states that the off-the-shelf tagger still uses the Penn Treebank tagset.

Splitting comma separated string in a PL/SQL stored proc

Many good solutions have been provided already. However, if he text is provided in a very simple comma delimited format or similar, and speed is of importance, then I have for you a solution with a TABLE function (in PL/SQL). I have also provided a rundown of some other solutions.

Please see more on the Blog Entry on Parsing a CSV into multiple columns.