Programs & Examples On #Flash html interaction

Why are unnamed namespaces used and what are their benefits?

Having something in an anonymous namespace means it's local to this translation unit (.cpp file and all its includes) this means that if another symbol with the same name is defined elsewhere there will not be a violation of the One Definition Rule (ODR).

This is the same as the C way of having a static global variable or static function but it can be used for class definitions as well (and should be used rather than static in C++).

All anonymous namespaces in the same file are treated as the same namespace and all anonymous namespaces in different files are distinct. An anonymous namespace is the equivalent of:

namespace __unique_compiler_generated_identifer0x42 {
    ...
}
using namespace __unique_compiler_generated_identifer0x42;

Can I have multiple primary keys in a single table?

A table can have multiple candidate keys. Each candidate key is a column or set of columns that are UNIQUE, taken together, and also NOT NULL. Thus, specifying values for all the columns of any candidate key is enough to determine that there is one row that meets the criteria, or no rows at all.

Candidate keys are a fundamental concept in the relational data model.

It's common practice, if multiple keys are present in one table, to designate one of the candidate keys as the primary key. It's also common practice to cause any foreign keys to the table to reference the primary key, rather than any other candidate key.

I recommend these practices, but there is nothing in the relational model that requires selecting a primary key among the candidate keys.

How to insert a new line in Linux shell script?

Use this echo statement

 echo -e "Hai\nHello\nTesting\n"

The output is

Hai
Hello
Testing

How to get a path to a resource in a Java JAR file

A File is an abstraction for a file in a filesystem, and the filesystems don't know anything about what are the contents of a JAR.

Try with an URI, I think there's a jar:// protocol that might be useful for your purpouses.

Recursive file search using PowerShell

When searching folders where you might get an error based on security (e.g. C:\Users), use the following command:

Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force

How to extract text from an existing docx file using python-docx

Using python-docx, as @Chinmoy Panda 's answer shows:

for para in doc.paragraphs:
    fullText.append(para.text)

However, para.text will lost the text in w:smarttag (Corresponding github issue is here: https://github.com/python-openxml/python-docx/issues/328), you should use the following function instead:

def para2text(p):
    rs = p._element.xpath('.//w:t')
    return u" ".join([r.text for r in rs])

How to replace all dots in a string using JavaScript

/**
 * ReplaceAll by Fagner Brack (MIT Licensed)
 * Replaces all occurrences of a substring in a string
 */
String.prototype.replaceAll = function( token, newToken, ignoreCase ) {
    var _token;
    var str = this + "";
    var i = -1;

    if ( typeof token === "string" ) {

        if ( ignoreCase ) {

            _token = token.toLowerCase();

            while( (
                i = str.toLowerCase().indexOf(
                    _token, i >= 0 ? i + newToken.length : 0
                ) ) !== -1
            ) {
                str = str.substring( 0, i ) +
                    newToken +
                    str.substring( i + token.length );
            }

        } else {
            return this.split( token ).join( newToken );
        }

    }
return str;
};

alert('okay.this.is.a.string'.replaceAll('.', ' '));

Faster than using regex...

EDIT:
Maybe at the time I did this code I did not used jsperf. But in the end such discussion is totally pointless, the performance difference is not worth the legibility of the code in the real world, so my answer is still valid, even if the performance differs from the regex approach.

EDIT2:
I have created a lib that allows you to do this using a fluent interface:

replace('.').from('okay.this.is.a.string').with(' ');

See https://github.com/FagnerMartinsBrack/str-replace.

Returning a value from thread?

I'm no kind of expert in threading, that's why I did it like this:

I created a Settings file and

Inside the new thread:

Setting.Default.ValueToBeSaved;
Setting.Default.Save();

Then I pick up that value whenever I need it.

How to prevent text in a table cell from wrapping

<th nowrap="nowrap">

or

<th style="white-space:nowrap;">

or

<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>

Calculate difference between two dates (number of days)?

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    DateTime d = Calendar1.SelectedDate;
    // int a;
    TextBox2.Text = d.ToShortDateString();
    string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
    string s1 =  Convert.ToDateTime(Label7.Text).ToShortDateString();
    DateTime dt = Convert.ToDateTime(s).Date;
    DateTime dt1 = Convert.ToDateTime(s1).Date;
    if (dt <= dt1)
    {
        Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
    }
    else
    {
        string diff = dt.Subtract(dt1).ToString();
        Response.Write(diff);
        Label18.Text = diff;
        Session["diff"] = Label18.Text;
    }
}   

Import text file as single character string

In case anyone is still looking at this question 3 years later, Hadley Wickham's readr package has a handy read_file() function that will do this for you.

# you only need to do this one time on your system
install.packages("readr")
library(readr)
mystring <- read_file("path/to/myfile.txt")

Python list directory, subdirectory, and files

You can take a look at this sample I made. It uses the os.path.walk function which is deprecated beware.Uses a list to store all the filepaths

root = "Your root directory"
ex = ".txt"
where_to = "Wherever you wanna write your file to"
def fileWalker(ext,dirname,names):
    '''
    checks files in names'''
    pat = "*" + ext[0]
    for f in names:
        if fnmatch.fnmatch(f,pat):
            ext[1].append(os.path.join(dirname,f))


def writeTo(fList):

    with open(where_to,"w") as f:
        for di_r in fList:
            f.write(di_r + "\n")






if __name__ == '__main__':
    li = []
    os.path.walk(root,fileWalker,[ex,li])

    writeTo(li)

Add image in pdf using jspdf

You defined Base64? If you not defined, occurs this error:

ReferenceError: Base64 is not defined

SQL Server: Invalid Column Name

If you are going to ALTER Table column and immediate UPDATE the table including the new column in the same script. Make sure that use GO command to after line of code of alter table as below.

ALTER TABLE Location 
ADD TransitionType SMALLINT NULL
GO   

UPDATE Location SET TransitionType =  4

ALTER TABLE Location 
    ALTER COLUMN TransitionType SMALLINT NOT NULL

How to convert a string to integer in C?

int atoi(const char* str){
    int num = 0;
    int i = 0;
    bool isNegetive = false;
    if(str[i] == '-'){
        isNegetive = true;
        i++;
    }
    while (str[i] && (str[i] >= '0' && str[i] <= '9')){
        num = num * 10 + (str[i] - '0');
        i++;
    }
    if(isNegetive) num = -1 * num;
    return num;
}

Property 'catch' does not exist on type 'Observable<any>'

Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below

=====================

Yes, you need to import the operator:

import 'rxjs/add/operator/catch';

Or import Observable this way:

import {Observable} from 'rxjs/Rx';

But in this case, you import all operators.

See this question for more details:

Segmentation Fault - C

Your scanf("%s", s); is commented out. That means s is uninitialized, so when this line ln = strlen(s); executes, you get a seg fault.

It always helps to initialize a pointer to NULL, and then test for null before using the pointer.

How to change active class while click to another link in bootstrap use jquery?

$(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
        $(this).removeClass("active");
    }
    $(this).addClass("active");
});

This is what I came up with. It checks if the "li" element has the class of active, if it doesn't it skips the remove class part. I'm a bit late to the party, but hope this helps. :)

Cache busting via params

It will bust the cache once, after the client has downloaded the resource every other response will be served from client cache unless:

  1. the v parameter is updated.
  2. the client clears their cache

How to keep two folders automatically synchronized?

I use this free program to synchronize local files and directories: https://github.com/Fitus/Zaloha.sh. The repository contains a simple demo as well.

The good point: It is a bash shell script (one file only). Not a black box like other programs. Documentation is there as well. Also, with some technical talents, you can "bend" and "integrate" it to create the final solution you like.

JQuery - $ is not defined

Just place jquery url on the top of your jquery code

like this--

<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>

<script type="text/javascript">
    $(function() {
        $('#post').click(function() {
            alert("test"); 
        });
    });
</script>

What is the difference between x86 and x64

x86 is a family of backward-compatible instruction set architectures based on the Intel 8086 CPU and its Intel 8088 variant.

An instruction set architecture (ISA) is an abstract model of a computer. It is also referred to as architecture or computer architecture.

A realization of an ISA is called an implementation. An ISA permits multiple implementations that may vary in performance, physical size, and monetary cost (among other things); because the ISA serves as the interface between software and hardware.

Software that has been written for an ISA can run on different implementations of the same ISA (Exp: 32bit or 64bit). This has enabled binary compatibility between different generations of computers to be easily achieved, and the development of computer families.

Both of these developments have helped to lower the cost of computers and to increase their applicability. For these reasons, the ISA is one of the most important abstractions in computing today.

Remove or uninstall library previously added : cocoapods

None of these worked for me. I have pod version 1.5.3 and the correct method was to remove the pods that were not longer needed from the Podfile and then run:

pod update

This updates your Podfile.lock file from your Podfile, removes libraries that have been removed and updates all of your libraries.

Oracle Convert Seconds to Hours:Minutes:Seconds

My version. Show Oracle DB uptime in format DDd HHh MMm SSs

select to_char(trunc((((86400*x)/60)/60)/24)) || 'd ' ||
   to_char(trunc(((86400*x)/60)/60)-24*(trunc((((86400*x)/60)/60)/24)), 'FM00') || 'h ' ||
   to_char(trunc((86400*x)/60)-60*(trunc(((86400*x)/60)/60)), 'FM00') || 'm ' ||
   to_char(trunc(86400*x)-60*(trunc((86400*x)/60)), 'FM00') || 's' "UPTIME"
 from (select (sysdate - t.startup_time) x from V$INSTANCE t);

idea from Date / Time Arithmetic with Oracle 9/10

Using Intent in an Android application to show another activity

In the Manifest

<activity android:name=".OrderScreen" />

In the Java Code where you have to place intent code

