Programs & Examples On #Enumerators

0

IEnumerable vs List - What to Use? How do they work?

A class that implement IEnumerable allows you to use the foreach syntax.

Basically it has a method to get the next item in the collection. It doesn't need the whole collection to be in memory and doesn't know how many items are in it, foreach just keeps getting the next item until it runs out.

This can be very useful in certain circumstances, for instance in a massive database table you don't want to copy the entire thing into memory before you start processing the rows.

Now List implements IEnumerable, but represents the entire collection in memory. If you have an IEnumerable and you call .ToList() you create a new list with the contents of the enumeration in memory.

Your linq expression returns an enumeration, and by default the expression executes when you iterate through using the foreach. An IEnumerable linq statement executes when you iterate the foreach, but you can force it to iterate sooner using .ToList().

Here's what I mean:

var things = 
    from item in BigDatabaseCall()
    where ....
    select item;

// this will iterate through the entire linq statement:
int count = things.Count();

// this will stop after iterating the first one, but will execute the linq again
bool hasAnyRecs = things.Any();

// this will execute the linq statement *again*
foreach( var thing in things ) ...

// this will copy the results to a list in memory
var list = things.ToList()

// this won't iterate through again, the list knows how many items are in it
int count2 = list.Count();

// this won't execute the linq statement - we have it copied to the list
foreach( var thing in list ) ...

Postgres Error: More than one row returned by a subquery used as an expression

USE LIMIT 1 - so It will return only 1 row. Example

customerId- (select id from enumeration where enumerations.name = 'Ready To Invoice' limit 1)

Android Animation Alpha

View.setOnTouchListener { v, event ->
    when (event.action) {
        MotionEvent.ACTION_DOWN -> {
            v.alpha = 0f
            v.invalidate()
        }
        MotionEvent.ACTION_UP -> {
            v.alpha = 1f
            v.invalidate()


        }
    }
    false
}

insert vertical divider line between two nested divs, not full height

Can't think of a only css solution, but couldn't you just had a div between those 2 and set in the css the properties to look like a line like shown in the image? If you are using divs as they were table cells this is a pretty simple solution to the problem

How do I remove lines between ListViews on Android?

You can put below property in listview tag

android:divider="@null"

(or) programmatically listview.Divider(null); here listview is ListView reference.

Prevent cell numbers from incrementing in a formula in Excel

There is something called 'locked reference' in excel which you can use for this, and you use $ symbols to lock a range. For your example, you would use:

=IF(B4<>"",B4/B$1,"")

This locks the 1 in B1 so that when you copy it to rows below, 1 will remain the same.

If you use $B$1, the range will not change when you copy it down a row or across a column.

no debugging symbols found when using gdb

The application has to be both compiled and linked with -g option. I.e. you need to put -g in both CPPFLAGS and LDFLAGS.

Embedding VLC plugin on HTML page

I found this piece of code somewhere in the web. Maybe it helps you and I give you an update so far I accomodated it for the same purpose... Maybe I don't.... who the futt knows... with all the nogodders and dobedders in here :-/

function runVLC(target, stream)
{
var support=true
var addr='rtsp://' + window.location.hostname + stream
if ($.browser.msie){
$(target).html('<object type = "application/x-vlc-plugin"' + 'version =  
"VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' + 
'events = "true"' + 'id = "vlc"></object>')
}
else if ($.browser.mozilla || $.browser.webkit){
$(target).html('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' + 
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' + 
'width="660" height="372"' + 
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' + 
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' + 
'branding="false"' + 'controls="false"' + 'aspectRatio="16:9"' + 
'target="whatever.mp4"></embed>')
}
else{
support=false
$(target).empty().html('<div id = "dialog_error">Error: browser not supported!</div>')
}
if (support){
var vlc = document.getElementById('vlc')
if (vlc){
var opt = new Array(':network-caching=300')
try{
var id = vlc.playlist.add(addr, '', opt)
vlc.playlist.playItem(id)
}
catch (e){
$(target).empty().html('<div id = "dialog_error">Error: ' + e + '<br>URL: ' + addr + 
'</div>')
}
}
}
}
/* $(target + ' object').css({'width': '100%', 'height': '100%'}) */

Greets

Gee

I reduce the whole crap now to:

function runvlc(){
var target=$('body')
var error=$('#dialog_error')
var support=true
var addr='rtsp://../html/media/video/TESTCARD.MP4'
if (navigator.userAgent.toLowerCase().indexOf("msie")!=-1){
target.append('<object type = "application/x-vlc-plugin"' + 'version = "
VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' + 
'events = "true"' + 'id = "vlc"></object>')
}
else if (navigator.userAgent.toLowerCase().indexOf("msie")==-1){
target.append('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' + 
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' + 
'width="660" height="372"' + 
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' + 
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' + 
'branding="false"' + 
'controls="false"' + 'aspectRatio="16:9"' + 'target="whatever.mp4">
</embed>')
}
else{
support=false
error.empty().html('Error: browser not supported!')
error.show()
if (support){
var vlc=document.getElementById('vlc')
if (vlc){
var options=new Array(':network-caching=300') /* set additional vlc--options */
try{ /* error handling */
var id = vlc.playlist.add(addr,'',options)
vlc.playlist.playItem(id)
}
catch (e){
error.empty().html('Error: ' + e + '<br>URL: ' + addr + '')
error.show()
}
}
}
}
};

Didn't get it to work in ie as well... 2b continued...

Greets

Gee

ADB Android Device Unauthorized

I tried many ways to solve this problem, this one works for me.

Install SnapPea on your PC. SnapPea

Plug your phone in USB Debugging mode and open SnapPea, a authorization dialog will show on your phone. The Dialog shows on the phone

Hope it helps.

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you can't use jackson-modules-java8 for whatever reasons you can (de-)serialize the instant field as long using @JsonIgnore and @JsonGetter & @JsonSetter:

public class MyBean {

    private Instant time = Instant.now();

    @JsonIgnore
    public Instant getTime() {
        return this.time;
    }

    public void setTime(Instant time) {
        this.time = time;
    }

    @JsonGetter
    private long getEpochTime() {
        return this.time.toEpochMilli();
    }

    @JsonSetter
    private void setEpochTime(long time) {
        this.time = Instant.ofEpochMilli(time);
    }
}

Example:

@Test
public void testJsonTime() throws Exception {
    String json = new ObjectMapper().writeValueAsString(new MyBean());
    System.out.println(json);
    MyBean myBean = new ObjectMapper().readValue(json, MyBean.class);
    System.out.println(myBean.getTime());
}

yields

{"epochTime":1506432517242}
2017-09-26T13:28:37.242Z

What is the difference between baud rate and bit rate?

Replies here are misleading. Saying true, but no one tell that for UART a symbol is not a single character but a single bit and this way the question was tagged.

For example 115200/8n1 is 11520 bytes per second as a single ASCII character is a 1 start bit plus 8 data bit plus 1 stop bit.

loading json data from local file into React JS

The simplest and most effective way to make a file available to your component is this:

var data = require('json!./data.json');

Note the json! before the path

How do I implement IEnumerable<T>

If you work with generics, use List instead of ArrayList. The List has exactly the GetEnumerator method you need.

List<MyObject> myList = new List<MyObject>();

Error: Unexpected value 'undefined' imported by the module

In case your index exports a module - That module should not import its components from the same index, it should import them directly from the components file.

I had this issue, and when I changed from importing the components in the module file using the index to importing them using the direct file, this resolved.

e.g changed:

import { NgModule } from '@angular/core';
import { MainNavComponent } from './index';
@NgModule({
  imports: [],
  exports: [MainNavComponent],
  declarations: [ MainNavComponent ],
  bootstrap:    [ MainNavComponent ]
})
export class MainNavModule {}

to:

import { NgModule } from '@angular/core';
import { MainNavComponent } from './MainNavComponent';
@NgModule({
  imports: [],
  exports: [MainNavComponent],
  declarations: [ MainNavComponent ],
  bootstrap:    [ MainNavComponent ]
})
export class MainNavModule {}

also remove the now unnecessary exports from you index, e.g:

export { MainNavModule } from './MainNavModule';
export { MainNavComponent } from './MainNavComponent';

to:

export { MainNavModule } from './MainNavModule';

How to update a menu item shown in the ActionBar?

In Kotlin 1.2 simply call:

invalidateOptionsMenu()

and the onCreateOptionsMenu function will be called again.

What is the difference between MVC and MVVM?

MVVM is a refinement (debatable) of the Presentation Model pattern. I say debatable, because the only difference is in how WPF provides the ability to do data binding and command handling.

How do you remove columns from a data.frame?

If you have a vector of names already,which there are several ways to create, you can easily use the subset function to keep or drop an object.

dat2 <- subset(dat, select = names(dat) %in% c(KEEP))

In this case KEEP is a vector of column names which is pre-created. For example:

#sample data via Brandon Bertelsen
df <- data.frame(a=rnorm(100),
                 b=rnorm(100),
                 c=rnorm(100),
                 d=rnorm(100),
                 e=rnorm(100),
                 f=rnorm(100),
                 g=rnorm(100))

#creating the initial vector of names
df1 <- as.matrix(as.character(names(df)))

#retaining only the name values you want to keep
KEEP <- as.vector(df1[c(1:3,5,6),])

#subsetting the intial dataset with the object KEEP
df3 <- subset(df, select = names(df) %in% c(KEEP))

Which results in:

> head(df)
            a          b           c          d
1  1.05526388  0.6316023 -0.04230455 -0.1486299
2 -0.52584236  0.5596705  2.26831758  0.3871873
3  1.88565261  0.9727644  0.99708383  1.8495017
4 -0.58942525 -0.3874654  0.48173439  1.4137227
5 -0.03898588 -1.5297600  0.85594964  0.7353428
6  1.58860643 -1.6878690  0.79997390  1.1935813
            e           f           g
1 -1.42751190  0.09842343 -0.01543444
2 -0.62431091 -0.33265572 -0.15539472
3  1.15130591  0.37556903 -1.46640276
4 -1.28886526 -0.50547059 -2.20156926
5 -0.03915009 -1.38281923  0.60811360
6 -1.68024349 -1.18317733  0.42014397

> head(df3)
        a          b           c           e
1  1.05526388  0.6316023 -0.04230455 -1.42751190
2 -0.52584236  0.5596705  2.26831758 -0.62431091
3  1.88565261  0.9727644  0.99708383  1.15130591
4 -0.58942525 -0.3874654  0.48173439 -1.28886526
5 -0.03898588 -1.5297600  0.85594964 -0.03915009
6  1.58860643 -1.6878690  0.79997390 -1.68024349
            f
1  0.09842343
2 -0.33265572
3  0.37556903
4 -0.50547059
5 -1.38281923
6 -1.18317733

How to make input type= file Should accept only pdf and xls

You could use JavaScript. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for PDF you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

How do I turn a python datetime into a string, with readable format date?

The datetime class has a method strftime. The Python docs documents the different formats it accepts:

For this specific example, it would look something like:

my_datetime.strftime("%B %d, %Y")

How do I convert a string to enum in TypeScript?

Typescript 3.9 propsal

enum Color{ RED, GREEN }

const color = 'RED' as Color;

easy peasy... lemon squeezy!

How to launch another aspx web page upon button click?

Edited and fixed (thanks to Shredder)

If you mean you want to open a new tab, try the below:

protected void Page_Load(object sender, EventArgs e)
{
    this.Form.Target = "_blank";
}

protected void Button1_Click(object sender, EventArgs e)
{

    Response.Redirect("Otherpage.aspx");
}

This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.

-J

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

I was upgrading gradle from 4.1 to 4.10 and my internet connection timed out.

So I fixed this issue by deleting "gradle-4.10-all" folder in .gradle/wrapper/dists

Where is `%p` useful with printf?

At least on one system that is not very uncommon, they do not print the same:

~/src> uname -m
i686
~/src> gcc -v
Using built-in specs.
Target: i686-pc-linux-gnu
[some output snipped]
gcc version 4.1.2 (Gentoo 4.1.2)
~/src> gcc -o printfptr printfptr.c
~/src> ./printfptr
0xbf8ce99c
bf8ce99c

Notice how the pointer version adds a 0x prefix, for instance. Always use %p since it knows about the size of pointers, and how to best represent them as text.

How remove border around image in css?

Also, in your html, remember to delete all blanks / line feeds / tabs between the closing tag and the opening tag.

<img src='a.png' /> <img src='b.png' /> will always display a space between the images even if the border attribute is set to 0, whereas <img src='a.png' /><img src='b.png' /> will not.

Having issues with a MySQL Join that needs to meet multiple conditions

SELECT 
    u . *
FROM
    room u
        JOIN
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

How to convert UTF-8 byte[] to string?

hier is a result where you didnt have to bother with encoding. I used it in my network class and send binary objects as string with it.

        public static byte[] String2ByteArray(string str)
        {
            char[] chars = str.ToArray();
            byte[] bytes = new byte[chars.Length * 2];

            for (int i = 0; i < chars.Length; i++)
                Array.Copy(BitConverter.GetBytes(chars[i]), 0, bytes, i * 2, 2);

            return bytes;
        }

        public static string ByteArray2String(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / 2];

            for (int i = 0; i < chars.Length; i++)
                chars[i] = BitConverter.ToChar(bytes, i * 2);

            return new string(chars);
        }

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

I copied remote origin url from another .git/config file, doing so my new .git/config file was missing following line in [remote "origin"] section

