Programs & Examples On #Shell icons

How can I get the current array index in a foreach loop?

$i = 0;
foreach ($arr as $key => $val) {
  if ($i === 0) {
    // first index
  }
  // current index is $i

  $i++;
}

How to add content to html body using JS?

Try the following syntax:

document.body.innerHTML += "<p>My new content</p>";

Remove everything after a certain character

If you also want to keep "?" and just remove everything after that particular character, you can do:

var str = "/Controller/Action?id=11112&value=4444",
    stripped = str.substring(0, str.indexOf('?') + '?'.length);

// output: /Controller/Action?

jQuery convert line breaks to br (nl2br equivalent)

I wrote a little jQuery extension for this:

$.fn.nl2brText = function (sText) {
    var bReturnValue = 'undefined' == typeof sText;
    if(bReturnValue) {
        sText = $('<pre>').html(this.html().replace(/<br[^>]*>/i, '\n')).text();
    }
    var aElms = [];
    sText.split(/\r\n|\r|\n/).forEach(function(sSubstring) {
        if(aElms.length) {
            aElms.push(document.createElement('br'));
        }
        aElms.push(document.createTextNode(sSubstring));
    });
    var $aElms = $(aElms);
    if(bReturnValue) {
        return $aElms;
    }
    return this.empty().append($aElms);
};

How to prevent scanf causing a buffer overflow in C?

If you are using gcc, you can use the GNU-extension a specifier to have scanf() allocate memory for you to hold the input:

int main()
{
  char *str = NULL;

  scanf ("%as", &str);
  if (str) {
      printf("\"%s\"\n", str);
      free(str);
  }
  return 0;
}

Edit: As Jonathan pointed out, you should consult the scanf man pages as the specifier might be different (%m) and you might need to enable certain defines when compiling.

php check if array contains all array values from another array

The previous answers are all doing more work than they need to. Just use array_diff. This is the simplest way to do it:

$containsAllValues = !array_diff($search_this, $all);

That's all you have to do.

TypeError: 'str' does not support the buffer interface

For Django in django.test.TestCase unit testing, I changed my Python2 syntax:

def test_view(self):
    response = self.client.get(reverse('myview'))
    self.assertIn(str(self.obj.id), response.content)
    ...

To use the Python3 .decode('utf8') syntax:

def test_view(self):
    response = self.client.get(reverse('myview'))
    self.assertIn(str(self.obj.id), response.content.decode('utf8'))
    ...

Navigation Drawer (Google+ vs. YouTube)

Personally I like the navigationDrawer in Google Drive official app. It just works and works great. I agree that the navigation drawer shouldn't move the action bar because is the key point to open and close the navigation drawer.

If you are still trying to get that behavior I recently create a project Called SherlockNavigationDrawer and as you may expect is the implementation of the Navigation Drawer with ActionBarSherlock and works for pre Honeycomb devices. Check it:

SherlockNavigationDrawer github

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

How to check the Angular version?

You should check package.json file in the project. There you will see all packages installed and versions of those packages.

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

When you define varchar etc without a length, the default is 1.

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

So, if you expect 400 bytes in the @trackingItems1 column from stock, use nvarchar(400).

Otherwise, you are trying to fit >1 character into nvarchar(1) = fail

As a comment, this is bad use of table value function too because it is "multi statement". It can be written like this and it will run better

ALTER FUNCTION [dbo].[testing1](@price int)
RETURNS
AS
   SELECT ta.item, ta.warehouse, ta.price 
   FROM   stock ta
   WHERE  ta.price >= @price;

Of course, you could just use a normal SELECT statement..

How to SUM and SUBTRACT using SQL?

I have tried this kind of technique. Multiply the subtract from data by (-1) and then sum() the both amount then you will get subtracted amount.

-- Loan Outstanding
    select  'Loan Outstanding' as Particular, sum(Unit), sum(UptoLastYear), sum(ThisYear), sum(UptoThisYear)
    from
    (
        select 
            sum(laod.dr) as Unit,
            sum(if(lao.created_at <= '2014-01-01',laod.dr,0)) as UptoLastYear,
            sum(if(lao.created_at between '2014-01-01' and '2015-07-14',laod.dr,0)) as ThisYear,
            sum(if(lao.created_at <= '2015-07-14',laod.dr,0)) as UptoThisYear
        from loan_account_opening as lao
        inner join loan_account_opening_detail as laod on lao.id=laod.loan_account_opening_id
        where lao.organization = 3
        union
        select
            sum(lr.installment)*-1 as Unit,
            sum(if(lr.created_at <= '2014-01-01',lr.installment,0))*-1 as UptoLastYear,
            sum(if(lr.created_at between '2014-01-01' and '2015-07-14',lr.installment,0))*-1 as ThisYear,
            sum(if(lr.created_at <= '2015-07-14',lr.installment,0))*-1 as UptoThisYear
        from loan_recovery as lr
        inner join loan_account_opening as lo on lr.loan_account_opening_id=lo.id
        where lo.organization = 3
    ) as t3

Reset push notification settings for app

I recently ran into the similar issue with react-native application. iPhone OS version was 13.1 I uninstalled the application and tried to install the app and noticed both location and notification permissions were not prompted.

On checking the settings, I could see my application was enabled for location(from previous installation) however there was no corresponding entry against the notification Tried uninstalling and rebooting without setting the time, it didn't work. Btw, I also tried to download the Appstore app, still same behavior.

The issue was resolved only after setting the device time.

Xcode 4 - "Archive" is greyed out?

I fixed this today...sort of. Although the archives still don't show up anywhere. But I got the Archive option back by going into Build Settings for the project and re-assigning my certs under "Code Signing Identity" for each build. They seemed to have gotten reset to something else when imported my 3.X project to 4.

I also used the instructions found here:

http://developer.apple.com/library/mac/#documentation/ToolsLanguages/Conceptual/Xcode4UserGuide/DistApps/DistApps.html#//apple_ref/doc/uid/TP40010215-CH11-DontLinkElementID_69

But I still can't get the actual archives to show up in Organizer (even though the files exist)

How to set a cell to NaN in a pandas dataframe

You can try these snippets.

In [16]:mydata = {'x' : [10, 50, 18, 32, 47, 20], 'y' : ['12', '11', 'N/A', '13', '15', 'N/A']}
In [17]:df=pd.DataFrame(mydata)

In [18]:df.y[df.y=="N/A"]=np.nan

Out[19]:df 
    x    y
0  10   12
1  50   11
2  18  NaN
3  32   13
4  47   15
5  20  NaN

PHP : send mail in localhost

It is configured to use localhost:25 for the mail server.

The error message says that it can't connect to localhost:25.

Therefore you have two options:

  1. Install / Properly configure an SMTP server on localhost port 25
  2. Change the configuration to point to some other SMTP server that you can connect to

Converting unix time into date-time via excel

If you have ########, it can help you:

=((A1/1000+1*3600)/86400+25569)

+1*3600 is GTM+1

Is there a kind of Firebug or JavaScript console debug for Android?

"USB Web debugging" is one option

"printing it on the screen" another.

But I prefer remote debugging through 'adobe edge inspect' formally known as adobe shadow. It uses weinre internally (=WEb INspect REmote)

You just install it + a small plugin in the browser (Chrome) and a free app you can download in the play-store. Then you have all the tools like the Chrome Development tools.

It has also support for iOS and Kindle Fire

Update

Like Chris noticed, you have to pay a subscription to use edge inspect. A cheap alternative is to use weinre directly, it's the base of edge inspect. Here's an article about how to set it up.

What is the best way to left align and right align two div tags?

You can do it with few lines of CSS code. You can align all div's which you want to appear next to each other to right.

<div class="div_r">First Element</div>
<div class="div_r">Second Element</div>

<style>
.div_r{
float:right;
color:red;
}
</style>

Get the selected option id with jQuery

Th easiest way to this is var id = $(this).val(); from inside an event like on change.

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.

  1. Remove the update on your component that is not working
  2. Put a temporary component with a bogus update within the component you were trying to update
  3. hit the page, the servlet exception error will tell you the correct client Id you need to reference.
  4. Remove bogus component and put correct clientId in the original update

Here is code example as my words may not describe it best.

<p:tabView id="tabs">
    <p:tab id="search" title="Search">                        
        <h:form id="insTable">
            <p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
                <p:column>
                    <p:commandLink id="select"

Remove the failing update within this component

 oncomplete="dlg.show()">
                        <f:setPropertyActionListener value="#{lndInstrument}" 
                                        target="#{instrumentBean.selectedInstrument}" />
                        <h:outputText value="#{lndInstrument.name}" />
                    </p:commandLink>                                    
                </p:column>
            </p:dataTable>
            <p:dialog id="dlg" modal="true" widgetVar="dlg">
                <h:panelGrid id="display">

Add a component within the component of the id you are trying to update using an update that will fail

   <p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>

                    <h:outputText value="Name:" />
                    <h:outputText value="#{instrumentBean.selectedInstrument.name}" />
                </h:panelGrid>
            </p:dialog>                            
        </h:form>
    </p:tab>
</p:tabView>

Hit this page and view the error. The error is: javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from tabs:insTable: BogusButton

So the correct clientId to use would then be the bold plus the id of the target container (display in this case)

tabs:insTable:display

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

Having just installed the XAMPP today, I decided to use a different default port for mysql, which was horrible. Make sure to add these lines to the phpMyAdmin config.inc.php:

$cfg['Servers'][$i]['host'] = 'localhost';