startActivity(new Intent(CurrentActivity.this, OrderScreen.class);

how to run mysql in ubuntu through terminal

You have to give a valid username. For example, to run query with user root you have to type the following command and then enter password when prompted:

mysql -u root -p

Once you are connected, prompt will be something like:

mysql>

Here you can write your query, after database selection, for example:

mysql> USE your_database;
mysql> SELECT * FROM your_table;

Stash only one file out of multiple files that have changed with Git?

Use git stash push, like this:

git stash push [--] [<pathspec>...]

For example:

git stash push -- my/file.sh

This is available since Git 2.13, released in spring 2017.

Get value of input field inside an iframe

<iframe id="upload_target" name="upload_target">
    <textarea rows="20" cols="100" name="result" id="result" ></textarea>
    <input type="text" id="txt1" />
</iframe>

You can Get value by JQuery

$(document).ready(function(){
  alert($('#upload_target').contents().find('#result').html());
  alert($('#upload_target').contents().find('#txt1').val());
});

work on only same domain link

How to wait for a number of threads to complete?

One way would be to make a List of Threads, create and launch each thread, while adding it to the list. Once everything is launched, loop back through the list and call join() on each one. It doesn't matter what order the threads finish executing in, all you need to know is that by the time that second loop finishes executing, every thread will have completed.

A better approach is to use an ExecutorService and its associated methods:

List<Callable> callables = ... // assemble list of Callables here
                               // Like Runnable but can return a value
ExecutorService execSvc = Executors.newCachedThreadPool();
List<Future<?>> results = execSvc.invokeAll(callables);
// Note: You may not care about the return values, in which case don't
//       bother saving them

Using an ExecutorService (and all of the new stuff from Java 5's concurrency utilities) is incredibly flexible, and the above example barely even scratches the surface.

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

Bit late to the party but this simple solution worked for me:

function chainError(err) {
  return Promise.reject(err)
};

stepOne()
.then(stepTwo, chainError)
.then(stepThreee, chainError);

This allows you to break out of the chain.

Cocoa Touch: How To Change UIView's Border Color And Thickness?

You need to use view's layer to set border property. e.g:

#import <QuartzCore/QuartzCore.h>
...
view.layer.borderColor = [UIColor redColor].CGColor;
view.layer.borderWidth = 3.0f;

You also need to link with QuartzCore.framework to access this functionality.

Twitter Bootstrap 3 Sticky Footer

This has been solved by flexbox, once and forever:

https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/

The HTML

<body class="Site">
  <header>…</header>
  <main class="Site-content">…</main>
  <footer>…</footer>
</body>

The CSS

.Site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.Site-content {
  flex: 1;
}

Is there shorthand for returning a default value if None in Python?

return "default" if x is None else x

try the above.

Appending to an existing string

Can I ask why this is important?

I know that this is not a direct answer to your question, but the fact that you are trying to preserve the object ID of a string might indicate that you should look again at what you are trying to do.

You might find, for instance, that relying on the object ID of a string will lead to bugs that are quite hard to track down.

Row count with PDO

As it often happens, this question is confusing as hell. People are coming here having two different tasks in mind:

  1. They need to know how many rows in the table
  2. They need to know whether a query returned any rows

That's two absolutely different tasks that have nothing in common and cannot be solved by the same function. Ironically, for neither of them the actual PDOStatement::rowCount() function has to be used.

Let's see why

Counting rows in the table

Before using PDO I just simply used mysql_num_rows().

Means you already did it wrong. Using mysql_num_rows() or rowCount() to count the number of rows in the table is a real disaster in terms of consuming the server resources. A database has to read all the rows from the disk, consume the memory on the database server, then send all this heap of data to PHP, consuming PHP process' memory as well, burdening your server with absolute no reason.
Besides, selecting rows only to count them simply makes no sense. A count(*) query has to be run instead. The database will count the records out of the index, without reading the actual rows and then only one row returned.

For this purpose the code suggested in the accepted answer is fair, save for the fact it won't be an "extra" query but the only query to run.

Counting the number rows returned.

The second use case is not as disastrous as rather pointless: in case you need to know whether your query returned any data, you always have the data itself!

Say, if you are selecting only one row. All right, you can use the fetched row as a flag:

$stmt->execute();
$row = $stmt->fetch();
if (!$row) { // here! as simple as that
    echo 'No data found';
}

In case you need to get many rows, then you can use fetchAll().

fetchAll() is something I won't want as I may sometimes be dealing with large datasets

Yes of course, for the first use case it would be twice as bad. But as we learned already, just don't select the rows only to count them, neither with rowCount() nor fetchAll().

But in case you are going to actually use the rows selected, there is nothing wrong in using fetchAll(). Remember that in a web application you should never select a huge amount of rows. Only rows that will be actually used on a web page should be selected, hence you've got to use LIMIT, WHERE or a similar clause in your SQL. And for such a moderate amount of data it's all right to use fetchAll(). And again, just use this function's result in the condition:

$stmt->execute();
$data = $stmt->fetchAll();
if (!$data) { // again, no rowCount() is needed!
    echo 'No data found';
}

And of course it will be absolute madness to run an extra query only to tell whether your other query returned any rows, as it suggested in the two top answers.

Counting the number of rows in a large resultset

In such a rare case when you need to select a real huge amount of rows (in a console application for example), you have to use an unbuffered query, in order to reduce the amount of memory used. But this is the actual case when rowCount() won't be available, thus there is no use for this function as well.

Hence, that's the only use case when you may possibly need to run an extra query, in case you'd need to know a close estimate for the number of rows selected.

How to find good looking font color if background color is known?

Might be strange to answer my own question, but here is another really cool color picker I never saw before. It does not solve my problem either :-(((( however I think it's much cooler to these I know already.

http://www.colorjack.com/

On the right, under Tools select "Color Sphere", a very powerful and customizable sphere (see what you can do with the pop-ups on top), "Color Galaxy", I'm still not sure how this works, but looks cool and "Color Studio" is also nice. Further it can export to all kind of formats (e.g. Illustrator or Photoshop, etc.)

How about this, I choose my background color there, let it create a complimentary color (from the first pop up) - this should have highest contrast and thus be best readable, now select the complementary color as main color and select neutral? Hmmm... not too great either, but we are getting better ;-)

Is an empty href valid?

As others have said, it is valid.

There are some downsides to each approach though:

href="#" adds an extra entry to the browser history (which is annoying when e.g. back-buttoning).

href="" reloads the page

href="javascript:;" does not seem to have any problems (other than looking messy and meaningless) - anyone know of any?

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

Make sure you verify your setting for "Prefer 32-bit". In my case Visual Studio 2012 had this setting checked by default. Trying to use anything from an external DLL failed until I unchecked "Prefer 32-bit".

enter image description here

How to find the most recent file in a directory using .NET, and without looping?

it's a bit late but...

your code will not work, because of list<FileInfo> lastUpdateFile = null; and later lastUpdatedFile.Add(file); so NullReference exception will be thrown. Working version should be:

private List<FileInfo> GetLastUpdatedFileInDirectory(DirectoryInfo directoryInfo)
{
    FileInfo[] files = directoryInfo.GetFiles();
    List<FileInfo> lastUpdatedFile = new List<FileInfo>();
    DateTime lastUpdate = DateTime.MinValue;
    foreach (FileInfo file in files)
    {
        if (file.LastAccessTime > lastUpdate)
        {
            lastUpdatedFile.Add(file);
            lastUpdate = file.LastAccessTime;
        }
    }

    return lastUpdatedFile;
}

Thanks

Ajax Upload image

Image upload using ajax and check image format and upload max size   

<form class='form-horizontal' method="POST"  id='document_form' enctype="multipart/form-data">
                                    <div class='optionBox1'>
                                        <div class='row inviteInputWrap1 block1'>
                                            <div class='col-3'>
                                                <label class='col-form-label'>Name</label>
                                                <input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <label class='col-form-label'>File</label>
                                                <input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <span class='deleteInviteWrap1 remove1 d-none'>
                                                    <i class='fas fa-trash'></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class='row'>
                                             <div class='col-8 pl-3 pb-4 mt-4'>
                                                <span class='btn btn-info add1 pr-3'>+ Add More</span>
                                                 <button class='btn btn-primary'>Submit</button> 
                                            </div>
                                        </div>
                                    </div>
                                    </form>     
                                    
                                    </div>  
                      
    
      $.validator.setDefaults({
       submitHandler: function (form) 
         {
               $.ajax({
                    url : "action1.php",
                    type : "POST",
                    data : new FormData(form),
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    dataType:'json',
                    processData: false,
                    success: function(data)
                    {
                        if(data.status =='success')
                            {
                                 swal("Document has been successfully uploaded!", {
                                    icon: "success",
                                 });
                                 setTimeout(function(){
                                    window.location.reload(); 
                                },1200);
                            }
                            else
                            {
                                swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
                            }   
                    },
                    error:function(data)
                    {
                        swal ( "Ops!" ,  "error in document upload." ,  "error" );
                    }
                });
            }
      });
    
      $('#document_form').validate({
        rules: {
            "name[]": {
              required: true
          },
          "file[]": {
              required: true,
              extension: "jpg,jpeg,png,pdf,doc",
              filesize :2000000 
          }
        },
        messages: {
            "name[]": {
            required: "Please enter name"
          },
          "file[]": {
            required: "Please enter file",
            extension :'Please upload only jpg,jpeg,png,pdf,doc'
          }
        },
        errorElement: 'span',
        errorPlacement: function (error, element) {
          error.addClass('invalid-feedback');
          element.closest('.col-3').append(error);
        },
        highlight: function (element, errorClass, validClass) {
          $(element).addClass('is-invalid');
        },
        unhighlight: function (element, errorClass, validClass) {
          $(element).removeClass('is-invalid');
        }
      });
    
      $.validator.addMethod('filesize', function(value, element, param) {
         return this.optional(element) || (element.files[0].size <= param)
        }, 'File size must be less than 2 MB');

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

I just had this same problem because I had used improper syntax in my config file. I meant to add:

maxmemory-policy allkeys-lru

to my config file, but instead only added:

allkeys-lru

which evidently prevented Redis from parsing the config file, which in turn prevented me from connecting through the cli. Fixing this syntax allowed me to connect to Redis.

What does numpy.random.seed(0) do?

A random seed specifies the start point when a computer generates a random number sequence.

For example, let’s say you wanted to generate a random number in Excel (Note: Excel sets a limit of 9999 for the seed). If you enter a number into the Random Seed box during the process, you’ll be able to use the same set of random numbers again. If you typed “77” into the box, and typed “77” the next time you run the random number generator, Excel will display that same set of random numbers. If you type “99”, you’ll get an entirely different set of numbers. But if you revert back to a seed of 77, then you’ll get the same set of random numbers you started with.

For example, “take a number x, add 900 +x, then subtract 52.” In order for the process to start, you have to specify a starting number, x (the seed). Let’s take the starting number 77:

Add 900 + 77 = 977 Subtract 52 = 925 Following the same algorithm, the second “random” number would be:

900 + 925 = 1825 Subtract 52 = 1773 This simple example follows a pattern, but the algorithms behind computer number generation are much more complicated

Where is git.exe located?

I am using Windows 10, Pycharm 2016.1.2 and here is the path that i found Github.exe at: (please note that the bold part is variable and you should replace it with applicable values...)

C:\Users**Salman**\AppData\Local\GitHub\PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad\bin\git.exe

For a boolean field, what is the naming convention for its getter/setter?

I believe it would be:

void setCurrent(boolean current)
boolean isCurrent()

How can I stream webcam video with C#?

I've used VideoCapX for our project. It will stream out as MMS/ASF stream which can be open by media player. You can then embed media player into your webpage.

If you won't need much control, or if you want to try out VideoCapX without writing a code, try U-Broadcast, they use VideoCapX behind the scene.

jQuery Validate Required Select

You only need to put validate[required] as class of this select and then put a option with value=""

for example:

<select class="validate[required]">
  <option value="">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

A good gotcha is any error code > 255 will be converted to error code % 256. One should be specifically careful about this if they are using a custom error code > 255 and expecting the exact error code in the application logic. http://www.tldp.org/LDP/abs/html/exitcodes.html

jQuery if div contains this text, replace that part of the text

If it's possible, you could wrap the word(s) you want to replace in a span tag, like so:

<div class="text_div">
    This div <span>contains</span> some text.
</div>

You can then easily change its contents with jQuery:

$('.text_div > span').text('hello everyone');

If you can't wrap it in a span tag, you could use regular expressions.

Center an element with "absolute" position and undefined width in CSS?

.center {
  position: absolute
  left: 50%;
  bottom: 5px;
}

.center:before {
    content: '';
    display: inline-block;
    margin-left: -50%;
}

Background color of text in SVG

You can combine filter with the text.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <meta charset=utf-8 />_x000D_
    <title>SVG colored patterns via mask</title>_x000D_
  </head>_x000D_
  <body>_x000D_
    <svg viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg">_x000D_
      <defs>_x000D_
        <filter x="0" y="0" width="1" height="1" id="bg-text">_x000D_
          <feFlood flood-color="white"/>_x000D_
          <feComposite in="SourceGraphic" operator="xor" />_x000D_
        </filter>_x000D_
      </defs>_x000D_
   <!-- something has already existed -->_x000D_
    <rect fill="red" x="150" y="20" width="100" height="50" />_x000D_
    <circle cx="50"  cy="50" r="50" fill="blue"/>_x000D_
      _x000D_
      <!-- Text render here -->_x000D_
      <text filter="url(#bg-text)" fill="black" x="20" y="50" font-size="30">text with color</text>_x000D_
      <text fill="black" x="20" y="50" font-size="30">text with color</text>_x000D_
    </svg>_x000D_
  </body>_x000D_
</html> 
_x000D_
_x000D_
_x000D_

Oracle SQL: Use sequence in insert with Select Statement

Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like

INSERT INTO HISTORICAL_CAR_STATS (
    HISTORICAL_CAR_STATS_ID, 
    YEAR,
    MONTH, 
    MAKE,
    MODEL,
    REGION,
    AVG_MSRP,
    CNT) 
SELECT MY_SEQ.nextval,
       year,
       month,
       make,
       model,
       region,
       avg_msrp,
       cnt
  FROM (SELECT '2010' year,
               '12' month,
               'ALL' make,
               'ALL' model,
               REGION,
               sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
               sum(cnt) cnt
          FROM HISTORICAL_CAR_STATS
         WHERE YEAR = '2010' 
           AND MONTH = '12'
           AND MAKE != 'ALL' 
         GROUP BY REGION)

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

It should be MM for months. You are asking for minutes.

DateTime.Now.ToString("dd/MM/yyyy");

See Custom Date and Time Format Strings on MSDN for details.

How to insert a timestamp in Oracle?

insert
into tablename (timestamp_value)
values (TO_TIMESTAMP(:ts_val, 'YYYY-MM-DD HH24:MI:SS'));

if you want the current time stamp to be inserted then:

insert
into tablename (timestamp_value)
values (CURRENT_TIMESTAMP);

Best way of invoking getter by reflection

I think this should point you towards the right direction:

import java.beans.*

for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
  if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
    System.out.println(pd.getReadMethod().invoke(foo));
}

Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for

// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);

However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:

Object value = PropertyUtils.getProperty(person, "name");

BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The error tells you that there is an error but you don´t catch it. This is how you can catch it:

getAllPosts().then(response => {
    console.log(response);
}).catch(e => {
    console.log(e);
});

You can also just put a console.log(reponse) at the beginning of your API callback function, there is definitely an error message from the Graph API in it.

More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

Or with async/await:

//some async function
try {
    let response = await getAllPosts();
} catch(e) {
    console.log(e);
}

MySQL stored procedure return value

You have done the stored procedure correctly but I think you have not referenced the valido variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido

This statement SELECT valido; should be like this SELECT @valido;

Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido

I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

Add STATS=10 or STATS=1 in backup command.

BACKUP DATABASE [xxxxxx] TO  DISK = N'E:\\Bachup_DB.bak' WITH NOFORMAT, NOINIT,  
NAME = N'xxxx-Complète Base de données Sauvegarde', SKIP, NOREWIND, NOUNLOAD, COMPRESSION,  STATS = 10
GO.

PHP display image BLOB from MySQL

Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:

echo "data: $mime" $result['$data']";

where: mime can be an image of any kind, text, word document, text document, PDF document, etc... content datatype is blob in database.

How to return a value from a Form in C#?

If you want to pass data to form2 from form1 without passing like new form(sting "data");

Do like that in form 1

using (Form2 form2= new Form2())
{
   form2.ReturnValue1 = "lalala";
   form2.ShowDialog();
}

in form 2 add

public string ReturnValue1 { get; set; }

private void form2_Load(object sender, EventArgs e)
{
   MessageBox.Show(ReturnValue1);
}

Also you can use value in form1 like this if you want to swap something in form1

just in form1

textbox.Text =form2.ReturnValue1

How to configure Visual Studio to use Beyond Compare

I'm using VS 2017 with projects hosted with Git on visualstudio.com hosting (msdn)

The link above worked for me with the "GITHUB FOR WINDOWS" instructions.

http://www.scootersoftware.com/support.php?zz=kb_vcs#githubwindows

The config file was located where it indicated at "c:\users\username\.gitconfig" and I just changed the BC4's to BC3's for my situation and used the appropriate path:

C:/Program Files (x86)/Beyond Compare 3/bcomp.exe

How to view the current heap size that an application is using?

Attach with jvisualvm from Sun Java 6 JDK. Startup flags are listed.

A non well formed numeric value encountered

This is an old question, but there is another subtle way this message can happen. It's explained pretty well here, in the docs.

Imagine this scenerio:

try {
  // code that triggers a pdo exception
} catch (Exception $e) {
  throw new MyCustomExceptionHandler($e);
}

And MyCustomExceptionHandler is defined roughly like:

class MyCustomExceptionHandler extends Exception {
  public function __construct($e) {
    parent::__construct($e->getMessage(), $e->getCode());
  }
}

This will actually trigger a new exception in the custom exception handler because the Exception class is expecting a number for the second parameter in its constructor, but PDOException might have dynamically changed the return type of $e->getCode() to a string.

A workaround for this would be to define you custom exception handler like:

class MyCustomExceptionHandler extends Exception {
  public function __construct($e) {
    parent::__construct($e->getMessage());
    $this->code = $e->getCode();
  }
}

Possible heap pollution via varargs parameter

The reason is because varargs give the option of being called with a non-parametrized object array. So if your type was List < A > ... , it can also be called with List[] non-varargs type.

Here is an example:

public static void testCode(){
    List[] b = new List[1];
    test(b);
}

@SafeVarargs
public static void test(List<A>... a){
}

As you can see List[] b can contain any type of consumer, and yet this code compiles. If you use varargs, then you are fine, but if you use the method definition after type-erasure - void test(List[]) - then the compiler will not check the template parameter types. @SafeVarargs will suppress this warning.

Android getting value from selected radiobutton

I have had problems getting radio buttons id's as well when the RadioButtons are dynamically generated. It does not seem to work if you try to manually set the ID's using RadioButton.setId(). What worked for me was to use View.getChildAt() and View.getParent() in order to iterate through the radio buttons and determine which one was checked. All you need is to first get the RadioGroup via findViewById(R.id.myRadioGroup) and then iterate through it's children. You'll know as you iterate through which button you are on, and you can simply use RadioButton.isChecked() to determine if that is the button that was checked.

How do I access store state in React Redux?

You should create separate component, which will be listening to state changes and updating on every state change:

import store from '../reducers/store';

class Items extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: [],
    };

    store.subscribe(() => {
      // When state will be updated(in our case, when items will be fetched), 
      // we will update local component state and force component to rerender 
      // with new data.

      this.setState({
        items: store.getState().items;
      });
    });
  }

  render() {
    return (
      <div>
        {this.state.items.map((item) => <p> {item.title} </p> )}
      </div>
    );
  }
};

render(<Items />, document.getElementById('app'));

count of entries in data frame in R

You could use table:

R> x <- read.table(textConnection('
   Believe Age Gender Presents Behaviour
1    FALSE   9   male       25   naughty
2     TRUE   5   male       20      nice
3     TRUE   4 female       30      nice
4     TRUE   4   male       34   naughty'
), header=TRUE)

R> table(x$Believe)

FALSE  TRUE 
    1     3 

Remove part of string in Java

// Java program to remove a substring from a string
public class RemoveSubString {

    public static void main(String[] args) {
        String master = "1,2,3,4,5";
        String to_remove="3,";

        String new_string = master.replace(to_remove, "");
        // the above line replaces the t_remove string with blank string in master

        System.out.println(master);
        System.out.println(new_string);

    }
}

python pip: force install ignoring dependencies

pip has a --no-dependencies switch. You should use that.

For more information, run pip install -h, where you'll see this line:

--no-deps, --no-dependencies
                        Ignore package dependencies

Changing the color of a clicked table row using jQuery

To change color of a cell:

$(document).on('click', '#table tbody td', function (event) {


    var selected = $(this).hasClass("obstacle");
    $("#table tbody td").removeClass("obstacle");
    if (!selected)
        $(this).addClass("obstacle");

});

Multiple Inheritance in C#

If X inherits from Y, that has two somewhat orthogonal effects:

  1. Y will provide default functionality for X, so the code for X only has to include stuff which is different from Y.
  2. Almost anyplace a Y would be expected, an X may be used instead.

Although inheritance provides for both features, it is not hard to imagine circumstances where either could be of use without the other. No .net language I know of has a direct way of implementing the first without the second, though one could obtain such functionality by defining a base class which is never used directly, and having one or more classes that inherit directly from it without adding anything new (such classes could share all their code, but would not be substitutable for each other). Any CLR-compliant language, however, will allow the use of interfaces which provide the second feature of interfaces (substitutability) without the first (member reuse).

How to get client IP address in Laravel 5+

Add namespace

use Request;

Then call the function

Request::ip();

SPAN vs DIV (inline-block)

I know this Q is old, but why not use all DIVs instead of the SPANs? Then everything plays all happy together.

Example:

<div> 
   <div> content1(divs,p, spans, etc) </div> 
   <div> content2(divs,p, spans, etc) </div> 
   <div> content3(divs,p, spans, etc) </div> 
</div> 
<div> 
   <div> content4(divs,p, spans, etc) </div> 
   <div> content5(divs,p, spans, etc) </div> 
   <div> content6(divs,p, spans, etc) </div> 
</div>

How to debug a Flask app

Install python-dotenv in your virtual environment.

Create a .flaskenv in your project root. By project root, I mean the folder which has your app.py file

Inside this file write the following:

FLASK_APP=myapp 
FLASK_ENV=development

Now issue the following command:

flask run

How can I get the file name from request.FILES?

The answer may be outdated, since there is a name property on the UploadedFile class. See: Uploaded Files and Upload Handlers (Django docs). So, if you bind your form with a FileField correctly, the access should be as easy as:

if form.is_valid():
    form.cleaned_data['my_file'].name

Wampserver icon not going green fully, mysql services not starting up?

Wow.. This works for me. Unistall the wamp server Make sure this dependencies are successfully installed Microsoft Visual C++ Redistributable Packages vcredist_Allversions(x32 orx64) depending on your OS. Reinstall the wamp server and you are good to go. Thank you

How To Accept a File POST

I'm surprised that a lot of you seem to want to save files on the server. Solution to keep everything in memory is as follows:

[HttpPost("api/upload")]
public async Task<IHttpActionResult> Upload()
{
    if (!Request.Content.IsMimeMultipartContent())
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 

    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);
    foreach (var file in provider.Contents)
    {
        var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
        var buffer = await file.ReadAsByteArrayAsync();
        //Do whatever you want with filename and its binary data.
    }

    return Ok();
}