fetch = +refs/heads/*:refs/remotes/origin/*

Adding above line fixed error: pathspec 'master' did not match any file(s) known to git.

Check if a Bash array contains a value

Borrowing from Dennis Williamson's answer, the following solution combines arrays, shell-safe quoting, and regular expressions to avoid the need for: iterating over loops; using pipes or other sub-processes; or using non-bash utilities.

declare -a array=('hello, stack' one 'two words' words last)
printf -v array_str -- ',,%q' "${array[@]}"

if [[ "${array_str},," =~ ,,words,, ]]
then
   echo 'Matches'
else
   echo "Doesn't match"
fi

The above code works by using Bash regular expressions to match against a stringified version of the array contents. There are six important steps to ensure that the regular expression match can't be fooled by clever combinations of values within the array:

  1. Construct the comparison string by using Bash's built-in printf shell-quoting, %q. Shell-quoting will ensure that special characters become "shell-safe" by being escaped with backslash \.
  2. Choose a special character to serve as a value delimiter. The delimiter HAS to be one of the special characters that will become escaped when using %q; that's the only way to guarantee that values within the array can't be constructed in clever ways to fool the regular expression match. I choose comma , because that character is the safest when eval'd or misused in an otherwise unexpected way.
  3. Combine all array elements into a single string, using two instances of the special character to serve as delimiter. Using comma as an example, I used ,,%q as the argument to printf. This is important because two instances of the special character can only appear next to each other when they appear as the delimiter; all other instances of the special character will be escaped.
  4. Append two trailing instances of the delimiter to the string, to allow matches against the last element of the array. Thus, instead of comparing against ${array_str}, compare against ${array_str},,.
  5. If the target string you're searching for is supplied by a user variable, you must escape all instances of the special character with a backslash. Otherwise, the regular expression match becomes vulnerable to being fooled by cleverly-crafted array elements.
  6. Perform a Bash regular expression match against the string.

How to update fields in a model without creating a new record in django?

You should do it this way ideally

t = TemperatureData.objects.get(id=1)
t.value = 999
t.save(['value'])

This allow you to specify which column should be saved and rest are left as they currently are in database. (https://code.djangoproject.com/ticket/4102)!

Get the full URL in PHP

I used this statement.

$base = "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]$my_web_base_path";
$url = $base . "/" . dirname(dirname(__FILE__));

I hope this will help you.

Alternative to deprecated getCellType

The accepted answer shows the reason for the deprecation but misses to name the alternative:

CellType    getCellTypeEnum()

where the CellType is the enum decribing the type of the cell.

The plan is to rename getCellTypeEnum() back to getCellType() in POI 4.0.

What are the differences between the urllib, urllib2, urllib3 and requests module?

One considerable difference is about porting Python2 to Python3. urllib2 does not exist for python3 and its methods ported to urllib. So you are using that heavily and want to migrate to Python3 in future, consider using urllib. However 2to3 tool will automatically do most of the work for you.

How do I get the path of the current executed file in Python?

this solution is robust even in executables

import inspect, os.path

filename = inspect.getframeinfo(inspect.currentframe()).filename
path     = os.path.dirname(os.path.abspath(filename))

Python unittest passing arguments

Unit testing is meant for testing the very basic functionality (the lowest level functions of the application) to be sure that your application building blocks work correctly. There is probably no formal definition of what does that exactly mean, but you should consider other kinds of testing for the bigger functionality -- see Integration testing. The unit testing framework may not be ideal for the purpose.

How do I convert a IPython Notebook into a Python file via commandline?

There's a very nice package called nb_dev which is designed for authoring Python packages in Jupyter Notebooks. Like nbconvert, it can turn a notebook into a .py file, but it is more flexible and powerful because it has a lot of nice additional authoring features to help you develop tests, documentation, and register packages on PyPI. It was developed by the fast.ai folks.

It has a bit of a learning curve, but the documentation is good and it is not difficult overall.

ionic build Android | error: No installed build tools found. Please install the Android build tools

I have tried all the above solution. None works. Until I was linked to https://forum.ionicframework.com/t/ionic-v4-no-installed-build-tools-found/152150.

Apparently, you must run the command as root. Sudo is not enough. You need to change to root user before you can run all the commands.

How can I convert a date into an integer?

var dates = dates_as_int.map(function(dateStr) {
    return new Date(dateStr).getTime();
});

=>

[1468959781804, 1469029434776, 1469199218634, 1469457574527]

Update: ES6 version:

const dates = dates_as_int.map(date => new Date(date).getTime())

Customizing Bootstrap CSS template

Use LESS with Bootstrap...

Here are the Bootstrap docs for how to use LESS

(they have moved since previous answers)

Mercurial undo last commit

In the current version of TortoiseHg Workbench 4.4.1 (07.2018) you can use Repository - Rollback/undo...:
enter image description here

How do I drop a foreign key in SQL Server?

You can also Right Click on the table, choose modify, then go to the attribute, right click on it, and choose drop primary key.

Struct memory layout in C

In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.

Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.

Possibly every remotely modern compiler implements #pragma pack which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)

From C99 §6.7.2.1:

12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

Jackson - How to process (deserialize) nested JSON?

@Patrick I would improve your solution a bit

@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {        
    ObjectNode objectNode = jp.readValueAsTree();
    JsonNode wrapped = objectNode.get(wrapperKey);
    JsonParser parser = node.traverse();
    parser.setCodec(jp.getCodec());
    Vendor mapped = parser.readValueAs(Vendor.class);
    return mapped;
}

It works faster :)

How to swap two variables in JavaScript

Destructing assignment is the best way to solve your problem.

_x000D_
_x000D_
var a = 1;
var b = 2;

[a, b] = [b, a];

console.log("After swap a =", a, " and b =", b);
_x000D_
_x000D_
_x000D_

Full width image with fixed height

If you don't want to lose the ratio of your image, then don't bother with height:300px; and just use width:100%;.

If the image is too large, then you will have to crop it using an image editor.

How to generate List<String> from SQL query?

I think this is what you're looking for.

List<String> columnData = new List<String>();

using(SqlConnection connection = new SqlConnection("conn_string"))
{
    connection.Open();
    string query = "SELECT Column1 FROM Table1";
    using(SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                columnData.Add(reader.GetString(0));
            }         
        }
    }
}

Not tested, but this should work fine.

SonarQube Exclude a directory

You can do the same with build.gradle

sonarqube {
properties {
    property "sonar.exclusions", "**/src/java/test/**/*.java"
  }
}

And if you want to exclude more files/directories then:

sonarqube {
properties {
    property "sonar.exclusions", "**/src/java/test/**/*.java, **/src/java/main/**/*.java"
  }
}

Retrieving Data from SQL Using pyodbc

You are so close!

import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')
cursor = cnxn.cursor()

cursor.execute("SELECT WORK_ORDER.TYPE,WORK_ORDER.STATUS, WORK_ORDER.BASE_ID, WORK_ORDER.LOT_ID FROM WORK_ORDER")
for row in cursor.fetchall():
    print row

(the "columns()" function collects meta-data about the columns in the named table, as opposed to the actual data).

Change File Extension Using C#

Convert file format to png

string newfilename , 
 string filename = "~/Photo/"  + lbl_ImgPath.Text.ToString();/*get filename from specific path where we store image*/
 string newfilename = Path.ChangeExtension(filename, ".png");/*Convert file format from jpg to png*/

Get path from open file in Python

You can get it like this also.

filepath = os.path.abspath(f.name)

How to pass multiple parameters from ajax to mvc controller?

You can do it by not initializing url and writing it at hardcode like this

//var url = '@Url.Action("ActionName", "Controller");

$.post("/Controller/ActionName?para1=" + data + "&para2=" + data2, function (result) {
        $("#" + data).html(result);
        ............. Your code
    });

While your controller side code must be like this below:

public ActionResult ActionName(string para1, string para2)
{
   Your Code .......
}

this was simple way. now we can do pass multiple data by json also like this:

var val1= $('#btn1').val();  
var val2= $('#btn2').val(); 
$.ajax({
                    type: "GET",
                    url: '@Url.Action("Actionre", "Contr")',
                    contentType: "application/json; charset=utf-8",
                    data: { 'para1': val1, 'para2': val2 },
                    dataType: "json",
                    success: function (cities) {
                        ur code.....
                    }
                });

While your controller side code will be same:

public ActionResult ActionName(string para1, string para2)
{
   Your Code .......
}

form_for with nested resources

You don't need to do special things in the form. You just build the comment correctly in the show action:

class ArticlesController < ActionController::Base
  ....
  def show
    @article = Article.find(params[:id])
    @new_comment = @article.comments.build
  end
  ....
end

and then make a form for it in the article view:

<% form_for @new_comment do |f| %>
   <%= f.text_area :text %>
   <%= f.submit "Post Comment" %>
<% end %>

by default, this comment will go to the create action of CommentsController, which you will then probably want to put redirect :back into so you're routed back to the Article page.

How can I reset or revert a file to a specific revision?

I think I've found it....from http://www-cs-students.stanford.edu/~blynn/gitmagic/ch02.html

Sometimes you just want to go back and forget about every change past a certain point because they're all wrong.

Start with:

$ git log

which shows you a list of recent commits, and their SHA1 hashes.

Next, type:

$ git reset --hard SHA1_HASH

to restore the state to a given commit and erase all newer commits from the record permanently.

Why does 2 mod 4 = 2?

MOD is remainder operator. That is why 2 mod 4 gives 2 as remainder. 4*0=0 and then 2-0=2. To make it more clear try to do same with 6 mod 4 or 8 mod 3.

Why is there no tuple comprehension in Python?

As another poster macm mentioned, the fastest way to create a tuple from a generator is tuple([generator]).


Performance Comparison

  • List comprehension:

    $ python3 -m timeit "a = [i for i in range(1000)]"
    10000 loops, best of 3: 27.4 usec per loop
    
  • Tuple from list comprehension:

    $ python3 -m timeit "a = tuple([i for i in range(1000)])"
    10000 loops, best of 3: 30.2 usec per loop
    
  • Tuple from generator:

    $ python3 -m timeit "a = tuple(i for i in range(1000))"
    10000 loops, best of 3: 50.4 usec per loop
    
  • Tuple from unpacking:

    $ python3 -m timeit "a = *(i for i in range(1000)),"
    10000 loops, best of 3: 52.7 usec per loop
    

My version of python:

$ python3 --version
Python 3.6.3

So you should always create a tuple from a list comprehension unless performance is not an issue.

Make index.html default, but allow index.php to be visited if typed in

DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml

it doesn't has any means? you may be just need to add like this!

<IfModule dir_module>
    DirectoryIndex index.php index.html index.htm
</IfModule>

enter image description here

How do I kill a VMware virtual machine that won't die?

If you are using Windows, the virtual machine should have it's own process that is visible in task manager. Use sysinternals Process Explorer to find the right one and then kill it from there.

Redis command to get all available keys?

redis-cli -h <host> -p <port> keys * 

where * is the pattern to list all keys

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

Getting started with Haskell

I suggest that you first start by reading BONUS' tutorial, And then reading Real World Haskell (online for free). Join the #Haskell IRC channel, on irc.freenode.com, and ask questions. These people are absolutely newbie friendly, and have helped me a lot over time. Also, right here on SO is a great place to get help with things you can't grasp! Try not to get discouraged, once it clicks, your mind will be blown.

BONUS' tutorial will prime you up, and get you ready for the thrill ride that Real World Haskell brings. I wish you luck!

SQL Combine Two Columns in Select Statement

I think this is what you are looking for -

select Address1+Address2 as CompleteAddress from YourTable
where Address1+Address2 like '%YourSearchString%'

To prevent a compound word being created when we append address1 with address2, you can use this -

select Address1 + ' ' + Address2 as CompleteAddress from YourTable 
where Address1 + ' ' + Address2 like '%YourSearchString%'

So, '123 Center St' and 'Apt 3B' will not be '123 Center StApt 3B' but will be '123 Center St Apt 3B'.

Android Studio-No Module

For me the sdk version mentioned in build.gradle wasn't installed. Used SDK Manager to install the right SDK version and it worked

What is SaaS, PaaS and IaaS? With examples

Adding to that, I have used AWS, heroku and currently using Jelastic and found -

Jelastic offers a Java and PHP cloud hosting platform. Jelastic automatically scales Java and PHP applications and allocates server resources, thus delivering true next-generation Java and PHP cloud computing. http://blog.jelastic.com/2013/04/16/elastic-beanstalk-vs-jelastic/ or http://cloud.dzone.com/articles/jelastic-vs-heroku-1

Personally I found -

  • Jelastic is faster
  • You don’t need to code to any jelastic APIs – just upload your application and select your stack. You can also mix and match software stacks at will.

Try any of them and explore yourself. Its fun :-)

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

Aggregate multiple columns at once

We can use the formula method of aggregate. The variables on the 'rhs' of ~ are the grouping variables while the . represents all other variables in the 'df1' (from the example, we assume that we need the mean for all the columns except the grouping), specify the dataset and the function (mean).

aggregate(.~id1+id2, df1, mean)

Or we can use summarise_each from dplyr after grouping (group_by)

library(dplyr)
df1 %>%
    group_by(id1, id2) %>% 
    summarise_each(funs(mean))

Or using summarise with across (dplyr devel version - ‘0.8.99.9000’)

df1 %>% 
    group_by(id1, id2) %>%
    summarise(across(starts_with('val'), mean))

Or another option is data.table. We convert the 'data.frame' to 'data.table' (setDT(df1), grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD) and get the mean.

library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)] 

data

df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b", 
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"), 
val1 = c(1L, 
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L, 
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

where is gacutil.exe?

On Windows 2012 R2, you can't install Visual Studio or SDK. You can use powershell to register assemblies into GAC. It didn't need any special installation for me.

Set-location "C:\Temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Temp\myGacLibrary.dll")

If you need to get the name and PublicKeyToken see this question.

PuTTY Connection Manager download?

I've found version 0.7.1 Alpha of PuTTY Connection Manager to be the most stable (it was previously hidden on the forums). It's available from PuTTY Connection Manager – Website Down.

Java switch statement: Constant expression required, but it IS constant

You get Constant expression required because you left the values off your constants. Try:

public abstract class Foo {
    ...
    public static final int BAR=0;
    public static final int BAZ=1;
    public static final int BAM=2;
    ...
}

Asp.net Validation of viewstate MAC failed

Dear All with all respict to answers up there there are case gives this error when web.config value is

<httpCookies httpOnlyCookies="true" requireSSL="true"/>

and link is http not https

How to check for a JSON response using RSpec?

You can also define a helper function inside spec/support/

module ApiHelpers
  def json_body
    JSON.parse(response.body)
  end
end

RSpec.configure do |config| 
  config.include ApiHelpers, type: :request
end

and use json_body whenever you need to access the JSON response.

For example, inside your request spec you can use it directly

context 'when the request contains an authentication header' do
  it 'should return the user info' do
    user  = create(:user)
    get URL, headers: authenticated_header(user)

    expect(response).to have_http_status(:ok)
    expect(response.content_type).to eq('application/vnd.api+json')
    expect(json_body["data"]["attributes"]["email"]).to eq(user.email)
    expect(json_body["data"]["attributes"]["name"]).to eq(user.name)
  end
end

(Excel) Conditional Formatting based on Adjacent Cell Value

I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:

Under Conditional Formatting > Manage Rules:

  1. Make a new rule with "Use a formula to determine which cells to format"
  2. Make your rule, but put a dollar sign only in front of the letter: $A2<$B2
  3. Under "Applies to", Manually select the second column (It would not work for me if I changed the value in the box, it just kept snapping back to what was already there), so it looks like $B$2:$B$100 (assuming you have 100 rows)

This worked for me in Excel 2016.

Git: "please tell me who you are" error

IMHO, the proper way to resolve this error is to configure your global git config file.

To do that run the following command: git config --global -e

An editor will appear where you can insert your default git configurations.

Here're are a few:

[user]
    name = your_username
    email = [email protected] 
[alias]
    # BASIC
    st = status
    ci = commit
    br = branch
    co = checkout
    df = diff

For more details, see Customizing Git - Git Configuration

When you see a command like, git config ...

$ git config --global core.whitespace \
    trailing-space,space-before-tab,indent-with-non-tab