$cfg['Servers'][$i]['port'] = 'port';`

Subtracting two lists in Python

To prove jkp's point that 'anything on one line will probably be helishly complex to understand', I created a one-liner. Please do not mod me down because I understand this is not a solution that you should actually use. It is just for demonstrational purposes.

The idea is to add the values in a one by one, as long as the total times you have added that value does is smaller than the total number of times this value is in a minus the number of times it is in b:

[ value for counter,value in enumerate(a) if a.count(value) >= b.count(value) + a[counter:].count(value) ]

The horror! But perhaps someone can improve on it? Is it even bug free?

Edit: Seeing Devin Jeanpierre comment about using a dictionary datastructure, I came up with this oneliner:

sum([ [value]*count for value,count in {value:a.count(value)-b.count(value) for value in set(a)}.items() ], [])

Better, but still unreadable.

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Bootstrap: How to center align content inside column?

Want to center an image? Very easy, Bootstrap comes with two classes, .center-block and text-center.

Use the former in the case of your image being a BLOCK element, for example, adding img-responsive class to your img makes the img a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.

Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.

 // In case you're dealing with a block element apply this to the element itself 
.center-block {
   margin-left:auto;
   margin-right:auto;
   display:block;
}

// In case you're dealing with a inline element apply this to the parent 
.text-center {
   text-align:center
}

What are the differences between the different saving methods in Hibernate?

+-------------------------------------------------------------------------------+
¦    METHOD    ¦            TRANSIENT          ¦            DETACHED            ¦
¦--------------+-------------------------------+--------------------------------¦
¦              ¦       sets id if doesn't      ¦   sets new id even if object   ¦
¦    save()    ¦     exist, persists to db,    ¦    already has it, persists    ¦
¦              ¦    returns attached object    ¦ to DB, returns attached object ¦
¦--------------+-------------------------------+--------------------------------¦
¦              ¦       sets id on object       ¦             throws             ¦
¦   persist()  ¦     persists object to DB     ¦       PersistenceException     ¦
¦              ¦                               ¦                                ¦
¦--------------+-------------------------------+--------------------------------¦
¦              ¦                               ¦                                ¦
¦   update()   ¦           Exception           ¦     persists and reattaches    ¦
¦              ¦                               ¦                                ¦
¦--------------+-------------------------------+--------------------------------¦
¦              ¦  copy the state of object in  ¦    copy the state of obj in    ¦
¦    merge()   ¦     DB, doesn't attach it,    ¦      DB, doesn't attach it,    ¦
¦              ¦    returns attached object    ¦     returns attached object    ¦
¦--------------+-------------------------------+--------------------------------¦
¦              ¦                               ¦                                ¦
¦saveOrUpdate()¦           as save()           ¦            as update()         ¦
¦              ¦                               ¦                                ¦
+-------------------------------------------------------------------------------+

How can I connect to MySQL in Python 3 on Windows?

I'm using cymysql with python3 on a raspberry pi I simply installed by: sudo pip3 install cython sudo pip3 install cymysql where cython is not necessary but should make cymysql faster

So far it works like a charm and very similar to MySQLdb

VBA: Convert Text to Number

Use the below function (changing [E:E] to the appropriate range for your needs) to circumvent this issue (or change to any other format such as "mm/dd/yyyy"):

[E:E].Select
With Selection
    .NumberFormat = "General"
    .Value = .Value
End With

P.S. In my experience, this VBA solution works SIGNIFICANTLY faster on large data sets and is less likely to crash Excel than using the 'warning box' method.

Could not find an implementation of the query pattern

Make sure these references are included:

  • System.Data.Linq
  • System.Data.Entity

Then add the using statement

using System.Linq;

How to fill color in a cell in VBA?

You need to use cell.Text = "#N/A" instead of cell.Value = "#N/A". The error in the cell is actually just text stored in the cell.

How do I change a single value in a data.frame?

In RStudio you can write directly in a cell. Suppose your data.frame is called myDataFrame and the row and column are called columnName and rowName. Then the code would look like:

myDataFrame["rowName", "columnName"] <- value

Hope that helps!

How to copy a java.util.List into another java.util.List

originalArrayList.addAll(copyArrayofList);

Please keep on mind whenever using the addAll() method for copy, the contents of both the array lists (originalArrayList and copyArrayofList) references to the same objects will be added to the list so if you modify any one of them then copyArrayofList also will also reflect the same change.

If you don't want side effect then you need to copy each of element from the originalArrayList to the copyArrayofList, like using a for or while loop. for deep copy you can use below code snippet.

but one more thing you need to do, implement the Cloneable interface and override the clone() method for SomeBean class.

public static List<SomeBean> cloneList(List<SomeBean> originalArrayList) {
    List<SomeBean> copyArrayofList = new ArrayList<SomeBean>(list.size());
    for (SomeBean item : list) copyArrayofList.add(item.clone());
    return clone;
}

Lining up labels with radio buttons in bootstrap

If you add the 'radio inline' class to the control label in the solution provided by user1938475 it should line up correctly with the other labels. Or if you're only using 'radio' like your 2nd example just include the 'radio' class.

<label class="radio control-label">Some label</label>

OR for 'radio inline'

<label class="radio-inline control-label">Some label</label>

What is EOF in the C programming language?

Couple of typos:

while((c = getchar())!= EOF)

in place of:

while((c = getchar() != EOF))

Also getchar() treats a return key as a valid input, so you need to buffer it too.EOF is a marker to indicate end of input. Generally it is an int with all bits set.


#include <stdio.h>
int main()
{
 int c;
 while((c = getchar())!= EOF)
 {
  if( getchar() == EOF )
    break;
  printf(" %d\n", c);
 }
  printf("%d %u %x- at EOF\n", c , c, c);
}

prints:

49
50
-1 4294967295 ffffffff- at EOF

for input:

1
2
<ctrl-d>

Recursive directory listing in DOS

You can get the parameters you are asking for by typing:

dir /?

For the full list, try:

dir /s /b /a:d

C++ where to initialize static const

Anywhere in one compilation unit (usually a .cpp file) would do:

foo.h

class foo {
    static const string s; // Can never be initialized here.
    static const char* cs; // Same with C strings.

    static const int i = 3; // Integral types can be initialized here (*)...
    static const int j; //     ... OR in cpp.
};

foo.cpp

#include "foo.h"
const string foo::s = "foo string";
const char* foo::cs = "foo C string";
// No definition for i. (*)
const int foo::j = 4;

(*) According to the standards you must define i outside of the class definition (like j is) if it is used in code other than just integral constant expressions. See David's comment below for details.

jQuery delete confirmation box

Simply works as:

$("a. close").live("click",function(event){
     return confirm("Do you want to delete?");
});

How to make padding:auto work in CSS?

You can reset the padding (and I think everything else) with initial to the default.

p {
    padding: initial;
}

When should I use Async Controllers in ASP.NET MVC?

My 5 cents:

  1. Use async/await if and only if you do an IO operation, like DB or external service webservice.
  2. Always prefer async calls to DB.
  3. Each time you query the DB.

P.S. There are exceptional cases for point 1, but you need to have a good understanding of async internals for this.

As an additional advantage, you can do few IO calls in parallel if needed:

Task task1 = FooAsync(); // launch it, but don't wait for result
Task task2 = BarAsync(); // launch bar; now both foo and bar are running
await Task.WhenAll(task1, task2); // this is better in regard to exception handling
// use task1.Result, task2.Result

text-align: right on <select> or <option>

The following CSS will right-align both the arrow and the options:

_x000D_
_x000D_
select { text-align-last: right; }_x000D_
option { direction: rtl; }
_x000D_
<!-- example usage -->_x000D_
Choose one: <select>_x000D_
  <option>The first option</option>_x000D_
  <option>A second, fairly long option</option>_x000D_
  <option>Last</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Convert an enum to List<string>

Use Enum's static method, GetNames. It returns a string[], like so:

Enum.GetNames(typeof(DataSourceTypes))

If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

You will need Using System.Linq; at the top of your class to use .ToList()

Xcode 4: create IPA file instead of .xcarchive

I went threw the same problem. None of the answers above worked for me, but i ended finding the solution on my own. The ipa file wasn't created because there was library files (libXXX.a) in Target-> Build Phases -> Copy Bundle with resources

Hope it will help someone :)

HTML checkbox onclick called in Javascript

jQuery has a function that can do this:

  1. include the following script in your head:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
    

    (or just download the jQuery.js file online and include it locally)

  2. use this script to toggle the check box when the input is clicked:

    var toggle = false;
    $("#INPUTNAMEHERE").click(function() {
            $("input[type=checkbox]").attr("checked",!toggle);
            toggle = !toggle;
    }); 
    

That should do what you want if I understood what you were trying to do.

How to add button in ActionBar(Android)?

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this:

@Override    
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.mainmenu, menu);
  return true;
}

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.menuitem1:
      Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
      break;
    case R.id.menuitem2:
      Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
      break;
  }
  return true;
}

What is the easiest way to ignore a JPA field during persistence?

To ignore a field, annotate it with @Transient so it will not be mapped by hibernate.
Source: Hibernate Annotations.

How to get the string size in bytes?

Use strlen to get the length of a null-terminated string.

sizeof returns the length of the array not the string. If it's a pointer (char *s), not an array (char s[]), it won't work, since it will return the size of the pointer (usually 4 bytes on 32-bit systems). I believe an array will be passed or returned as a pointer, so you'd lose the ability to use sizeof to check the size of the array.

So, only if the string spans the entire array (e.g. char s[] = "stuff"), would using sizeof for a statically defined array return what you want (and be faster as it wouldn't need to loop through to find the null-terminator) (if the last character is a null-terminator, you will need to subtract 1). If it doesn't span the entire array, it won't return what you want.

An alternative to all this is actually storing the size of the string.

CSS Background Opacity

You can use CSS 3 :before to have a semi-transparent background and you can do this with just one container. Use something like this

<article>
  Text.
</article>

Then apply some CSS

article {
  position: relative;
  z-index: 1;
}

article::before {
  content: "";
  position: absolute;
  top: 0; 
  left: 0;
  width: 100%; 
  height: 100%;  
  opacity: .4; 
  z-index: -1;
  background: url(path/to/your/image);
}

Sample: http://codepen.io/anon/pen/avdsi

Note: You might need to adjust the z-index values.

React ignores 'for' attribute of the label element

Yes, for react,

for becomes htmlFor

class becomes className

etc.

see full list of how HTML attributes are changed here:

https://facebook.github.io/react/docs/dom-elements.html

Pandas group-by and sum

If you want to keep the original columns Fruit and Name, use reset_index(). Otherwise Fruit and Name will become part of the index.

df.groupby(['Fruit','Name'])['Number'].sum().reset_index()

Fruit   Name       Number
Apples  Bob        16
Apples  Mike        9
Apples  Steve      10
Grapes  Bob        35
Grapes  Tom        87
Grapes  Tony       15
Oranges Bob        67
Oranges Mike       57
Oranges Tom        15
Oranges Tony        1

As seen in the other answers:

df.groupby(['Fruit','Name'])['Number'].sum()

               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Grapes  Bob        35
        Tom        87
        Tony       15
Oranges Bob        67
        Mike       57
        Tom        15
        Tony        1

xml.LoadData - Data at the root level is invalid. Line 1, position 1

Use Load() method instead, it will solve the problem. See more

Creating a simple XML file using python

For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates

For a Jinja example, see my answer to a similar question.

Here is an example of generating your xml with string templates.

import string
from xml.sax.saxutils import escape

inner_template = string.Template('    <field${id} name="${name}">${value}</field${id}>')

outer_template = string.Template("""<root>
 <doc>
${document_list}
 </doc>
</root>
 """)

data = [
    (1, 'foo', 'The value for the foo document'),
    (2, 'bar', 'The <value> for the <bar> document'),
]

inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result

Output:

<root>
 <doc>
    <field1 name="foo">The value for the foo document</field1>
    <field2 name="bar">The &lt;value&gt; for the &lt;bar&gt; document</field2>
 </doc>
</root>

The downer of the template approach is that you won't get escaping of < and > for free. I danced around that problem by pulling in a util from xml.sax

How can I select an element in a component template?

Instead of injecting ElementRef and using querySelector or similar from there, a declarative way can be used instead to access elements in the view directly:

<input #myname>
@ViewChild('myname') input; 

element

ngAfterViewInit() {
  console.log(this.input.nativeElement.value);
}

StackBlitz example

  • @ViewChild() supports directive or component type as parameter, or the name (string) of a template variable.
  • @ViewChildren() also supports a list of names as comma separated list (currently no spaces allowed @ViewChildren('var1,var2,var3')).
  • @ContentChild() and @ContentChildren() do the same but in the light DOM (<ng-content> projected elements).

descendants

@ContentChildren() is the only one that allows to also query for descendants

@ContentChildren(SomeTypeOrVarName, {descendants: true}) someField; 

{descendants: true} should be the default but is not in 2.0.0 final and it's considered a bug
This was fixed in 2.0.1

read

If there are a component and directives the read parameter allows to specify which instance should be returned.

For example ViewContainerRef that is required by dynamically created components instead of the default ElementRef

@ViewChild('myname', { read: ViewContainerRef }) target;

subscribe changes

Even though view children are only set when ngAfterViewInit() is called and content children are only set when ngAfterContentInit() is called, if you want to subscribe to changes of the query result, it should be done in ngOnInit()

https://github.com/angular/angular/issues/9689#issuecomment-229247134

@ViewChildren(SomeType) viewChildren;
@ContentChildren(SomeType) contentChildren;

ngOnInit() {
  this.viewChildren.changes.subscribe(changes => console.log(changes));
  this.contentChildren.changes.subscribe(changes => console.log(changes));
}

direct DOM access

can only query DOM elements, but not components or directive instances:

export class MyComponent {
  constructor(private elRef:ElementRef) {}
  ngAfterViewInit() {
    var div = this.elRef.nativeElement.querySelector('div');
    console.log(div);
  }

  // for transcluded content
  ngAfterContentInit() {
    var div = this.elRef.nativeElement.querySelector('div');
    console.log(div);
  }
}

get arbitrary projected content

See Access transcluded content

What's the difference between next() and nextLine() methods from Scanner class?

A scanner breaks its input into tokens using a delimiter pattern, which is by default known the Whitespaces.

Next() uses to read a single word and when it gets a white space,it stops reading and the cursor back to its original position. NextLine() while this one reads a whole word even when it meets a whitespace.the cursor stops when it finished reading and cursor backs to the end of the line. so u don't need to use a delimeter when you want to read a full word as a sentence.you just need to use NextLine().

 public static void main(String[] args) {
            // TODO code application logic here
           String str;
            Scanner input = new Scanner( System.in );
            str=input.nextLine();
            System.out.println(str);
       }

How to convert date in to yyyy-MM-dd Format?

You can't format the Date itself. You can only get the formatted result in String. Use SimpleDateFormat as mentioned by others.

Moreover, most of the getter methods in Date are deprecated.

Delete all lines starting with # or ; in Notepad++

Its possible, but not directly.

In short, go to the search, use your regex, check "mark line" and click "Find all". It results in bookmarks for all those lines.

In the search menu there is a point "delete bookmarked lines" voila.

I found the answer here (the correct answer is the second one, not the accepted!): How to delete specific lines on Notepad++?

How to check if cursor exists (open status)

Close the cursor, if it is empty then deallocate it:

IF CURSOR_STATUS('global','myCursor') >= -1
 BEGIN
  IF CURSOR_STATUS('global','myCursor') > -1
   BEGIN
    CLOSE myCursor
   END
 DEALLOCATE myCursor
END

Type converting slices of interfaces

The thing you are missing is that T and interface{} which holds a value of T have different representations in memory so can't be trivially converted.

A variable of type T is just its value in memory. There is no associated type information (in Go every variable has a single type known at compile time not at run time). It is represented in memory like this:

  • value

An interface{} holding a variable of type T is represented in memory like this

  • pointer to type T
  • value

So coming back to your original question: why go does't implicitly convert []T to []interface{}?

Converting []T to []interface{} would involve creating a new slice of interface {} values which is a non-trivial operation since the in-memory layout is completely different.

Get paragraph text inside an element

If you use eg. "id" you can do it this way:

_x000D_
_x000D_
   (function() {_x000D_
    let x = document.getElementById("idName");_x000D_
    let y = document.getElementById("liName");_x000D_
    _x000D_
    y.addEventListener('click', function(e) {_x000D_
        y.appendChild(x);_x000D_
    });_x000D_
_x000D_
  _x000D_
})();
_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
    <title></title>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <p id="idName">TEXT</p>_x000D_
    <ul>_x000D_
        <li id="liName">_x000D_
_x000D_
        </li>_x000D_
    </ul>_x000D_
</body>_x000D_
<script src="js/scripts/script.js"></script>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

'invalid value encountered in double_scalars' warning, possibly numpy

I encount this while I was calculating np.var(np.array([])). np.var will divide size of the array which is zero in this case.

Unsupported operand type(s) for +: 'int' and 'str'

try,

str_list = " ".join([str(ele) for ele in numlist])

this statement will give you each element of your list in string format

print("The list now looks like [{0}]".format(str_list))

and,

change print(numlist.pop(2)+" has been removed") to

print("{0} has been removed".format(numlist.pop(2)))

as well.

How do you run a Python script as a service in Windows?

https://www.chrisumbel.com/article/windows_services_in_python

  1. Follow up the PySvc.py

  2. changing the dll folder

I know this is old but I was stuck on this forever. For me, this specific problem was solved by copying this file - pywintypes36.dll

From -> Python36\Lib\site-packages\pywin32_system32

To -> Python36\Lib\site-packages\win32

setx /M PATH "%PATH%;C:\Users\user\AppData\Local\Programs\Python\Python38-32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Scripts;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pywin32_system32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\win32
  1. changing the path to python folder by

cd C:\Users\user\AppData\Local\Programs\Python\Python38-32

  1. NET START PySvc
  2. NET STOP PySvc

JavaScript: Upload file

Pure JS

You can use fetch optionally with await-try-catch

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
     
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

_x000D_
_x000D_
async function SavePhoto(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user)); 
    
    const ctrl = new AbortController()    // timeout
    setTimeout(() => ctrl.abort(), 5000);
    
    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
_x000D_
_x000D_

Old school approach - xhr

let photo = document.getElementById("image-file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);

_x000D_
_x000D_
function SavePhoto(e) 
{
    let user = { name:'john', age:34 };
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    let photo = e.files[0];      
    
    formData.append("user", JSON.stringify(user));   
    formData.append("photo", photo);
    
    xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
    xhr.timeout = 5000;
    xhr.open("POST", '/upload/image'); 
    xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
_x000D_
_x000D_

SUMMARY

  • In server side you can read original file name (and other info) which is automatically included to request by browser in filename formData parameter.
  • You do NOT need to set request header Content-Type to multipart/form-data - this will be set automatically by browser.
  • Instead of /upload/image you can use full address like http://.../upload/image.
  • If you want to send many files in single request use multiple attribute: <input multiple type=... />, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];... formData.append("photo2", photo2);)
  • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
  • You can set timeout: for fetch using AbortController, for old approach by xhr.timeout= milisec
  • This solutions should work on all major browsers.

How to stop/terminate a python script from running?

To stop a running program, use Ctrl+C to terminate the process.

To handle it programmatically in python, import the sys module and use sys.exit() where you want to terminate the program.

import sys
sys.exit()

Compiling problems: cannot find crt1.o

This is a BUG reported in launchpad, but there is a workaround :

Run this to see where these files are located

$ find /usr/ -name crti*
/usr/lib/x86_64-linux-gnu/crti.o

then add this path to LIBRARY_PATH variable

$ export LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LIBRARY_PATH

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

When you use VARIABLE = value, if value is actually a reference to another variable, then the value is only determined when VARIABLE is used. This is best illustrated with an example:

VAL = foo
VARIABLE = $(VAL)
VAL = bar

# VARIABLE and VAL will both evaluate to "bar"

When you use VARIABLE := value, you get the value of value as it is now. For example:

VAL = foo
VARIABLE := $(VAL)
VAL = bar

# VAL will evaluate to "bar", but VARIABLE will evaluate to "foo"

Using VARIABLE ?= val means that you only set the value of VARIABLE if VARIABLE is not set already. If it's not set already, the setting of the value is deferred until VARIABLE is used (as in example 1).

VARIABLE += value just appends value to VARIABLE. The actual value of value is determined as it was when it was initially set, using either = or :=.

Make div scrollable

Use overflow-y:auto for displaying scroll automatically when the content exceeds the divs set height.

See this demo

String replace method is not replacing characters

package com.tulu.ds;

public class EmailSecurity {
    public static void main(String[] args) {
        System.out.println(returnSecuredEmailID("[email protected]"));
    }
    private static String returnSecuredEmailID(String email){
        String str=email.substring(1, email.lastIndexOf("@")-1);
        return email.replaceAll(email.substring(1, email.lastIndexOf("@")-1),replacewith(str.length(),"*"));
    }
    private static String replacewith(int length,String replace) {
        String finalStr="";
        for(int i=0;i<length;i++){
            finalStr+=replace;
        }
        return finalStr;
    }   
}

How to add title to subplots in Matplotlib?

fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=1, ncols=4,figsize=(11, 7))

grid = plt.GridSpec(2, 2, wspace=0.2, hspace=0.5)

ax1 = plt.subplot(grid[0, 0])
ax2 = plt.subplot(grid[0, 1:])
ax3 = plt.subplot(grid[1, :1])
ax4 = plt.subplot(grid[1, 1:])

ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')

plt.show()

enter image description here

How to escape single quotes within single quoted strings

I just use shell codes.. e.g. \x27 or \\x22 as applicable. No hassle, ever really.

Invalid default value for 'dateAdded'

Change the type from datetime to timestamp and it will work! I had the same issue for mysql 5.5.56-MariaDB - MariaDB Server Hope it can help... sorry if depricated

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

Thanks for the suggestions. I finally found a solution to this problem after reading this. It turns out that these dependencies were coming from a dependency to ZooKeeper.

I modified my pom.xml as following and it solved the problem:

    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>3.3.2</version>
        <exclusions>
            <exclusion>
                <groupId>com.sun.jmx</groupId>
                <artifactId>jmxri</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jdmk</groupId>
                <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
                <groupId>javax.jms</groupId>
                <artifactId>jms</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

change text of button and disable button in iOS

In Swift 3, you can simply change the title of a button by:

button.setTitle("Title", for: .normal)

and you disable the button by:

button.isEnabled = false

.normal is the same as UIControlState.normal because the type is inferred.

How can I remove a style added with .css() function?

Simple is cheap in web development. I recommend using empty string when removing a particular style

$(element).style.attr = '  ';

Generate .pem file used to set up Apple Push Notifications

There's much simpler solution today — pem. This tool makes life much easier.

For example, to generate or renew your push notification certificate just enter:

fastlane pem 

and it's done in under a minute. In case you need a sandbox certificate, enter:

fastlane pem --development

And that's pretty it.

JavaScript or jQuery browser back button click detector

The 'popstate' event only works when you push something before. So you have to do something like this:

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    window.history.pushState('forward', null, './#forward');

    $(window).on('popstate', function() {
      alert('Back button was pressed.');
    });

  }
});

For browser backward compatibility I recommend: history.js

break/exit script

You can use the pskill function in the R "tools" package to interrupt the current process and return to the console. Concretely, I have the following function defined in a startup file that I source at the beginning of each script. You can also copy it directly at the start of your code, however. Then insert halt() at any point in your code to stop script execution on the fly. This function works well on GNU/Linux and judging from the R documentation, it should also work on Windows (but I didn't check).

# halt: interrupts the current R process; a short iddle time prevents R from
# outputting further results before the SIGINT (= Ctrl-C) signal is received 
halt <- function(hint = "Process stopped.\n") {
    writeLines(hint)
    require(tools, quietly = TRUE)
    processId <- Sys.getpid() 
    pskill(processId, SIGINT)
    iddleTime <- 1.00
    Sys.sleep(iddleTime)
}

Get Context in a Service

As Service is already a Context itself

you can even get it through:

Context mContext = this;

OR

Context mContext = [class name].this;  //[] only specify the class name
// mContext = JobServiceSchedule.this; 

MongoDB logging all queries

I think that while not elegant, the oplog could be partially used for this purpose: it logs all the writes - but not the reads...

You have to enable replicatoon, if I'm right. The information is from this answer from this question: How to listen for changes to a MongoDB collection?

IIS - 401.3 - Unauthorized

I have struggled on this same issue for several days. It can be solved by modifying the security user access properties of the file system folder on which your site is mapped. But IIS_IUSRS is not the only account you must authorize.

  • In IIS management console, in the Authentication part of the configuration of your site, modify the "Anonymous authentication" line and check the account set as "Specific user" (mine is IUSR).
  • Give read and execution permission on the folder of your site to the account listed as the specific user.

OR

  • In IIS management console, in the Authentication part of the configuration of your site, modify the "Anonymous authentication" line by selecting "Identity of the application pool" instead of "Specific user".

Get all inherited classes of an abstract class

It may not be the elegant way but you can iterate all classes in the assembly and invoke Type.IsSubclassOf(AbstractDataExport) for each one.

Change background color on mouseover and remove it after mouseout

After lot of struggle finally got it working. ( Perfectly tested)

The below example will also support the fact that color of already clicked button should not be changes

JQuery Code

var flag = 0; // Flag is to check if you are hovering on already clicked item

$("a").click(function() {
    $('a').removeClass("YourColorClass");
    $(this).addClass("YourColorClass");
    flag=1;
}); 

$("a").mouseover(function() {
    if ($(this).hasClass("YourColorClass")) {
        flag=1;
    }
    else{
        $(this).addClass("YourColorClass");
    };
});

$("a").mouseout(function() {
    if (flag == 0) {
        $(this).removeClass("YourColorClass");
    }
    else{
        flag = 0;
    }
});

"implements Runnable" vs "extends Thread" in Java

You can use them jointly

Example :

public class A implements Runnable{

    @Override
    public void run() {


        while(true){
             System.out.println("Class A is running");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }}

    }

}



public class Test {

    public static void main(String[] args) {

        Thread myThread =new Thread(new A());// 1
        myThread.start();
        System.out.println(" executed after thread A");//will never be reached

    }

} 

How to set time delay in javascript

For sync calls you can use the method below:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

how to change the dist-folder path in angular-cli after 'ng build'

The only thing that worked for me was to change outDir in in both angular-cli.json AND src/tsconfig.json.

I wanted my dist-folder outside the angular project folder. If I didn't change the setting in src/tsconfig.json as well, Angular CLI would throw warnings whenever I build the project.

Here are the most important lines ...

// angular-cli.json
{
  ...
  "apps": [
    {
      "outDir": "../dist",
      ...
    }
  ],
  ...
}

And ...

// tsconfig.json
{
  "compilerOptions": {
    "outDir": "../../dist/out-tsc",
    ...
  }
}

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I run into the same problem with linker complaining about the main executable missing. This happened during our solution port to the new Visual Studio 2013. The solution is a varied mix of managed and un-managed projects/code. The problem (and fix) ended up being a missing app.config file in the solution folder. Took a day to figure this one out :(, as output log was not very helpful.

Improving bulk insert performance in Entity framework

Although a late reply, but I'm posting the answer because I suffered the same pain. I've created a new GitHub project just for that, as of now, it supports Bulk insert/update/delete for Sql server transparently using SqlBulkCopy.

https://github.com/MHanafy/EntityExtensions

There're other goodies as well, and hopefully, It will be extended to do more down the track.

Using it is as simple as

var insertsAndupdates = new List<object>();
var deletes = new List<object>();
context.BulkUpdate(insertsAndupdates, deletes);

Hope it helps!

Trying to get Laravel 5 email to work

I've had the same problem; my MAIL_ENCRYPTION was tls on mail.php but it was null on .env file.
So I changed null to tls and it worked!

How to get a user's client IP address in ASP.NET?

use this

Dns.GetHostEntry(Dns.GetHostName())

Get fragment (value after hash '#') from a URL in php

You need to parse the url first, so it goes like this:

$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

If you need to parse the actual url of the current browser, you need to request to call the server.

$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

File tree view in Notepad++

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

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

Folder as Workspace

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

Using number_format method in Laravel

Here's another way of doing it, add in app\Providers\AppServiceProvider.php

use Illuminate\Support\Str;

...

public function boot()
{
    // add Str::currency macro
    Str::macro('currency', function ($price)
    {
        return number_format($price, 2, '.', '\'');
    });
}

Then use Str::currency() in the blade templates or directly in the Expense model.

@foreach ($Expenses as $Expense)
    <tr>
        <td>{{{ $Expense->type }}}</td>
        <td>{{{ $Expense->narration }}}</td>
        <td>{{{ Str::currency($Expense->price) }}}</td>
        <td>{{{ $Expense->quantity }}}</td>
        <td>{{{ Str::currency($Expense->amount) }}}</td>                                                            
    </tr>
@endforeach

How to completely uninstall kubernetes

In my "Ubuntu 16.04", I use next steps to completely remove and clean Kubernetes (installed with "apt-get"):

kubeadm reset
sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube*   
sudo apt-get autoremove  
sudo rm -rf ~/.kube

And restart the computer.

Node.js get file extension

// you can send full url here
function getExtension(filename) {
    return filename.split('.').pop();
}

If you are using express please add the following line when configuring middleware (bodyParser)

app.use(express.bodyParser({ keepExtensions: true}));

Java web start - Unable to load resource

changing java proxy settings to direct connection did not fix my issue.

What worked for me:

  1. Run "Configure Java" as administrator.
  2. Go to Advanced
  3. Scroll to bottom
  4. Under: "Advanced Security Settings" uncheck "Use SSL 2.0 compatible ClientHello format"
  5. Save

Retrieving Android API version programmatically

android.os.Build.VERSION.SDK should give you the value of the API Level. You can easily find the mapping from api level to android version in the android documentation. I believe, 8 is for 2.2, 7 for 2.1, and so on.

How can I slice an ArrayList out of an ArrayList in Java?

This is how I solved it. I forgot that sublist was a direct reference to the elements in the original list, so it makes sense why it wouldn't work.

ArrayList<Integer> inputA = new ArrayList<Integer>(input.subList(0, input.size()/2));

Installing a specific version of angular with angular cli

Yes, it's possible to install a specific version of Angular using npm:

npm install -g @angular/[email protected]

Next, you need to use the ng new command to create an Angular project based on the specific version you used when installing the CLI:

ng new your-project-name

This will generate a project based on Angular v8.3.19, the version which was specified when installing Angular CLI.

Android WebView not loading URL

Note : Make sure internet permission is given.

In android 9.0,

Webview or Imageloader can not load url or image because android 9 have network security issue which need to be enable by manifest file for all sub domain. so either you can add security config file.

  1. Add @xml/network_security_config into your resources:

_x000D_
_x000D_
<network-security-config>_x000D_
    <domain-config cleartextTrafficPermitted="true">_x000D_
    <domain includeSubdomains="true">www.google.com</domain>_x000D_
    </domain-config>_x000D_
</network-security-config>
_x000D_
_x000D_
_x000D_

  1. Add this security config to your Manifest like this:

_x000D_
_x000D_
<application_x000D_
   _x000D_
    android:networkSecurityConfig="@xml/network_security_config"_x000D_
    ...>_x000D_
</application>
_x000D_
_x000D_
_x000D_

if you want to allow all sub domain

_x000D_
_x000D_
<application_x000D_
   android:usesCleartextTraffic="true"_x000D_
    ...>_x000D_
</application>
_x000D_
_x000D_
_x000D_

Note: To solve the problem, don't use both of point 2 (android:networkSecurityConfig="@xml/network_security_config" and android:usesCleartextTraffic="true") choose one of them

Convert MySQL to SQlite

There is a mysql2sqlite.sh script on GitHub

As described in the header, the script can be used like this:

./mysql2sqlite.sh myDbase | sqlite3 database.sqlite

alternatives

How do I convert a String to a BigInteger?

According to the documentation:

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

It means that you can use a String to initialize a BigInteger object, as shown in the following snippet:

sum = sum.add(new BigInteger(newNumber));

Compiling an application for use in highly radioactive environments

This answer assumes you are concerned with having a system that works correctly, over and above having a system that is minimum cost or fast; most people playing with radioactive things value correctness / safety over speed / cost

Several people have suggested hardware changes you can make (fine - there's lots of good stuff here in answers already and I don't intend repeating all of it), and others have suggested redundancy (great in principle), but I don't think anyone has suggested how that redundancy might work in practice. How do you fail over? How do you know when something has 'gone wrong'? Many technologies work on the basis everything will work, and failure is thus a tricky thing to deal with. However, some distributed computing technologies designed for scale expect failure (after all with enough scale, failure of one node of many is inevitable with any MTBF for a single node); you can harness this for your environment.

Here are some ideas:

  • Ensure that your entire hardware is replicated n times (where n is greater than 2, and preferably odd), and that each hardware element can communicate with each other hardware element. Ethernet is one obvious way to do that, but there are many other far simpler routes that would give better protection (e.g. CAN). Minimise common components (even power supplies). This may mean sampling ADC inputs in multiple places for instance.

  • Ensure your application state is in a single place, e.g. in a finite state machine. This can be entirely RAM based, though does not preclude stable storage. It will thus be stored in several place.

  • Adopt a quorum protocol for changes of state. See RAFT for example. As you are working in C++, there are well known libraries for this. Changes to the FSM would only get made when a majority of nodes agree. Use a known good library for the protocol stack and the quorum protocol rather than rolling one yourself, or all your good work on redundancy will be wasted when the quorum protocol hangs up.

  • Ensure you checksum (e.g. CRC/SHA) your FSM, and store the CRC/SHA in the FSM itself (as well as transmitting in the message, and checksumming the messages themselves). Get the nodes to check their FSM regularly against these checksum, checksum incoming messages, and check their checksum matches the checksum of the quorum.

  • Build as many other internal checks into your system as possible, making nodes that detect their own failure reboot (this is better than carrying on half working provided you have enough nodes). Attempt to let them cleanly remove themselves from the quorum during rebooting in case they don't come up again. On reboot have them checksum the software image (and anything else they load) and do a full RAM test before reintroducing themselves to the quorum.

  • Use hardware to support you, but do so carefully. You can get ECC RAM, for instance, and regularly read/write through it to correct ECC errors (and panic if the error is uncorrectable). However (from memory) static RAM is far more tolerant of ionizing radiation than DRAM is in the first place, so it may be better to use static DRAM instead. See the first point under 'things I would not do' as well.

Let's say you have an 1% chance of failure of any given node within one day, and let's pretend you can make failures entirely independent. With 5 nodes, you'll need three to fail within one day, which is a .00001% chance. With more, well, you get the idea.

Things I would not do:

  • Underestimate the value of not having the problem to start off with. Unless weight is a concern, a large block of metal around your device is going to be a far cheaper and more reliable solution than a team of programmers can come up with. Ditto optical coupling of inputs of EMI is an issue, etc. Whatever, attempt when sourcing your components to source those rated best against ionizing radiation.

  • Roll your own algorithms. People have done this stuff before. Use their work. Fault tolerance and distributed algorithms are hard. Use other people's work where possible.

  • Use complicated compiler settings in the naive hope you detect more failures. If you are lucky, you may detect more failures. More likely, you will use a code-path within the compiler which has been less tested, particularly if you rolled it yourself.

  • Use techniques which are untested in your environment. Most people writing high availability software have to simulate failure modes to check their HA works correctly, and miss many failure modes as a result. You are in the 'fortunate' position of having frequent failures on demand. So test each technique, and ensure its application actual improves MTBF by an amount that exceeds the complexity to introduce it (with complexity comes bugs). Especially apply this to my advice re quorum algorithms etc.

Found a swap file by the name

Looks like you have an open git commit or git merge going on, and an editor is still open editing the commit message.

Two choices:

  1. Find the session and finish it (preferable).
  2. Delete the .swp file (if you're sure the other git session has gone away).

Clarification from comments:

  • The session is the editing session.
  • You can see what .swp is being used by entering the command :sw within the editing session, but generally it's a hidden file in the same directory as the file you are using, with a .swp file suffix (i.e. ~/myfile.txt would be ~/.myfile.txt.swp).

Mysql select distinct

Are you looking for "SELECT * FROM temp_tickets GROUP BY ticket_id ORDER BY ticket_id ?

UPDATE

SELECT t.* 
FROM 
(SELECT ticket_id, MAX(id) as id FROM temp_tickets GROUP BY ticket_id) a  
INNER JOIN temp_tickets t ON (t.id = a.id)

How can I convert this foreach code to Parallel.ForEach?

Foreach loop:

  • Iterations takes place sequentially, one by one
  • foreach loop is run from a single Thread.
  • foreach loop is defined in every framework of .NET
  • Execution of slow processes can be slower, as they're run serially
    • Process 2 can't start until 1 is done. Process 3 can't start until 2 & 1 are done...
  • Execution of quick processes can be faster, as there is no threading overhead

Parallel.ForEach:

  • Execution takes place in parallel way.
  • Parallel.ForEach uses multiple Threads.
  • Parallel.ForEach is defined in .Net 4.0 and above frameworks.
  • Execution of slow processes can be faster, as they can be run in parallel
    • Processes 1, 2, & 3 may run concurrently (see reused threads in example, below)
  • Execution of quick processes can be slower, because of additional threading overhead

The following example clearly demonstrates the difference between traditional foreach loop and

Parallel.ForEach() Example

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ParallelForEachExample
{
    class Program
    {
        static void Main()
        {
            string[] colors = {
                                  "1. Red",
                                  "2. Green",
                                  "3. Blue",
                                  "4. Yellow",
                                  "5. White",
                                  "6. Black",
                                  "7. Violet",
                                  "8. Brown",
                                  "9. Orange",
                                  "10. Pink"
                              };
            Console.WriteLine("Traditional foreach loop\n");
            //start the stopwatch for "for" loop
            var sw = Stopwatch.StartNew();
            foreach (string color in colors)
            {
                Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(10);
            }
            Console.WriteLine("foreach loop execution time = {0} seconds\n", sw.Elapsed.TotalSeconds);
            Console.WriteLine("Using Parallel.ForEach");
            //start the stopwatch for "Parallel.ForEach"
             sw = Stopwatch.StartNew();
            Parallel.ForEach(colors, color =>
            {
                Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(10);
            }
            );
            Console.WriteLine("Parallel.ForEach() execution time = {0} seconds", sw.Elapsed.TotalSeconds);
            Console.Read();
        }
    }
}

Output

Traditional foreach loop
1. Red, Thread Id= 10
2. Green, Thread Id= 10
3. Blue, Thread Id= 10
4. Yellow, Thread Id= 10
5. White, Thread Id= 10
6. Black, Thread Id= 10
7. Violet, Thread Id= 10
8. Brown, Thread Id= 10
9. Orange, Thread Id= 10
10. Pink, Thread Id= 10
foreach loop execution time = 0.1054376 seconds

Using Parallel.ForEach example

1. Red, Thread Id= 10
3. Blue, Thread Id= 11
4. Yellow, Thread Id= 11
2. Green, Thread Id= 10
5. White, Thread Id= 12
7. Violet, Thread Id= 14
9. Orange, Thread Id= 13
6. Black, Thread Id= 11
8. Brown, Thread Id= 10
10. Pink, Thread Id= 12
Parallel.ForEach() execution time = 0.055976 seconds

Checkout Jenkins Pipeline Git SCM with credentials?

It solved for me using

checkout scm: ([
                    $class: 'GitSCM',
                    userRemoteConfigs: [[credentialsId: '******',url: ${project_url}]],
                    branches: [[name: 'refs/tags/${project_tag}']]
            ])

Load local JSON file into variable

If you pasted your object into content.json directly, it is invalid JSON. JSON keys and values must be wrapped in double quotes (" not ') unless the value is numeric, boolean, null, or composite (array or object). JSON cannot contain functions or undefined values. Below is your object as valid JSON.

{
  "id": "whatever",
  "name": "start",
  "children": [
    {
      "id": "0.9685",
      "name": " contents:queue"
    },
    {
      "id": "0.79281",
      "name": " contents:mqq_error"
    }
  ]
}

You also had an extra }.

Python string class like StringBuilder in C#?

There is no explicit analogue - i think you are expected to use string concatenations(likely optimized as said before) or third-party class(i doubt that they are a lot more efficient - lists in python are dynamic-typed so no fast-working char[] for buffer as i assume). Stringbuilder-like classes are not premature optimization because of innate feature of strings in many languages(immutability) - that allows many optimizations(for example, referencing same buffer for slices/substrings). Stringbuilder/stringbuffer/stringstream-like classes work a lot faster than concatenating strings(producing many small temporary objects that still need allocations and garbage collection) and even string formatting printf-like tools, not needing of interpreting formatting pattern overhead that is pretty consuming for a lot of format calls.

Git in Visual Studio - add existing project?

If you want to open an existing project from GitHub, you need to do the following (these are steps only for Visual Studio 2013!!!! And newer, as in older versions there are no built-in Git installation):

  1. Team explorer ? Connect to teamProjects ? Local GitRepositories ? Clone.

  2. Copy/paste your GitHub address from the browser.

  3. Select a local path for this project.

How may I reference the script tag that loaded the currently-executing script?

I was inserting script tags dynamically with this usual alternative to eval and simply set a global property currentComponentScript right before adding to the DOM.

  const old = el.querySelector("script")[0];
  const replacement = document.createElement("script");
  replacement.setAttribute("type", "module");
  replacement.appendChild(document.createTextNode(old.innerHTML));
  window.currentComponentScript = replacement;
  old.replaceWith(replacement);

Doesn't work in a loop though. The DOM doesn't run the scripts until the next macrotask so a batch of them will only see the last value set. You'd have to setTimeout the whole paragraph, and then setTimeout the next one after the previous finishes. I.e. chain the setTimeouts, not just call setTimeout multiple times in a row from a loop.

unknown type name 'uint8_t', MinGW

I had to include "PROJECT_NAME/osdep.h" and that includes the os specific configurations.

I would look in other files using the types you are interested in and find where/how they are defined (by looking at includes).

Running CMD command in PowerShell

Try this:

& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME

To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

For capturing groups, I'm used to using preg_match_all in PHP and I've tried to replicate it's functionality here:

<script>

// Return all pattern matches with captured groups
RegExp.prototype.execAll = function(string) {
    var match = null;
    var matches = new Array();
    while (match = this.exec(string)) {
        var matchArray = [];
        for (i in match) {
            if (parseInt(i) == i) {
                matchArray.push(match[i]);
            }
        }
        matches.push(matchArray);
    }
    return matches;
}

// Example
var someTxt = 'abc123 def456 ghi890';
var results = /[a-z]+(\d+)/g.execAll(someTxt);

// Output
[["abc123", "123"],
 ["def456", "456"],
 ["ghi890", "890"]]

</script>

Last segment of URL in jquery

I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.

window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));

How can I find matching values in two arrays?

If your values are non-null strings or numbers, you can use an object as a dictionary:

var map = {}, result = [], i;
for (i = 0; i < array1.length; ++i) {
    map[array1[i]] = 1;
}

for (i = 0; i < array2.length; ++i) {
    if (map[array2[i]] === 1) {
        result.push(array2[i]);

        // avoid returning a value twice if it appears twice in array 2
        map[array2[i]] = 0;
    }
}

return result;

Download an SVN repository?

If you have proxy i suggest using SVNGITDownloader it is under .NET Framework and its source code is available

How to execute .sql script file using JDBC

I use this bit of code to import sql statements created by mysqldump:

public static void importSQL(Connection conn, InputStream in) throws SQLException
{
    Scanner s = new Scanner(in);
    s.useDelimiter("(;(\r)?\n)|(--\n)");
    Statement st = null;
    try
    {
        st = conn.createStatement();
        while (s.hasNext())
        {
            String line = s.next();
            if (line.startsWith("/*!") && line.endsWith("*/"))
            {
                int i = line.indexOf(' ');
                line = line.substring(i + 1, line.length() - " */".length());
            }

            if (line.trim().length() > 0)
            {
                st.execute(line);
            }
        }
    }
    finally
    {
        if (st != null) st.close();
    }
}

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

querying WHERE condition to character length?

SELECT *
   FROM   my_table
   WHERE  substr(my_field,1,5) = "abcde";

How do I output an ISO 8601 formatted string in JavaScript?

The question asked was ISO format with reduced precision. Voila:

 new Date().toISOString().slice(0, 19) + 'Z'
 // '2014-10-23T13:18:06Z'

Assuming the trailing Z is wanted, otherwise just omit.

Mime type for WOFF fonts?

I have had the same problem, font/opentype worked for me

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Notepad++ Setting for Disabling Auto-open Previous Files

Go to: Settings > Preferences > Backup > and Uncheck Remember current session for next launch

In older versions (6.5-), this option is located on Settings > Preferences > MISC.

Error CS1705: "which has a higher version than referenced assembly"

I had this error because "Rebuild" was not really rebuilding.

Solution: Close Visual Studio, really go and delete the bin folder, then rebuild, it might work better.

Also, sometimes Visual Studio lies about references, so check the HintPathin your .csproj files.

Defining a `required` field in Bootstrap

Form validation can be enabled in markup via the data-api or via JavaScript. Automatically enable form validation by adding data-toggle="validator" to your form element.

<form role="form" data-toggle="validator">
   ...
</form>

Or activate validation via JavaScript:

$('#myForm').validator()

and you need to use required flag in input field

For more details Click Here

Determine on iPhone if user has enabled push notifications

Though Zac's answer was perfectly correct till iOS 7, it has changed since iOS 8 arrived. Because enabledRemoteNotificationTypes has been deprecated from iOS 8 onwards. For iOS 8 and later, you need to use isRegisteredForRemoteNotifications.

  • for iOS 7 and before --> Use enabledRemoteNotificationTypes
  • for iOS 8 and later --> Use isRegisteredForRemoteNotifications.

Function to Calculate Median in SQL Server

This works with SQL 2000:

DECLARE @testTable TABLE 
( 
    VALUE   INT
)
--INSERT INTO @testTable -- Even Test
--SELECT 3 UNION ALL
--SELECT 5 UNION ALL
--SELECT 7 UNION ALL
--SELECT 12 UNION ALL
--SELECT 13 UNION ALL
--SELECT 14 UNION ALL
--SELECT 21 UNION ALL
--SELECT 23 UNION ALL
--SELECT 23 UNION ALL
--SELECT 23 UNION ALL
--SELECT 23 UNION ALL
--SELECT 29 UNION ALL
--SELECT 40 UNION ALL
--SELECT 56

--
--INSERT INTO @testTable -- Odd Test
--SELECT 3 UNION ALL
--SELECT 5 UNION ALL
--SELECT 7 UNION ALL
--SELECT 12 UNION ALL
--SELECT 13 UNION ALL
--SELECT 14 UNION ALL
--SELECT 21 UNION ALL
--SELECT 23 UNION ALL
--SELECT 23 UNION ALL
--SELECT 23 UNION ALL
--SELECT 23 UNION ALL
--SELECT 29 UNION ALL
--SELECT 39 UNION ALL
--SELECT 40 UNION ALL
--SELECT 56


DECLARE @RowAsc TABLE
(
    ID      INT IDENTITY,
    Amount  INT
)

INSERT INTO @RowAsc
SELECT  VALUE 
FROM    @testTable 
ORDER BY VALUE ASC

SELECT  AVG(amount)
FROM @RowAsc ra
WHERE ra.id IN
(
    SELECT  ID 
    FROM    @RowAsc
    WHERE   ra.id -
    (
        SELECT  MAX(id) / 2.0 
        FROM    @RowAsc
    ) BETWEEN 0 AND 1

)

Create new XML file and write data to it?

With FluidXML you can generate and store an XML document very easily.

$doc = fluidxml();

$doc->add('Album', true)
        ->add('Track', 'Track Title');

$doc->save('album.xml');

Loading a document from a file is equally simple.

$doc = fluidify('album.xml');

$doc->query('//Track')
        ->attr('id', 123);

https://github.com/servo-php/fluidxml

What are the lesser known but useful data structures?

Nested sets are nice for representing trees in the relational databases and running queries on them. For instance, ActiveRecord (Ruby on Rails' default ORM) comes with a very simple nested set plugin, which makes working with trees trivial.

Preprocessor check if multiple defines are not defined

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)

How store a range from excel into a Range variable?

Define what GetData is. At the moment it is not defined.

Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer) as variant

cannot make a static reference to the non-static field

you can keep your withdraw and deposit methods static if you want however you'd have to write it like the code below. sb = starting balance and eB = ending balance.

Account account = new Account(1122, 20000, 4.5);

    double sB = Account.withdraw(account.getBalance(), 2500);
    double eB = Account.deposit(sB, 3000);
    System.out.println("Balance is " + eB);
    System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
    account.setDateCreated(new Date());
    System.out.println("The account was created " + account.getDateCreated());

Safe width in pixels for printing web pages?

A printer doesn't understand pixels, it understand dots (pt in CSS). The best solution is to write an extra CSS for printing, with all of its measures in dots.

Then, in your HTML code, in head section, put:

<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="style_print.css" rel="stylesheet" type="text/css" media="print">

Why doesn't list have safe "get" method like dictionary?

Dictionaries are for look ups. It makes sense to ask if an entry exists or not. Lists are usually iterated. It isn't common to ask if L[10] exists but rather if the length of L is 11.

jQuery Find and List all LI elements within a UL within a specific DIV

Are you thinking about something like this?

$('ul li').each(function(i)
{
   $(this).attr('rel'); // This is your rel value
});

IE6/IE7 css border on select element

You'd need a custom-designed select box with CSS and JavaScript. You'd need to make absolutely sure it degrades perfectly to a standard select element should a user have JavaScript disabled.

IMO, it's just not worth the effort. Stick with font stylings within the select to make it close to your site's design; leave the borders, etc., to the box elements.

How to `wget` a list of URLs in a text file?

If you also want to preserve the original file name, try with:

wget --content-disposition --trust-server-names -i list_of_urls.txt

Difference between "and" and && in Ruby?

and has lower precedence than &&.

But for an unassuming user, problems might occur if it is used along with other operators whose precedence are in between, for example, the assignment operator:

def happy?() true; end
def know_it?() true; end

todo = happy? && know_it? ? "Clap your hands" : "Do Nothing"

todo
# => "Clap your hands"

todo = happy? and know_it? ? "Clap your hands" : "Do Nothing"

todo
# => true

Python decorators in classes

The simple way to do it. All you need is to put the decorator method outside the class. You can still use it inside.

def my_decorator(func):
    #this is the key line. There's the aditional self parameter
    def wrap(self, *params, **kwargs):
        # you can use self here as if you were inside the class
        return func()
    return wrap

class Test(object):
    @my_decorator
    def bar(self):
        pass

Call Python script from bash with argument

I have a bash script that calls a small python routine to display a message window. As I need to use killall to stop the python script I can't use the above method as it would then mean running killall python which could take out other python programmes so I use

pythonprog.py "$argument" & # The & returns control straight to the bash script so must be outside the backticks. The preview of this message is showing it without "`" either side of the command for some reason.