C# event with custom arguments

You declare a delegate for the parameters:

public enum MyEvents { Event1 }

public delegate void MyEventHandler(MyEvents e);

public static event MyEventHandler EventTriggered;

Although all events in the framework takes a parameter that is or derives from EventArgs, you can use any parameters you like. However, people are likely to expect the pattern used in the framework, which might make your code harder to follow.

Setting a max character length in CSS

Modern CSS Grid Answer

View the fully working code on CodePen. Given the following HTML:

<div class="container">
    <p>Several paragraphs of text...</p>
</div>

You can use CSS Grid to create three columns and tell the container to take a maximum width of 70 characters for the middle column which contains our paragraph.

.container
{
  display: grid;
  grid-template-columns: 1fr, 70ch 1fr;
}

p {
  grid-column: 2 / 3;
}

This is what it looks like (Checkout CodePen for a fully working example):

enter image description here

Here is another example where you can use minmax to set a range of values. On small screens the width will be set to 50 characters wide and on large screens it will be 70 characters wide.

.container
{
  display: grid;
  grid-template-columns: 1fr minmax(50ch, 70ch) 1fr;
}

p {
  grid-column: 2 / 3;
}

List append() in for loop

No need to re-assign.

a=[]
for i in range(5):    
    a.append(i)
a