... you can put that into your global git config file as:

[core]
   whitespace = space-before-tab,-indent-with-non-tab,trailing-space

For one off configurations, you can use something like git config --global user.name 'your_username'

If you don't set your git configurations globally, you'll need to do so for each and every git repo you work with locally.

The user.name and user.email settings tell git who you are, so subsequent git commit commands will not complain, *** Please tell me who you are.

Many times, the commands git suggests you run are not what you should run. This time, the suggested commands are not bad:

$ git commit -m 'first commit'

*** Please tell me who you are.

Run

  git config --global user.email "[email protected]"
  git config --global user.name "Your Name"

Tip: Until I got very familiar with git, making a backup of my project file--before running the suggested git commands and exploring things I thought would work--saved my bacon on more than a few occasions.

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

I also needed to install npm in Windows and got it through the Chocolatey pacakage manager. For those who haven't heard about it, Chocolatey is a package manager for Windows, that gives you the convenience of an apt-get in Windows environments. To get it go to https://chocolatey.org/ where there's a PowerShell script to download it and install it. After that you can run:

chocolatey install npm

and you're good to go.

Note that the standalone npm is no longer being updated and the last version that is out there is known to have problems on Windows. Another option you can look at is extracting npm from the MSI using LessMSI.

How do I automatically scroll to the bottom of a multiline text box?

At regular intervals, I am adding new lines of text to it. I would like the textbox to automatically scroll to the bottom-most entry (the newest one) whenever a new line is added.

If you use TextBox.AppendText(string text), it will automatically scroll to the end of the newly appended text. It avoids the flickering scrollbar if you're calling it in a loop.

It also happens to be an order of magnitude faster than concatenating onto the .Text property. Though that might depend on how often you're calling it; I was testing with a tight loop.


This will not scroll if it is called before the textbox is shown, or if the textbox is otherwise not visible (e.g. in a different tab of a TabPanel). See TextBox.AppendText() not autoscrolling. This may or may not be important, depending on if you require autoscroll when the user can't see the textbox.

It seems that the alternative method from the other answers also don't work in this case. One way around it is to perform additional scrolling on the VisibleChanged event:

textBox.VisibleChanged += (sender, e) =>
{
    if (textBox.Visible)
    {
        textBox.SelectionStart = textBox.TextLength;
        textBox.ScrollToCaret();
    }
};

Internally, AppendText does something like this:

textBox.Select(textBox.TextLength + 1, 0);
textBox.SelectedText = textToAppend;

But there should be no reason to do it manually.

(If you decompile it yourself, you'll see that it uses some possibly more efficient internal methods, and has what seems to be a minor special case.)

What are WSDL, SOAP and REST?

REST is light-weight in terms of encoding, much more useful for light weight devices i.e. non strict APIs.

REST is format independent. XML, HTML, JSON all options are available.

REST provides abilities for on 2 point message transfer (not surprising since REST stands for REpresentational State Transfer) where WSDL/SOAP interaction is multiple point message interaction.

REST does not require a new extension for XML messages, where in WSDL/SOAP this is the case.

WSDL/SOAP uses multiple transport protocols, REST relies on only HTTP. Therefore WSDL/SOAP can be used like a RESTful way, however simple requests can be overly complicated/heavy weighted.

A simple analogy: REST is like a motoboy delivers your food easy and quick. XML extended WSDL/SOAP more like UPS delivery, more structured and serious stuff but comes with a cost.

Inserting multiple rows in a single SQL query?

In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.

INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.

For example:

INSERT INTO MyTable
  ( Column1, Column2, Column3 )
VALUES
  ('John', 123, 'Lloyds Office'), 
  ('Jane', 124, 'Lloyds Office'), 
  ('Billy', 125, 'London Office'),
  ('Miranda', 126, 'Bristol Office');

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

We needed to serialise an arbitrary object hierarchy, where the root or any of the nested properties in the hierarchy could be instances of Error.

Our solution was to use the replacer param of JSON.stringify(), e.g.:

_x000D_
_x000D_
function jsonFriendlyErrorReplacer(key, value) {_x000D_
  if (value instanceof Error) {_x000D_
    return {_x000D_
      // Pull all enumerable properties, supporting properties on custom Errors_x000D_
      ...value,_x000D_
      // Explicitly pull Error's non-enumerable properties_x000D_
      name: value.name,_x000D_
      message: value.message,_x000D_
      stack: value.stack,_x000D_
    }_x000D_
  }_x000D_
_x000D_
  return value_x000D_
}_x000D_
_x000D_
let obj = {_x000D_
    error: new Error('nested error message')_x000D_
}_x000D_
_x000D_
console.log('Result WITHOUT custom replacer:', JSON.stringify(obj))_x000D_
console.log('Result WITH custom replacer:', JSON.stringify(obj, jsonFriendlyErrorReplacer))
_x000D_
_x000D_
_x000D_

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 
margin:10px;
}

DEMO

How to display the first few characters of a string in Python?

If you want first 2 letters and last 2 letters of a string then you can use the following code: name = "India" name[0:2]="In" names[-2:]="ia"

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

PHP Curl And Cookies

You can define different cookies for every user with CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR. Make different file for every user so each one would have it's own cookie-based session on remote server.

Detect Windows version in .net

One way:

public string GetOSVersion()
{
  int _MajorVersion = Environment.OSVersion.Version.Major;

  switch (_MajorVersion) {
    case 5:
      return "Windows XP";
    case 6:
      switch (Environment.OSVersion.Version.Minor) {
        case 0:
          return "Windows Vista";
        case 1:
          return "Windows 7";
        default:
          return "Windows Vista & above";
      }
      break;
    default:
      return "Unknown";
  }
}

Then simply do wrap a select case around the function.

How to check if a column exists in a SQL Server table?

A more concise version

IF COL_LENGTH('table_name','column_name') IS NULL
BEGIN
/* Column does not exist or caller does not have permission to view the object */
END

The point about permissions on viewing metadata applies to all answers not just this one.

Note that the first parameter table name to COL_LENGTH can be in one, two, or three part name format as required.

An example referencing a table in a different database is

COL_LENGTH('AdventureWorks2012.HumanResources.Department','ModifiedDate')

One difference with this answer compared to using the metadata views is that metadata functions such as COL_LENGTH always only return data about committed changes irrespective of the isolation level in effect.

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

For .NET > 4.0 you can use

TimeSpan time = TimeSpan.FromSeconds(seconds);

//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");

or if you want date time format then you can also do this

TimeSpan time = TimeSpan.FromSeconds(seconds);
DateTime dateTime = DateTime.Today.Add(time);
string displayTime = dateTime.ToString("hh:mm:tt");

For more you can check Custom TimeSpan Format Strings

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

HighCharts Hide Series Name from the Legend

Looks like HighChart 2.2.0 has resolved this issue. I tried it here with the same code you have, and the first series is hidden now. Could you try it with HighChart 2.2.0?

"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)

  1. -- close SIP(system Integrity Protection) -- then reboot, use command +R to enter debug mode, then select terminal: csrutil disable reboot

2.

sudo C_INCLUDE_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2 :/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2/libxml :/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include pip install scrapy --ignore-installed six

3. -- then remove old six, install it again sudo rm -rf /Library/Python/2.7/site-packages/six* sudo rm -rf /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six* sudo pip install six

4. -- then set it back csrutil enable reboot

-- crappy works now

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

Test if element is present using Selenium WebDriver?

public boolean isElementDisplayed() {
        return !driver.findElements(By.xpath("...")).isEmpty();
    }

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

I had the same issue however with doing an upload of a very large file using a python-requests client posting to a nginx+uwsgi backend.

What ended up being the cause was the the backend had a cap on the max file size for uploads lower than what the client was trying to send.

The error never showed up in our uwsgi logs since this limit was actually one imposed by nginx.

Upping the limit in nginx removed the error.

java : convert float to String and String to float

To go the full manual route: This method converts doubles to strings by shifting the number's decimal point around and using floor (to long) and modulus to extract the digits. Also, it uses counting by base division to figure out the place where the decimal point belongs. It can also "delete" higher parts of the number once it reaches the places after the decimal point, to avoid losing precision with ultra-large doubles. See commented code at the end. In my testing, it is never less precise than the Java float representations themselves, when they actually show these imprecise lower decimal places.

/**
 * Convert the given double to a full string representation, i.e. no scientific notation
 * and always twelve digits after the decimal point.
 * @param d The double to be converted
 * @return A full string representation
 */
public static String fullDoubleToString(final double d) {
    // treat 0 separately, it will cause problems on the below algorithm
    if (d == 0) {
        return "0.000000000000";
    }
    // find the number of digits above the decimal point
    double testD = Math.abs(d);
    int digitsBeforePoint = 0;
    while (testD >= 1) {
        // doesn't matter that this loses precision on the lower end
        testD /= 10d;
        ++digitsBeforePoint;
    }

    // create the decimal digits
    StringBuilder repr = new StringBuilder();
    // 10^ exponent to determine divisor and current decimal place
    int digitIndex = digitsBeforePoint;
    double dabs = Math.abs(d);
    while (digitIndex > 0) {
        // Recieves digit at current power of ten (= place in decimal number)
        long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
        repr.append(digit);
        --digitIndex;
    }

    // insert decimal point
    if (digitIndex == 0) {
        repr.append(".");
    }

    // remove any parts above the decimal point, they create accuracy problems
    long digit = 0;
    dabs -= (long)Math.floor(dabs);
    // Because of inaccuracy, move to entirely new system of computing digits after decimal place.
    while (digitIndex > -12) {
        // Shift decimal point one step to the right
        dabs *= 10d;
        final var oldDigit = digit;
        digit = (long)Math.floor(dabs) % 10;
        repr.append(digit);

        // This may avoid float inaccuracy at the very last decimal places.
        // However, in practice, inaccuracy is still as high as even Java itself reports.
        // dabs -= oldDigit * 10l;
        --digitIndex;
    }

    return repr.insert(0, d < 0 ? "-" : "").toString(); 
}

Note that while StringBuilder is used for speed, this method can easily be rewritten to use arrays and therefore also work in other languages.

How to remove a file from the index in git?

According to my humble opinion and my work experience with git, staging area is not the same as index. I may be wrong of course, but as I said, my experience in using git and my logic tell me, that index is a structure that follows your changes to your working area(local repository) that are not excluded by ignoring settings and staging area is to keep files that are already confirmed to be committed, aka files in index on which add command was run on. You don't notice and realize that "slight" difference, because you use git commit -a -m "comment" adding indexed and cached files to stage area and committing in one command or using IDEs like IDEA for that too often. And cache is that what keeps changes in indexed files. If you want to remove file from index that has not been added to staging area before, options proposed before match for you, but... If you have done that already, you will need to use

Git restore --staged <file>

And, please, don't ask me where I was 10 years ago... I missed you, this answer is for further generations)

Any way of using frames in HTML5?

You'll have to resort to XHTML or HTML 4.01 for this. Although iframe is still there in HTML5, its use is not recommended for embedding content meant for the user.

And be sure to tell your teacher that frames haven't been state-of-the-art since the late nineties. They have no place in any kind of education at all, except possibly for historical reasons.

Create a .tar.bz2 file Linux

Try this from different folder:

sudo tar -cvjSf folder.tar.bz2 folder/*

Display images in asp.net mvc

Make sure you image is a relative path such as:

@Url.Content("~/Content/images/myimage.png")

MVC4

<img src="~/Content/images/myimage.png" />

You could convert the byte[] into a Base64 string on the fly.

string base64String = Convert.ToBase64String(imageBytes);

<img src="@String.Format("data:image/png;base64,{0}", base64string)" />

Parsing command-line arguments in C

#include <stdio.h>

int main(int argc, char **argv)
{
    size_t i;
    size_t filename_i = -1;

    for (i = 0; i < argc; i++)
    {
        char const *option =  argv[i];
        if (option[0] == '-')
        {
            printf("I am a flagged option");
            switch (option[1])
            {
                case 'a':
                    /*someting*/
                    break;
                case 'b':
                    break;
                case '-':
                    /* "--" -- the next argument will be a file.*/
                    filename_i = i;
                    i = i + 1;
                    break;
                default:
                    printf("flag not recognised %s", option);
                    break;
            }
        }
        else
        {   
            printf("I am a positional argument");
        }

        /* At this point, if -- was specified, then filename_i contains the index
         into argv that contains the filename. If -- was not specified, then filename_i will be -1*/
     }
  return 0;
}

How to find first element of array matching a boolean condition in JavaScript?

It should be clear by now that JavaScript offers no such solution natively; here are the closest two derivatives, the most useful first:

  1. Array.prototype.some(fn) offers the desired behaviour of stopping when a condition is met, but returns only whether an element is present; it's not hard to apply some trickery, such as the solution offered by Bergi's answer.

  2. Array.prototype.filter(fn)[0] makes for a great one-liner but is the least efficient, because you throw away N - 1 elements just to get what you need.

Traditional search methods in JavaScript are characterized by returning the index of the found element instead of the element itself or -1. This avoids having to choose a return value from the domain of all possible types; an index can only be a number and negative values are invalid.

Both solutions above don't support offset searching either, so I've decided to write this:

(function(ns) {
  ns.search = function(array, callback, offset) {
    var size = array.length;

    offset = offset || 0;
    if (offset >= size || offset <= -size) {
      return -1;
    } else if (offset < 0) {
      offset = size - offset;
    }

    while (offset < size) {
      if (callback(array[offset], offset, array)) {
        return offset;
      }
      ++offset;
    }
    return -1;
  };
}(this));

search([1, 2, NaN, 4], Number.isNaN); // 2
search([1, 2, 3, 4], Number.isNaN); // -1
search([1, NaN, 3, NaN], Number.isNaN, 2); // 3

Angular 2 @ViewChild annotation returns undefined

For Angular: Change *ngIf with display style 'block' or 'none' in HTML.

selector: 'app',
template:  `
    <controls [style.display]="controlsOn ? 'block' : 'none'"></controls>
    <slideshow (mousemove)="onMouseMove()"></slideshow>
`,
directives: [SlideshowComponent, ControlsComponent]

How can an html element fill out 100% of the remaining screen height, using css only?

You can use vh on the min-height property.

min-height: 100vh;

You can do as follows, depending on how you are using the margins...

min-height: calc(100vh - 10px) //Considering you're using some 10px margin top on an outside element

How to solve "Fatal error: Class 'MySQLi' not found"?

Some distributions (such as Gentoo) support multiple installations of PHP, and you have to make sure you're using one with mysqli installed and enabled.

On Gentoo, I had installed a new PHP (with the mysqli USE flag enabled), but I needed to activate the new version of PHP (since the old one must have been missing mysqli):

# eselect php list apache2
  [1]   php5.3 *
  [2]   php5.5