As long as the python script will run from the cli by name rather than python pythonprog.py this works within the script. If you need more than one argument just use a space between each one within the quotes.

How to delete duplicate lines in a file without sorting it in Unix?

This can be achieved using awk
Below Line will display unique Values

awk file_name | uniq

You can output these unique values to a new file

awk file_name | uniq > uniq_file_name

new file uniq_file_name will contain only Unique values, no duplicates

Why can't I use switch statement on a String?

public class StringSwitchCase { 

    public static void main(String args[]) {

        visitIsland("Santorini"); 
        visitIsland("Crete"); 
        visitIsland("Paros"); 

    } 

    public static void visitIsland(String island) {
         switch(island) {
          case "Corfu": 
               System.out.println("User wants to visit Corfu");
               break; 
          case "Crete": 
               System.out.println("User wants to visit Crete");
               break; 
          case "Santorini": 
               System.out.println("User wants to visit Santorini");
               break; 
          case "Mykonos": 
               System.out.println("User wants to visit Mykonos");
               break; 
         default: 
               System.out.println("Unknown Island");
               break; 
         } 
    } 

} 

How do I check if a given Python string is a substring of another one?

string.find("substring") will help you. This function returns -1 when there is no substring.

How to change letter spacing in a Textview?

after API >=21 there is inbuild method provided by TextView called setLetterSpacing