Classes vs. Modules in VB.NET

Modules are VB counterparts to C# static classes. When your class is designed solely for helper functions and extension methods and you don't want to allow inheritance and instantiation, you use a Module.

By the way, using Module is not really subjective and it's not deprecated. Indeed you must use a Module when it's appropriate. .NET Framework itself does it many times (System.Linq.Enumerable, for instance). To declare an extension method, it's required to use Modules.

Excel VBA function to print an array to the workbook

My tested version

Sub PrintArray(RowPrint, ColPrint, ArrayName, WorkSheetName)

Sheets(WorkSheetName).Range(Cells(RowPrint, ColPrint), _
Cells(RowPrint + UBound(ArrayName, 2) - 1, _
ColPrint + UBound(ArrayName, 1) - 1)) = _
WorksheetFunction.Transpose(ArrayName)

End Sub

Problems with local variable scope. How to solve it?

I found this approach useful. This way you do not need a class nor final

 btnInsert.addMouseListener(new MouseAdapter() {
        private Statement _statement;

        public MouseAdapter setStatement(Statement _stmnt)
        {
            _statement = _stmnt;
            return this;
        }
        @Override
        public void mouseDown(MouseEvent e) {
            String name = text.getText();
            String from = text_1.getText();
            String to = text_2.getText();
            String price = text_3.getText();

            String query = "INSERT INTO booking (name, fromst, tost, price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
            try {
                _statement.executeUpdate(query);
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }.setStatement(statement));

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

I have done this before, I think you need to remove the ActionResult. Make it a void and remove the return View(MyView). this is the solution

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

How does the above for-each loop work?

Like many other array features, the JSL mentions arrays explicitly and gives them magical properties. JLS 7 14.14.2:

EnhancedForStatement:

    for ( FormalParameter : Expression ) Statement

[...]

If the type of Expression is a subtype of Iterable, then the translation is as follows

[...]

Otherwise, the Expression necessarily has an array type, T[]. [[ MAGIC! ]]

Let L1 ... Lm be the (possibly empty) sequence of labels immediately preceding the enhanced for statement.

The enhanced for statement is equivalent to a basic for statement of the form:

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    VariableModifiersopt TargetType Identifier = #a[#i];
    Statement
}

#a and #i are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

Is the array converted to a list to get the iterator?

Let's javap it up:

public class ArrayForLoop {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        for (int i : arr)
            System.out.println(i);
    }
}

then:

javac ArrayForLoop.java
javap -v ArrayForLoop

main method with a bit of editing to make it easier to read:

 0: iconst_3
 1: newarray       int
 3: dup
 4: iconst_0
 5: iconst_1
 6: iastore
 7: dup
 8: iconst_1
 9: iconst_2
10: iastore
11: dup
12: iconst_2
13: iconst_3
14: iastore

15: astore_1
16: aload_1
17: astore_2
18: aload_2
19: arraylength
20: istore_3
21: iconst_0
22: istore        4

24: iload         4
26: iload_3
27: if_icmpge     50
30: aload_2
31: iload         4
33: iaload
34: istore        5
36: getstatic     #2    // Field java/lang/System.out:Ljava/io/PrintStream;
39: iload         5
41: invokevirtual #3    // Method java/io/PrintStream.println:(I)V
44: iinc          4, 1
47: goto          24
50: return

Breakdown:

  • 0 to 14: create the array
  • 15 to 22: prepare for the for loop. At 22, store integer 0 from stack into local position 4. THAT is the loop variable.
  • 24 to 47: the loop. The loop variable is retrieved at 31, and incremented at 44. When it equals the array length which is stored in local variable 3 on the check at 27, the loop ends.

Conclusion: it is the same as doing an explicit for loop with an index variable, no itereators involved.

How to make an input type=button act like a hyperlink and redirect using a get request?

For those who stumble upon this from a search (Google) and are trying to translate to .NET and MVC code. (as in my case)

@using (Html.BeginForm("RemoveLostRolls", "Process", FormMethod.Get)) {
     <input type="submit" value="Process" />
}

This will show a button labeled "Process" and take you to "/Process/RemoveLostRolls". Without "FormMethod.Get" it worked, but was seen as a "post".

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

@NathanClement was a bit faster. Yet, here is the complete code (slightly more elaborate):

Option Explicit

Public Sub ExportWorksheetAndSaveAsCSV()

Dim wbkExport As Workbook
Dim shtToExport As Worksheet

Set shtToExport = ThisWorkbook.Worksheets("Sheet1")     'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False                       'Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\tmp\test.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False

End Sub

join list of lists in python

If you're only going one level deep, a nested comprehension will also work:

>>> x = [["a","b"], ["c"]]
>>> [inner
...     for outer in x
...         for inner in outer]
['a', 'b', 'c']

On one line, that becomes:

>>> [j for i in x for j in i]
['a', 'b', 'c']

How do I compare two columns for equality in SQL Server?

The closest approach I can think of is NULLIF:

SELECT 
    ISNULL(NULLIF(O.ShipName, C.CompanyName), 1),
    O.ShipName,      
    C.CompanyName,
    O.OrderId
FROM [Northwind].[dbo].[Orders] O
INNER JOIN [Northwind].[dbo].[Customers] C
ON C.CustomerId = O.CustomerId

GO

NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.

So, above query will return 1 for records in which that columns are equal, the first expression otherwise.

Why cannot cast Integer to String in java?

Objects can be converted to a string using the toString() method:

String myString = myIntegerObject.toString();

There is no such rule about casting. For casting to work, the object must actually be of the type you're casting to.

Code coverage with Mocha

Now (2021) the preferred way to use istanbul is via its "state of the art command line interface" nyc.

Setup

First, install it in your project with

npm i nyc --save-dev

Then, if you have a npm based project, just change the test script inside the scripts object of your package.json file to execute code coverage of your mocha tests:

{
  "scripts": {
    "test": "nyc --reporter=text mocha"
  }
}

Run

Now run your tests

npm test

and you will see a table like this in your console, just after your tests output:

Istanbul Nyc Mocha code coverage

Customization

Html report

Just use

nyc --reporter=html

instead of text. Now it will produce a report inside ./coverage/index.html.

Report formats

Istanbul supports a wide range of report formats. Just look at its reports library to find the most useful for you. Just add a --reporter=REPORTER_NAME option for each format you want. For example, with

nyc --reporter=html --reporter=text

you will have both the console and the html report.

Don't run coverage with npm test

Just add another script in your package.json and leave the test script with only your test runner (e.g. mocha):

{
  "scripts": {
    "test": "mocha",
    "test-with-coverage": "nyc --reporter=text mocha"
  }
}

Now run this custom script

npm run test-with-coverage

to run tests with code coverage.

Force test failing if code coverage is low

Fail if the total code coverage is below 90%:

nyc --check-coverage --lines 90 

Fail if the code coverage of at least one file is below 90%:

nyc --check-coverage --lines 90 --per-file

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

$ is a function provided by the jQuery library, it won't be available unless you have loaded the jQuery library.

You need to add jQuery (typically with a <script> element which can point at a local copy of the library or one hosted on a CDN). Make sure you are using a current and supported version: Many answers on this question recommend using 1.x or 2.x versions of jQuery which are no longer supported and have known security issues.

<script src="/path/to/jquery.js"></script>

Make sure you load jQuery before you run any script which depends on it.

The jQuery homepage will have a link to download the current version of the library (at the time of writing it is 3.5.1 but that may change by the time you read this).

Further down the page you will find a section on using jQuery with a CDN which links to a number of places that will host the library for you.