# eselect php set apache2 2
You have to run `/etc/init.d/apache2 restart' for the changes to take effect
# /etc/init.d/apache2 restart

jQuery .search() to any string

search() is a String method.

You are executing the attr function on every <li> element. You need to invoke each and use the this reference within.

Example:

$('li').each(function() {
    var isFound = $(this).attr('title').search(/string/i);
    //do something based on isFound...
});

Minimum 6 characters regex expression

Something along the lines of this?

<asp:TextBox id="txtUsername" runat="server" />

<asp:RegularExpressionValidator
    id="RegularExpressionValidator1"
    runat="server"
    ErrorMessage="Field not valid!"
    ControlToValidate="txtUsername"
    ValidationExpression="[0-9a-zA-Z]{6,}" />

How to configure welcome file list in web.xml

This is my way to setup Servlet as welcome page.

I share for whom concern.

web.xml

  <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Demo</servlet-name>
        <servlet-class>servlet.Demo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Demo</servlet-name>
        <url-pattern></url-pattern>
    </servlet-mapping>

Servlet class

@WebServlet(name = "/demo")
public class Demo extends HttpServlet {
   public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException  {
       RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
   }
}

How can I combine multiple rows into a comma-delimited list in Oracle?

The fastest way it is to use the Oracle collect function.

You can also do this:

select *
  2    from (
  3  select deptno,
  4         case when row_number() over (partition by deptno order by ename)=1
  5             then stragg(ename) over
  6                  (partition by deptno
  7                       order by ename
  8                         rows between unbounded preceding
  9                                  and unbounded following)
 10         end enames
 11    from emp
 12         )
 13   where enames is not null

Visit the site ask tom and search on 'stragg' or 'string concatenation' . Lots of examples. There is also a not-documented oracle function to achieve your needs.

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

JQuery - Call the jquery button click event based on name property

You can use the name property for that particular element. For example to set a border of 2px around an input element with name xyz, you can use;

$(function() {
    $("input[name = 'xyz']").css("border","2px solid red");
})

DEMO

How to clear browsing history using JavaScript?

to disable back function of the back button:

window.addEventListener('popstate', function (event) {
  history.pushState(null, document.title, location.href);
});

Phone validation regex

I tried :

^(1[ \-\+]{0,3}|\+1[ -\+]{0,3}|\+1|\+)?((\(\+?1-[2-9][0-9]{1,2}\))|(\(\+?[2-8][0-9][0-9]\))|(\(\+?[1-9][0-9]\))|(\(\+?[17]\))|(\([2-9][2-9]\))|([ \-\.]{0,3}[0-9]{2,4}))?([ \-\.][0-9])?([ \-\.]{0,3}[0-9]{2,4}){2,3}$

I took care of special country codes like 1-97... as well. Here are the numbers I tested against (from Puneet Lamba and MCattle):

***** PASS *****
18005551234
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1.800.555.1234
+1.800.555.1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
(+230) 5 911 4450
123345678
(1) 345 654 67
+1 245436
1-976 33567
(1-734) 5465654
+(230) 2 345 6568
***** CORRECTLY FAILING *****
(003) 555-1212
(103) 555-1212
(911) 555-1212
1-800-555-1234p
800x555x1234
+1 800 555x1234
***** FALSE POSITIVES *****
180055512345
1 800 5555 1234
+867 800 555 1234
1 (800)  555-1234
86 800 555 1212

Originally posted here: Regular expression to match standard 10 digit phone number

How do malloc() and free() work?

Your program crashes because it used memory that does not belong to you. It may be used by someone else or not - if you are lucky you crash, if not the problem may stay hidden for a long time and come back and bite you later.

As far as malloc/free implementation goes - entire books are devoted to the topic. Basically the allocator would get bigger chunks of memory from the OS and manage them for you. Some of the problems an allocator must address are:

  • How to get new memory
  • How to store it - ( list or other structure, multiple lists for memory chunks of different size, and so on )
  • What to do if the user requests more memory than currently available ( request more memory from OS, join some of the existing blocks, how to join them exactly, ... )
  • What to do when the user frees memory
  • Debug allocators may give you bigger chunk that you requested and fill it some byte pattern, when you free the memory the allocator can check if wrote outside of the block ( which is probably happening in your case) ...

SELECT max(x) is returning null; how can I make it return 0?

You can also use COALESCE ( expression [ ,...n ] ) - returns first non-null like:

SELECT COALESCE(MAX(X),0) AS MaxX
FROM tbl
WHERE XID = 1

Get TimeZone offset value from TimeZone without TimeZone name

I need to save the phone's timezone in the format [+/-]hh:mm

No, you don't. Offset on its own is not enough, you need to store the whole time zone name/id. For example I live in Oslo where my current offset is +02:00 but in winter (due to ) it is +01:00. The exact switch between standard and summer time depends on factors you don't want to explore.

So instead of storing + 02:00 (or should it be + 01:00?) I store "Europe/Oslo" in my database. Now I can restore full configuration using:

TimeZone tz = TimeZone.getTimeZone("Europe/Oslo")

Want to know what is my time zone offset today?

tz.getOffset(new Date().getTime()) / 1000 / 60   //yields +120 minutes

However the same in December:

Calendar christmas = new GregorianCalendar(2012, DECEMBER, 25);
tz.getOffset(christmas.getTimeInMillis()) / 1000 / 60   //yields +60 minutes

Enough to say: store time zone name or id and every time you want to display a date, check what is the current offset (today) rather than storing fixed value. You can use TimeZone.getAvailableIDs() to enumerate all supported timezone IDs.

How to print variables in Perl

print "Number of lines: $nids\n";
print "Content: $ids\n";

How did Perl complain? print $ids should work, though you probably want a newline at the end, either explicitly with print as above or implicitly by using say or -l/$\.

If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}:

print "foo${ids}bar";

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.

$products = DB::table('products AS pr')
        ->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
        ->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
        ->orderBy('pr.id', 'desc')
        ->get();

Hope this helps.

Clearing a text field on button click

If you are trying to "Submit and Reset" the the "form" with one Button click, Try this!

Here I have used jQuery function, it can be done by simple JavaScript also...

        <form id="form_data">
           <input type="anything"  name="anything" />
           <input type="anything"  name="anything" />

             <!-- Save and Reset button -->
           <button type="button" id="btn_submit">Save</button>
           <button type="reset" id="btn_reset" style="display: none;"></button>
        </form>

<script type="text/javascript">
$(function(){
    $('#btn_submit').click(function(){
        // Do what ever you want
       $('#btn_reset').click();  // Clicking reset button
    });
});
</script>

jQuery creating objects

May be you want this (oop in javascript)

function box(color)
{
    this.color=color;
}

var box1=new box('red');    
var box2=new box('white');    

DEMO.

For more information.

How to detect the device orientation using CSS media queries?

I would go for aspect-ratio, it offers way more possibilities.

/* Exact aspect ratio */
@media (aspect-ratio: 2/1) {
    ...
}

/* Minimum aspect ratio */
@media (min-aspect-ratio: 16/9) {
    ...
}

/* Maximum aspect ratio */
@media (max-aspect-ratio: 8/5) {
    ...
}

Both, orientation and aspect-ratio depend on the actual size of the viewport and have nothing todo with the device orientation itself.

Read more: https://dev.to/ananyaneogi/useful-css-media-query-features-o7f

Upload DOC or PDF using PHP

    <?php

    //create table

    /*

    --
    -- Database: `mydb`
    --

    -- --------------------------------------------------------

    --
    -- Table structure for table `tbl_user_data`
    --

    CREATE TABLE `tbl_user_data` (
      `attachment_id` int(11) NOT NULL,
      `attachment` varchar(200) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    --
    -- Indexes for dumped tables
    --

    --
    -- Indexes for table `tbl_user_data`
    --
    ALTER TABLE `tbl_user_data`
      ADD PRIMARY KEY (`attachment_id`);

    --
    -- AUTO_INCREMENT for dumped tables
    --

    --
    -- AUTO_INCREMENT for table `tbl_user_data`
    --
    ALTER TABLE `tbl_user_data`
      MODIFY `attachment_id` int(11) NOT NULL AUTO_INCREMENT;

      */
    $servername = "localhost";
    $username = "root";
    $password = "";
    // Create connection
    $dbname = "myDB";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    if(isset($_POST['submit'])){

      $fileName=$_FILES["resume"]["name"];
      $fileSize=$_FILES["resume"]["size"]/1024;
      $fileType=$_FILES["resume"]["type"];
      $fileTmpName=$_FILES["resume"]["tmp_name"];
      $statusMsg = '';
      $random=rand(1111,9999);
      $newFileName=$random.$fileName;

      //file upload path
      $targetDir = "resumeUpload/";
      $fileName = basename($_FILES["resume"]["name"]);
      $targetFilePath = $targetDir . $newFileName;
      $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

      if(!empty($_FILES["resume"]["name"])) {
          //allow certain file formats
          //$allowTypes = array('jpg','png','jpeg','gif','pdf','docx','doc');
          $allowTypes = array('pdf','docx','doc');
          if(in_array($fileType, $allowTypes)){
              //upload file to server
              if(move_uploaded_file($_FILES["resume"]["tmp_name"], $targetFilePath)){
                  $statusMsg = "The file ".$fileName. " has been uploaded.";
              }else{
                  $statusMsg = "Sorry, there was an error uploading your file.";
              }
          }else{
              $statusMsg = 'Sorry, only DOC,DOCX, & PDF files are allowed to upload.';
          }
      }else{
          $statusMsg = 'Please select a file to upload.';
      }

      //display status message
      echo $statusMsg;

      $sql="INSERT INTO `tbl_user_data` (`attachment_id`, `attachment`) VALUES
      ('NULL', '$newFileName')";

      if (mysqli_query($conn, $sql)) {

       $last_id = mysqli_insert_id($conn);
         echo "upload success";
      } else {
          echo "Error: " . $sql . "<br>" . mysqli_error($conn);
      }


    }

    ?>
    <form id="frm_upload" action="" method="post" enctype="multipart/form-data">
    Upload Resume:<input type="file" name="resume" id="resume">
    <button type="submit" name="submit">Apply  Now</button> 
    </form>

     //output sample[![check here for sample output][1]][1]

bootstrap datepicker setDate format dd/mm/yyyy

format : "DD/MM/YYYY" should resolve your issue. If you need more help regarding available formats, please visit http://momentjs.com/ which is used by this control internally.

I was facing an issue where this "format" thing was working fine on local machine but when I deployed the application on server, the date was not getting populated and the control was empty. when I commented the format code, it started working but then I didn't have the format that I needed. I fixed that issue using globalization entries in web.config.

<system.web>
    <globalization
    requestEncoding="utf-8"
    responseEncoding="utf-8"
    culture="en-GB"
    uiCulture="en-GB" />    
</system.web>

This helped in ensuring that both local & server environments have same culture.

Automatically set appsettings.json for dev and release environments in asp.net core?

I have added screenshots of a working environment, because it cost me several hours of R&D.

  1. First, add a key to your launch.json file.

    See the below screenshot, I have added Development as my environment.

    Declaration of the environment variable in launch.json

  2. Then, in your project, create a new appsettings.{environment}.json file that includes the name of the environment.

    In the following screenshot, look for two different files with the names:

    • appsettings.Development.Json
    • appSetting.json


    Project view of appsettings JSON files

  3. And finally, configure it to your StartUp class like this:

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
    
        Configuration = builder.Build();
    }
    
  4. And at last, you can run it from the command line like this:

    dotnet run --environment "Development"
    

    where "Development" is the name of my environment.

Difference between javacore, thread dump and heap dump in Websphere

A Thread dump is a dump of all threads's stack traces, i.e. as if each Thread suddenly threw an Exception and printStackTrace'ed that. This is so that you can see what each thread is doing at some specific point, and is for example very good to catch deadlocks.

A heap dump is a "binary dump" of the full memory the JVM is using, and is for example useful if you need to know why you are running out of memory - in the heap dump you could for example see that you have one billion User objects, even though you should only have a thousand, which points to a memory retention problem.

What is the JUnit XML format specification that Hudson supports?

The top answer of the question Anders Lindahl refers to an xsd file.

Personally I found this xsd file also very useful (I don't remember how I found that one). It looks a bit less intimidating, and as far as I used it, all the elements and attributes seem to be recognized by Jenkins (v1.451)

One thing though: when adding multiple <failure ... elements, only one was retained in Jenkins. When creating the xml file, I now concatenate all the failures in one.


Update 2016-11 The link is broken now. A better alternative is this page from cubic.org: JUnit XML reporting file format, where a nice effort has been taken to provide a sensible documented example. Example and xsd are copied below, but their page looks waay nicer.


sample JUnit XML file

<?xml version="1.0" encoding="UTF-8"?>
<!-- a description of the JUnit XML format and how Jenkins parses it. See also junit.xsd -->

<!-- if only a single testsuite element is present, the testsuites
     element can be omitted. All attributes are optional. -->
<testsuites disabled="" <!-- total number of disabled tests from all testsuites. -->
            errors=""   <!-- total number of tests with error result from all testsuites. -->
            failures="" <!-- total number of failed tests from all testsuites. -->
            name=""
            tests=""    <!-- total number of successful tests from all testsuites. -->
            time=""     <!-- time in seconds to execute all test suites. -->
        >

  <!-- testsuite can appear multiple times, if contained in a testsuites element.
       It can also be the root element. -->
  <testsuite name=""      <!-- Full (class) name of the test for non-aggregated testsuite documents.
                               Class name without the package for aggregated testsuites documents. Required -->
         tests=""     <!-- The total number of tests in the suite, required. -->
         disabled=""  <!-- the total number of disabled tests in the suite. optional -->
             errors=""    <!-- The total number of tests in the suite that errored. An errored test is one that had an unanticipated problem,
                               for example an unchecked throwable; or a problem with the implementation of the test. optional -->
             failures=""  <!-- The total number of tests in the suite that failed. A failure is a test which the code has explicitly failed
                               by using the mechanisms for that purpose. e.g., via an assertEquals. optional -->
             hostname=""  <!-- Host on which the tests were executed. 'localhost' should be used if the hostname cannot be determined. optional -->
         id=""        <!-- Starts at 0 for the first testsuite and is incremented by 1 for each following testsuite -->
         package=""   <!-- Derived from testsuite/@name in the non-aggregated documents. optional -->
         skipped=""   <!-- The total number of skipped tests. optional -->
         time=""      <!-- Time taken (in seconds) to execute the tests in the suite. optional -->
         timestamp="" <!-- when the test was executed in ISO 8601 format (2014-01-21T16:17:18). Timezone may not be specified. optional -->
         >

    <!-- Properties (e.g., environment settings) set during test
     execution. The properties element can appear 0 or once. -->
    <properties>
      <!-- property can appear multiple times. The name and value attributres are required. -->
      <property name="" value=""/>
    </properties>

    <!-- testcase can appear multiple times, see /testsuites/testsuite@tests -->
    <testcase name=""       <!-- Name of the test method, required. -->
          assertions="" <!-- number of assertions in the test case. optional -->
          classname=""  <!-- Full class name for the class the test method is in. required -->
          status=""
          time=""       <!-- Time taken (in seconds) to execute the test. optional -->
          >

      <!-- If the test was not executed or failed, you can specify one
           the skipped, error or failure elements. -->

      <!-- skipped can appear 0 or once. optional -->
      <skipped/>

      <!-- Indicates that the test errored. An errored test is one
           that had an unanticipated problem. For example an unchecked
           throwable or a problem with the implementation of the
           test. Contains as a text node relevant data for the error,
           for example a stack trace. optional -->
      <error message="" <!-- The error message. e.g., if a java exception is thrown, the return value of getMessage() -->
         type=""    <!-- The type of error that occured. e.g., if a java execption is thrown the full class name of the exception. -->
         ></error>

      <!-- Indicates that the test failed. A failure is a test which
       the code has explicitly failed by using the mechanisms for
       that purpose. For example via an assertEquals. Contains as
       a text node relevant data for the failure, e.g., a stack
       trace. optional -->
      <failure message="" <!-- The message specified in the assert. -->
           type=""    <!-- The type of the assert. -->
           ></failure>

      <!-- Data that was written to standard out while the test was executed. optional -->
      <system-out></system-out>

      <!-- Data that was written to standard error while the test was executed. optional -->
      <system-err></system-err>
    </testcase>

    <!-- Data that was written to standard out while the test suite was executed. optional -->
    <system-out></system-out>
    <!-- Data that was written to standard error while the test suite was executed. optional -->
    <system-err></system-err>
  </testsuite>
</testsuites>

JUnit XSD file

<?xml version="1.0" encoding="UTF-8" ?>
<!-- from https://svn.jenkins-ci.org/trunk/hudson/dtkit/dtkit-format/dtkit-junit-model/src/main/resources/com/thalesgroup/dtkit/junit/model/xsd/junit-4.xsd -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="failure">
        <xs:complexType mixed="true">
            <xs:attribute name="type" type="xs:string" use="optional"/>
            <xs:attribute name="message" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="error">
        <xs:complexType mixed="true">
            <xs:attribute name="type" type="xs:string" use="optional"/>
            <xs:attribute name="message" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="properties">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="property" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="property">
        <xs:complexType>
            <xs:attribute name="name" type="xs:string" use="required"/>
            <xs:attribute name="value" type="xs:string" use="required"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="skipped" type="xs:string"/>
    <xs:element name="system-err" type="xs:string"/>
    <xs:element name="system-out" type="xs:string"/>

    <xs:element name="testcase">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="skipped" minOccurs="0" maxOccurs="1"/>
                <xs:element ref="error" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element ref="failure" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element ref="system-out" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element ref="system-err" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:string" use="required"/>
            <xs:attribute name="assertions" type="xs:string" use="optional"/>
            <xs:attribute name="time" type="xs:string" use="optional"/>
            <xs:attribute name="classname" type="xs:string" use="optional"/>
            <xs:attribute name="status" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="testsuite">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="properties" minOccurs="0" maxOccurs="1"/>
                <xs:element ref="testcase" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element ref="system-out" minOccurs="0" maxOccurs="1"/>
                <xs:element ref="system-err" minOccurs="0" maxOccurs="1"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:string" use="required"/>
            <xs:attribute name="tests" type="xs:string" use="required"/>
            <xs:attribute name="failures" type="xs:string" use="optional"/>
            <xs:attribute name="errors" type="xs:string" use="optional"/>
            <xs:attribute name="time" type="xs:string" use="optional"/>
            <xs:attribute name="disabled" type="xs:string" use="optional"/>
            <xs:attribute name="skipped" type="xs:string" use="optional"/>
            <xs:attribute name="timestamp" type="xs:string" use="optional"/>
            <xs:attribute name="hostname" type="xs:string" use="optional"/>
            <xs:attribute name="id" type="xs:string" use="optional"/>
            <xs:attribute name="package" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="testsuites">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="testsuite" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:string" use="optional"/>
            <xs:attribute name="time" type="xs:string" use="optional"/>
            <xs:attribute name="tests" type="xs:string" use="optional"/>
            <xs:attribute name="failures" type="xs:string" use="optional"/>
            <xs:attribute name="disabled" type="xs:string" use="optional"/>
            <xs:attribute name="errors" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>

</xs:schema>

Ignoring directories in Git repositories on Windows

Create a file named .gitignore in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended):

dir_to_ignore/

More information is here.

Using a Loop to add objects to a list(python)

The problem appears to be that you are reinitializing the list to an empty list in each iteration:

while choice != 0:
    ...
    a = []
    a.append(s)

Try moving the initialization above the loop so that it is executed only once.

a = []
while choice != 0:
    ...
    a.append(s)

Sublime Text 2 Code Formatting

Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.

For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).

Greets

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

If by chance this error happens when working with SharePoint 2010: Rename your .json file extensions and be sure to update your restService path. No additional "track by $index" was required.

Luckily I was forwarded this link to this rationale:

.json becomes an important file type in SP2010. SP2010 includes certains webservice endpoints. The location of these files is 14hive\isapi folder. The extension of these files are .json. That is the reason it gives such a error.

"cares only that the contents of a json file is json - not its file extension"

Once the file extensions are changed, should be all set.

Get last 5 characters in a string

str.Substring(str.Length - 5)

TypeError: $.browser is undefined

$.browser has been removed from JQuery 1.9. You can to use Modernizr project instead

http://jquery.com/upgrade-guide/1.9/#jquery-browser-removed

UPDATE TO SUPPORT IE 10 AND IE 11 (TRIDENT version)

To complete the @daniel.moura answer, here is a version which support IE 11 and +

var matched, browser;

jQuery.uaMatch = function( ua ) {
    ua = ua.toLowerCase();

    var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
        /(msie)[\s?]([\w.]+)/.exec( ua ) ||       
        /(trident)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        [];

    return {
        browser: match[ 1 ] || "",
        version: match[ 2 ] || "0"
    };
};

matched = jQuery.uaMatch( navigator.userAgent );
//IE 11+ fix (Trident) 
matched.browser = matched.browser == 'trident' ? 'msie' : matched.browser;
browser = {};

if ( matched.browser ) {
    browser[ matched.browser ] = true;
    browser.version = matched.version;
}

// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
    browser.webkit = true;
} else if ( browser.webkit ) {
    browser.safari = true;
}

jQuery.browser = browser;
// log removed - adds an extra dependency
//log(jQuery.browser)

How should I throw a divide by zero exception in Java without actually dividing by zero?

There are two ways you could do this. Either create your own custom exception class to represent a divide by zero error or throw the same type of exception the java runtime would throw in this situation.

Define custom exception

public class DivideByZeroException() extends ArithmeticException {
}

Then in your code you would check for a divide by zero and throw this exception:

if (divisor == 0) throw new DivideByZeroException();

Throw ArithmeticException

Add to your code the check for a divide by zero and throw an arithmetic exception:

if (divisor == 0) throw new java.lang.ArithmeticException("/ by zero");

Additionally, you could consider throwing an illegal argument exception since a divisor of zero is an incorrect argument to pass to your setKp() method:

if (divisor == 0) throw new java.lang.IllegalArgumentException("divisor == 0");

How do I get the directory that a program is running from?

On Windows the simplest way is to use the _get_pgmptr function in stdlib.h to get a pointer to a string which represents the absolute path to the executable, including the executables name.

char* path;
_get_pgmptr(&path);
printf(path); // Example output: C:/Projects/Hello/World.exe

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

PHP: How to use array_filter() to filter array keys?

Starting from PHP 5.6, you can use the ARRAY_FILTER_USE_KEY flag in array_filter:

$result = array_filter($my_array, function ($k) use ($allowed) {
    return in_array($k, $allowed);
}, ARRAY_FILTER_USE_KEY);


Otherwise, you can use this function (from TestDummy):

function filter_array_keys(array $array, $callback)
{
    $matchedKeys = array_filter(array_keys($array), $callback);

    return array_intersect_key($array, array_flip($matchedKeys));
}

$result = filter_array_keys($my_array, function ($k) use ($allowed) {
    return in_array($k, $allowed);
});


And here is an augmented version of mine, which accepts a callback or directly the keys:

function filter_array_keys(array $array, $keys)
{
    if (is_callable($keys)) {
        $keys = array_filter(array_keys($array), $keys);
    }

    return array_intersect_key($array, array_flip($keys));
}

// using a callback, like array_filter:
$result = filter_array_keys($my_array, function ($k) use ($allowed) {
    return in_array($k, $allowed);
});

// or, if you already have the keys:
$result = filter_array_keys($my_array, $allowed));


Last but not least, you may also use a simple foreach:

$result = [];
foreach ($my_array as $key => $value) {
    if (in_array($key, $allowed)) {
        $result[$key] = $value;
    }
}

How to move table from one tablespace to another in oracle 11g

Try this to move your table (tbl1) to tablespace (tblspc2).

alter table tb11 move tablespace tblspc2;

Error: «Could not load type MvcApplication»

If you're hosting in IIS express and you open your project in two different locations, then you might see this error.

The solution is to go to Project/Properties/Web/Servers and click Create Virtual Directory.

How do I deal with corrupted Git object files?

For anyone stumbling across the same issue:

I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.

What is the difference between pull and clone in git?

git clone <remote-url> <=>

  • create a new directory
  • git init // init new repository
  • git remote add origin <remote-url> // add remote
  • git fetch // fetch all remote branchs
  • git switch <default_branch> // switch to the default branch

git pull <=>

  • fetch ALL remote branches
  • merge CURRENT local branch with tracking remote branch (not another branch) (if local branch existed)

git pull <remote> <branch> <=>

  • fetch the remote branch
  • merge CURRENT local branch with the remote branch (if local branch existed)

HTTP GET in VBS

You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP (I recommend the more explicit MSXML2.XMLHTTP.3.0 progID) however you may need to do different things with the response, it may not be text.

The XMLHTTP also has a responseBody property which is a byte array version of the reponse and there is a responseStream which is an IStream wrapper for the response.

Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0 or WinHttp.WinHttpRequest.5.1 (which has a near identical interface).

Here is an example of using XmlHttp to fetch a PDF file and store it:-

Dim oXMLHTTP
Dim oStream

Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")

oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send

If oXMLHTTP.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write oXMLHTTP.responseBody
    oStream.SaveToFile "c:\somefolder\file.pdf"
    oStream.Close
End If

How do I indent multiple lines at once in Notepad++?

in Notepad++v6.1.8 (Unicode) it works after removing the QuickText plugin.

HTML character codes for this ? or this ?

I usually use the excellent Gucharmap to look up Unicode characters. It's installed on all recent Linux installations with Gnome under the name "Character Map". I don't know of any equivalent tools for Windows or Mac OS X, but its homepage lists a few.

Difference between Pragma and Cache-Control headers?

Stop using (HTTP 1.0) Replaced with (HTTP 1.1 since 1999)
Expires: [date] Cache-Control: max-age=[seconds]
Pragma: no-cache Cache-Control: no-cache

If it's after 1999, and you're still using Expires or Pragma, you're doing it wrong.

I'm looking at you Stackoverflow:

200 OK
Pragma: no-cache
Content-Type: application/json
X-Frame-Options: SAMEORIGIN
X-Request-Guid: a3433194-4a03-4206-91ea-6a40f9bfd824
Strict-Transport-Security: max-age=15552000
Content-Length: 54
Accept-Ranges: bytes
Date: Tue, 03 Apr 2018 19:03:12 GMT
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: cache-yyz8333-YYZ
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1522782193.766958,VS0,VE30
Vary: Fastly-SSL
X-DNS-Prefetch-Control: off
Cache-Control: private

tl;dr: Pragma is a legacy of HTTP/1.0 and hasn't been needed since Internet Explorer 5, or Netscape 4.7. Unless you expect some of your users to be using IE5: it's safe to stop using it.


  • Expires: [date] (deprecated - HTTP 1.0)
  • Pragma: no-cache (deprecated - HTTP 1.0)
  • Cache-Control: max-age=[seconds]
  • Cache-Control: no-cache (must re-validate the cached copy every time)

And the conditional requests:

  • Etag (entity tag) based conditional requests
    • Server: Etag: W/“1d2e7–1648e509289”
    • Client: If-None-Match: W/“1d2e7–1648e509289”
    • Server: 304 Not Modified
  • Modified date based conditional requests
    • Server: last-modified: Thu, 09 May 2019 19:15:47 GMT
    • Client: If-Modified-Since: Fri, 13 Jul 2018 10:49:23 GMT
    • Server: 304 Not Modified

last-modified: Thu, 09 May 2019 19:15:47 GMT

Clear back stack using fragments

With all due respect to all involved parties; I'm very surprised to see how many of you could clear the entire fragment back stack with a simple

fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

According to Android documentation (regarding the name argument - the "null" in the claimed working proposals).

If null, only the top state is popped

Now, I do realize that I'm lacking knowledge of your particular implementations (like how many entries you have in the back stack at the given point in time), but I would bet all my money on the accepted answer when expecting a well defined behaviour over a wider range of devices and vendors:

(for reference, something along with this)

FragmentManager fm = getFragmentManager(); // or 'getSupportFragmentManager();'
int count = fm.getBackStackEntryCount();
for(int i = 0; i < count; ++i) {    
    fm.popBackStack();
}

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

Detect if checkbox is checked or unchecked in Angular.js ng-change event

The state of the checkbox will be reflected on whatever model you have it bound to, in this case, $scope.answers[item.questID]

Converting char* to float or double

Code posted by you is correct and should have worked. But check exactly what you have in the char*. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL. Check what you have in the char* against maximum values that float and double can represent on your computer.

Check this page for strtod reference and this page for atof reference.

I have tried the example you provided in both Windows and Linux and it worked fine.

Show image using file_get_contents

Do i need to modify the headers and just echo it or something?

exactly.

Send a header("content-type: image/your_image_type"); and the data afterwards.

Git: How to remove proxy

If you already unset the proxy from global and local level and still see the proxy details while you do

         git config -l

then unset the variable from system level, generally the configuration stored at below location

 C:\Program Files\Git\mingw64/etc/gitconfig

How can I remove an element from a list, with lodash?

You can now use _.reject which allows you to filter based on what you need to get rid of, instead of what you need to keep.

unlike _.pull or _.remove that only work on arrays, ._reject is working on any Collection

obj.subTopics = _.reject(obj.subTopics, (o) => {
  return o.number >= 32;
});

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

In my case, it's related to the Toggle Vrapper Icon in the Eclipse.

If you are getting the bold black cursor, then the icon must be enabled. So, click on the Toggle Vrapper Icon to disable. It's located in the Eclipse's Toolbar. Please see the attached image for the clarity.

enter image description here

$http.get(...).success is not a function

If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.

 $scope.login = function () {
        $scope.btntext = "Please wait...!";
        $http({
            method: "POST",
            url: '/Home/userlogin', // link UserLogin with HomeController 
            data: $scope.user
         }).then(function (response) {
            console.log("Result value is : " + parseInt(response));
            data = response.data;
            $scope.btntext = 'Login';
            if (data == 1) {
                window.location.href = '/Home/dashboard';
             }
            else {
            alert(data);
        }
        }, function (error) {

        alert("Failed Login");
        });

The above snipit works for a login page.

spring PropertyPlaceholderConfigurer and context:property-placeholder

First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties. In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.

After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:

<context:property-placeholder location="classpath:config/properties/database.properties"/>

Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:

<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>

There's usually not any reason to define them separately, though.

How can I enable cURL for an installed Ubuntu LAMP stack?

I tried most of the previous answers, but it didn’t work for my machine, Ubuntu 18.04 (Bionic Beaver), but what worked for me was this.

First: check your PHP version

$ php -version

Second: add your PHP version to the command. Mine was:

  $ sudo apt-get install php7.2-curl

Lastly, restart the Apache server:

sudo service apache2 restart

Although most persons claimed that it not necessary to restart Apache :)

Two Divs on the same row and center align both of them

You could do this

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>  

http://jsfiddle.net/jasongennaro/MZrym/

  1. wrap it in a div with text-align:center;
  2. give the innder divs a display:inline-block; instead of a float

Best also to put that css in a stylesheet.

CMD what does /im (taskkill)?

If you type the executable name and a /? switch at the command line, there is typically help information available. Doing so with taskkill /? provides the following, for instance:

TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]

Description:
    This tool is used to terminate tasks by process id (PID) or image name.

Parameter List:
    /S    system           Specifies the remote system to connect to.

    /U    [domain\]user    Specifies the user context under which the
                           command should execute.

    /P    [password]       Specifies the password for the given user
                           context. Prompts for input if omitted.

    /FI   filter           Applies a filter to select a set of tasks.
                           Allows "*" to be used. ex. imagename eq acme*

    /PID  processid        Specifies the PID of the process to be terminated.
                           Use TaskList to get the PID.

    /IM   imagename        Specifies the image name of the process
                           to be terminated. Wildcard '*' can be used
                           to specify all tasks or image names.

    /T                     Terminates the specified process and any
                           child processes which were started by it.

    /F                     Specifies to forcefully terminate the process(es).

    /?                     Displays this help message.

Filters:
    Filter Name   Valid Operators           Valid Value(s)
    -----------   ---------------           -------------------------
    STATUS        eq, ne                    RUNNING |
                                            NOT RESPONDING | UNKNOWN
    IMAGENAME     eq, ne                    Image name
    PID           eq, ne, gt, lt, ge, le    PID value
    SESSION       eq, ne, gt, lt, ge, le    Session number.
    CPUTIME       eq, ne, gt, lt, ge, le    CPU time in the format
                                            of hh:mm:ss.
                                            hh - hours,
                                            mm - minutes, ss - seconds
    MEMUSAGE      eq, ne, gt, lt, ge, le    Memory usage in KB
    USERNAME      eq, ne                    User name in [domain\]user
                                            format
    MODULES       eq, ne                    DLL name
    SERVICES      eq, ne                    Service name
    WINDOWTITLE   eq, ne                    Window title

    NOTE
    ----
    1) Wildcard '*' for /IM switch is accepted only when a filter is applied.
    2) Termination of remote processes will always be done forcefully (/F).
    3) "WINDOWTITLE" and "STATUS" filters are not considered when a remote
       machine is specified.

Examples:
    TASKKILL /IM notepad.exe
    TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
    TASKKILL /F /IM cmd.exe /T 
    TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
    TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe
    TASKKILL /S system /U domain\username /FI "USERNAME ne NT*" /IM *
    TASKKILL /S system /U username /P password /FI "IMAGENAME eq note*"

You can also find this information, as well as documentation for most of the other command-line utilities, in the Microsoft TechNet Command-Line Reference

How can I use the python HTMLParser library to extract data from a specific div tag?

class LinksParser(HTMLParser.HTMLParser):
  def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.recording = 0
    self.data = []

  def handle_starttag(self, tag, attributes):
    if tag != 'div':
      return
    if self.recording:
      self.recording += 1
      return
    for name, value in attributes:
      if name == 'id' and value == 'remository':
        break
    else:
      return
    self.recording = 1

  def handle_endtag(self, tag):
    if tag == 'div' and self.recording:
      self.recording -= 1

  def handle_data(self, data):
    if self.recording:
      self.data.append(data)

self.recording counts the number of nested div tags starting from a "triggering" one. When we're in the sub-tree rooted in a triggering tag, we accumulate the data in self.data.

The data at the end of the parse are left in self.data (a list of strings, possibly empty if no triggering tag was met). Your code from outside the class can access the list directly from the instance at the end of the parse, or you can add appropriate accessor methods for the purpose, depending on what exactly is your goal.

The class could be easily made a bit more general by using, in lieu of the constant literal strings seen in the code above, 'div', 'id', and 'remository', instance attributes self.tag, self.attname and self.attvalue, set by __init__ from arguments passed to it -- I avoided that cheap generalization step in the code above to avoid obscuring the core points (keep track of a count of nested tags and accumulate data into a list when the recording state is active).

What does %~dp0 mean, and how does it work?

%~dp0 expands to current directory path of the running batch file.

To get clear understanding, let's create a batch file in a directory.

C:\script\test.bat

with contents:

@echo off
echo %~dp0

When you run it from command prompt, you will see this result:

C:\script\

file_get_contents behind a proxy?

There's a similar post here: http://techpad.co.uk/content.php?sid=137 which explains how to do it.

function file_get_contents_proxy($url,$proxy){

    // Create context stream
    $context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
    $context = stream_context_create($context_array);

    // Use context stream with file_get_contents
    $data = file_get_contents($url,false,$context);

    // Return data via proxy
    return $data;

}

How should I store GUID in MySQL tables?

Adding to the answer by ThaBadDawg, use these handy functions (thanks to a wiser collegue of mine) to get from 36 length string back to a byte array of 16.

DELIMITER $$

CREATE FUNCTION `GuidToBinary`(
    $Data VARCHAR(36)
) RETURNS binary(16)
DETERMINISTIC
NO SQL
BEGIN
    DECLARE $Result BINARY(16) DEFAULT NULL;
    IF $Data IS NOT NULL THEN
        SET $Data = REPLACE($Data,'-','');
        SET $Result =
            CONCAT( UNHEX(SUBSTRING($Data,7,2)), UNHEX(SUBSTRING($Data,5,2)),
                    UNHEX(SUBSTRING($Data,3,2)), UNHEX(SUBSTRING($Data,1,2)),
                    UNHEX(SUBSTRING($Data,11,2)),UNHEX(SUBSTRING($Data,9,2)),
                    UNHEX(SUBSTRING($Data,15,2)),UNHEX(SUBSTRING($Data,13,2)),
                    UNHEX(SUBSTRING($Data,17,16)));
    END IF;
    RETURN $Result;
END

$$

CREATE FUNCTION `ToGuid`(
    $Data BINARY(16)
) RETURNS char(36) CHARSET utf8
DETERMINISTIC
NO SQL
BEGIN
    DECLARE $Result CHAR(36) DEFAULT NULL;
    IF $Data IS NOT NULL THEN
        SET $Result =
            CONCAT(
                HEX(SUBSTRING($Data,4,1)), HEX(SUBSTRING($Data,3,1)),
                HEX(SUBSTRING($Data,2,1)), HEX(SUBSTRING($Data,1,1)), '-', 
                HEX(SUBSTRING($Data,6,1)), HEX(SUBSTRING($Data,5,1)), '-',
                HEX(SUBSTRING($Data,8,1)), HEX(SUBSTRING($Data,7,1)), '-',
                HEX(SUBSTRING($Data,9,2)), '-', HEX(SUBSTRING($Data,11,6)));
    END IF;
    RETURN $Result;
END
$$

CHAR(16) is actually a BINARY(16), choose your preferred flavour

To follow the code better, take the example given the digit-ordered GUID below. (Illegal characters are used for illustrative purposes - each place a unique character.) The functions will transform the byte ordering to achieve a bit order for superior index clustering. The reordered guid is shown below the example.

12345678-9ABC-DEFG-HIJK-LMNOPQRSTUVW
78563412-BC9A-FGDE-HIJK-LMNOPQRSTUVW

Dashes removed:

123456789ABCDEFGHIJKLMNOPQRSTUVW
78563412BC9AFGDEHIJKLMNOPQRSTUVW

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

Express.js - app.listen vs server.listen

Express is basically a wrapper of http module that is created for the ease of the developers in such a way that..

  1. They can set up middlewares to respond to HTTP Requests (easily) using express.
  2. They can dynamically render HTML Pages based on passing arguments to templates using express.
  3. They can also define routing easily using express.

How do you kill all current connections to a SQL Server 2005 database?

I've always used:


ALTER DATABASE DB_NAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
GO 
SP_RENAMEDB 'DB_NAME','DB_NAME_NEW'
Go 
ALTER DATABASE DB_NAME_NEW  SET MULTI_USER -- set back to multi user 
GO 

How to import an existing directory into Eclipse?

These days, there's a better solution for importing an existing PHP project. The PDT plugin now has an option on the New PHP Project dialog just for this. So:

From File->New->PHP Project:

New PHP Project Dialog with "Create project at existing location" options badly circled

Is there a way to pass javascript variables in url?

Summary

With either string concatenation or string interpolation (via template literals).

Here with JavaScript template literal:

function geoPreview() {
    var lat = document.getElementById("lat").value;
    var long = document.getElementById("long").value;

    window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${lat}&lon=${long}&setLatLon=Set`;
}