check this for more

Is it possible to override / remove background: none!important with jQuery?

Yes it is possible depending on what css you have, you simply just declare the same thing with a different background like this

ul li {
    background: none !important;
}

ul li{
    background: blue !important;
}

But you have to make sure the declaration comes after the first one seeing as it is cascading.

Demo

You can also create a style tag in jQuery like this

$('head').append('<style> #an-element li { background: inherit !important;} </style>');

Demo

You cannot see any changes because it's not inheriting any background but it is overwriting the background: none;

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

How to download a folder from github?

You can download the complete folder under Clone or Download options (Git URL or Download Zip)

  1. There is a button of Download Zip

  2. By using command you can download the complete folder on your machine but for that you need git on your machine. You can find the Git url uner

    git clone https://github.com/url

Binary search (bisection) in Python

  • s is a list.
  • binary(s, 0, len(s) - 1, find) is the initial call.
  • Function returns an index of the queried item. If there is no such item it returns -1.

    def binary(s,p,q,find):
        if find==s[(p+q)/2]:
            return (p+q)/2
        elif p==q-1 or p==q:
            if find==s[q]:
                return q
            else:
                return -1
        elif find < s[(p+q)/2]:
            return binary(s,p,(p+q)/2,find)
        elif find > s[(p+q)/2]:
            return binary(s,(p+q)/2+1,q,find)
    