(NB: Some other libraries provide a $ function, and browsers have native $ variables which are only available in the Developer Tools Console, but this question isn't about those).

Using setattr() in python

The Python docs say all that needs to be said, as far as I can see.

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

If this isn't enough, explain what you don't understand.

Cleanest way to write retry logic?

Exponential backoff is a good retry strategy than simply trying x number of times. You can use a library like Polly to implement it.

How to delete empty folders using windows command prompt?

If you want to use Varun's ROBOCOPY command line in the Explorer context menu (i.e. right-click) here is a Windows registry import. I tried adding this as a comment to his answer, but the inline markup wasn't feasible.

I've tested this on my own Windows 10 PC, but use at your own risk. It will open a new command prompt, run the command, and pause so you can see the output.

  1. Copy into a new text file:

    Windows Registry Editor Version 5.00

    [HKEY_CURRENT_USER\Software\Classes\directory\Background\shell\Delete Empty Folders\command] @="C:\Windows\System32\Cmd.exe /C \"C:\Windows\System32\Robocopy.exe \"%V\" \"%V\" /s /move\" && PAUSE"

    [HKEY_CURRENT_USER\Software\Classes\directory\shell\Delete Empty Folders\command] @="C:\Windows\System32\Cmd.exe /C \"C:\Windows\System32\Robocopy.exe \"%V\" \"%V\" /s /move\" && PAUSE"

  2. Rename the .txt extension to .reg

  3. Double click to import.

Android: Rotate image in imageview by an angle

Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
imageView.setImageMatrix(matrix);

how to use?

public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   TextView textChanger;
   ImageView imageView;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      textChanger = findViewById(R.id.textChanger);
      imageView=findViewById(R.id.imageView);
      textChanger.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            roateImage(imageView);
         }
      });
   }
   private void roateImage(ImageView imageView) {
      Matrix matrix = new Matrix();
      imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
      matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2,    imageView.getDrawable().getBounds().height()/2);
      imageView.setImageMatrix(matrix);
   }
}

Matching exact string with JavaScript

Either modify the pattern beforehand so that it only matches the entire string:

var r = /^a$/

or check afterward whether the pattern matched the whole string:

function matchExact(r, str) {
   var match = str.match(r);
   return match && str === match[0];
}

Get integer value from string in swift

I'd use:

var stringNumber = "1234"
var numberFromString = stringNumber.toInt()
println(numberFromString)

Note toInt():

If the string represents an integer that fits into an Int, returns the corresponding integer.

How do I get JSON data from RESTful service using Python?

Well first of all I think rolling out your own solution for this all you need is urllib2 or httplib2 . Anyways in case you do require a generic REST client check this out .

https://github.com/scastillo/siesta

However i think the feature set of the library will not work for most web services because they shall probably using oauth etc .. . Also I don't like the fact that it is written over httplib which is a pain as compared to httplib2 still should work for you if you don't have to handle a lot of redirections etc ..

How to hide the bar at the top of "youtube" even when mouse hovers over it?

To remove you tube controls and title you can do something like this.

<iframe width="560" height="315" src="https://www.youtube.com/embed/zP0Wnb9RI9Q?autoplay=1&showinfo=0&controls=0" frameborder="0" allowfullscreen ></iframe>

check this example how it look

showinfo=0 is used to remove title and &controls=0 is used for remove controls like volume,play,pause,expend.

parent & child with position fixed, parent overflow:hidden bug

You could consider using CSS clip: rect(top, right, bottom, left); to clip a fixed positioned element to a parent. See demo at http://jsfiddle.net/lmeurs/jf3t0fmf/.

Beware, use with care!

Though the clip style is widely supported, main disadvantages are that:

  1. The parent's position cannot be static or relative (one can use an absolutely positioned parent inside a relatively positioned container);
  2. The rect coordinates do not support percentages, though the auto value equals 100%, ie. clip: rect(auto, auto, auto, auto);;
  3. Possibillities with child elements are limited in at least IE11 & Chrome34, ie. we cannot set the position of child elements to relative or absolute or use CSS3 transform like scale.

See http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/ for more info.

EDIT: Chrome seems to handle positioning of and CSS3 transforms on child elements a lot better when applying backface-visibility, so just to be sure we added:

-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
backface-visibility: hidden;

to the main child element.

Also note that it's not fully supported by older / mobile browsers or it might take some extra effort. See our implementation for the menu at bellafuchsia.com.

  1. IE8 shows the menu well, but menu links are not clickable;
  2. IE9 does not show the menu under the fold;
  3. iOS Safari <5 does not show the menu well;
  4. iOS Safari 5+ repaints the clipped content on scroll after scrolling;
  5. FF (at least 13+), IE10+, Chrome and Chrome for Android seem to play nice.

EDIT 2014-11-02: Demo URL has been updated.

PHP, get file name without file extension

Short

echo pathinfo(__FILE__)['filename']; // since php 5.2

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

Is there any way to specify a suggested filename when using data: URI?

This one works with Firefox 43.0 (older not tested):

dl.js:

function download() {
  var msg="Hello world!";
  var blob = new File([msg], "hello.bin", {"type": "application/octet-stream"});

  var a = document.createElement("a");
  a.href = URL.createObjectURL(blob);

  window.location.href=a;
}

dl.html

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8"/>
    <title>Test</title>
    <script type="text/javascript" src="dl.js"></script>
</head>

<body>
<button id="create" type="button" onclick="download();">Download</button>
</body>
</html>

If button is clicked it offered a file named hello.bin for download. Trick is to use File instead of Blob.

reference: https://developer.mozilla.org/de/docs/Web/API/File

Create new XML file and write data to it?

PHP has several libraries for XML Manipulation.

The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'Root' );
    $ele->nodeValue = 'Hello XML World';
    $doc->appendChild( $ele );
    $doc->save('MyXmlFile.xml');
?>

Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.

How to export and import a .sql file from command line with options?

If you're already running the SQL shell, you can use the source command to import data:

use databasename;
source data.sql;

Set selected item in Android BottomNavigationView

Seems to be fixed in SupportLibrary 25.1.0 :) Edit: It seems to be fixed, that the state of the selection is saved, when rotating the screen.

Center an item with position: relative

If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto

Vertical centering is a bit tricker, but possible.

how to use JSON.stringify and json_decode() properly

jsonText = $_REQUEST['myJSON'];

$decodedText = html_entity_decode($jsonText);