Both parameters are unused and can be removed.

Remarks

String Concatenation

Join strings with the + operator:

window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=" + elemA + "&lon=" + elemB + "&setLatLon=Set";

String Interpolation

For more concise code, use JavaScript template literals to replace expressions with their string representations. Template literals are enclosed by `` and placeholders surrounded with ${}:

window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${elemA}&lon=${elemB}&setLatLon=Set`;

Template literals are available since ECMAScript 2015 (ES6).

What's a "static method" in C#?

A static function, unlike a regular (instance) function, is not associated with an instance of the class.

A static class is a class which can only contain static members, and therefore cannot be instantiated.

For example:

class SomeClass {
    public int InstanceMethod() { return 1; }
    public static int StaticMethod() { return 42; }
}

In order to call InstanceMethod, you need an instance of the class:

SomeClass instance = new SomeClass();
instance.InstanceMethod();   //Fine
instance.StaticMethod();     //Won't compile

SomeClass.InstanceMethod();  //Won't compile
SomeClass.StaticMethod();    //Fine

How to get the number of columns in a matrix?

When want to get row size with size() function, below code can be used:

size(A,1)

Another usage for it:

[height, width] = size(A)

So, you can get 2 dimension of your matrix.

Figure out size of UILabel based on String in Swift

extension String{

    func widthWithConstrainedHeight(_ height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)

        let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return ceil(boundingBox.width)
    }

    func heightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat? {
        let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return ceil(boundingBox.height)
    }

}

Remove sensitive files and their commits from Git history

If you pushed to GitHub, force pushing is not enough, delete the repository or contact support

Even if you force push one second afterwards, it is not enough as explained below.

The only valid courses of action are:

  • is what leaked a changeable credential like a password?

    • yes: modify your passwords immediately, and consider using more OAuth and API keys!

    • no (naked pics):

      • do you care if all issues in the repository get nuked?

        • no: delete the repository

        • yes:

          • contact support
          • if the leak is very critical to you, to the point that you are willing to get some repository downtime to make it less likely to leak, make it private while you wait for GitHub support to reply to you

Force pushing a second later is not enough because:

If you delete the repository instead of just force pushing however, commits do disappear even from the API immediately and give 404, e.g. https://api.github.com/repos/cirosantilli/test-dangling-delete/commits/8c08448b5fbf0f891696819f3b2b2d653f7a3824 This works even if you recreate another repository with the same name.

To test this out, I have created a repo: https://github.com/cirosantilli/test-dangling and did:

git init
git remote add origin [email protected]:cirosantilli/test-dangling.git

touch a
git add .
git commit -m 0
git push

touch b
git add .
git commit -m 1
git push

touch c
git rm b
git add .
git commit --amend --no-edit
git push -f

See also: How to remove a dangling commit from GitHub?

git filter-repo is now officially recommended over git filter-branch

This is mentioned in the manpage of git filter-branch in Git 2.5 itself.

With git filter repo, you could either remove certain files with: Remove folder and its contents from git/GitHub's history

pip install git-filter-repo
git filter-repo --path path/to/remove1 --path path/to/remove2 --invert-paths

This automatically removes empty commits.

Or you can replace certain strings with: How to replace a string in a whole Git history?

git filter-repo --replace-text <(echo 'my_password==>xxxxxxxx')

Meaning of "referencing" and "dereferencing" in C

I've always heard them used in the opposite sense:

  • & is the reference operator -- it gives you a reference (pointer) to some object

  • * is the dereference operator -- it takes a reference (pointer) and gives you back the referred to object;

Fastest way to write huge data in text file Java

Only for the sake of statistics:

The machine is old Dell with new SSD

CPU: Intel Pentium D 2,8 Ghz

SSD: Patriot Inferno 120GB SSD

4000000 'records'
175.47607421875 MB

Iteration 0
Writing raw... 3.547 seconds
Writing buffered (buffer size: 8192)... 2.625 seconds
Writing buffered (buffer size: 1048576)... 2.203 seconds
Writing buffered (buffer size: 4194304)... 2.312 seconds

Iteration 1
Writing raw... 2.922 seconds
Writing buffered (buffer size: 8192)... 2.406 seconds
Writing buffered (buffer size: 1048576)... 2.015 seconds
Writing buffered (buffer size: 4194304)... 2.282 seconds

Iteration 2
Writing raw... 2.828 seconds
Writing buffered (buffer size: 8192)... 2.109 seconds
Writing buffered (buffer size: 1048576)... 2.078 seconds
Writing buffered (buffer size: 4194304)... 2.015 seconds

Iteration 3
Writing raw... 3.187 seconds
Writing buffered (buffer size: 8192)... 2.109 seconds
Writing buffered (buffer size: 1048576)... 2.094 seconds
Writing buffered (buffer size: 4194304)... 2.031 seconds

Iteration 4
Writing raw... 3.093 seconds
Writing buffered (buffer size: 8192)... 2.141 seconds
Writing buffered (buffer size: 1048576)... 2.063 seconds
Writing buffered (buffer size: 4194304)... 2.016 seconds

As we can see the raw method is slower the buffered.

How to create nonexistent subdirectories recursively using Bash?

mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8

How to turn off word wrapping in HTML?

If you want a HTML only solution, we can just use the pre tag. It defines "preformatted text" which means that it does not format word-wrapping. Here is a quick example to explain:

_x000D_
_x000D_
div {
    width: 200px;
    height: 200px;
    padding: 20px;
    background: #adf;
}
pre {
    width: 200px;
    height: 200px;
    padding: 20px;
    font: inherit;
    background: #fda;
}
_x000D_
<div>Look at this, this text is very neat, isn't it? But it's not quite what we want, though, is it? This text shouldn't be here! It should be all the way over there! What can we do?</div>
<pre>The pre tag has come to the rescue! Yay! However, we apologise in advance for any horizontal scrollbars that may be caused. If you need support, please raise a support ticket.</pre>
_x000D_
_x000D_
_x000D_

What does template <unsigned int N> mean?

It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:

unsigned int x = N;

In fact, we can create algorithms which evaluate at compile time (from Wikipedia):

template <int N>
struct Factorial 
{
     enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

Render HTML in React Native

Edit Jan 2021: The React Native docs currently recommend React Native WebView:

<WebView
    originWhitelist={['*']}
    source={{ html: '<p>Here I am</p>' }}
/>

https://github.com/react-native-webview/react-native-webview


Edit March 2017: the html prop has been deprecated. Use source instead:

<WebView source={{html: '<p>Here I am</p>'}} />

https://facebook.github.io/react-native/docs/webview.html#html

Thanks to Justin for pointing this out.


Edit Feb 2017: the PR was accepted a while back, so to render HTML in React Native, simply:

<WebView html={'<p>Here I am</p>'} />

Original Answer:

I don't think this is currently possible. The behavior you're seeing is expected, since the Text component only outputs... well, text. You need another component that outputs HTML - and that's the WebView.

Unfortunately right now there's no way of just directly setting the HTML on this component:

https://github.com/facebook/react-native/issues/506

However I've just created this PR which implements a basic version of this feature so hopefully it'll land in some form soonish.

Command to find information about CPUs on a UNIX machine

There is no standard Unix command, AFAIK. I haven't used Sun OS, but on Linux, you can use this:

cat /proc/cpuinfo

Sorry that it is Linux, not Sun OS. There is probably something similar though for Sun OS.

How to get all subsets of a set? (powerset)

Here it is my solutions, it is similar (conceptually) with the solution of lmiguelvargasf.

Let me say that -[math item] by defintion the powerset do contain the empty set -[personal taste] and also that I don't like using frozenset.

So the input is a list and the output will be a list of lists. The function could close earlier, but I like the element of the power set to be order lexicographically, that essentially means nicely.

def power_set(L):
    """
    L is a list.
    The function returns the power set, but as a list of lists.
    """
    cardinality=len(L)
    n=2 ** cardinality
    powerset = []
    
    for i in range(n):
        a=bin(i)[2:]
        subset=[]
        for j in range(len(a)):
            if a[-j-1]=='1':
                subset.append(L[j])
        powerset.append(subset)
        
    #the function could stop here closing with
    #return powerset

    powerset_orderred=[]
    for k in range(cardinality+1):
        for w in powerset:
            if len(w)==k:
                powerset_orderred.append(w)
        
    return powerset_orderred

What values for checked and selected are false?

The checked and selected attributes are allowed only two values, which are a copy of the attribute name and (from HTML 5 onwards) an empty string. Giving any other value is an error.

If you don't want to set the attribute, then the entire attribute must be omitted.

Note that in HTML 4 you may omit everything except the value. HTML 5 changed this to omit everything except the name (which makes no practical difference).

Thus, the complete (aside from variations in cAsE) set of valid representations of the attribute are:

<input ... checked="checked"> <!-- All versions of HTML / XHTML -->
<input ...          checked > <!-- Only HTML 4.01 and earlier -->
<input ... checked          > <!-- Only HTML 5 and later -->
<input ... checked=""       > <!-- Only HTML 5 and later -->

Documents served as text/html (HTML or XHTML) will be fed through a tag soup parser, and the presence of a checked attribute (with any value) will be treated as "This element should be checked". Thus, while invalid, checked="true", checked="yes", and checked="false" will all trigger the checked state.

I've not had any inclination to find out what error recovery mechanisms are in place for XML parsing mode should a different value be given to the attribute, but I would expect that the legacy of HTML and/or simple error recovery would treat it in the same way: If the attribute is there then the element is checked.

(And all the above applies equally to selected as it does to checked.)

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

CSS: center element within a <div> element

If the child element is inline (e.g not a div, table etc) I would wrap it up inside a div or a p and make the wrapper's text align css property equal to center.

    <div id="container">
        This text is aligned to the left.<br>
        So is this text.<br>
        <div style="text-align: center">
            This <button>button</button> is centered.
        </div>
        This text is still aligned left.
    </div>

Otherwise, if the element is a block (display: block, e.g a div or a p) with a fixed width, I'd set its margin left and right css properties to auto.

    <div id="container">
        This text is aligned to the left.<br>
        So is this text.<br>
        <div style="margin: 0 auto; width: 200px; background: red; color: white;">
            My parent is centered.
        </div>
        This text is still aligned left.
    </div>

You could of course add a text-align: center to the wrapper element to make its contents centered as well.

I won't bother with positioning because IMHO its not the way to go for the OPs problem but be sure to check this link out, very helpful.

How do I get column datatype in Oracle with PL-SQL with low privileges?

ALL_TAB_COLUMNS should be queryable from PL/SQL. DESC is a SQL*Plus command.

SQL> desc all_tab_columns;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OWNER                                     NOT NULL VARCHAR2(30)
 TABLE_NAME                                NOT NULL VARCHAR2(30)
 COLUMN_NAME                               NOT NULL VARCHAR2(30)
 DATA_TYPE                                          VARCHAR2(106)
 DATA_TYPE_MOD                                      VARCHAR2(3)
 DATA_TYPE_OWNER                                    VARCHAR2(30)
 DATA_LENGTH                               NOT NULL NUMBER
 DATA_PRECISION                                     NUMBER
 DATA_SCALE                                         NUMBER
 NULLABLE                                           VARCHAR2(1)
 COLUMN_ID                                          NUMBER
 DEFAULT_LENGTH                                     NUMBER
 DATA_DEFAULT                                       LONG
 NUM_DISTINCT                                       NUMBER
 LOW_VALUE                                          RAW(32)
 HIGH_VALUE                                         RAW(32)
 DENSITY                                            NUMBER
 NUM_NULLS                                          NUMBER
 NUM_BUCKETS                                        NUMBER
 LAST_ANALYZED                                      DATE
 SAMPLE_SIZE                                        NUMBER
 CHARACTER_SET_NAME                                 VARCHAR2(44)
 CHAR_COL_DECL_LENGTH                               NUMBER
 GLOBAL_STATS                                       VARCHAR2(3)
 USER_STATS                                         VARCHAR2(3)
 AVG_COL_LEN                                        NUMBER
 CHAR_LENGTH                                        NUMBER
 CHAR_USED                                          VARCHAR2(1)
 V80_FMT_IMAGE                                      VARCHAR2(3)
 DATA_UPGRADED                                      VARCHAR2(3)
 HISTOGRAM                                          VARCHAR2(15)

vba: get unique values from array

There is no VBA built in functionality for removing duplicates from an array, however you could use the next function:

Function RemoveDuplicates(MyArray As Variant) As Variant
    With CreateObject("scripting.dictionary")
        For Each item In MyArray
            c00 = .Item(item)
        Next
        sn = .keys ' the array .keys contains all unique keys
        MsgBox Join(.keys, vbLf) ' you can join the array into a string
        RemoveDuplicates = .keys ' return an array without duplicates
    End With
End Function

Pointers, smart pointers or shared pointers?

To add a small bit to Sydius' answer, smart pointers will often provide a more stable solution by catching many easy to make errors. Raw pointers will have some perfromance advantages and can be more flexible in certain circumstances. You may also be forced to use raw pointers when linking into certain 3rd party libraries.

Naming Conventions: What to name a boolean variable?

Haskell uses init to refer to all but the last element of a list (the inverse of tail, basically); would isInInit work, or is that too opaque?

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

Change the selected value of a drop-down list with jQuery

So I changed it so that now it executes after a 300 miliseconds using setTimeout. Seems to be working now.

I have run into this many times when loading data from an Ajax call. I too use .NET, and it takes time to get adjusted to the clientId when using the jQuery selector. To correct the problem that you're having and to avoid having to add a setTimeout property, you can simply put "async: false" in the Ajax call, and it will give the DOM enough time to have the objects back that you are adding to the select. A small sample below:

$.ajax({
    type: "POST",
    url: document.URL + '/PageList',
    data: "{}",
    async: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        var pages = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

        $('#locPage' + locId).find('option').remove();

        $.each(pages, function () {
            $('#locPage' + locId).append(
                $('<option></option>').val(this.PageId).html(this.Name)
            );
        });
    }
});

How to use Oracle's LISTAGG function with a unique filter?

Super simple answer - solved!

my full answer here it is now built in in some oracle versions.

select group_id, 
regexp_replace(
    listagg(name, ',') within group (order by name)
    ,'([^,]+)(,\1)*(,|$)', '\1\3')
from demotable
group by group_id;  

This only works if you specify the delimiter to ',' not ', ' ie works only for no spaces after the comma. If you want spaces after the comma - here is a example how.

select 
replace(
    regexp_replace(
     regexp_replace('BBall, BBall, BBall, Football, Ice Hockey ',',\s*',',')            
    ,'([^,]+)(,\1)*(,|$)', '\1\3')
,',',', ') 
from dual

gives BBall, Football, Ice Hockey

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

Create a function that addresses all the whitespace possibilites and enable only those that seem appropriate:

SELECT dbo.ShowWhiteSpace(myfield) from mytable

Uncomment only those whitespace cases you want to test for:


CREATE FUNCTION dbo.ShowWhiteSpace (@str varchar(8000))
RETURNS varchar(8000)
AS
BEGIN
     DECLARE @ShowWhiteSpace varchar(8000);
     SET @ShowWhiteSpace = @str
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(32), '[?]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(13), '[CR]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(10), '[LF]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(9),  '[TAB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(1),  '[SOH]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(2),  '[STX]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(3),  '[ETX]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(4),  '[EOT]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(5),  '[ENQ]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(6),  '[ACK]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(7),  '[BEL]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(8),  '[BS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(11), '[VT]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(12), '[FF]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(14), '[SO]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(15), '[SI]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(16), '[DLE]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(17), '[DC1]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(18), '[DC2]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(19), '[DC3]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(20), '[DC4]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(21), '[NAK]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(22), '[SYN]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(23), '[ETB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(24), '[CAN]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(25), '[EM]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(26), '[SUB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(27), '[ESC]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(28), '[FS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(29), '[GS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(30), '[RS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(31), '[US]')
     RETURN(@ShowWhiteSpace)
END

jQuery Set Selected Option Using Next

$('#my_sel').val($('#my_sel option:selected').next().val());
$('#my_sel').val($('#my_sel option:selected').prev().val());

What do curly braces mean in Verilog?

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

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

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

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

How to properly export an ES6 class in Node 4?

Use

// aspect-type.js
class AspectType {

}

export default AspectType;

Then to import it

// some-other-file.js
import AspectType from './aspect-type';

Read http://babeljs.io/docs/learn-es2015/#modules for more details

Converting bytes to megabytes

Divide by 2 to the power of 20, (1024*1024) bytes = 1 megabyte

1024*1024 = 1,048,576   
2^20 = 1,048,576
1,048,576/1,048,576 = 1  

It is the same thing.

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

Finding common rows (intersection) in two Pandas dataframes

My understanding is that this question is better answered over in this post.

But briefly, the answer to the OP with this method is simply:

s1 = pd.merge(df1, df2, how='inner', on=['user_id'])

Which gives s1 with 5 columns: user_id and the other two columns from each of df1 and df2.

Biggest advantage to using ASP.Net MVC vs web forms

Anyone old enough to remember classic ASP will remember the nightmare of opening a page with code mixed in with html and javascript - even the smallest page was a pain to figure out what the heck it was doing. I could be wrong, and I hope I am, but MVC looks like going back to those bad old days.

When ASP.Net came along it was hailed as the savior, separating code from content and allowing us to have web designers create the html and coders work on the code behind. If we didn't want to use ViewState, we turned it off. If we didn't want to use code behind for some reason, we could place our code inside the html just like classic ASP. If we didn't want to use PostBack we redirected to another page for processing. If we didn't want to use ASP.Net controls we used standard html controls. We could even interrogate the Response object if we didn't want to use ASP.Net runat="server" on our controls.

Now someone in their great wisdom (probably someone who never programmed classic ASP) has decided it's time to go back to the days of mixing code with content and call it "separation of concerns". Sure, you can create cleaner html, but you could with classic ASP. To say "you are not programming correctly if you have too much code inside your view" is like saying "if you wrote well structured and commented code in classic ASP it is far cleaner and better than ASP.NET"

If I wanted to go back to mixing code with content I'd look at developing using PHP which has a far more mature environment for that kind of development. If there are so many problems with ASP.NET then why not fix those issues?

Last but not least the new Razor engine means it is even harder to distinguish between html and code. At least we could look for opening and closing tags i.e. <% and %> in ASP but now the only indication will be the @ symbol.

It might be time to move to PHP and wait another 10 years for someone to separate code from content once again.

Binary Search Tree - Java Implementation


Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view


import java.util.NoSuchElementException;
import java.util.Scanner;

import org.junit.experimental.max.MaxCore;

class BSTNode {

    BSTNode left = null;
    BSTNode rigth = null;
    int data = 0;

    public BSTNode() {
        super();
    }

    public BSTNode(int data) {
        this.left = null;
        this.rigth = null;
        this.data = data;
    }

    @Override
    public String toString() {
        return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
    }

}


class BinarySearchTree {

    BSTNode root = null;

    public BinarySearchTree() {

    }

    public void insert(int data) {
        BSTNode node = new BSTNode(data);
        if (root == null) {
            root = node;
            return;
        }

        BSTNode currentNode = root;
        BSTNode parentNode = null;

        while (true) {
            parentNode = currentNode;
            if (currentNode.data == data)
                throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");

            if (currentNode.data > data) {
                currentNode = currentNode.left;
                if (currentNode == null) {
                    parentNode.left = node;
                    return;
                }
            } else {
                currentNode = currentNode.rigth;
                if (currentNode == null) {
                    parentNode.rigth = node;
                    return;
                }
            }
        }
    }

    public int countNodes() {
        return countNodes(root);
    }

    private int countNodes(BSTNode node) {
        if (node == null) {
            return 0;
        } else {
            int count = 1;
            count += countNodes(node.left);
            count += countNodes(node.rigth);
            return count;
        }
    }

    public boolean searchNode(int data) {
        if (empty())
            return empty();
        return searchNode(data, root);
    }

    public boolean searchNode(int data, BSTNode node) {
        if (node != null) {
            if (node.data == data)
                return true;
            else if (node.data > data)
                return searchNode(data, node.left);
            else if (node.data < data)
                return searchNode(data, node.rigth);
        }
        return false;
    }

    public boolean delete(int data) {
        if (empty())
            throw new NoSuchElementException("Tree is Empty");

        BSTNode currentNode = root;
        BSTNode parentNode = root;
        boolean isLeftChild = false;

        while (currentNode.data != data) {
            parentNode = currentNode;
            if (currentNode.data > data) {
                isLeftChild = true;
                currentNode = currentNode.left;
            } else if (currentNode.data < data) {
                isLeftChild = false;
                currentNode = currentNode.rigth;
            }
            if (currentNode == null)
                return false;
        }

        // CASE 1: node with no child
        if (currentNode.left == null && currentNode.rigth == null) {
            if (currentNode == root)
                root = null;
            if (isLeftChild)
                parentNode.left = null;
            else
                parentNode.rigth = null;
        }

        // CASE 2: if node with only one child
        else if (currentNode.left != null && currentNode.rigth == null) {
            if (root == currentNode) {
                root = currentNode.left;
            }
            if (isLeftChild)
                parentNode.left = currentNode.left;
            else
                parentNode.rigth = currentNode.left;
        } else if (currentNode.rigth != null && currentNode.left == null) {
            if (root == currentNode)
                root = currentNode.rigth;
            if (isLeftChild)
                parentNode.left = currentNode.rigth;
            else
                parentNode.rigth = currentNode.rigth;
        }

        // CASE 3: node with two child
        else if (currentNode.left != null && currentNode.rigth != null) {

            // Now we have to find minimum element in rigth sub tree
            // that is called successor
            BSTNode successor = getSuccessor(currentNode);
            if (currentNode == root)
                root = successor;
            if (isLeftChild)
                parentNode.left = successor;
            else
                parentNode.rigth = successor;
            successor.left = currentNode.left;
        }

        return true;
    }

    private BSTNode getSuccessor(BSTNode deleteNode) {

        BSTNode successor = null;
        BSTNode parentSuccessor = null;
        BSTNode currentNode = deleteNode.left;

        while (currentNode != null) {
            parentSuccessor = successor;
            successor = currentNode;
            currentNode = currentNode.left;
        }

        if (successor != deleteNode.rigth) {
            parentSuccessor.left = successor.left;
            successor.rigth = deleteNode.rigth;
        }

        return successor;
    }

    public int nodeWithMinimumValue() {
        return nodeWithMinimumValue(root);
    }

    private int nodeWithMinimumValue(BSTNode node) {
        if (node.left != null)
            return nodeWithMinimumValue(node.left);
        return node.data;
    }

    public int nodewithMaximumValue() {
        return nodewithMaximumValue(root);
    }

    private int nodewithMaximumValue(BSTNode node) {
        if (node.rigth != null)
            return nodewithMaximumValue(node.rigth);
        return node.data;
    }

    public int parent(int data) {
        return parent(root, data);
    }

    private int parent(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode parent = null;
        BSTNode current = node;

        while (current.data != data) {
            parent = current;
            if (current.data > data)
                current = current.left;
            else
                current = current.rigth;
            if (current == null)
                throw new IllegalArgumentException(data + " is not a node in tree");
        }
        return parent.data;
    }

    public int sibling(int data) {
        return sibling(root, data);
    }

    private int sibling(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode cureent = node;
        BSTNode parent = null;
        boolean isLeft = false;

        while (cureent.data != data) {
            parent = cureent;
            if (cureent.data > data) {
                cureent = cureent.left;
                isLeft = true;
            } else {
                cureent = cureent.rigth;
                isLeft = false;
            }
            if (cureent == null)
                throw new IllegalArgumentException("No Parent node found");
        }
        if (isLeft) {
            if (parent.rigth != null) {
                return parent.rigth.data;
            } else
                throw new IllegalArgumentException("No Sibling is there");
        } else {
            if (parent.left != null)
                return parent.left.data;
            else
                throw new IllegalArgumentException("No Sibling is there");
        }
    }

    public void leafNodes() {
        if (empty())
            throw new IllegalArgumentException("Empty");
        leafNode(root);
    }

    private void leafNode(BSTNode node) {
        if (node == null)
            return;
        if (node.rigth == null && node.left == null)
            System.out.print(node.data + " ");
        leafNode(node.left);
        leafNode(node.rigth);
    }

    public int level(int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        return level(root, data, 1);
    }

    private int level(BSTNode node, int data, int level) {
        if (node == null)
            return 0;
        if (node.data == data)
            return level;
        int result = level(node.left, data, level + 1);
        if (result != 0)
            return result;
        result = level(node.rigth, data, level + 1);
        return result;
    }

    public int depth() {
        return depth(root);
    }

    private int depth(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(depth(node.left), depth(node.rigth));
    }

    public int height() {
        return height(root);
    }

    private int height(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(height(node.left), height(node.rigth));
    }

    public void leftView() {
        leftView(root);
    }

    private void leftView(BSTNode node) {
        if (node == null)
            return;
        int height = height(node);

        for (int i = 1; i <= height; i++) {
            printLeftView(node, i);
        }
    }

    private boolean printLeftView(BSTNode node, int level) {
        if (node == null)
            return false;

        if (level == 1) {
            System.out.print(node.data + " ");
            return true;
        } else {
            boolean left = printLeftView(node.left, level - 1);
            if (left)
                return true;
            else
                return printLeftView(node.rigth, level - 1);
        }
    }

    public void mirroeView() {
        BSTNode node = mirroeView(root);
        preorder(node);
        System.out.println();
        inorder(node);
        System.out.println();
        postorder(node);
        System.out.println();
    }

    private BSTNode mirroeView(BSTNode node) {
        if (node == null || (node.left == null && node.rigth == null))
            return node;

        BSTNode temp = node.left;
        node.left = node.rigth;
        node.rigth = temp;

        mirroeView(node.left);
        mirroeView(node.rigth);
        return node;
    }

    public void preorder() {
        preorder(root);
    }

    private void preorder(BSTNode node) {
        if (node != null) {
            System.out.print(node.data + " ");
            preorder(node.left);
            preorder(node.rigth);
        }
    }

    public void inorder() {
        inorder(root);
    }

    private void inorder(BSTNode node) {
        if (node != null) {
            inorder(node.left);
            System.out.print(node.data + " ");
            inorder(node.rigth);
        }
    }

    public void postorder() {
        postorder(root);
    }

    private void postorder(BSTNode node) {
        if (node != null) {
            postorder(node.left);
            postorder(node.rigth);
            System.out.print(node.data + " ");
        }
    }

    public boolean empty() {
        return root == null;
    }

}

public class BinarySearchTreeTest {
    public static void main(String[] l) {
        System.out.println("Weleome to Binary Search Tree");
        Scanner scanner = new Scanner(System.in);
        boolean yes = true;
        BinarySearchTree tree = new BinarySearchTree();
        do {
            System.out.println("\n1. Insert");
            System.out.println("2. Search Node");
            System.out.println("3. Count Node");
            System.out.println("4. Empty Status");
            System.out.println("5. Delete Node");
            System.out.println("6. Node with Minimum Value");
            System.out.println("7. Node with Maximum Value");
            System.out.println("8. Find Parent node");
            System.out.println("9. Count no of links");
            System.out.println("10. Get the sibling of any node");
            System.out.println("11. Print all the leaf node");
            System.out.println("12. Get the level of node");
            System.out.println("13. Depth of the tree");
            System.out.println("14. Height of Binary Tree");
            System.out.println("15. Left View");
            System.out.println("16. Mirror Image of Binary Tree");
            System.out.println("Enter Your Choice :: ");
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                try {
                    System.out.println("Enter Value");
                    tree.insert(scanner.nextInt());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 2:
                System.out.println("Enter the node");
                System.out.println(tree.searchNode(scanner.nextInt()));
                break;

            case 3:
                System.out.println(tree.countNodes());
                break;

            case 4:
                System.out.println(tree.empty());
                break;

            case 5:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.delete(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 6:
                try {
                    System.out.println(tree.nodeWithMinimumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 7:
                try {
                    System.out.println(tree.nodewithMaximumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 8:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.parent(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 9:
                try {
                    System.out.println(tree.countNodes() - 1);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 10:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.sibling(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 11:
                try {
                    tree.leafNodes();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 12:
                try {
                    System.out.println("Enter the node");
                    System.out.println("Level is : " + tree.level(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 13:
                try {
                    System.out.println(tree.depth());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 14:
                try {
                    System.out.println(tree.height());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 15:
                try {
                    tree.leftView();
                    System.out.println();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 16:
                try {
                    tree.mirroeView();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            default:
                break;
            }
            tree.preorder();
            System.out.println();
            tree.inorder();
            System.out.println();
            tree.postorder();
        } while (yes);
        scanner.close();
    }
}

Loop through files in a folder using VBA?

Here's my interpretation as a Function Instead:

'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String

    Dim StrFile As String
    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile

    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir

    Loop

End Function

Possible to make labels appear when hovering over a point in matplotlib?

It seems none of the other answers here actually answer the question. So here is a code that uses a scatter and shows an annotation upon hovering over the scatter points.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)

norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn

fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)

annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

def update_annot(ind):

    pos = sc.get_offsets()[ind["ind"][0]]
    annot.xy = pos
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), 
                           " ".join([names[n] for n in ind["ind"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
    annot.get_bbox_patch().set_alpha(0.4)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", hover)

plt.show()

enter image description here

Because people also want to use this solution for a line plot instead of a scatter, the following would be the same solution for plot (which works slightly differently).

_x000D_
_x000D_
import matplotlib.pyplot as plt_x000D_
import numpy as np; np.random.seed(1)_x000D_
_x000D_
x = np.sort(np.random.rand(15))_x000D_
y = np.sort(np.random.rand(15))_x000D_
names = np.array(list("ABCDEFGHIJKLMNO"))_x000D_
_x000D_
norm = plt.Normalize(1,4)_x000D_
cmap = plt.cm.RdYlGn_x000D_
_x000D_
fig,ax = plt.subplots()_x000D_
line, = plt.plot(x,y, marker="o")_x000D_
_x000D_
annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",_x000D_
                    bbox=dict(boxstyle="round", fc="w"),_x000D_
                    arrowprops=dict(arrowstyle="->"))_x000D_
annot.set_visible(False)_x000D_
_x000D_
def update_annot(ind):_x000D_
    x,y = line.get_data()_x000D_
    annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])_x000D_
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), _x000D_
                           " ".join([names[n] for n in ind["ind"]]))_x000D_
    annot.set_text(text)_x000D_
    annot.get_bbox_patch().set_alpha(0.4)_x000D_
_x000D_
_x000D_
def hover(event):_x000D_
    vis = annot.get_visible()_x000D_
    if event.inaxes == ax:_x000D_
        cont, ind = line.contains(event)_x000D_
        if cont:_x000D_
            update_annot(ind)_x000D_
            annot.set_visible(True)_x000D_
            fig.canvas.draw_idle()_x000D_
        else:_x000D_
            if vis:_x000D_
                annot.set_visible(False)_x000D_
                fig.canvas.draw_idle()_x000D_
_x000D_
fig.canvas.mpl_connect("motion_notify_event", hover)_x000D_
_x000D_
plt.show()
_x000D_
_x000D_
_x000D_

In case someone is looking for a solution for lines in twin axes, refer to How to make labels appear when hovering over a point in multiple axis?

In case someone is looking for a solution for bar plots, please refer to e.g. this answer.

What is external linkage and internal linkage?

  • A global variable has external linkage by default. Its scope can be extended to files other than containing it by giving a matching extern declaration in the other file.
  • The scope of a global variable can be restricted to the file containing its declaration by prefixing the declaration with the keyword static. Such variables are said to have internal linkage.

Consider following example:

1.cpp

void f(int i);
extern const int max = 10;
int n = 0;
int main()
{
    int a;
    //...
    f(a);
    //...
    f(a);
    //...
}
  1. The signature of function f declares f as a function with external linkage (default). Its definition must be provided later in this file or in other translation unit (given below).
  2. max is defined as an integer constant. The default linkage for constants is internal. Its linkage is changed to external with the keyword extern. So now max can be accessed in other files.
  3. n is defined as an integer variable. The default linkage for variables defined outside function bodies is external.

2.cpp

#include <iostream>
using namespace std;

extern const int max;
extern int n;
static float z = 0.0;

void f(int i)
{
    static int nCall = 0;
    int a;
    //...
    nCall++;
    n++;
    //...
    a = max * z;
    //...
    cout << "f() called " << nCall << " times." << endl;
}
  1. max is declared to have external linkage. A matching definition for max (with external linkage) must appear in some file. (As in 1.cpp)
  2. n is declared to have external linkage.
  3. z is defined as a global variable with internal linkage.
  4. The definition of nCall specifies nCall to be a variable that retains its value across calls to function f(). Unlike local variables with the default auto storage class, nCall will be initialized only once at the start of the program and not once for each invocation of f(). The storage class specifier static affects the lifetime of the local variable and not its scope.

NB: The keyword static plays a double role. When used in the definitions of global variables, it specifies internal linkage. When used in the definitions of the local variables, it specifies that the lifetime of the variable is going to be the duration of the program instead of being the duration of the function.

Hope that helps!

Extracting extension from filename in Python

For simple use cases one option may be splitting from dot:

>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'

No error when file doesn't have an extension:

>>> "filename".split(".")[-1]
'filename'

But you must be careful:

>>> "png".split(".")[-1]
'png'    # But file doesn't have an extension

Also will not work with hidden files in Unix systems:

>>> ".bashrc".split(".")[-1]
'bashrc'    # But this is not an extension

For general use, prefer os.path.splitext

How to add a button to UINavigationBar?

The answers above are good, but I'd like to flesh them out with a few more tips:

If you want to modify the title of the back button (the arrow-y looking one at the left of the navigation bar) you MUST do it in the PREVIOUS view controller, not the one for which it will display. It's like saying "hey, if you ever push another view controller on top of this one, call the back button "Back" (or whatever) instead of the default."

If you want to hide the back button during a special state, such as while a UIPickerView is displayed, use self.navigationItem.hidesBackButton = YES; and remember to set it back when you leave the special state.

If you want to display one of the special symbolic buttons, use the form initWithBarButtonSystemItem:target:action with a value like UIBarButtonSystemItemAdd

Remember, the meaning of that symbol is up to you, but be careful of the Human Interface Guidelines. Using UIBarButtonSystemItemAdd to mean deleting an item will probably get your application rejected.