What is char ** in C?

Technically, the char* is not an array, but a pointer to a char.

Similarly, char** is a pointer to a char*. Making it a pointer to a pointer to a char.

C and C++ both define arrays behind-the-scenes as pointer types, so yes, this structure, in all likelihood, is array of arrays of chars, or an array of strings.

Cross-platform way of getting temp directory in Python

I use:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

This is because on MacOS, i.e. Darwin, tempfile.gettempdir() and os.getenv('TMPDIR') return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; it is one that I do not always want.

how to get program files x86 env variable?

IMHO, one point that is missing in this discussion is that whatever variable you use, it is guaranteed to always point at the appropriate folder. This becomes critical in the rare cases where Windows is installed on a drive other than C:\

Android : difference between invisible and gone?

  • View.INVISIBLE->The View is invisible but it will occupy some space in layout

  • View.GONE->The View is not visible and it will not occupy any space in layout

How to set default value to all keys of a dict object in python?

defaultdict can do something like that for you.

Example:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d
defaultdict(<class 'list'>, {})
>>> d['new'].append(10)
>>> d
defaultdict(<class 'list'>, {'new': [10]})

Fail during installation of Pillow (Python module) in Linux

This worked for me to solve jpeg and zlib error :

C:\Windows\system32>pip3 install pillow --global-option="build_e
xt" --global-option="--disable-zlib" --global-option="--disable-jpeg"