$myArray = json_decode($decodedText, true);`

jQuery ajax success error

I had the same problem;

textStatus = 'error'
errorThrown = (empty)
xhr.status = 0

That fits my problem exactly. It turns out that when I was loading the HTML-page from my own computer this problem existed, but when I loaded the HTML-page from my webserver it went alright. Then I tried to upload it to another domain, and again the same error occoured. Seems to be a cross-domain problem. (in my case at least)

I have tried calling it this way also:

var request = $.ajax({
url: "http://crossdomain.url.net/somefile.php", dataType: "text",
crossDomain: true,
xhrFields: {
withCredentials: true
}
});

but without success.

This post solved it for me: jQuery AJAX cross domain

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.

That is neither a good idea in terms of peformance nor in terms of fail-safety.

Don't poach on the Connection-Pool's territory

There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.

So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.

If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).

Conclusion:

  • Don't reuse connections or any ADO.NET objects at all.
  • Don't make them static/shared(in VB.NET)
  • Always create, open(in case of Connections), use, close and dispose them where you need them(f.e. in a method)
  • use the using-statement to dispose and close(in case of Connections) implicitely

That's true not only for Connections(although most noticable). Every object implementing IDisposable should be disposed(simplest by using-statement), all the more in the System.Data.SqlClient namespace.

All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.


Edit: Here's a possible implementation of your retrievePromotion-method:

public Promotion retrievePromotion(int promotionID)
{
    Promotion promo = null;
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
        using (var da = new SqlDataAdapter(queryString, connection))
        {
            // you could also use a SqlDataReader instead
            // note that a DataTable does not need to be disposed since it does not implement IDisposable
            var tblPromotion = new DataTable();
            // avoid SQL-Injection
            da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
            da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
            try
            {
                connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise 
                da.Fill(tblPromotion);
                if (tblPromotion.Rows.Count != 0)
                {
                    var promoRow = tblPromotion.Rows[0];
                    promo = new Promotion()
                    {
                        promotionID    = promotionID,
                        promotionTitle = promoRow.Field<String>("PromotionTitle"),
                        promotionUrl   = promoRow.Field<String>("PromotionURL")
                    };
                }
            }
            catch (Exception ex)
            {
                // log this exception or throw it up the StackTrace
                // we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
                throw;
            }
        }
    }
    return promo;
}

how to concat two columns into one with the existing column name in mysql?

I am a novice and I did it this way:

Create table Name1
(
F_Name varchar(20),
L_Name varchar(20),
Age INTEGER
)

Insert into Name1
Values
('Tom', 'Bombadil', 32),
('Danny', 'Fartman', 43),
('Stephine', 'Belchlord', 33),
('Corry', 'Smallpants', 95)
Go

Update Name1
Set F_Name = CONCAT(F_Name, ' ', L_Name)
Go

Alter Table Name1
Drop column L_Name
Go

Update Table_Name
Set F_Name

Maintain aspect ratio of div but fill screen width and height in CSS?

My original question for this was how to both have an element of a fixed aspect, but to fit that within a specified container exactly, which makes it a little fiddly. If you simply want an individual element to maintain its aspect ratio it is a lot easier.

The best method I've come across is by giving an element zero height and then using percentage padding-bottom to give it height. Percentage padding is always proportional to the width of an element, and not its height, even if its top or bottom padding.

W3C Padding Properties

So utilising that you can give an element a percentage width to sit within a container, and then padding to specify the aspect ratio, or in other terms, the relationship between its width and height.

.object {
    width: 80%; /* whatever width here, can be fixed no of pixels etc. */
    height: 0px;
    padding-bottom: 56.25%;
}
.object .content {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    padding: 40px;
}

So in the above example the object takes 80% of the container width, and then its height is 56.25% of that value. If it's width was 160px then the bottom padding, and thus the height would be 90px - a 16:9 aspect.

The slight problem here, which may not be an issue for you, is that there is no natural space inside your new object. If you need to put some text in for example and that text needs to take it's own padding values you need to add a container inside and specify the properties in there.

Also vw and vh units aren't supported on some older browsers, so the accepted answer to my question might not be possible for you and you might have to use something more lo-fi.

Trying to mock datetime.date.today(), but not working

It's possible to mock functions from datetime module without adding side_effects

import mock
from datetime import datetime
from where_datetime_used import do

initial_date = datetime.strptime('2018-09-27', "%Y-%m-%d")
with mock.patch('where_datetime_used.datetime') as mocked_dt:
    mocked_dt.now.return_value = initial_date
    do()

Convert an int to ASCII character

My way to do this job is:

char to int
char var;
cout<<(int)var-48;
    
int to char
int var;
cout<<(char)(var|48);

And I write these functions for conversions:

int char2int(char *szBroj){
    int counter=0;
    int results=0;
    while(1){
        if(szBroj[counter]=='\0'){
            break;
        }else{
            results*=10;
            results+=(int)szBroj[counter]-48;
            counter++;
        }
    }
    return results;
}

char * int2char(int iNumber){
    int iNumbersCount=0;
    int iTmpNum=iNumber;
    while(iTmpNum){
        iTmpNum/=10;
        iNumbersCount++;
    }
    char *buffer=new char[iNumbersCount+1];
    for(int i=iNumbersCount-1;i>=0;i--){
        buffer[i]=(char)((iNumber%10)|48);
        iNumber/=10;
    }
    buffer[iNumbersCount]='\0';
    return buffer;
}

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Try using the QueryDefs. Create the query with parameters. Then use something like this:

Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef

Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("Your Query Name")

qdf.Parameters("Parameter 1").Value = "Parameter Value"
qdf.Parameters("Parameter 2").Value = "Parameter Value"
qdf.Execute
qdf.Close

Set qdf = Nothing
Set dbs = Nothing

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

composer laravel create project

No this step isn't equal to downloading the laravel.zip by using the command composer create-project laravel/laravel laravel you actually download the laravel project as well as dependent packages so its one step ahead.

If you are using windows environment you can solve the problem by deleting the composer environment variable you created to install the composer. And this command will run properly.

How to convert date to timestamp?

/**
 * Date to timestamp
 * @param  string template
 * @param  string date
 * @return string
 * @example         datetotime("d-m-Y", "26-02-2012") return 1330207200000
 */
function datetotime(template, date){
    date = date.split( template[1] );
    template = template.split( template[1] );
    date = date[ template.indexOf('m') ]
        + "/" + date[ template.indexOf('d') ]
        + "/" + date[ template.indexOf('Y') ];

    return (new Date(date).getTime());
}

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

use DBName

select * from TABLE_NAME A

where A.date >= '2018-06-26 21:24' and A.date <= '2018-06-26 21:28';

How do you generate a random double uniformly distributed between 0 and 1 from C++?

An old school solution like:

double X=((double)rand()/(double)RAND_MAX);

Should meet all your criteria (portable, standard and fast). obviously the random number generated has to be seeded the standard procedure is something like:

srand((unsigned)time(NULL));

Count the cells with same color in google spreadsheet

function countbackgrounds() {
 var book = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = book.getActiveSheet();
 var range_input = sheet.getRange("B3:B4");
 var range_output = sheet.getRange("B6");
 var cell_colors = range_input.getBackgroundColors();
 var color = "#58FA58";
 var count = 0;

 for(var r = 0; r < cell_colors.length; r++) {
   for(var c = 0; c < cell_colors[0].length; c++) {
     if(cell_colors[r][c] == color) {
       count = count + 1;
     }
   }
 }
    range_output.setValue(count);
 }

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Your code was compiled with Java 8.

Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.

Hope this helps...

Android Webview gives net::ERR_CACHE_MISS message

I tried above solution, but the following code help me to close this issue.

if (18 < Build.VERSION.SDK_INT ){
    //18 = JellyBean MR2, KITKAT=19
    mWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}

Any way to clear python's IDLE window?

The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen down lots of lines, eg:

print ("\n" * 100)

Though you could put this in a function:

def cls(): print ("\n" * 100)

And then call it when needed as cls()

cannot find zip-align when publishing app

On a Mac, I did the following:

  1. Find it on o/s (I had already downloaded build tools for 19 and 20)

  2. Press Ctrl-Open to allow apps from the internet

  3. Move it from sdk/build-tools/android-4.4W folder to sdk/tools/. Whew.

Android: How can I pass parameters to AsyncTask's onPreExecute()?

1) For me that's the most simple way passing parameters to async task is like this

// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);

Declare and use the async task like here

private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {

    @Override
    protected Void doInBackground(Boolean...pParams) 
    {
        Boolean param1, param2, param3;

        //

          param1=pParams[0];    
          param2=pParams[1];
          param3=pParams[2];    
      ....
}                           

2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.

 /* Generic Async Task    */
interface MyGenericMethod {
    int execute(String param);
}

protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
    public String mParam;                           // member variable to parameterize the function
    @Override
    protected Void doInBackground(MyGenericMethod... params) {
        //  do something here
        params[0].execute("Myparameter");
        return null;
    }       
}

// to start the asynctask do something like that
public void startAsyncTask()
{
    // 
    AsyncTask<MyGenericMethod, Void, Void>  mytest = new testtask().execute(new MyGenericMethod() {
        public int execute(String param) {
            //body
            return 1;
        }
    });     
}

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

Just to follow up, problem solved! I mentioned mod_sec settings for my server as being the possible culprit as suggested and they were able to fix this issue. Here's what the tech agent said to tell them when you go to support:

Just let them know you need the rule 340163 whitelisted for domain.com as its hitting a mod_sec rule.

Apparently you will need to do this for each domain that is having the issue, but it works. Thanks for all the suggestions everyone!

How can I hide a TD tag using inline JavaScript or CSS?

Everything is possible (or almost) with css, just use:

display: none; //to hide

display: table-cell //to show

Why use pip over easy_install?

Two reasons, there may be more:

  1. pip provides an uninstall command

  2. if an installation fails in the middle, pip will leave you in a clean state.

Getting java.net.SocketTimeoutException: Connection timed out in android

I've searched all over the web and after reading lot of docs regarding connection timeout exception, the thing I understood is that, preventing SocketTimeoutException is beyond our limit. One way to effectively handle it is to define a connection timeout and later handle it by using a try-catch block. Hope this will help anyone in future who are facing the same issue.

HttpUrlConnection conn = (HttpURLConnection) url.openConnection();

//set the timeout in milliseconds
conn.setConnectTimeout(7000);

Does hosts file exist on the iPhone? How to change it?

In case anybody else falls onto this page, you can also solve this by using the Ip address in the URL request instead of the domain:

NSURL *myURL = [NSURL URLWithString:@"http://10.0.0.2/mypage.php"];

Then you specify the Host manually:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];
[request setAllHTTPHeaderFields:[NSDictionary dictionaryWithObjectAndKeys:@"myserver",@"Host"]];

As far as the server is concerned, it will behave the exact same way as if you had used http://myserver/mypage.php, except that the iPhone will not have to do a DNS lookup.

100% Public API.

JavaFX FXML controller - constructor vs initialize method

In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.

import javafx.fxml.Initializable;

class MyController implements Initializable {
    @FXML private TableView<MyModel> tableView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tableView.getItems().addAll(getDataFromSource());
    }
}

Parameters:

location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized. 

And the note of the docs why the simple way of using @FXML public void initialize() works:

NOTE This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.

jQuery get value of selected radio button

By Name only

$(function () {
    $('input[name="EventType"]:radio').change(function () {
        alert($("input[name='EventType']:checked").val());
    });
});

How to empty ("truncate") a file on linux that already exists and is protected in someway?

Any one can try this command to truncate any file in linux system

This will surely work in any format :

truncate -s 0 file.txt

Internet Explorer 11- issue with security certificate error prompt

This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level

You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property

You can do that by following steps:

  1. Click on Gear icon at the top of the browser window.
  2. Select Internet Options.
  3. Select the Security tab at the top.
  4. Click the Custom Level... button.
  5. Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
  6. Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
  7. Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
  8. Close and restart the browser.

enter image description here

Current time in microseconds in java

You can use System.nanoTime():

long start = System.nanoTime();
// do stuff
long end = System.nanoTime();
long microseconds = (end - start) / 1000;

to get time in nanoseconds but it is a strictly relative measure. It has no absolute meaning. It is only useful for comparing to other nano times to measure how long something took to do.

GROUP_CONCAT ORDER BY

You can use ORDER BY inside the GROUP_CONCAT function in this way:

SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC) AS views, 
group_concat(li.percentage ORDER BY li.percentage ASC) 
FROM li GROUP BY client_id

How to preserve request url with nginx proxy_pass

Just proxy_set_header Host $host miss port for my case. Solved by:



    location / {
     proxy_pass http://BACKENDIP/;
     include /etc/nginx/proxy.conf;
    }

and then in the proxy.conf



    proxy_redirect off;
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

How to add header data in XMLHttpRequest when using formdata?

Check to see if the key-value pair is actually showing up in the request:

In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers

Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like: F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.

But as other answers have said:

xhttp.setRequestHeader(key, value);

should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

How to return a file (FileContentResult) in ASP.NET WebAPI

If you want to return IHttpActionResult you can do it like this:

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.pdf"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    var response = ResponseMessage(result);

    return response;
}

Best way to remove duplicate entries from a data table

A simple way would be:

 var newDt= dt.AsEnumerable()
                 .GroupBy(x => x.Field<int>("ColumnName"))
                 .Select(y => y.First())
                 .CopyToDataTable();

Is there an opposite of include? for Ruby Arrays?

Try something like this:

@players.include?(p.name) ? false : true

File URL "Not allowed to load local resource" in the Internet Browser

I didn't realise from your original question that you were opening a file on the local machine, I thought you were sending a file from the web server to the client.

Based on your screenshot, try formatting your link like so:

<a href="file:///C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">Klik hier</a>

(without knowing the contents of each of your recordset variables I can't give you the exact ASP code)

How can I switch word wrap on and off in Visual Studio Code?

Go to menu FilePreferencesUser Settings.

It will open up Default Settings and settings.json automatically. Just add the following in the settings.json file and save it. This will overwrite the default settings.

// Place your settings in this file to overwrite the default settings
{ "editor.wrappingColumn": 0 }

Screenshot of settings being edited.

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

Segmentation fault on large array sizes

You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.

If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

int* array = new int[1000000];

But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to 1000000 elements.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

This thread is a bit older but here something I just came across:

Try this code:

$date = new DateTime();
$arr = ['date' => $date];

echo $date->format('Ymd') . '<br>';
mytest($arr);
echo $date->format('Ymd') . '<br>';

function mytest($params = []) {
    if (isset($params['date'])) {
        $params['date']->add(new DateInterval('P1D'));
    }
}

http://codepad.viper-7.com/gwPYMw

Note there is no amp for the $params parameter and still it changes the value of $arr['date']. This doesn't really match with all the other explanations here and what I thought until now.

If I clone the $params['date'] object, the 2nd outputted date stays the same. If I just set it to a string it doesn't effect the output either.

No ConcurrentList<T> in .Net 4.0?

I gave it a try a while back (also: on GitHub). My implementation had some problems, which I won't get into here. Let me tell you, more importantly, what I learned.

Firstly, there's no way you're going to get a full implementation of IList<T> that is lockless and thread-safe. In particular, random insertions and removals are not going to work, unless you also forget about O(1) random access (i.e., unless you "cheat" and just use some sort of linked list and let the indexing suck).

What I thought might be worthwhile was a thread-safe, limited subset of IList<T>: in particular, one that would allow an Add and provide random read-only access by index (but no Insert, RemoveAt, etc., and also no random write access).

This was the goal of my ConcurrentList<T> implementation. But when I tested its performance in multithreaded scenarios, I found that simply synchronizing adds to a List<T> was faster. Basically, adding to a List<T> is lightning fast already; the complexity of the computational steps involved is miniscule (increment an index and assign to an element in an array; that's really it). You would need a ton of concurrent writes to see any sort of lock contention on this; and even then, the average performance of each write would still beat out the more expensive albeit lockless implementation in ConcurrentList<T>.

In the relatively rare event that the list's internal array needs to resize itself, you do pay a small cost. So ultimately I concluded that this was the one niche scenario where an add-only ConcurrentList<T> collection type would make sense: when you want guaranteed low overhead of adding an element on every single call (so, as opposed to an amortized performance goal).

It's simply not nearly as useful a class as you would think.

Making the Android emulator run faster

On this year google I/O (2011), Google demonstrated a faster emulator. The problem is not so much on the byte code between ARM and x86 but the software rendering performed by QEMU. They bypass the rendering of QEMU and send the rendering directly to an X server I believe. They showed a car game with really good performace and fps.

I wonder when that will be available for developers...

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

Short Answer: No. Until recently(about 1 month ago), you could do that but with the latest updates, it is not possible. (see Update to Android SDK Tools 23.0.5 and avd doesn't start).

I was doing something similar: Doing development in a virtual machine and hence couldn't use the Hardware acceleration features as they are available only in the host machine. I was using Intel x86 images with Use Host GPU option; as they were much faster than the ARM version even without hardware acceleration. But then, after this update, my emulator AVDs which were working earlier are no longer starting with the same exact error message. Also, both genymotion and Xamarin Android emulators can't be used as they also need hardware acceleration(they are actually VMs which use Hardware acceleration for speed, and hence can't be run inside another VM).

I have found this solution but haven't tried it yet. The basic idea is that to still develop inside a VM; but for testing connect to an Emulator running on the host machine(and this Emulator VM can now use the hardware acceleration feature).

How to implement swipe gestures for mobile devices?

There is also an AngularJS module called angular-gestures which is based on hammer.js: https://github.com/wzr1337/angular-gestures

ERROR: Cannot open source file " "

This was the top result when googling "cannot open source file" so I figured I would share what my issue was since I had already included the correct path.

I'm not sure about other IDEs or compilers, but least for Visual Studio, make sure there isn't a space in your list of include directories. I had put a space between the ; of the last entry and the beginning of my new entry which then caused Visual Studio to disregard my inclusion.

Changing CSS style from ASP.NET code

I find that code gets messy fast when C# code is used to modify CSS values. Perhaps a better approach is for your code to dynamically set the class attribute on the div tag and then store any specific CSS settings in the style sheet.

That might not work for your situation, but its a decent default position if you need to change the style on the fly in server side code.

RSA encryption and decryption in Python

Here is my implementation for python 3 and pycrypto

from Crypto.PublicKey import RSA
key = RSA.generate(4096)
f = open('/home/john/Desktop/my_rsa_public.pem', 'wb')
f.write(key.publickey().exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_private.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()

f = open('/home/john/Desktop/my_rsa_public.pem', 'rb')
f1 = open('/home/john/Desktop/my_rsa_private.pem', 'rb')
key = RSA.importKey(f.read())
key1 = RSA.importKey(f1.read())

x = key.encrypt(b"dddddd",32)

print(x)
z = key1.decrypt(x)
print(z)

Call two functions from same onclick

Try this

<input id ="btn" type="button" value="click" onclick="pay();cls()"/>

How can I enable MySQL's slow query log without restarting MySQL?

Find log enabled or not?

SHOW VARIABLES LIKE '%log%';

Set the logs:-

SET GLOBAL general_log = 'ON'; 

SET GLOBAL slow_query_log = 'ON'; 

What is the difference between a var and val definition in Scala?

Val - values are typed storage constants. Once created its value cant be re-assigned. a new value can be defined with keyword val.

eg. val x: Int = 5

Here type is optional as scala can infer it from the assigned value.

Var - variables are typed storage units which can be assigned values again as long as memory space is reserved.

eg. var x: Int = 5

Data stored in both the storage units are automatically de-allocated by JVM once these are no longer needed.

In scala values are preferred over variables due to stability these brings to the code particularly in concurrent and multithreaded code.

Manage toolbar's navigation and back button from fragment in android

Add a toolbar to your xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment title"/>

</android.support.v7.widget.Toolbar>

Then inside your onCreateView method in the Fragment:

Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         getActivity().onBackPressed();
    }
});

Batch command date and time in file name

@For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do @(

Set DayW=%%A

Set Day=%%B

Set Month=%%C


Set Year=%%D


Set All=%%D%%B%%C
)
"C:\Windows\CWBZIP.EXE" "c:\transfer\ziptest%All%.zip" "C:\transfer\MB5L.txt"

This takes MB5L.txt and compresses it to ziptest20120204.zip if run on 4 Feb 2012

std::vector versus std::array in C++

std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin(), end(), iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).

Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.

std::array is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.

It's more limited than std::vector, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of std::vector and of the other containers, so you can use it easily with STL algorithms & co. Anyhow, for the very limitation of fixed size it's much less flexible than std::vector.

For an introduction to std::array, have a look at this article; for a quick introduction to std::vector and to the the operations that are possible on it, you may want to look at its documentation.


  1. Actually, I think that in the standard they are described in terms of maximum complexity of the different operations (e.g. random access in constant time, iteration over all the elements in linear time, add and removal of elements at the end in constant amortized time, etc), but AFAIK there's no other method of fulfilling such requirements other than using a dynamic array. As stated by @Lucretiel, the standard actually requires that the elements are stored contiguously, so it is a dynamic array, stored where the associated allocator puts it.

how to implement a long click listener on a listview

In xml add

<ListView android:longClickable="true">

In java file

lv.setLongClickable(true) 

try this setOnItemLongClickListener()

lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long l) {
                //final String category = "Position at : "+pos;
                final String category = ((TextView) view.findViewById(R.id.textView)).getText().toString();
                Toast.makeText(getActivity(),""+category,Toast.LENGTH_LONG).show();
                args = new Bundle();
                args.putString("category", category);
                return false;
            }
        });

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

The answer of your question is that you must set the same value in Primary and secondary key. Thanks

How to convert FileInputStream to InputStream?

InputStream is;

try {
    is = new FileInputStream("c://filename");

    is.close(); 
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

return is;

get all characters to right of last dash

test.Substring(test.LastIndexOf("-"))

How to access the elements of a 2D array?

If you have

a=[[1,1],[2,1],[3,1]]
b=[[1,2],[2,2],[3,2]]

Then

a[1][1]

Will work fine. It points to the second column, second row just like you wanted.

I'm not sure what you did wrong.

To multiply the cells in the third column you can just do

c = [a[2][i] * b[2][i] for i in range(len(a[2]))] 

Which will work for any number of rows.

Edit: The first number is the column, the second number is the row, with your current layout. They are both numbered from zero. If you want to switch the order you can do

a = zip(*a)

or you can create it that way:

a=[[1, 2, 3], [1, 1, 1]]

Utilizing multi core for tar+gzip/bzip compression/decompression

Common approach

There is option for tar program:

-I, --use-compress-program PROG
      filter through PROG (must accept -d)

You can use multithread version of archiver or compressor utility.

Most popular multithread archivers are pigz (instead of gzip) and pbzip2 (instead of bzip2). For instance:

$ tar -I pbzip2 -cf OUTPUT_FILE.tar.bz2 paths_to_archive
$ tar --use-compress-program=pigz -cf OUTPUT_FILE.tar.gz paths_to_archive

Archiver must accept -d. If your replacement utility hasn't this parameter and/or you need specify additional parameters, then use pipes (add parameters if necessary):

$ tar cf - paths_to_archive | pbzip2 > OUTPUT_FILE.tar.gz
$ tar cf - paths_to_archive | pigz > OUTPUT_FILE.tar.gz

Input and output of singlethread and multithread are compatible. You can compress using multithread version and decompress using singlethread version and vice versa.

p7zip

For p7zip for compression you need a small shell script like the following:

#!/bin/sh
case $1 in
  -d) 7za -txz -si -so e;;
   *) 7za -txz -si -so a .;;
esac 2>/dev/null

Save it as 7zhelper.sh. Here the example of usage:

$ tar -I 7zhelper.sh -cf OUTPUT_FILE.tar.7z paths_to_archive
$ tar -I 7zhelper.sh -xf OUTPUT_FILE.tar.7z

xz

Regarding multithreaded XZ support. If you are running version 5.2.0 or above of XZ Utils, you can utilize multiple cores for compression by setting -T or --threads to an appropriate value via the environmental variable XZ_DEFAULTS (e.g. XZ_DEFAULTS="-T 0").

This is a fragment of man for 5.1.0alpha version:

Multithreaded compression and decompression are not implemented yet, so this option has no effect for now.

However this will not work for decompression of files that haven't also been compressed with threading enabled. From man for version 5.2.2:

Threaded decompression hasn't been implemented yet. It will only work on files that contain multiple blocks with size information in block headers. All files compressed in multi-threaded mode meet this condition, but files compressed in single-threaded mode don't even if --block-size=size is used.

Recompiling with replacement

If you build tar from sources, then you can recompile with parameters

--with-gzip=pigz
--with-bzip2=lbzip2
--with-lzip=plzip

After recompiling tar with these options you can check the output of tar's help:

$ tar --help | grep "lbzip2\|plzip\|pigz"
  -j, --bzip2                filter the archive through lbzip2
      --lzip                 filter the archive through plzip
  -z, --gzip, --gunzip, --ungzip   filter the archive through pigz

How to clear all <div>s’ contents inside a parent <div>?

I know this is a jQuery related question, but I believe someone might get here expecting a pure Javascript solution. So, if you were trying to do this using js, you could use the innerHTML property and set it to an empty string.

document.getElementById('masterdiv').innerHTML = '';

How to skip "are you sure Y/N" when deleting files in batch files

Add /Q for quiet mode and it should remove the prompt.

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

You can convert your string to a DateTime value like this:

DateTime date = DateTime.Parse(something);

You can convert a DateTime value to a formatted string like this:

date.ToString("yyyyMMdd");

Where to put default parameter value in C++?

Adding one more point. Function declarations with default argument should be ordered from right to left and from top to bottom.

For example in the below function declaration if you change the declaration order then the compiler gives you a missing default parameter error. Reason the compiler allows you to separate the function declaration with default argument within the same scope but it should be in order from RIGHT to LEFT (default arguments) and from TOP to BOTTOM(order of function declaration default argument).

//declaration
void function(char const *msg, bool three, bool two, bool one = false);
void function(char const *msg, bool three = true, bool two, bool one); // Error 
void function(char const *msg, bool three, bool two = true, bool one); // OK
//void function(char const *msg, bool three = true, bool two, bool one); // OK

int main() {
    function("Using only one Default Argument", false, true);
    function("Using Two Default Arguments", false);
    function("Using Three Default Arguments");
    return 0;
}

//definition
void function(char const *msg, bool three, bool two, bool one ) {
    std::cout<<msg<<" "<<three<<" "<<two<<" "<<one<<std::endl;
}

How to .gitignore all files/folder in a folder, but not the folder itself?

Put this .gitignore into the folder, then git add .gitignore.

*
*/
!.gitignore

The * line tells git to ignore all files in the folder, but !.gitignore tells git to still include the .gitignore file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore it needs.

Edit: May be obvious but also add */ to the .gitignore to also ignore subfolders.

format a number with commas and decimals in C# (asp.net MVC3)

I had the same problem. I wanted to format numbers like the "General" format in spreadsheets, meaning show decimals if they're significant, but chop them off if not. In other words:

1234.56 => 1,234.56

1234 => 1,234

It needs to support a maximum number of places after the decimal, but don't put trailing zeros or dots if not required, and of course, it needs to be culture friendly. I never really figured out a clean way to do it using String.Format alone, but a combination of String.Format and Regex.Replace with some culture help from NumberFormatInfo.CurrentInfo did the job (LinqPad C# Program).

string FormatNumber<T>(T number, int maxDecimals = 4) {
    return Regex.Replace(String.Format("{0:n" + maxDecimals + "}", number),
                         @"[" + System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "]?0+$", "");
}   

void Main(){
    foreach (var test in new[] { 123, 1234, 1234.56, 123456.789, 1234.56789123 } )
        Console.WriteLine(test + " = " + FormatNumber(test));
}

Produces:

123 = 123
1234 = 1,234
1234.56 = 1,234.56
123456.789 = 123,456.789
1234.56789123 = 1,234.5679

Change default global installation directory for node.js modules in Windows?

In Windows, if you want to move the npm or nodejs folder in disk C to another location, but it still makes sure node and npm works well, you can create symlink like this: Open Command Prompt:

mklink /D "your_location_want_to_create_symlink" "location_of_node_npm_file"

Example:

mklink /D "C:\Users\MyUser\AppData\Roaming\npm" "D:\Nodejs Data\npm"

Now you've created a symlink for npm folder, this symlink will refer to D:\Nodejs Data\npmEverything will work well.

Calling a Sub and returning a value

Private Sub Main()
    Dim value = getValue()
    'do something with value
End Sub

Private Function getValue() As Integer
    Return 3
End Function

Printing Even and Odd using two Threads in Java

package com.example;

public class MyClass  {
    static int mycount=0;
    static Thread t;
    static Thread t2;
    public static void main(String[] arg)
    {
        t2=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " even \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>25)
                    System.exit(0);
                run();
            }
        });
        t=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " odd \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>26)
                    System.exit(0);
                run();
            }
        });
        t.start();
        t2.start();
    }
}

How to return temporary table from stored procedure

YES YOU CAN.

In your stored procedure, you fill the table @tbRetour.

At the very end of your stored procedure, you write:

SELECT * FROM @tbRetour 

To execute the stored procedure, you write:

USE [...]
GO

DECLARE @return_value int

EXEC @return_value = [dbo].[getEnregistrementWithDetails]
@id_enregistrement_entete = '(guid)'

GO

Windows batch: formatted date into variable

If you have Python installed, you can do

python -c "import datetime;print(datetime.date.today().strftime('%Y-%m-%d'))"

You can easily adapt the format string to your needs.

How can I convert a hex string to a byte array?

Here's a nice fun LINQ example.

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

@AspectJ pointcut for all methods of a class with specific annotation

You could use Spring's PerformanceMonitoringInterceptor and programmatically register the advice using a beanpostprocessor.

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Monitorable
{

}


public class PerformanceMonitorBeanPostProcessor extends ProxyConfig implements BeanPostProcessor, BeanClassLoaderAware, Ordered,
    InitializingBean
{

  private Class<? extends Annotation> annotationType = Monitorable.class;

  private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

  private Advisor advisor;

  public void setBeanClassLoader(ClassLoader classLoader)
  {
    this.beanClassLoader = classLoader;
  }

  public int getOrder()
  {
    return LOWEST_PRECEDENCE;
  }

  public void afterPropertiesSet()
  {
    Pointcut pointcut = new AnnotationMatchingPointcut(this.annotationType, true);
    Advice advice = getInterceptor();
    this.advisor = new DefaultPointcutAdvisor(pointcut, advice);
  }

  private Advice getInterceptor()
  {
    return new PerformanceMonitoringInterceptor();
  }

  public Object postProcessBeforeInitialization(Object bean, String beanName)
  {
    return bean;
  }

  public Object postProcessAfterInitialization(Object bean, String beanName)
  {
    if(bean instanceof AopInfrastructureBean)
    {
      return bean;
    }
    Class<?> targetClass = AopUtils.getTargetClass(bean);
    if(AopUtils.canApply(this.advisor, targetClass))
    {
      if(bean instanceof Advised)
      {
        ((Advised)bean).addAdvisor(this.advisor);
        return bean;
      }
      else
      {
        ProxyFactory proxyFactory = new ProxyFactory(bean);
        proxyFactory.copyFrom(this);
        proxyFactory.addAdvisor(this.advisor);
        return proxyFactory.getProxy(this.beanClassLoader);
      }
    }
    else
    {
      return bean;
    }
  }
}

How do I get the Git commit count?

git config --global alias.count 'rev-list --all --count'

If you add this to your config, you can just reference the command;

git count

How to decode encrypted wordpress admin password?

You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.

There's a good howto here:

https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/

Basically:

  1. generate a new hash from a known password using e.g. http://scriptserver.mainframe8.com/wordpress_password_hasher.php, as described in the above link, or any other product that uses the phpass library,
  2. use your DB interface (e.g. phpMyAdmin) to update the user_pass field with the new hash string.

If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).

Adding an onclick event to a table row

Here is how I do this. I create a table with a thead and tbody tags. And then add a click event to the tbody element by id.

<script>
    document.getElementById("mytbody").click = clickfunc;
    function clickfunc(e) {
        // to find what td element has the data you are looking for
        var tdele = e.target.parentNode.children[x].innerHTML;
        // to find the row
        var trele = e.target.parentNode;
    }
</script>
<table>
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
        </tr>
    </thead>
    <tbody id="mytbody">
        <tr><td>Data Row</td><td>1</td></tr>
        <tr><td>Data Row</td><td>2</td></tr>
        <tr><td>Data Row</td><td>3</td></tr>
    </tbody>
</table>

how to generate web service out of wsdl

This may be very late in answering. But might be helpful to needy: How to convert WSDL to SVC :

  1. Assuming you are having .wsdl file at location "E:\" for ease in access further.
  2. Prepare the command for each .wsdl file as: E:\YourServiceFileName.wsdl
  3. Permissions: Assuming you are having the Administrative rights to perform permissions. Open directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin
  4. Right click to amd64 => Security => Edit => Add User => Everyone Or Current User => Allow all permissions => OK.
  5. Prepare the Commands for each file in text editor as: wsdl.exe E:\YourServiceFileName.wsdl /l:CS /server.
  6. Now open Visual studio command prompt from : C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts\VS2013 x64 Native Tools Command Prompt.
  7. Execute above command.
  8. Go to directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64, Where respective .CS file should be generated.

    9.Move generated CS file to appropriate location.

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

How to add values in a variable in Unix shell scripting?

In ksh ,bash ,sh:

$ count7=0                     
$ count1=5
$ 
$ (( count7 += count1 ))
$ echo $count7
$ 5

Creating a 3D sphere in Opengl using Visual C++

Here's the code:

glPushMatrix();
glTranslatef(18,2,0);
glRotatef(angle, 0, 0, 0.7);
glColor3ub(0,255,255);
glutWireSphere(3,10,10);
glPopMatrix();

Cannot open output file, permission denied

Try restarting your IDE. It worked for me. Although I tried to end the process in the task manager, the process never got killed.

How to get the user input in Java?

You can make a simple program to ask for user's name and print what ever the reply use inputs.

Or ask user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like a behavior of a calculator.

So there you need Scanner class. You have to import java.util.Scanner; and in the code you need to use

Scanner input = new Scanner(System.in);

Input is a variable name.

Scanner input = new Scanner(System.in);

System.out.println("Please enter your name : ");
s = input.next(); // getting a String value

System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer

System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double

See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();

According to a String, int and a double varies same way for the rest. Don't forget the import statement at the top of your code.

Also see the blog post "Scanner class and getting User Inputs".

CodeIgniter: "Unable to load the requested class"

In Windows, capitalization in paths doesn't matter. In Linux it does.

When you autoload, use "Foo" not "foo".

I believe that will do the trick.

I think it works when you take it out of autoloading because codeigniter is smart enough to figure out the capitalization in the path and classes are case independent in php.

HTML Table cellspacing or padding just top / bottom

This might be a little better:

td {
  padding:2px 0;
}

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

I was trying on a release build via adb install -r -d <app-release>.apk

Make sure you're running the debug build, then the menu will work via the shortcut or CLI.

JQuery $.ajax() post - data in a java servlet

For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:

  &A2168=1&A1837=5&A8472=1&A1987=2

On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:

Enumeration keys = request.getParameterNames(); 
HashMap map = new HashMap(); 
String key = null; 
while(keys.hasMoreElements()){ 
      key = keys.nextElement().toString(); 
      map.put(key, request.getParameter(key)); 
}

Is an anchor tag without the href attribute safe?

Short answer: No.

Long answer:

First, without an href attribute, it will not be a link. If it isn't a link then it wont be keyboard (or breath switch, or various other not pointer based input device) accessible (unless you use HTML 5 features of tabindex which are not universally supported). It is very rare that it is appropriate for a control to not have keyboard access.

Second. You should have an alternative for when the JavaScript does not run (because it was slow to load from the server, an Internet connection was dropped (e.g. mobile signal on a moving train), JS is turned off, etc, etc).

Make use of progressive enhancement by unobtrusive JS.

Android EditText Hint

To complete Sunit's answer, you can use a selector, not to the text string but to the textColorHint. You must add this attribute on your editText:

android:textColorHint="@color/text_hint_selector"

And your text_hint_selector should be:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:color="@android:color/transparent" />
    <item android:color="@color/hint_color" />
</selector>

Java Long primitive type maximum limit

Long.MAX_VALUE is 9,223,372,036,854,775,807.

If you were executing your function once per nanosecond, it would still take over 292 years to encounter this situation according to this source.

When that happens, it'll just wrap around to Long.MIN_VALUE, or -9,223,372,036,854,775,808 as others have said.