how to install multiple versions of IE on the same system?

MultipleIE , IETester there are many similar to those.

Multiple IE supports IE3 IE4.01 IE5 IE5.5 and IE6 and "is no longer maintained and there are no plans to continue maintaining it! Thanks and good luck!".

IETester seems a better choice : IE10, IE9, IE8, IE7 IE 6 and IE5.5 on Windows 8 desktop, Windows 7, Vista and XP

Simplest way to have a configuration file in a Windows Forms C# application

Use:

System.Configuration.ConfigurationSettings.AppSettings["MyKey"];

AppSettings has been deprecated and is now considered obsolete (link).

In addition, the appSettings section of the app.config has been replaced by the applicationSettings section.

As someone else mentioned, you should be using System.Configuration.ConfigurationManager (link) which is new for .NET 2.0.

Unable to set default python version to python3 in ubuntu

If you have Ubuntu 20.04 LTS (Focal Fossa) you can install python-is-python3:

sudo apt install python-is-python3

which replaces the symlink in /usr/bin/python to point to /usr/bin/python3.

Download JSON object as a file from browser

You could try using:

  • the native JavaScript API's Blob constructor and
  • the FileSaver.js saveAs() method

No need to deal with any HTML elements at all.

var data = {
    key: 'value'
};
var fileName = 'myData.json';

// Create a blob of the data
var fileToSave = new Blob([JSON.stringify(data)], {
    type: 'application/json',
    name: fileName
});

// Save the file
saveAs(fileToSave, fileName);

If you wanted to pretty print the JSON, per this answer, you could use:

JSON.stringify(data,undefined,2)

How to use Monitor (DDMS) tool to debug application

Go to

Tools > Android > Android Device Monitor

in v0.8.6. That will pull up the DDMS eclipse perspective.

how to open

Java: get greatest common divisor

If you are using Java 1.5 or later then this is an iterative binary GCD algorithm which uses Integer.numberOfTrailingZeros() to reduce the number of checks and iterations required.

public class Utils {
    public static final int gcd( int a, int b ){
        // Deal with the degenerate case where values are Integer.MIN_VALUE
        // since -Integer.MIN_VALUE = Integer.MAX_VALUE+1
        if ( a == Integer.MIN_VALUE )
        {
            if ( b == Integer.MIN_VALUE )
                throw new IllegalArgumentException( "gcd() is greater than Integer.MAX_VALUE" );
            return 1 << Integer.numberOfTrailingZeros( Math.abs(b) );
        }
        if ( b == Integer.MIN_VALUE )
            return 1 << Integer.numberOfTrailingZeros( Math.abs(a) );

        a = Math.abs(a);
        b = Math.abs(b);
        if ( a == 0 ) return b;
        if ( b == 0 ) return a;
        int factorsOfTwoInA = Integer.numberOfTrailingZeros(a),
            factorsOfTwoInB = Integer.numberOfTrailingZeros(b),
            commonFactorsOfTwo = Math.min(factorsOfTwoInA,factorsOfTwoInB);
        a >>= factorsOfTwoInA;
        b >>= factorsOfTwoInB;
        while(a != b){
            if ( a > b ) {
                a = (a - b);
                a >>= Integer.numberOfTrailingZeros( a );
            } else {
                b = (b - a);
                b >>= Integer.numberOfTrailingZeros( b );
            }
        }
        return a << commonFactorsOfTwo;
    }
}

Unit test:

import java.math.BigInteger;
import org.junit.Test;
import static org.junit.Assert.*;

public class UtilsTest {
    @Test
    public void gcdUpToOneThousand(){
        for ( int x = -1000; x <= 1000; ++x )
            for ( int y = -1000; y <= 1000; ++y )
            {
                int gcd = Utils.gcd(x, y);
                int expected = BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).intValue();
                assertEquals( expected, gcd );
            }
    }

    @Test
    public void gcdMinValue(){
        for ( int x = 0; x < Integer.SIZE-1; x++ ){
            int gcd = Utils.gcd(Integer.MIN_VALUE,1<<x);
            int expected = BigInteger.valueOf(Integer.MIN_VALUE).gcd(BigInteger.valueOf(1<<x)).intValue();
            assertEquals( expected, gcd );
        }
    }
}

Reading/parsing Excel (xls) files with Python

Using pandas:

import pandas as pd

xls = pd.ExcelFile(r"yourfilename.xls") #use r before absolute file path 

sheetX = xls.parse(2) #2 is the sheet number+1 thus if the file has only 1 sheet write 0 in paranthesis

var1 = sheetX['ColumnName']

print(var1[1]) #1 is the row number...

Date Format in Swift

swift 3

let date : Date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let todaysDate = dateFormatter.string(from: date)

How does python numpy.where() work?

How do they achieve internally that you are able to pass something like x > 5 into a method?

The short answer is that they don't.

Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__, __lt__, etc all return boolean arrays where the given condition is true).

E.g.

x = np.arange(9).reshape(3,3)
print x > 5

yields:

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

This is the same reason why something like if x > 5: raises a ValueError if x is a numpy array. It's an array of True/False values, not a single value.

Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5] yields [6 7 8], in this case.

Honestly, it's fairly rare that you actually need numpy.where but it just returns the indicies where a boolean array is True. Usually you can do what you need with simple boolean indexing.

DataTable: Hide the Show Entries dropdown but keep the Search box

To hide "show entries" but still have pagination. I used the code below and it worked.

"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bInfo": false,
"bAutoWidth": false

Display a RecyclerView in Fragment

You should retrieve RecyclerView in a Fragment after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
    final FragmentActivity c = getActivity();
    final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(c);
    recyclerView.setLayoutManager(layoutManager);

    new Thread(new Runnable() {
        @Override
        public void run() {
            final RecyclerAdapter adapter = new RecyclerAdapter(c);
            c.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recyclerView.setAdapter(adapter);
                }
            });
        }
    }).start();

    return view;
}

Change font-weight of FontAwesome icons?

.star-light::after {
    content: "\f005";
    font-family: "FontAwesome";
    font-size: 3.2rem;
    color: #fff;
    font-weight: 900;
    background-color: red;
}

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

Check your AWS S3 Bucket Region and Pass proper Region in Connection Request.

In My Senario I have set 'APSouth1' for Asia Pacific (Mumbai)

using (var client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.APSouth1))
{
    GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest
    {
        BucketName = bucketName,
        Key = keyName,
        Expires = DateTime.Now.AddMinutes(50),
    };
    urlString = client.GetPreSignedURL(request1);
}

How can I mark a foreign key constraint using Hibernate annotations?

@Column is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions to Question, since an instance represents a single question, and not several ones. Then create the association:

@Entity
@Table(name = "UserAnswer")
public class UserAnswer {

    // this entity needs an ID:
    @Id
    @Column(name="useranswer_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "question_id")
    private Question question;

    @Column(name = "response")
    private String response;

    //getter and setter 
}

The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

How to click a link whose href has a certain substring in Selenium?

You can do this:

//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));

//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
    if(linkList.get(i).getAttribute("href").contains("long"))
    {
        linkList.get(i).click();
        break;
    }
}

in this what we r doing is first we are finding all the <a> tags and storing them in a list.After that we are iterating the list one by one to find <a> tag whose href attribute contains long string. And then we click on that particular <a> tag and comes out of the loop.

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

It just means that the server cannot find your image.

Remember The image path must be relative to the CSS file location

Check the path and if the image file exist.

Angular4 - No value accessor for form control

You should use formControlName="surveyType" on an input and not on a div

Install Qt on Ubuntu

Also take a look at awesome project aqtinstall https://github.com/miurahr/aqtinstall/ (it can install any Qt version on Linux, Mac and Windows machines without any interaction!) and GitHub Action that uses this tool: https://github.com/jurplel/install-qt-action

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

This is a simple solution for merging two dictionaries where += can be applied to the values, it has to iterate over a dictionary only once

a = {'a':1, 'b':2, 'c':3}

dicts = [{'b':3, 'c':4, 'd':5},
         {'c':9, 'a':9, 'd':9}]

def merge_dicts(merged,mergedfrom):
    for k,v in mergedfrom.items():
        if k in merged:
            merged[k] += v
        else:
            merged[k] = v
    return merged

for dct in dicts:
    a = merge_dicts(a,dct)
print (a)
#{'c': 16, 'b': 5, 'd': 14, 'a': 10}

How to get the location of the DLL currently executing?

Reflection is your friend, as has been pointed out. But you need to use the correct method;

Assembly.GetEntryAssembly()     //gives you the entrypoint assembly for the process.
Assembly.GetCallingAssembly()   // gives you the assembly from which the current method was called.
Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined
Assembly.GetAssembly( Type t )  // gives you the assembly in which the specified type is defined.

Get UserDetails object from Security Context in Spring MVC controller

That's another solution (Spring Security 3):

public String getLoggedUser() throws Exception {
    String name = SecurityContextHolder.getContext().getAuthentication().getName();
    return (!name.equals("anonymousUser")) ? name : null;
}

error: pathspec 'test-branch' did not match any file(s) known to git

This error can also appear if your git branch is not correct even though case sensitive wise. In my case I was getting this error as actual branch name was "CORE-something" but I was taking pull like "core-something".

Scale the contents of a div by a percentage?

You can simply use the zoom property:

#myContainer{
    zoom: 0.5;
    -moz-transform: scale(0.5);
}

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

How to create border in UIButton?

You can set the border properties on the CALayer by accessing the layer property of the button.

First, add Quartz

#import <QuartzCore/QuartzCore.h>

Set properties:

myButton.layer.borderWidth = 2.0f;
myButton.layer.borderColor = [UIColor greenColor].CGColor;

See:

https://developer.apple.com/documentation/quartzcore/calayer#//apple_ref/occ/cl/CALayer

The CALayer in the link above allows you to set other properties like corner radius, maskToBounds etc...

Also, a good article on button fun:

https://web.archive.org/web/20161221132308/http://www.apptite.be/tutorial_custom_uibuttons.php

How to convert datatype:object to float64 in python?

Or you can use regular expression to handle multiple items as the general case of this issue,

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(r'[,.%]','')) 
df['CTR'] = pd.to_numeric(df['CTR'].str.replace(r'[^\d%]',''))

Make an image width 100% of parent div, but not bigger than its own width

Found this post on a Google search, and it solved my issue thanks to @jwal reply, but I made one addition to his solution.

img.content.x700 {
  width: auto !important; /*override the width below*/
  width: 100%;
  max-width: 678px;
  float: left;
  clear: both;
}

With the above I changed the max-width to the dimensions of the content container that my image is in. In this case it is: container width - padding - boarder = max width

This way my image won't break out of the containing div, and I can still float the image within the content div.

I've tested in IE 9, FireFox 18.0.2 and Chrome 25.0.1364.97, Safari iOS and seems to work.

Additional: I tested this on an image 1024px wide displayed at 678px (the max width), and an image 500px wide displayed at 500px (width of the image).

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

@NoCanDo: You cannot create an array with different data types because java only supports variables with a specific data type or object. When you are creating an array, you are pulling together an assortment of similar variables -- almost like an extended variable. All of the variables must be of the same type therefore. Java cannot differentiate the data type of your variable unless you tell it what it is. Ex: int tells all your variables declared to it are of data type int. What you could do is create 3 arrays with corresponding information.

int bookNumber[] = {1, 2, 3, 4, 5};
int bookName[] = {nameOfBook1, nameOfBook2, nameOfBook3, nameOfBook4, nameOfBook5} // etc.. etc..

Now, a single index number gives you all the info for that book. Ex: All of your arrays with index number 0 ([0]) have information for book 1.

Get DateTime.Now with milliseconds precision

try using datetime.now.ticks. this provides nanosecond precision. taking the delta of two ticks (stoptick - starttick)/10,000 is the millisecond of specified interval.

https://docs.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=netframework-4.7.2

Run react-native on android emulator

You probably haven't run the Android SDK in forever. So you probably just have to update it. If you open the Android Studio Software it'll probably let you know that and ask to update it for you. Otherwise refer to following link: Update Android SDK

How to use *ngIf else?

ngif expression resulting value won’t just be the boolean true or false

if the expression is just a object, it still evaluate it as truthiness.

if the object is undefined, or non-exist, then ngif will evaluate it as falseness.

common use is if an object loaded, exist, then display the content of this object, otherwise display "loading.......".

 <div *ngIf="!object">
     Still loading...........
 </div>

<div *ngIf="object">
     <!-- the content of this object -->

           object.info, object.id, object.name ... etc.
 </div>

another example:

  things = {
 car: 'Honda',
 shoes: 'Nike',
 shirt: 'Tom Ford',
 watch: 'Timex'
 };

 <div *ngIf="things.car; else noCar">
  Nice car!
 </div>

<ng-template #noCar>
   Call a Uber.
</ng-template>

 <!-- Nice car ! -->

anthoer example:

<div *ngIf="things.car; let car">
   Nice {{ car }}!
 </div>
<!-- Nice Honda! -->

ngif template

ngif angular 4

The entity name must immediately follow the '&' in the entity reference

All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.

Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:

  • < the start of a tag.
  • > the end of a tag.
  • " the start and end of an attribute value.
  • ' the alternative start and end of an attribute value.
  • & the start of an entity (which ends with ;).

In case of & which is not followed by # (e.g. &#160;, &#xA0;, etc), the XML parser is implicitly looking for one of the five predefined entity names lt, gt, amp, quot and apos, or any manually defined entity name. However, in your particular case, you was using & as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:

The entity name must immediately follow the '&' in the entity reference

In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The & must be escaped as &amp;.

So, in your particular case, the

if (Modernizr.canvas && Modernizr.localstorage && 

must become

if (Modernizr.canvas &amp;&amp; Modernizr.localstorage &amp;&amp;

to make it XML-valid.

However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:

<h:outputScript>
    <![CDATA[
        // ...
    ]]>
</h:outputScript>

The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".

But, much better is to just put the JS code in its own JS file which you include by <script src>, or in JSF terms, the <h:outputScript>.

<h:outputScript name="onload.js" target="body" />

(note the target="body"; this way JSF will automatically render the <script> at the very end of <body>, regardless of where <h:outputScript> itself is located, hereby achieving the same effect as with window.onload and $(document).ready(); so you don't need to use those anymore in that script)

This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.

See also:

How to COUNT rows within EntityFramework without loading contents?

As I understand it, the selected answer still loads all of the related tests. According to this msdn blog, there is a better way.

http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

Specifically

using (var context = new UnicornsContext())

    var princess = context.Princesses.Find(1);

    // Count how many unicorns the princess owns 
    var unicornHaul = context.Entry(princess)
                      .Collection(p => p.Unicorns)
                      .Query()
                      .Count();
}

When do you use Java's @Override annotation and why?

It makes absolutely no sense to use @Override when implementing an interface method. There's no advantage to using it in that case--the compiler will already catch your mistake, so it's just unnecessary clutter.

how to properly display an iFrame in mobile safari

<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" src="url" />
</div>

I'm building my first site and this helped me get this working for all sites that I use iframe embededding for.

Thanks!

How can apply multiple background color to one div

The A div can actually be made without :before or :after selector but using linear gradient as your first try. The only difference is that you must specify 4 positions. Dark grey from 0 to 50% and ligth grey from 50% to 100% like this:

background: linear-gradient(to right,  #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%);

As you know, B div is made from a linear gradient having 2 positions like this:

background: linear-gradient(to right,  #9c9e9f 0%,#f6f6f6 100%);

For the C div, i use the same kind of gradient as div A ike this:

background: linear-gradient(to right,  #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%);

But this time i used the :after selector with a white background like if the second part of your div was smaller. * Please note that I added a better alternative below.

Check this jsfiddle or the snippet below for complete cross-browser code.

_x000D_
_x000D_
div{_x000D_
    position:relative;_x000D_
    width:80%;_x000D_
    height:100px;_x000D_
    color:red;_x000D_
    text-align:center;_x000D_
    line-height:100px;_x000D_
    margin-bottom:10px;_x000D_
}_x000D_
_x000D_
.a{_x000D_
    background: #9c9e9f; /* Old browsers */_x000D_
    background: -moz-linear-gradient(left,  #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%); /* FF3.6+ */_x000D_
    background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(50%,#9c9e9f), color-stop(50%,#f6f6f6), color-stop(100%,#f6f6f6)); /* Chrome,Safari4+ */_x000D_
    background: -webkit-linear-gradient(left,  #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* Chrome10+,Safari5.1+ */_x000D_
    background: -o-linear-gradient(left,  #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* Opera 11.10+ */_x000D_
    background: -ms-linear-gradient(left,  #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* IE10+ */_x000D_
    background: linear-gradient(to right,  #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* W3C */_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6',GradientType=1 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.b{_x000D_
    background: #9c9e9f; /* Old browsers */_x000D_
    background: -moz-linear-gradient(left,  #9c9e9f 0%, #f6f6f6 100%); /* FF3.6+ */_x000D_
    background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(100%,#f6f6f6)); /* Chrome,Safari4+ */_x000D_
    background: -webkit-linear-gradient(left,  #9c9e9f 0%,#f6f6f6 100%); /* Chrome10+,Safari5.1+ */_x000D_
    background: -o-linear-gradient(left,  #9c9e9f 0%,#f6f6f6 100%); /* Opera 11.10+ */_x000D_
    background: -ms-linear-gradient(left,  #9c9e9f 0%,#f6f6f6 100%); /* IE10+ */_x000D_
    background: linear-gradient(to right,  #9c9e9f 0%,#f6f6f6 100%); /* W3C */_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6',GradientType=1 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.c{    _x000D_
    background: #9c9e9f; /* Old browsers */_x000D_
    background: -moz-linear-gradient(left,  #9c9e9f 0%, #9c9e9f 50%, #33ccff 50%, #33ccff 100%); /* FF3.6+ */_x000D_
    background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(50%,#9c9e9f), color-stop(50%,#33ccff), color-stop(100%,#33ccff)); /* Chrome,Safari4+ */_x000D_
    background: -webkit-linear-gradient(left,  #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* Chrome10+,Safari5.1+ */_x000D_
    background: -o-linear-gradient(left,  #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* Opera 11.10+ */_x000D_
    background: -ms-linear-gradient(left,  #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* IE10+ */_x000D_
    background: linear-gradient(to right,  #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* W3C */_x000D_
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#33ccff',GradientType=1 ); /* IE6-9 */_x000D_
}_x000D_
.c:after{_x000D_
    content:"";_x000D_
    position:absolute;_x000D_
    right:0;_x000D_
    bottom:0;_x000D_
    width:50%;_x000D_
    height:20%;_x000D_
    background-color:white;_x000D_
}
_x000D_
<div class="a">A</div>_x000D_
<div class="b">B</div>_x000D_
<div class="c">C</div>
_x000D_
_x000D_
_x000D_


There is also an alternative for the C div without using a white background to hide the a part of the second section. Instead, we make the second part transparent and we use the :after selector to act as a colored background with the desired position and size.

See this jsfiddle or the snippet below for this updated solution.

_x000D_
_x000D_
div {_x000D_
  position: relative;_x000D_
  width: 80%;_x000D_
  height: 100px;_x000D_
  color: red;_x000D_
  text-align: center;_x000D_
  line-height: 100px;_x000D_
  margin-bottom: 10px;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  background: #9c9e9f;_x000D_
  /* Old browsers */_x000D_
  background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
  /* FF3.6+ */_x000D_
  background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(50%, #9c9e9f), color-stop(50%, #f6f6f6), color-stop(100%, #f6f6f6));_x000D_
  /* Chrome,Safari4+ */_x000D_
  background: -webkit-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
  /* Chrome10+,Safari5.1+ */_x000D_
  background: -o-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
  /* Opera 11.10+ */_x000D_
  background: -ms-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
  /* IE10+ */_x000D_
  background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
  /* W3C */_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6', GradientType=1);_x000D_
  /* IE6-9 */_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background: #9c9e9f;_x000D_
  /* Old browsers */_x000D_
  background: -moz-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
  /* FF3.6+ */_x000D_
  background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(100%, #f6f6f6));_x000D_
  /* Chrome,Safari4+ */_x000D_
  background: -webkit-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
  /* Chrome10+,Safari5.1+ */_x000D_
  background: -o-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
  /* Opera 11.10+ */_x000D_
  background: -ms-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
  /* IE10+ */_x000D_
  background: linear-gradient(to right, #9c9e9f 0%, #f6f6f6 100%);_x000D_
  /* W3C */_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6', GradientType=1);_x000D_
  /* IE6-9 */_x000D_
}_x000D_
_x000D_
.c {_x000D_
  background: #9c9e9f;_x000D_
  /* Old browsers */_x000D_
  background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
  /* FF3.6+ */_x000D_
  background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(50%, #9c9e9f), color-stop(50%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0)));_x000D_
  /* Chrome,Safari4+ */_x000D_
  background: -webkit-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
  /* Chrome10+,Safari5.1+ */_x000D_
  background: -o-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
  /* Opera 11.10+ */_x000D_
  background: -ms-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
  /* IE10+ */_x000D_
  background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
  /* W3C */_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#ffffff00', GradientType=1);_x000D_
  /* IE6-9 */_x000D_
}_x000D_
_x000D_
.c:after {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  width: 50%;_x000D_
  height: 80%;_x000D_
  background-color: #33ccff;_x000D_
  z-index: -1_x000D_
}
_x000D_
<div class="a">A</div>_x000D_
<div class="b">B</div>_x000D_
<div class="c">C</div>
_x000D_
_x000D_
_x000D_

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

You mean that want to get status codes?

VolleyError has a member variable type of NetworkResponse and it is public.

You can access error.networkResponse.statusCode for http error code.

I hope it is helpful for you.

mysqldump Error 1045 Access denied despite correct passwords etc

In Past same problem occurred to me after I copied the mysqldump statement from a MS Word file.

But When typing the statement directly, everything worked fine.

In hex editor the "-" of the not working statement was represented by the unicode char e2 80 93 (http://www.fileformat.info/info/unicode/char/2013/index.htm)

In sort, type password directly and check the copy paste code as the uni-code (or other encoding) strings might cause an issue..

Pretty graphs and charts in Python

NodeBox is awesome for raw graphics creation.

How to get object size in memory?

In debug mode

load SOS

and execute dumpheap command.

How much overhead does SSL impose?

I second @erickson: The pure data-transfer speed penalty is negligible. Modern CPUs reach a crypto/AES throughput of several hundred MBit/s. So unless you are on resource constrained system (mobile phone) TLS/SSL is fast enough for slinging data around.

But keep in mind that encryption makes caching and load balancing much harder. This might result in a huge performance penalty.

But connection setup is really a show stopper for many application. On low bandwidth, high packet loss, high latency connections (mobile device in the countryside) the additional roundtrips required by TLS might render something slow into something unusable.

For example we had to drop the encryption requirement for access to some of our internal web apps - they where next to unusable if used from china.

Make Div Draggable using CSS

Only using css techniques this does not seem possible to me. But you could use jqueryui draggable:

$('#drag_me').draggable();

Disable button in WPF?

I know this isn't as elegant as the other posts, but it's a more straightforward xaml/codebehind example of how to accomplish the same thing.

Xaml:

<StackPanel Orientation="Horizontal">
   <TextBox Name="TextBox01" VerticalAlignment="Top" HorizontalAlignment="Left" Width="70" />
   <Button Name="Button01" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,0,0,0" />
</StackPanel>

CodeBehind:

Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        Button01.IsEnabled = False
        Button01.Content = "I am Disabled"

End Sub

Private Sub TextBox01_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox01.TextChanged

        If TextBox01.Text.Trim.Length > 0 Then
            Button01.IsEnabled = True
            Button01.Content = "I am Enabled"
        Else
            Button01.IsEnabled = False
            Button01.Content = "I am Disabled"
        End If

End Sub

Break when a value changes using the Visual Studio debugger

As Peter Mortensen wrote:

In the Visual Studio 2005 menu:

Debug -> New Breakpoint -> New Data Breakpoint

Enter: &myVariable

Additional information:

Obviously, the system must know which address in memory to watch. So - set a normal breakpoint to the initialisation of myVariable (or myClass.m_Variable) - run the system and wait till it stops at that breakpoint. - Now the Menu entry is enabled, and you can watch the variable by entering &myVariable, or the instance by entering &myClass.m_Variable. Now the addresses are well defined.

Sorry when I did things wrong by explaining an already given solution. But I could not add a comment, and there has been some comments regarding this.

The module ".dll" was loaded but the entry-point was not found

What solved it for me was using :

regasm.exe 'xx.dll' /tlb /codebase /register

It is however, important to understand the difference between regasm.exe and regsvr.exe:

What is difference between RegAsm.exe and regsvr32? How to generate a tlb file using regsvr32?