Programs & Examples On #Argument passing

Argument-passing may refer to two different things: (1) the process of providing a program being started with some initial pieces of information (the arguments) on its command line; (2) the process of providing the initial values (the arguments) for the parameters of a function when it is called.

JavaScript variable number of arguments to function

Although I generally agree that the named arguments approach is useful and flexible (unless you care about the order, in which case arguments is easiest), I do have concerns about the cost of the mbeasley approach (using defaults and extends). This is an extreme amount of cost to take for pulling default values. First, the defaults are defined inside the function, so they are repopulated on every call. Second, you can easily read out the named values and set the defaults at the same time using ||. There is no need to create and merge yet another new object to get this information.

function load(context) {
   var parameter1 = context.parameter1 || defaultValue1,
       parameter2 = context.parameter2 || defaultValue2;

   // do stuff
}

This is roughly the same amount of code (maybe slightly more), but should be a fraction of the runtime cost.

Calculate percentage Javascript

try

var result = (35.8 / 100) * 10;

Thanks

How to convert a command-line argument to int?

The approach with istringstream can be improved in order to check that no other characters have been inserted after the expected argument:

#include <sstream>

int main(int argc, char *argv[])
{
    if (argc >= 2)
    {
        std::istringstream iss( argv[1] );
        int val;

        if ((iss >> val) && iss.eof()) // Check eofbit
        {
            // Conversion successful
        }
    }

    return 0;
}

Postgres integer arrays as parameters?

You can always use a properly formatted string. The trick is the formatting.

command.Parameters.Add("@array_parameter", string.Format("{{{0}}}", string.Join(",", array));

Note that if your array is an array of strings, then you'll need to use array.Select(value => string.Format("\"{0}\", value)) or the equivalent. I use this style for an array of an enumerated type in PostgreSQL, because there's no automatic conversion from the array.

In my case, my enumerated type has some values like 'value1', 'value2', 'value3', and my C# enumeration has matching values. In my case, the final SQL query ends up looking something like (E'{"value1","value2"}'), and this works.

Pass in an array of Deferreds to $.when()

When calling multiple parallel AJAX calls, you have two options for handling the respective responses.

  1. Use Synchronous AJAX call/ one after another/ not recommended
  2. Use Promises' array and $.when which accepts promises and its callback .done gets called when all the promises are return successfully with respective responses.

Example

_x000D_
_x000D_
function ajaxRequest(capitalCity) {_x000D_
   return $.ajax({_x000D_
        url: 'https://restcountries.eu/rest/v1/capital/'+capitalCity,_x000D_
        success: function(response) {_x000D_
        },_x000D_
        error: function(response) {_x000D_
          console.log("Error")_x000D_
        }_x000D_
    });_x000D_
}_x000D_
$(function(){_x000D_
   var capitalCities = ['Delhi', 'Beijing', 'Washington', 'Tokyo', 'London'];_x000D_
   $('#capitals').text(capitalCities);_x000D_
_x000D_
   function getCountryCapitals(){ //do multiple parallel ajax requests_x000D_
      var promises = [];   _x000D_
      for(var i=0,l=capitalCities.length; i<l; i++){_x000D_
            var promise = ajaxRequest(capitalCities[i]);_x000D_
            promises.push(promise);_x000D_
      }_x000D_
  _x000D_
      $.when.apply($, promises)_x000D_
        .done(fillCountryCapitals);_x000D_
   }_x000D_
  _x000D_
   function fillCountryCapitals(){_x000D_
        var countries = [];_x000D_
        var responses = arguments;_x000D_
        for(i in responses){_x000D_
            console.dir(responses[i]);_x000D_
            countries.push(responses[i][0][0].nativeName)_x000D_
        }  _x000D_
        $('#countries').text(countries);_x000D_
   }_x000D_
  _x000D_
   getCountryCapitals()_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
  <h4>Capital Cities : </h4> <span id="capitals"></span>_x000D_
  <h4>Respective Country's Native Names : </h4> <span id="countries"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to HTML encode/escape a string? Is there a built-in?

Comparaison of the different methods:

> CGI::escapeHTML("quote ' double quotes \"")
=> "quote &#39; double quotes &quot;"

> Rack::Utils.escape_html("quote ' double quotes \"")
=> "quote &#x27; double quotes &quot;"

> ERB::Util.html_escape("quote ' double quotes \"")
=> "quote &#39; double quotes &quot;"

I wrote my own to be compatible with Rails ActiveMailer escaping:

def escape_html(str)
  CGI.escapeHTML(str).gsub("&#39;", "'")
end

Proper way to catch exception from JSON.parse

i post something into an iframe then read back the contents of the iframe with json parse...so sometimes it's not a json string

Try this:

if(response) {
    try {
        a = JSON.parse(response);
    } catch(e) {
        alert(e); // error in the above string (in this case, yes)!
    }
}

What can cause a “Resource temporarily unavailable” on sock send() command

"Resource temporarily unavailable" is the error message corresponding to EAGAIN, which means that the operation would have blocked but nonblocking operation was requested. For send(), that could be due to any of:

  • explicitly marking the file descriptor as nonblocking with fcntl(); or
  • passing the MSG_DONTWAIT flag to send(); or
  • setting a send timeout with the SO_SNDTIMEO socket option.

How to return XML in ASP.NET?

I'm surprised that nobody seems to have ever mentioned that you can use XDocument / XElement which are available in .NET 4.0 and make it much easier to output XML.

Getting date format m-d-Y H:i:s.u from milliseconds

if you are using Carbon, you can use the defined spec "RFC3339_EXTENDED". or customize it.

Carbon::RFC3339_EXTENDED = 'Y-m-d\TH:i:s.vP';

How to get JSON from webpage into Python script

Late answer, but for python>=3.6 you can use:

import dload
j = dload.json(url)

Install dload with:

pip3 install dload

WCF error - There was no endpoint listening at

Different case but may help someone,

In my case Window firewall was enabled on Server,

Two thinks can be done,

1) Disable windows firewall (your on risk but it will get thing work)

2) Add port in inbound rule.

Thanks .

How to add line break for UILabel?

In xCode 11, Swift 5 the \n works fine, try the below code:

textlabel.numberOfLines = 0
textlabel.text = "This is line one \n This is line two \n This is line three"

Windows command prompt log to a file

In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file. Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).

How to compare each item in a list with the rest, only once?

Use itertools.combinations(mylist, 2)

mylist = range(5)
for x,y in itertools.combinations(mylist, 2):
    print x,y

0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

various option are available such as:

 Double d= 123.12;
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64); // b = 123.1200000
b = b.setScale(2, BigDecimal.ROUND_HALF_UP);  // b = 123.12

BigDecimal b1 =new BigDecimal(collectionFileData.getAmount(), MathContext.DECIMAL64).setScale(2, BigDecimal.ROUND_HALF_UP)  // b1= 123.12

 d = (double) Math.round(d * 100) / 100;
BigDecimal b2 = new BigDecimal(d.toString());  // b2= 123.12



Getting full URL of action in ASP.NET MVC

This may be just me being really, really picky, but I like to only define constants once. If you use any of the approaches defined above, your action constant will be defines multiple times.

To avoid this, you can do the following:

    public class Url
    {
        public string LocalUrl { get; }

        public Url(string localUrl)
        {
            LocalUrl = localUrl;
        }

        public override string ToString()
        {
            return LocalUrl;
        }
    }

    public abstract class Controller
    {
        public Url RootAction => new Url(GetUrl());

        protected abstract string Root { get; }

        public Url BuildAction(string actionName)
        {
            var localUrl = GetUrl() + "/" + actionName;
            return new Url(localUrl);
        }

        private string GetUrl()
        {
            if (Root == "")
            {
                return "";
            }

            return "/" + Root;
        }

        public override string ToString()
        {
            return GetUrl();
        }
    }

Then create your controllers, say for example the DataController:

    public static readonly DataController Data = new DataController();
    public class DataController : Controller
    {
        public const string DogAction = "dog";
        public const string CatAction = "cat";
        public const string TurtleAction = "turtle";

        protected override string Root => "data";

        public Url Dog => BuildAction(DogAction);
        public Url Cat => BuildAction(CatAction);
        public Url Turtle => BuildAction(TurtleAction);
    }

Then just use it like:

    // GET: Data/Cat
    [ActionName(ControllerRoutes.DataController.CatAction)]
    public ActionResult Etisys()
    {
        return View();
    }

And from your .cshtml (or any code)

<ul>
    <li><a href="@ControllerRoutes.Data.Dog">Dog</a></li>
    <li><a href="@ControllerRoutes.Data.Cat">Cat</a></li>
</ul>

This is definitely a lot more work, but I rest easy knowing compile time validation is on my side.

How to 'insert if not exists' in MySQL?

Something worth noting is that INSERT IGNORE will still increment the primary key whether the statement was a success or not just like a normal INSERT would.

This will cause gaps in your primary keys that might make a programmer mentally unstable. Or if your application is poorly designed and depends on perfect incremental primary keys, it might become a headache.

Look into innodb_autoinc_lock_mode = 0 (server setting, and comes with a slight performance hit), or use a SELECT first to make sure your query will not fail (which also comes with a performance hit and extra code).

How to combine date from one field with time from another field - MS SQL Server

Convert the first date stored in a datetime field to a string, then convert the time stored in a datetime field to string, append the two and convert back to a datetime field all using known conversion formats.

Convert(datetime, Convert(char(10), MYDATETIMEFIELD, 103) + ' ' + Convert(char(8), MYTIMEFIELD, 108), 103) 

How to use onClick with divs in React.js

This works

var Box = React.createClass({
    getInitialState: function() {
        return {
            color: 'white'
        };
    },

    changeColor: function() {
        var newColor = this.state.color == 'white' ? 'black' : 'white';
        this.setState({ color: newColor });
    },

    render: function() {
        return (
            <div>
                <div
                    className='box'
                    style={{background:this.state.color}}
                    onClick={this.changeColor}
                >
                    In here already
                </div>
            </div>
        );
    }
});

ReactDOM.render(<Box />, document.getElementById('div1'));
ReactDOM.render(<Box />, document.getElementById('div2'));
ReactDOM.render(<Box />, document.getElementById('div3'));

and in your css, delete the styles you have and put this

.box {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  float: left;
}

You have to style the actual div you are calling onClick on. Give the div a className and then style it. Also remember to remove this block where you are rendering App into the dom, App is not defined

ReactDOM.render(<App />,document.getElementById('root'));

Programmatically navigate using react router V4

this.props.history.push("/url")

If you have not found this.props.history available in your component , then try this

import {withRouter} from 'react-router-dom'
export default withRouter(MyComponent)  

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

Terminology

First, let's get some terminology out of the way...

upstream <= The remote git repo (likely whose master or release branch is in production)

forked-repo <= The remote [experimental git repo] (https://docs.github.com/en/github/getting-started-with-github/fork-a-repo) also known as "origin".

local repo <= The files and directories that you work with on your local workstaion, which you likely got by running a git clone my-forked-repo.git command

local index <= Also known as your local git "stage", i.e., where you stage your files before pushing them to you remote repo.

Github workflow process

Next, let's talk about the process of getting your changes to the upstream repo:

The process is generally to work on a feature branch and then push said branch, and open a Pull Request, either to your forked-repo's master branch or to the upstream's master branch

Create a feature branch by running git checkout -b FEATURE_BRANCH_NAME

Add/delete/modify files project files.

Add files by running git add .

Commit your files to your index by running git commit -m'My commit message'

Push your staged files by running git push origin FEATURE_BRANCH_NAME

Solution for entirely different commit histories

The master and upstreambranch are entirely different commit histories message can occur when you've forked a git repository and have changed your git history.

For example, if you fork a repo and pull your forked repo to work on it locally...

If then you decide to rewrite the entire application and then decide it's a good idea to deleting all existing files, including the forked-repo's .git directory. You add new files and directories to recreate your app and also recreate your .git directory with git init command.

Now, your application works great with your new files and you want to get it merged into the upstream repo. However, when you push your changes you get that "...entirely different commit histories..." error message.

You'll see that your original git commit will be different in your new local directory and if in your remote fork (as well as your upstream). Check this out by running this command in your current directory: git log --reverse master. Then running the following: pushd $(mktemp -d); git clone https://github.com/my-forking-username/my-forked-repo.git; git log --reverse master; popd

You must fix your local .git repo to match your remote my-forked-repo if you want to push your commits and subsequently perform a pull request (in hopes of merging your new updates to the upstream/master branch).

git clone https://github.com/my-forking-username/my-forked-repo.git
cd my-forked-repo
git checkout -b my-new-files-branch-name
# Delete all files and directories except for the .git directory
git add .
git commit -m'Remove old files'
# Copy your new files to this my-forked-repo directory
git add .
git commit -m'Add new files'
git push origin my-new-files-branch-name

Create a PR on GitHub and request to merge your my-new-files-branch-name branch in your my-forked-repo into master.

Note: The "...entirely different commit histories..." error message can also occur in non-forked repos for the same reasons and can be fixed with the same solution above.

Place input box at the center of div

The catch is that input elements are inline. We have to make it block (display:block) before positioning it to center : margin : 0 auto. Please see the code below :

<html>
<head>
    <style>
        div.wrapper {
            width: 300px;
            height:300px;
            border:1px solid black;
        }

        input[type="text"] {
             display: block;
             margin : 0 auto;
        }

    </style>
</head>
<body>

    <div class='wrapper'>
        <input type='text' name='ok' value='ok'>
    </div>    


</body>
</html>

But if you have a div which is positioned = absolute then we need to do the things little bit differently.Now see this!

  <html>
     <head>
    <style>
        div.wrapper {
            position:  absolute;
            top : 200px;
            left: 300px;
            width: 300px;
            height:300px;
            border:1px solid black;
        }

        input[type="text"] {
             position: relative;
             display: block;
             margin : 0 auto;
        }

    </style>
</head>
<body>

    <div class='wrapper'>
        <input type='text' name='ok' value='ok'>
    </div>  

</body>
</html>

Hoping this can be helpful.Thank you.

Create a HTML table where each TR is a FORM

You may have issues with column width, but you can set those explicitly.

<table>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  </table>

You may want to also consider making it a single form, and then using jQuery to select the form elements from the row you want, serialize them, and submit them as the form.

See: http://api.jquery.com/serialize/

Also, there are a number of very nice grid plugins: http://www.google.com/search?q=jquery+grid&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

Going through a text file line by line in C

In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).

What is the difference between "is None" and "== None"

If you use numpy,

if np.zeros(3)==None: pass

will give you error when numpy does elementwise comparison

How to install Anaconda on RaspBerry Pi 3 Model B

Installing Miniconda on Raspberry Pi and adding Python 3.5 / 3.6

Skip the first section if you have already installed Miniconda successfully.

Installation of Miniconda on Raspberry Pi

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
sudo md5sum Miniconda3-latest-Linux-armv7l.sh
sudo /bin/bash Miniconda3-latest-Linux-armv7l.sh

Accept the license agreement with yes

When asked, change the install location: /home/pi/miniconda3

Do you wish the installer to prepend the Miniconda3 install location to PATH in your /root/.bashrc ? yes

Now add the install path to the PATH variable:

sudo nano /home/pi/.bashrc

Go to the end of the file .bashrc and add the following line:

export PATH="/home/pi/miniconda3/bin:$PATH"

Save the file and exit.

To test if the installation was successful, open a new terminal and enter

conda

If you see a list with commands you are ready to go.

But how can you use Python versions greater than 3.4 ?


Adding Python 3.5 / 3.6 to Miniconda on Raspberry Pi

After the installation of Miniconda I could not yet install Python versions higher than Python 3.4, but i needed Python 3.5. Here is the solution which worked for me on my Raspberry Pi 4:

First i added the Berryconda package manager by jjhelmus (kind of an up-to-date version of the armv7l version of Miniconda):

conda config --add channels rpi

Only now I was able to install Python 3.5 or 3.6 without the need for compiling it myself:

conda install python=3.5
conda install python=3.6

Afterwards I was able to create environments with the added Python version, e.g. with Python 3.5:

conda create --name py35 python=3.5

The new environment "py35" can now be activated:

source activate py35

Using Python 3.7 on Raspberry Pi

Currently Jonathan Helmus, who is the developer of berryconda, is working on adding Python 3.7 support, if you want to see if there is an update or if you want to support him, have a look at this pull request. (update 20200623) berryconda is now inactive, This project is no longer active, no recipe will be updated and no packages will be added to the rpi channel. If you need to run Python 3.7 on your Pi right now, you can do so without Miniconda. Check if you are running the latest version of Raspbian OS called Buster. Buster ships with Python 3.7 preinstalled (source), so simply run your program with the following command:

Python3.7 app-that-needs-python37.py

I hope this solution will work for you too!

Difference between links and depends_on in docker_compose.yml

The post needs an update after the links option is deprecated.

Basically, links is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.

For docker run, --link is also deprecated and should be replaced by a custom network.

docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image

depends_on expresses start order (and implicitly image pulling order), which was a good side effect of links.

linux execute command remotely

I think this article explains well:

Running Commands on a Remote Linux / UNIX Host

Google is your best friend ;-)

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

it's also a good thing to make sure you have the right import

I had an issue like that and I found out that the bean was using

    javax.faces.view.ViewScoped;
                 ^

instead of

    javax.faces.bean.ViewScoped;
                 ^

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

You can use the text method and pass a function that returns the modified text, using the native String.prototype.replace method to perform the replacement:

?$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 
});?????

Here's a working example.

How to uninstall/upgrade Angular CLI?

Angular cli has moved to @angular/cli, so as from the github readme,

sudo npm uninstall -g @angular/cli
npm cache clean

Difference between save and saveAndFlush in Spring data jpa

Depending on the hibernate flush mode that you are using (AUTO is the default) save may or may not write your changes to the DB straight away. When you call saveAndFlush you are enforcing the synchronization of your model state with the DB.

If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save() and saveAndFlush() because the select triggers a flush first. See the documention.

Can I embed a .png image into an html page?

The 64base method works for large images as well, I use that method to embed all the images into my website, and it works every time. I've done with files up to 2Mb size, jpg and png.

How to read/write from/to file using Go?

The Read method takes a byte parameter because that is the buffer it will read into. It's a common Idiom in some circles and makes some sense when you think about it.

This way you can determine how many bytes will be read by the reader and inspect the return to see how many bytes actually were read and handle any errors appropriately.

As others have pointed in their answers bufio is probably what you want for reading from most files.

I'll add one other hint since it's really useful. Reading a line from a file is best accomplished not by the ReadLine method but the ReadBytes or ReadString method instead.

Set System.Drawing.Color values

You could create a color using the static FromArgb method:

Color redColor = Color.FromArgb(255, 0, 0);

You can also specify the alpha using the following overload.

PostgreSQL database service

The solution was simply to comment the lines "work_mem=256MB" and "maintenance_work_mem=$3GB" in the file postgresql.conf and try to start the postgresql service. (start -> run -> services.msc) and look for the postgresql-[version] service then right click and start.

How do I use valgrind to find memory leaks?

How to Run Valgrind

Not to insult the OP, but for those who come to this question and are still new to Linux—you might have to install Valgrind on your system.

sudo apt install valgrind  # Ubuntu, Debian, etc.
sudo yum install valgrind  # RHEL, CentOS, Fedora, etc.

Valgrind is readily usable for C/C++ code, but can even be used for other languages when configured properly (see this for Python).

To run Valgrind, pass the executable as an argument (along with any parameters to the program).

valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1

The flags are, in short:

  • --leak-check=full: "each individual leak will be shown in detail"
  • --show-leak-kinds=all: Show all of "definite, indirect, possible, reachable" leak kinds in the "full" report.
  • --track-origins=yes: Favor useful output over speed. This tracks the origins of uninitialized values, which could be very useful for memory errors. Consider turning off if Valgrind is unacceptably slow.
  • --verbose: Can tell you about unusual behavior of your program. Repeat for more verbosity.
  • --log-file: Write to a file. Useful when output exceeds terminal space.

Finally, you would like to see a Valgrind report that looks like this:

HEAP SUMMARY:
    in use at exit: 0 bytes in 0 blocks
  total heap usage: 636 allocs, 636 frees, 25,393 bytes allocated

All heap blocks were freed -- no leaks are possible

ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

I have a leak, but WHERE?

So, you have a memory leak, and Valgrind isn't saying anything meaningful. Perhaps, something like this:

5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (in /home/Peri461/Documents/executable)

Let's take a look at the C code I wrote too:

#include <stdlib.h>

int main() {
    char* string = malloc(5 * sizeof(char)); //LEAK: not freed!
    return 0;
}

Well, there were 5 bytes lost. How did it happen? The error report just says main and malloc. In a larger program, that would be seriously troublesome to hunt down. This is because of how the executable was compiled. We can actually get line-by-line details on what went wrong. Recompile your program with a debug flag (I'm using gcc here):

gcc -o executable -std=c11 -Wall main.c         # suppose it was this at first
gcc -o executable -std=c11 -Wall -ggdb3 main.c  # add -ggdb3 to it

Now with this debug build, Valgrind points to the exact line of code allocating the memory that got leaked! (The wording is important: it might not be exactly where your leak is, but what got leaked. The trace helps you find where.)

5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (main.c:4)

Techniques for Debugging Memory Leaks & Errors

  • Make use of www.cplusplus.com! It has great documentation on C/C++ functions.
  • General advice for memory leaks:
    • Make sure your dynamically allocated memory does in fact get freed.
    • Don't allocate memory and forget to assign the pointer.
    • Don't overwrite a pointer with a new one unless the old memory is freed.
  • General advice for memory errors:
    • Access and write to addresses and indices you're sure belong to you. Memory errors are different from leaks; they're often just IndexOutOfBoundsException type problems.
    • Don't access or write to memory after freeing it.
  • Sometimes your leaks/errors can be linked to one another, much like an IDE discovering that you haven't typed a closing bracket yet. Resolving one issue can resolve others, so look for one that looks a good culprit and apply some of these ideas:

    • List out the functions in your code that depend on/are dependent on the "offending" code that has the memory error. Follow the program's execution (maybe even in gdb perhaps), and look for precondition/postcondition errors. The idea is to trace your program's execution while focusing on the lifetime of allocated memory.
    • Try commenting out the "offending" block of code (within reason, so your code still compiles). If the Valgrind error goes away, you've found where it is.
  • If all else fails, try looking it up. Valgrind has documentation too!

A Look at Common Leaks and Errors

Watch your pointers

60 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C2BB78: realloc (vg_replace_malloc.c:785)
   by 0x4005E4: resizeArray (main.c:12)
   by 0x40062E: main (main.c:19)

And the code:

#include <stdlib.h>
#include <stdint.h>

struct _List {
    int32_t* data;
    int32_t length;
};
typedef struct _List List;

List* resizeArray(List* array) {
    int32_t* dPtr = array->data;
    dPtr = realloc(dPtr, 15 * sizeof(int32_t)); //doesn't update array->data
    return array;
}

int main() {
    List* array = calloc(1, sizeof(List));
    array->data = calloc(10, sizeof(int32_t));
    array = resizeArray(array);

    free(array->data);
    free(array);
    return 0;
}

As a teaching assistant, I've seen this mistake often. The student makes use of a local variable and forgets to update the original pointer. The error here is noticing that realloc can actually move the allocated memory somewhere else and change the pointer's location. We then leave resizeArray without telling array->data where the array was moved to.

Invalid write

1 errors in context 1 of 1:
Invalid write of size 1
   at 0x4005CA: main (main.c:10)
 Address 0x51f905a is 0 bytes after a block of size 26 alloc'd
   at 0x4C2B975: calloc (vg_replace_malloc.c:711)
   by 0x400593: main (main.c:5)

And the code:

#include <stdlib.h>
#include <stdint.h>

int main() {
    char* alphabet = calloc(26, sizeof(char));

    for(uint8_t i = 0; i < 26; i++) {
        *(alphabet + i) = 'A' + i;
    }
    *(alphabet + 26) = '\0'; //null-terminate the string?

    free(alphabet);
    return 0;
}

Notice that Valgrind points us to the commented line of code above. The array of size 26 is indexed [0,25] which is why *(alphabet + 26) is an invalid write—it's out of bounds. An invalid write is a common result of off-by-one errors. Look at the left side of your assignment operation.

Invalid read

1 errors in context 1 of 1:
Invalid read of size 1
   at 0x400602: main (main.c:9)
 Address 0x51f90ba is 0 bytes after a block of size 26 alloc'd
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x4005E1: main (main.c:6)

And the code:

#include <stdlib.h>
#include <stdint.h>

int main() {
    char* destination = calloc(27, sizeof(char));
    char* source = malloc(26 * sizeof(char));

    for(uint8_t i = 0; i < 27; i++) {
        *(destination + i) = *(source + i); //Look at the last iteration.
    }

    free(destination);
    free(source);
    return 0;
}

Valgrind points us to the commented line above. Look at the last iteration here, which is
*(destination + 26) = *(source + 26);. However, *(source + 26) is out of bounds again, similarly to the invalid write. Invalid reads are also a common result of off-by-one errors. Look at the right side of your assignment operation.


The Open Source (U/Dys)topia

How do I know when the leak is mine? How do I find my leak when I'm using someone else's code? I found a leak that isn't mine; should I do something? All are legitimate questions. First, 2 real-world examples that show 2 classes of common encounters.

Jansson: a JSON library

#include <jansson.h>
#include <stdio.h>

int main() {
    char* string = "{ \"key\": \"value\" }";

    json_error_t error;
    json_t* root = json_loads(string, 0, &error); //obtaining a pointer
    json_t* value = json_object_get(root, "key"); //obtaining a pointer
    printf("\"%s\" is the value field.\n", json_string_value(value)); //use value

    json_decref(value); //Do I free this pointer?
    json_decref(root);  //What about this one? Does the order matter?
    return 0;
}

This is a simple program: it reads a JSON string and parses it. In the making, we use library calls to do the parsing for us. Jansson makes the necessary allocations dynamically since JSON can contain nested structures of itself. However, this doesn't mean we decref or "free" the memory given to us from every function. In fact, this code I wrote above throws both an "Invalid read" and an "Invalid write". Those errors go away when you take out the decref line for value.

Why? The variable value is considered a "borrowed reference" in the Jansson API. Jansson keeps track of its memory for you, and you simply have to decref JSON structures independent of each other. The lesson here: read the documentation. Really. It's sometimes hard to understand, but they're telling you why these things happen. Instead, we have existing questions about this memory error.

SDL: a graphics and gaming library

#include "SDL2/SDL.h"

int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return 1;
    }

    SDL_Quit();
    return 0;
}

What's wrong with this code? It consistently leaks ~212 KiB of memory for me. Take a moment to think about it. We turn SDL on and then off. Answer? There is nothing wrong.

That might sound bizarre at first. Truth be told, graphics are messy and sometimes you have to accept some leaks as being part of the standard library. The lesson here: you need not quell every memory leak. Sometimes you just need to suppress the leaks because they're known issues you can't do anything about. (This is not my permission to ignore your own leaks!)

Answers unto the void

How do I know when the leak is mine?
It is. (99% sure, anyway)

How do I find my leak when I'm using someone else's code?
Chances are someone else already found it. Try Google! If that fails, use the skills I gave you above. If that fails and you mostly see API calls and little of your own stack trace, see the next question.

I found a leak that isn't mine; should I do something?
Yes! Most APIs have ways to report bugs and issues. Use them! Help give back to the tools you're using in your project!


Further Reading

Thanks for staying with me this long. I hope you've learned something, as I tried to tend to the broad spectrum of people arriving at this answer. Some things I hope you've asked along the way: How does C's memory allocator work? What actually is a memory leak and a memory error? How are they different from segfaults? How does Valgrind work? If you had any of these, please do feed your curiousity:

jQuery get values of checked checkboxes into array

     var ids = [];

$('input[id="find-table"]:checked').each(function() {
   ids.push(this.value); 
});

This one worked for me!

Dealing with HTTP content in HTTPS pages

I don't know if this would fit what you are doing, but as a quick fix I would "wrap" the http content into an https script. For instance, on your page that is served through https i would introduce an iframe that would replace your rss feed and in the src attr of the iframe put a url of a script on your server that captures the feed and outputs the html. the script is reading the feed through http and outputs it through https (thus "wrapping")

Just a thought

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

Android Design Support Library expandable Floating Action Button(FAB) menu

In case anyone is still looking for this functionality: I made an Android library that has this ability and much more, called ExpandableFab (https://github.com/nambicompany/expandable-fab).

The Material Design spec refers to this functionality as 'Speed Dial' and ExpandableFab implements it along with many additional features.

Nearly everything is customizable (colors, text, size, placement, margins, animations and more) and optional (don't need an Overlay, or FabOptions, or Labels, or icons, etc). Every property can be accessed or set through XML layouts or programmatically - whatever you prefer.

Written 100% in Kotlin but comes with full JavaDoc and KDoc (published API is well documented). Also comes with an example app so you can see different use cases with 0 coding.

Github: https://github.com/nambicompany/expandable-fab

Library website (w/ links to full documentation): https://nambicompany.github.io/expandable-fab/

Regular ExpandableFab implementing Material Design 'Speed Dial' functionality A highly customized ExpandableFab implementing Material Design 'Speed Dial' functionality

In Android, how do I set margins in dp programmatically?

Created a Kotlin Extension function for those of you who might find it handy.

Make sure to pass in pixels not dp. Happy coding :)

fun View.addLayoutMargins(left: Int? = null, top: Int? = null,
                      right: Int? = null, bottom: Int? = null) {
    this.layoutParams = ViewGroup.MarginLayoutParams(this.layoutParams)
            .apply {
                left?.let { leftMargin = it }
                top?.let { topMargin = it }
                right?.let { rightMargin = it }
                bottom?.let { bottomMargin = it }
            }
}

Creating and appending text to txt file in VB.NET

Try it this way:

Dim filePath As String = 
  String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))

if File.Exists(filePath) then

Using writer As New StreamWriter(filePath, True)
writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)

Else
writer.WriteLine("Start Error Log for today")
End Using

end if

How to access Winform textbox control from another class?

You can change the access modifier for the generated field in Form1.Designer.cs from private to public. Change this

private System.Windows.Forms.TextBox textBox1;

by this

public System.Windows.Forms.TextBox textBox1;

You can now handle it using a reference of the form Form1.textBox1.

Visual Studio will not overwrite this if you make any changes to the control properties, unless you delete it and recreate it.

You can also chane it from the UI if you are not confortable with editing code directly. Look for the Modifiers property:

Modifiers

Couldn't connect to server 127.0.0.1:27017

Adding the bin to PATH in Environment Variables helped.

GOTO Installation Path and copy the ../bin to the PATH variables in environment variables in Windows

How to render a DateTime object in a Twig template

It depends on the format you want the date to be shown as.

Static date format

If you want to display a static format, which is the same for all locales (for instance ISO 8601 for an Atom feed), you should use Twig's date filter:

{{ game.gameDate|date('Y-m-d\\TH:i:sP') }}

Which will allways return a datetime in the following format:

2014-05-02T08:55:41Z

The format strings accepted by the date filter are the same as you would use for PHP's date() function. (the only difference is that, as far as I know, you can't use the predefined constants which can be used in the PHP date() function)

Localized dates (and times)

However, since you want to render it in the browser, you'll likely want to show it in a human-readable format, localised for the user's language and location. Instead of doing the localization yourself, you can use the Intl Extension for this (which makes use of PHP's IntlDateFormatter). It provides a filter localizeddate which will output the date and time using a localized format.

localizeddate( date_format, time_format [, locale ] )

Arguments for localizeddate:

  • date_format: One of the format strings (see below)
  • time_format: One of the format strings (see below)
  • locale: (optional) Use this to override the configured locale. Leave this argument out to use the default locale, which can be configured in Symfony's configuration.

(there are more, see the docs for the complete list of possible arguments)

For date_format and time_format you can use one of the following strings:

  • 'none' if you don't want to include this element
  • 'short' for the most abbreviated style (12/13/52 or 3:30pm in an English locale)
  • 'medium' for the medium style (Jan 12, 1952 in an English locale)
  • 'long' for the long style (January 12, 1952 or 3:30:32pm in an English locale)
  • 'full' for the completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST in an English locale)

Example

So, for instance, if you want to display the date in a format equivalent to February 6, 2014 at 10:52 AM, use the following line in your Twig template:

{{ game.gameDate|localizeddate('long', 'short') }}

However, if you use a different locale, the result will be localized for that locale:

  • 6 februari 2014 10:52 for the nl locale;
  • 6 février 2014 10:52 for the fr locale;
  • 6. Februar 2014 10:52 for the de locale; etc.

As you can see, localizeddate does not only translate the month names but also uses the local notations. The English notation puts the date after the month, where Dutch, French and German notations put it before the month. English and German month names start with an uppercase letter, whereas Dutch and French month names are lowercase. And German dates have a dot appended.

Installation / setting the locale

Installation instructions for the Intl extension can be found in this seperate answer.

web-api POST body object always null

I had this problem in my .NET Framework Web API, because my model existed in a .NET Standard project that referenced a different version of data annotations.

Adding the ReadAsAsync line below highlighted the cause for me:

public async Task<HttpResponseMessage> Register(RegistrationDetails registrationDetails)
{
    var regDetails = await Request.Content.ReadAsAsync<RegistrationDetails>();

What is float in Java?

In JAVA, values like:

  1. 8.5
  2. 3.9
  3. (and so on..)

Is assumed as double and not float.

You can also perform a cast in order to solve the problem:

float b = (float) 3.5;

Another solution:

float b = 3.5f;

Add property to an array of objects

You can use the forEach method to execute a provided function once for each element in the array. In this provided function you can add the Active property to the element.

Results.forEach(function (element) {
  element.Active = "false";
});

C++ Boost: undefined reference to boost::system::generic_category()

try

g++ -c main.cpp && g++ main.o /usr/lib/x86_64-linux-gnu/libboost_system.so && ./a.out 

/usr/lib/x86_64-linux-gnu/ is the location of the boost library

use find /usr/ -name '*boost*.so' to find the boost library location

Choosing a jQuery datagrid plugin?

You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations

Update

The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:

Assigning a variable NaN in python without numpy

Yes -- use math.nan.

>>> from math import nan
>>> print(nan)
nan
>>> print(nan + 2)
nan
>>> nan == nan
False
>>> import math
>>> math.isnan(nan)
True

Before Python 3.5, one could use float("nan") (case insensitive).

Note that checking to see if two things that are NaN are equal to one another will always return false. This is in part because two things that are "not a number" cannot (strictly speaking) be said to be equal to one another -- see What is the rationale for all comparisons returning false for IEEE754 NaN values? for more details and information.

Instead, use math.isnan(...) if you need to determine if a value is NaN or not.

Furthermore, the exact semantics of the == operation on NaN value may cause subtle issues when trying to store NaN inside container types such as list or dict (or when using custom container types). See Checking for NaN presence in a container for more details.


You can also construct NaN numbers using Python's decimal module:

>>> from decimal import Decimal
>>> b = Decimal('nan')
>>> print(b)
NaN
>>> print(repr(b))
Decimal('NaN')
>>>
>>> Decimal(float('nan'))
Decimal('NaN')
>>> 
>>> import math
>>> math.isnan(b)
True

math.isnan(...) will also work with Decimal objects.


However, you cannot construct NaN numbers in Python's fractions module:

>>> from fractions import Fraction
>>> Fraction('nan')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\fractions.py", line 146, in __new__
    numerator)
ValueError: Invalid literal for Fraction: 'nan'
>>>
>>> Fraction(float('nan'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\fractions.py", line 130, in __new__
    value = Fraction.from_float(numerator)
  File "C:\Python35\lib\fractions.py", line 214, in from_float
    raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
ValueError: Cannot convert nan to Fraction.

Incidentally, you can also do float('Inf'), Decimal('Inf'), or math.inf (3.5+) to assign infinite numbers. (And also see math.isinf(...))

However doing Fraction('Inf') or Fraction(float('inf')) isn't permitted and will throw an exception, just like NaN.

If you want a quick and easy way to check if a number is neither NaN nor infinite, you can use math.isfinite(...) as of Python 3.2+.


If you want to do similar checks with complex numbers, the cmath module contains a similar set of functions and constants as the math module:

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

var SendInfo= { SendInfo: [... your elements ...]};

        $.ajax({
            type: 'post',
            url: 'Your-URI',
            data: JSON.stringify(SendInfo),
            contentType: "application/json; charset=utf-8",
            traditional: true,
            success: function (data) {
                ...
            }
        });

and in action

public ActionResult AddDomain(IEnumerable<PersonSheets> SendInfo){
...

you can bind your array like this

var SendInfo = [];

$(this).parents('table').find('input:checked').each(function () {
    var domain = {
        name: $("#id-manuf-name").val(),
        address: $("#id-manuf-address").val(),
        phone: $("#id-manuf-phone").val(),
    }

    SendInfo.push(domain);
});

hope this can help you.

How to determine whether a given Linux is 32 bit or 64 bit?

First you have to download Virtual Box. Then select new and a 32-bit Linux. Then boot the linux using it. If it boots then it is 32 bit if it doesn't then it is a 64 bit.

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

Try installing these packages.

sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-pil python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev libssl-dev

sudo easy_install greenlet

sudo easy_install gevent

How to get browser width using JavaScript code?

Why nobody mentions matchMedia?

if (window.matchMedia("(min-width: 400px)").matches) {
  /* the viewport is at least 400 pixels wide */
} else {
  /* the viewport is less than 400 pixels wide */
}

Did not test that much, but tested with android default and android chrome browsers, desktop chrome, so far it looks like it works well.

Of course it does not return number value, but returns boolean - if matches or not, so might not exactly fit the question but that's what we want anyway and probably the author of question wants.

How do I remove diacritics (accents) from a string in .NET?

What this person said:

Encoding.ASCII.GetString(Encoding.GetEncoding(1251).GetBytes(text));

It actually splits the likes of å which is one character (which is character code 00E5, not 0061 plus the modifier 030A which would look the same) into a plus some kind of modifier, and then the ASCII conversion removes the modifier, leaving the only a.

Javascript string replace with regex to strip off illegal characters

What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).

Syntax: [characters] where characters is a list with characters.

Example:

var cleanString = dirtyString.replace(/[|&;$%@"<>()+,]/g, "");

jQuery - How to dynamically add a validation rule

You need to call .validate() before you can add rules this way, like this:

$("#myForm").validate(); //sets up the validator
$("input[id*=Hours]").rules("add", "required");

The .validate() documentation is a good guide, here's the blurb about .rules("add", option):

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.

Looking for a good Python Tree data structure

Here's something I was working on.

class Tree:
    def __init__(self, value, *children):
        '''Singly linked tree, children do not know who their parent is.
        '''
        self.value = value
        self.children = tuple(children)

    @property
    def arguments(self):
        return (self.value,) + self.children

    def __eq__(self, tree):
        return self.arguments == tree.arguments

    def __repr__(self):
        argumentStr = ', '.join(map(repr, self.arguments))
        return '%s(%s)' % (self.__class__.__name__, argumentStr)

Use as such (numbers used as example values): t = Tree(1, Tree(2, Tree(4)), Tree(3, Tree(5)))

Changing datagridview cell color based on condition

Surprised no one mentioned a simple if statement can make sure your loop only gets executed once per format (on the first column, of the first row).

    private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        // once per format
        if (e.ColumnIndex == 0 && e.RowIndex == 0)
        {
            foreach (DataGridViewRow row in dgv.Rows)
                if (row != null)
                    row.DefaultCellStyle.BackColor = Color.Red;
        }
    }

Detect changes in the DOM

2015 update, new MutationObserver is supported by modern browsers:

Chrome 18+, Firefox 14+, IE 11+, Safari 6+

If you need to support older ones, you may try to fall back to other approaches like the ones mentioned in this 5 (!) year old answer below. There be dragons. Enjoy :)


Someone else is changing the document? Because if you have full control over the changes you just need to create your own domChanged API - with a function or custom event - and trigger/call it everywhere you modify things.

The DOM Level-2 has Mutation event types, but older version of IE don't support it. Note that the mutation events are deprecated in the DOM3 Events spec and have a performance penalty.

You can try to emulate mutation event with onpropertychange in IE (and fall back to the brute-force approach if non of them is available).

For a full domChange an interval could be an over-kill. Imagine that you need to store the current state of the whole document, and examine every element's every property to be the same.

Maybe if you're only interested in the elements and their order (as you mentioned in your question), a getElementsByTagName("*") can work. This will fire automatically if you add an element, remove an element, replace elements or change the structure of the document.

I wrote a proof of concept:

(function (window) {
    var last = +new Date();
    var delay = 100; // default delay

    // Manage event queue
    var stack = [];

    function callback() {
        var now = +new Date();
        if (now - last > delay) {
            for (var i = 0; i < stack.length; i++) {
                stack[i]();
            }
            last = now;
        }
    }

    // Public interface
    var onDomChange = function (fn, newdelay) {
        if (newdelay) delay = newdelay;
        stack.push(fn);
    };

    // Naive approach for compatibility
    function naive() {

        var last = document.getElementsByTagName('*');
        var lastlen = last.length;
        var timer = setTimeout(function check() {

            // get current state of the document
            var current = document.getElementsByTagName('*');
            var len = current.length;

            // if the length is different
            // it's fairly obvious
            if (len != lastlen) {
                // just make sure the loop finishes early
                last = [];
            }

            // go check every element in order
            for (var i = 0; i < len; i++) {
                if (current[i] !== last[i]) {
                    callback();
                    last = current;
                    lastlen = len;
                    break;
                }
            }

            // over, and over, and over again
            setTimeout(check, delay);

        }, delay);
    }

    //
    //  Check for mutation events support
    //

    var support = {};

    var el = document.documentElement;
    var remain = 3;

    // callback for the tests
    function decide() {
        if (support.DOMNodeInserted) {
            window.addEventListener("DOMContentLoaded", function () {
                if (support.DOMSubtreeModified) { // for FF 3+, Chrome
                    el.addEventListener('DOMSubtreeModified', callback, false);
                } else { // for FF 2, Safari, Opera 9.6+
                    el.addEventListener('DOMNodeInserted', callback, false);
                    el.addEventListener('DOMNodeRemoved', callback, false);
                }
            }, false);
        } else if (document.onpropertychange) { // for IE 5.5+
            document.onpropertychange = callback;
        } else { // fallback
            naive();
        }
    }

    // checks a particular event
    function test(event) {
        el.addEventListener(event, function fn() {
            support[event] = true;
            el.removeEventListener(event, fn, false);
            if (--remain === 0) decide();
        }, false);
    }

    // attach test events
    if (window.addEventListener) {
        test('DOMSubtreeModified');
        test('DOMNodeInserted');
        test('DOMNodeRemoved');
    } else {
        decide();
    }

    // do the dummy test
    var dummy = document.createElement("div");
    el.appendChild(dummy);
    el.removeChild(dummy);

    // expose
    window.onDomChange = onDomChange;
})(window);

Usage:

onDomChange(function(){ 
    alert("The Times They Are a-Changin'");
});

This works on IE 5.5+, FF 2+, Chrome, Safari 3+ and Opera 9.6+

How to convert hashmap to JSON object in Java

You can use:

new JSONObject(map);

Caution: This will only work for a Map<String, String>!

Other functions you can get from its documentation
http://stleary.github.io/JSON-java/index.html

How to generate JAXB classes from XSD?

In Eclipse, right click on the xsd file you want to get --> Generate --> Java... --> Generator: "Schema to JAXB Java Classes".

I just faced the same problem, I had a bunch of xsd files, only one of them being the XML Root Element and it worked well what I explained above in Eclipse

How to find patterns across multiple lines using grep?

With silver searcher:

ag 'abc.*(\n|.)*efg'

similar to ring bearer's answer, but with ag instead. Speed advantages of silver searcher could possibly shine here.

Pushing an existing Git repository to SVN

Here's how we made it work:

Clone your Git repository somewhere on your machine.

Open .git/config and add the following (from Maintaining a read-only SVN mirror of a Git repository):

[svn-remote "svn"]
    url = https://your.svn.repo
    fetch = :refs/remotes/git-svn

Now, from a console window, type these:

git svn fetch svn
git checkout -b svn git-svn
git merge master

Now, if it breaks here for whatever reason, type these three lines:

git checkout --theirs .
git add .
git commit -m "some message"

And finally, you can commit to SVN:

git svn dcommit

Note: I always scrap that folder afterwards.

What is the use of static constructors?

From Static Constructors (C# Programming Guide):

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

  • A static constructor cannot be called directly.

  • The user has no control on when the static constructor is executed in the program.

  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

In my case, which none of the answers above stated. If your device is using the miniUsb connector, make sure you are using a cable that is not charge-only. I became accustom to using developing with a newer Usb-C device and could not fathom a charge-only cable got mixed with my pack especially since there is no visible way to tell the difference.

Before you uninstall and go through a nightmare of driver reinstall and android menu options. Try a different cable first.

Select the top N values by group

# start with the mtcars data frame (included with your installation of R)
mtcars

# pick your 'group by' variable
gbv <- 'cyl'
# IMPORTANT NOTE: you can only include one group by variable here
# ..if you need more, the `order` function below will need
# one per inputted parameter: order( x$cyl , x$am )

# choose whether you want to find the minimum or maximum
find.maximum <- FALSE

# create a simple data frame with only two columns
x <- mtcars

# order it based on 
x <- x[ order( x[ , gbv ] , decreasing = find.maximum ) , ]

# figure out the ranks of each miles-per-gallon, within cyl columns
if ( find.maximum ){
    # note the negative sign (which changes the order of mpg)
    # *and* the `rev` function, which flips the order of the `tapply` result
    x$ranks <- unlist( rev( tapply( -x$mpg , x[ , gbv ] , rank ) ) )
} else {
    x$ranks <- unlist( tapply( x$mpg , x[ , gbv ] , rank ) )
}
# now just subset it based on the rank column
result <- x[ x$ranks <= 3 , ]

# look at your results
result

# done!

# but note only *two* values where cyl == 4 were kept,
# because there was a tie for third smallest, and the `rank` function gave both '3.5'
x[ x$ranks == 3.5 , ]

# ..if you instead wanted to keep all ties, you could change the
# tie-breaking behavior of the `rank` function.
# using the `min` *includes* all ties.  using `max` would *exclude* all ties
if ( find.maximum ){
    # note the negative sign (which changes the order of mpg)
    # *and* the `rev` function, which flips the order of the `tapply` result
    x$ranks <- unlist( rev( tapply( -x$mpg , x[ , gbv ] , rank , ties.method = 'min' ) ) )
} else {
    x$ranks <- unlist( tapply( x$mpg , x[ , gbv ] , rank , ties.method = 'min' ) )
}
# and there are even more options..
# see ?rank for more methods

# now just subset it based on the rank column
result <- x[ x$ranks <= 3 , ]

# look at your results
result
# and notice *both* cyl == 4 and ranks == 3 were included in your results
# because of the tie-breaking behavior chosen.

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

Fatal error: Class 'ZipArchive' not found in

For PHP 7.x

sudo apt-get install php-zip

For PHP 5.x

sudo apt-get install php5.x-zip
// (for example sudo apt-get install php5.6-zip)

And then restart the Apache server

sudo service apache2 restart

How to get nth jQuery element

If I understand your question correctly, you can always just wrap the get function like so:

var $someJqueryEl = $($('.myJqueryEls').get(3));

How to duplicate a git repository? (without forking)

If you just want to create a new repository using all or most of the files from an existing one (i.e., as a kind of template), I find the easiest approach is to make a new repo with the desired name etc, clone it to your desktop, then just add the files and folders you want in it.

You don't get all the history etc, but you probably don't want that in this case.

What is the current directory in a batch file?

%__CD__% , %CD% , %=C:%

There's also another dynamic variable %__CD__% which points to the current directory but alike %CD% it has a backslash at the end. This can be useful if you want to append files to the current directory.

With %=C:% %=D:% you can access the last accessed directory for the corresponding drive. If the variable is not defined you haven't accessed the drive on the current cmd session.

And %__APPDIR__% expands to the executable that runs the current script a.k.a. cmd.exe directory.

Bootstrap full responsive navbar with logo or brand name text

Just set the height and width where you are adding that logo. I tried and its working fine

Disable spell-checking on HTML textfields

An IFrame WILL "trigger" the spell checker (if it has content-editable set to true) just as a textfield, at least in Chrome.

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

Found one more way of doing it

 if let parameters = route.parameters {

                    for (key, value) in parameters {
                         if value is String {
                            if let temp = value as? String {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if value is NSArray {
                            if let temp = value as? [Double]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                            else if let temp = value as? [Int]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                            else if let temp = value as? [String]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if CFGetTypeID(value as CFTypeRef) == CFNumberGetTypeID() {
                            if let temp = value as? Int {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID(){
                            if let temp = value as? Bool {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                    }
                }

                if let items: [MultipartData] = route.multipartData{
                    for item in items {
                        if let value = item.value{
                            multipartFormData.append(value, withName: item.key, fileName: item.fileName, mimeType: item.mimeType)
                        }
                    }
                }

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

Try this:

PM> Enable-migrations -force
PM> Add-migration MigrationName
PM> Update-database -force

Loop in Jade (currently known as "Pug") template engine

Here is a very simple jade file that have a loop in it. Jade is very sensitive about white space. After loop definition line (for) you should give an indent(tab) to stuff that want to go inside the loop. You can do this without {}:

- var arr=['one', 'two', 'three'];
- var s = 'string';
doctype html
html
    head
    body
        section= s
        - for (var i=0; i<3; i++)
            div= arr[i]

How to call a JavaScript function from PHP?

You can't. You can call a JS function from HTML outputted by PHP, but that's a whole 'nother thing.

MySQL query to get column names?

IN WORDPRESS:

global $wpdb;   $table_name=$wpdb->prefix.'posts';
foreach ( $wpdb->get_col( "DESC " . $table_name, 0 ) as $column_name ) {
  var_dump( $column_name );
}

get the selected index value of <select> tag in php

$gender = $_POST['gender'];
echo $gender;  

it will echoes the selected value.

System.Data.OracleClient requires Oracle client software version 8.1.7

Update 1: It is possible for different users to have different path. But its not the likely problem here. There is more chance that the user that the iwam user doesn't have permission to the oracle client directory.

Update 0: Its suppose to work. Check for environment variable ( That are needed to find the oracle client and tnsnames.ora ). Also, Maybe you have a 32/64 bit issues. Also, consider using the Oracle Data Provider for .NET ( search for odp.net)

Android: ScrollView vs NestedScrollView

In addition to the nested scrolling NestedScrollView added one major functionality, which could even make it interesting outside of nested contexts: It has build in support for OnScrollChangeListener. Adding a OnScrollChangeListener to the original ScrollView below API 23 required subclassing ScrollView or messing around with the ViewTreeObserver of the ScrollView which often means even more work than subclassing. With NestedScrollView it can be done using the build-in setter.

How to import .py file from another directory?

You can add to the system-path at runtime:

import sys
sys.path.insert(0, 'path/to/your/py_file')

import py_file

This is by far the easiest way to do it.

How to make lists contain only distinct element in Python?

one-liner and preserve order

list(OrderedDict.fromkeys([2,1,1,3]))

although you'll need

from collections import OrderedDict

JQuery get all elements by class name

One possible way is to use .map() method:

var all = $(".mbox").map(function() {
    return this.innerHTML;
}).get();

console.log(all.join());

DEMO: http://jsfiddle.net/Y4bHh/

N.B. Please don't use document.write. For testing purposes console.log is the best way to go.

Best way to include CSS? Why use @import?

I think @import is most useful when writing code for multiple devices. Include a conditional statement to only include the style for the device in question, then only one sheet gets loaded. You can still use the link tag to add any common style elements.

What does HTTP/1.1 302 mean exactly?

According to RFC 1945/Hypertext Transfer Protocol - HTTP / 1.0:

   302 Moved Temporarily

   The requested resource resides temporarily under a different URL.
   Since the redirection may be altered on occasion, the client should
   continue to use the Request-URI for future requests.

   The URL must be given by the Location field in the response. Unless
   it was a HEAD request, the Entity-Body of the response should
   contain a short note with a hyperlink to the new URI(s).

   If the 302 status code is received in response to a request using
   the POST method, the user agent must not automatically redirect the
   request unless it can be confirmed by the user, since this might
   change the conditions under which the request was issued.

       Note: When automatically redirecting a POST request after
       receiving a 302 status code, some existing user agents will
       erroneously change it into a GET request.

How do I convert ticks to minutes?

there are 600 million ticks per minute. ticksperminute

How do I group Windows Form radio buttons?

Radio button without panel

public class RadioButton2 : RadioButton
{
   public string GroupName { get; set; }
}

private void RadioButton2_Clicked(object sender, EventArgs e)
{
    RadioButton2 rb = (sender as RadioButton2);

    if (!rb.Checked)
    {
       foreach (var c in Controls)
       {
           if (c is RadioButton2 && (c as RadioButton2).GroupName == rb.GroupName)
           {
              (c as RadioButton2).Checked = false;
           }
       }

       rb.Checked = true;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    //a group
    RadioButton2 rb1 = new RadioButton2();
    rb1.Text = "radio1";
    rb1.AutoSize = true;
    rb1.AutoCheck = false;
    rb1.Top = 50;
    rb1.Left = 50;
    rb1.GroupName = "a";
    rb1.Click += RadioButton2_Clicked;
    Controls.Add(rb1);

    RadioButton2 rb2 = new RadioButton2();
    rb2.Text = "radio2";
    rb2.AutoSize = true;
    rb2.AutoCheck = false;
    rb2.Top = 50;
    rb2.Left = 100;
    rb2.GroupName = "a";
    rb2.Click += RadioButton2_Clicked;
    Controls.Add(rb2);

    //b group
    RadioButton2 rb3 = new RadioButton2();
    rb3.Text = "radio3";
    rb3.AutoSize = true;
    rb3.AutoCheck = false;
    rb3.Top = 80;
    rb3.Left = 50;
    rb3.GroupName = "b";
    rb3.Click += RadioButton2_Clicked;
    Controls.Add(rb3);

    RadioButton2 rb4 = new RadioButton2();
    rb4.Text = "radio4";
    rb4.AutoSize = true;
    rb4.AutoCheck = false;
    rb4.Top = 80;
    rb4.Left = 100;
    rb4.GroupName = "b";
    rb4.Click += RadioButton2_Clicked;
    Controls.Add(rb4);
}

symbol(s) not found for architecture i386

Sometimes there are source files which are missing from your target.

  1. examine which symbols are missing
  2. target->build phases->compile source
  3. add the missing source files if they are not listed
  4. command+b for bliss

You can select the files that seem to be "missing" and check in the right-hand utility bar that their checkboxes are selected for the Target you are building.

jQuery to remove an option from drop down list, given option's text/value

$('#id option').remove();

This will clear the Drop Down list. if you want to clear to select value then $("#id option:selected").remove();

How to set up file permissions for Laravel?

I decided to write my own script to ease some of the pain of setting up projects.

Run the following inside your project root:

wget -qO- https://raw.githubusercontent.com/defaye/bootstrap-laravel/master/bootstrap.sh | sh

Wait for the bootstrapping to complete and you're good to go.

Review the script before use.

Disabling Minimize & Maximize On WinForm?

public Form1()
{
InitializeComponent();
//this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
}

__init__() missing 1 required positional argument

The problem is with, you

def __init__(self, data):

when you create object from DHT class you should pass parameter the data should be dict type, like

data={'one':1,'two':2,'three':3}
dhtObj=DHT(data)

But in your code youshould to change is

data={'one':1,'two':2,'three':3}
if __name__ == '__main__': DHT(data).showData()

Or

if __name__ == '__main__': DHT({'one':1,'two':2,'three':3}).showData()

Change Screen Orientation programmatically using a Button

Yes, you can set the screen orientation programatically anytime you want using:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

for landscape and portrait mode respectively. The setRequestedOrientation() method is available for the Activity class, so it can be used inside your Activity.

And this is how you can get the current screen orientation and set it adequatly depending on its current state:

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
final int orientation = display.getOrientation(); 
 // OR: orientation = getRequestedOrientation(); // inside an Activity

// set the screen orientation on button click
Button btn = (Button) findViewById(R.id.yourbutton);
btn.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {

              switch(orientation) {
                   case Configuration.ORIENTATION_PORTRAIT:
                       setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                       break;
                   case Configuration.ORIENTATION_LANDSCAPE:
                       setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                       break;                   
               }
          }
   });

Taken from here: http://techblogon.com/android-screen-orientation-change-rotation-example/

EDIT

Also, you can get the screen orientation using the Configuration:

Activity.getResources().getConfiguration().orientation

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

Parcelable encountered IOException writing serializable object getactivity()

I am also phase these error and i am little bit change in modelClass which are implemented Serializable interface like:

At that Model class also implement Parcelable interface with writeToParcel() override method

Then just got error to "create creator" so CREATOR is write and also create with modelclass contructor with arguments & without arguments..

       @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(id);
            dest.writeString(name);
        }

        protected ArtistTrackClass(Parcel in) {
            id = in.readString();
            name = in.readString();
        }

       public ArtistTrackClass() {

        }

    public static final Creator<ArtistTrackClass> CREATOR = new Creator<ArtistTrackClass>() {
        @Override
        public ArtistTrackClass createFromParcel(Parcel in) {
            return new ArtistTrackClass(in);
        }

        @Override
        public ArtistTrackClass[] newArray(int size) {
            return new ArtistTrackClass[size];
        }
    };

Here,

ArtistTrackClass -> ModelClass

Constructor with Parcel arguments "read our attributes" and writeToParcel() is "write our attributes"

Get all validation errors from Angular 2 FormGroup

For whom it might concern - I tweaked around with Andreas code in order to get all errors code in a flat object for easier logging errors that might appear.

Please consider:

export function collectErrors(control: AbstractControl): any | null {
  let errors = {};
  let recursiveFunc = (control: AbstractControl) => {
    if (isFormGroup(control)) {
      return Object.entries(control.controls).reduce(
        (acc, [key, childControl]) => {
          const childErrors = recursiveFunc(childControl);
          if (childErrors) {
            if (!isFormGroup(childControl)) {
              errors = { ...errors, [key]: childErrors };
            }
            acc = { ...acc, [key]: childErrors };
          }
          return acc;
        },
        null
      );
    } else {
      return control.errors;
    }
  };
  recursiveFunc(control);
  return errors;
}

What is the question mark for in a Typescript parameter name

This is to make the variable of Optional type. Otherwise declared variables shows "undefined" if this variable is not used.

export interface ISearchResult {  
  title: string;  
  listTitle:string;
  entityName?: string,
  lookupName?:string,
  lookupId?:string  
}

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

I looked at existing answers but I also found that setting the button frame is an important first step.

Here is a function that I use that takes care of this:

const CGFloat kImageTopOffset   = -15;
const CGFloat kTextBottomOffset = -25;

+ (void) centerButtonImageTopAndTextBottom: (UIButton*)         button 
                                     frame: (CGRect)            buttonFrame
                                      text: (NSString*)         textString
                                 textColor: (UIColor*)          textColor
                                      font: (UIFont*)           textFont
                                     image: (UIImage*)          image
                                  forState: (UIControlState)    buttonState
{
    button.frame = buttonFrame;

    [button setTitleColor: (UIColor*)       textColor
                 forState: (UIControlState) buttonState];

    [button setTitle: (NSString*) textString
            forState: (UIControlState) buttonState ];


    [button.titleLabel setFont: (UIFont*) textFont ];

    [button setTitleEdgeInsets: UIEdgeInsetsMake( 0.0, -image.size.width, kTextBottomOffset,  0.0)]; 

    [button setImage: (UIImage*)       image 
            forState: (UIControlState) buttonState ];

    [button setImageEdgeInsets: UIEdgeInsetsMake( kImageTopOffset, 0.0, 0.0,- button.titleLabel.bounds.size.width)];
}

checking memory_limit in PHP

Not so exact but simpler solution:

$limit = str_replace(array('G', 'M', 'K'), array('000000000', '000000', '000'), ini_get('memory_limit'));
if($limit < 500000000) ini_set('memory_limit', '500M');                     

How to rename uploaded file before saving it into a directory?

You guess correctly. Read the manual page for move_uploaded_file. Set the second parameter to whereever your want to save the file.

If it doesn't work, there is something wrong with your $fileName. Please post your most recent code.

How to replace space with comma using sed?

If you want the output on terminal then,

$sed 's/ /,/g' filename.txt

But if you want to edit the file itself i.e. if you want to replace space with the comma in the file then,

$sed -i 's/ /,/g' filename.txt

SQL Query for Logins

Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.

How do I set multipart in axios with react?

Here's how I do file upload in react using axios

import React from 'react'
import axios, { post } from 'axios';

class SimpleReactFileUpload extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault() // Stop form submit
    this.fileUpload(this.state.file).then((response)=>{
      console.log(response.data);
    })
  }

  onChange(e) {
    this.setState({file:e.target.files[0]})
  }

  fileUpload(file){
    const url = 'http://example.com/file-upload';
    const formData = new FormData();
    formData.append('file',file)
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    return  post(url, formData,config)
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}



export default SimpleReactFileUpload

Source

Python: "Indentation Error: unindent does not match any outer indentation level"

I had this same problem and it had nothing to do with tabs. This was my problem code:

def genericFunction(variable):

    for line in variable:

       line = variable


   if variable != None:
      return variable

Note the above for is indented with more spaces than the line that starts with if. This is bad. All your indents must be consistent. So I guess you could say I had a stray space and not a stray tab.

XmlWriter to Write to a String Instead of to a File

Use StringBuilder:

var sb = new StringBuilder();
    using (XmlWriter xmlWriter = XmlWriter.Create(sb))
    {
        ...
    }
return sb.ToString();

Change the bullet color of list

You have to use image

.listStyle {
    list-style: none;
    background: url(bullet.jpg) no-repeat left center;
    padding-left: 40px;
}

How to disable mouse scroll wheel scaling with Google Maps API

Just in case you want to do this dynamically;

function enableScrollwheel(map) {
    if(map) map.setOptions({ scrollwheel: true });
}

function disableScrollwheel(map) {
    if(map) map.setOptions({ scrollwheel: false });
}

Sometimes you have to show something "complex" over the map (or the map is a small part of the layout), and this scroll zooming gets in the middle, but once you have a clean map, this way of zooming is nice.

SQL Logic Operator Precedence: And and Or

And has precedence over Or, so, even if a <=> a1 Or a2

Where a And b 

is not the same as

Where a1 Or a2 And b,

because that would be Executed as

Where a1 Or (a2 And b)

and what you want, to make them the same, is the following (using parentheses to override rules of precedence):

 Where (a1 Or a2) And b

Here's an example to illustrate:

Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0

Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F

For those who like to consult references (in alphabetic order):

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

In my particular case, I had a similar error on a legacy website used in my organization. To solve the issue, I had to list the website a a "Trusted site".

To do so:

  • Click the Tools button, and then Internet options.
  • Go on the Security tab.
  • Click on Trusted sites and then on the sites button.
  • Enter the url of the website and click on Add.

I'm leaving this here in the remote case it will help someone.

Find a string by searching all tables in SQL Server Management Studio 2008

To update TechDo's answer for SQL server 2012. You need to change: 'FROM ' + @TableName + ' (NOLOCK) ' to FROM ' + @TableName + 'WITH (NOLOCK) ' +

Other wise you will get the following error: Deprecated feature 'Table hint without WITH' is not supported in this version of SQL Server.

Below is the complete updated stored procedure:

CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN

    CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

    SET NOCOUNT ON

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    SET  @TableName = ''
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    WHILE @TableName IS NOT NULL

    BEGIN
        SET @ColumnName = ''
        SET @TableName = 
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM     INFORMATION_SCHEMA.TABLES
            WHERE         TABLE_TYPE = 'BASE TABLE'
                AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                AND    OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                             ), 'IsMSShipped'
                               ) = 0
        )

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )

            IF @ColumnName IS NOT NULL

            BEGIN
                INSERT INTO #Results
                EXEC
                (
                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                    FROM ' + @TableName + 'WITH (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END    
    END

    SELECT ColumnName, ColumnValue FROM #Results
END

PHP: if !empty & empty

For several cases, or even just a few cases involving a lot of criteria, consider using a switch.

switch( true ){

    case ( !empty($youtube) && !empty($link) ):{
        // Nothing is empty...
        break;
    }

    case ( !empty($youtube) && empty($link) ):{
        // One is empty...
        break;
    }

    case ( empty($youtube) && !empty($link) ):{
        // The other is empty...
        break;
    }

    case ( empty($youtube) && empty($link) ):{
        // Everything is empty
        break;
    }

    default:{
        // Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
        // That way if you change it, or miss a case, you have some default handler.
        break;
    }

}

If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.

Note that the { } around the cases aren't required, but they are nice for readability and code folding.

More about switch: http://php.net/manual/en/control-structures.switch.php

Getting RAW Soap Data from a Web Reference Client running in ASP.net

It looks like Tim Carter's solution doesn't work if the call to the web reference throws an exception. I've been trying to get at the raw web resonse so I can examine it (in code) in the error handler once the exception is thrown. However, I'm finding that the response log written by Tim's method is blank when the call throws an exception. I don't completely understand the code, but it appears that Tim's method cuts into the process after the point where .Net has already invalidated and discarded the web response.

I'm working with a client that's developing a web service manually with low level coding. At this point, they are adding their own internal process error messages as HTML formatted messages into the response BEFORE the SOAP formatted response. Of course, the automagic .Net web reference blows up on this. If I could get at the raw HTTP response after an exception is thrown, I could look for and parse any SOAP response within the mixed returning HTTP response and know that they received my data OK or not.

Later ...

Here's a solution that does work, even after an execption (note that I'm only after the response - could get the request too):

namespace ChuckBevitt
{
    class GetRawResponseSoapExtension : SoapExtension
    {
        //must override these three methods
        public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
        {
            return null;
        }
        public override object GetInitializer(Type serviceType)
        {
            return null;
        }
        public override void Initialize(object initializer)
        {
        }

        private bool IsResponse = false;

        public override void ProcessMessage(SoapMessage message)
        {
            //Note that ProcessMessage gets called AFTER ChainStream.
            //That's why I'm looking for AfterSerialize, rather than BeforeDeserialize
            if (message.Stage == SoapMessageStage.AfterSerialize)
                IsResponse = true;
            else
                IsResponse = false;
        }

        public override Stream ChainStream(Stream stream)
        {
            if (IsResponse)
            {
                StreamReader sr = new StreamReader(stream);
                string response = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();

                File.WriteAllText(@"C:\test.txt", response);

                byte[] ResponseBytes = Encoding.ASCII.GetBytes(response);
                MemoryStream ms = new MemoryStream(ResponseBytes);
                return ms;

            }
            else
                return stream;
        }
    }
}

Here's how you configure it in the config file:

<configuration>
     ...
  <system.web>
    <webServices>
      <soapExtensionTypes>
        <add type="ChuckBevitt.GetRawResponseSoapExtension, TestCallWebService"
           priority="1" group="0" />
      </soapExtensionTypes>
    </webServices>
  </system.web>
</configuration>

"TestCallWebService" shoud be replaced with the name of the library (that happened to be the name of the test console app I was working in).

You really shouldn't have to go to ChainStream; you should be able to do it more simply from ProcessMessage as:

public override void ProcessMessage(SoapMessage message)
{
    if (message.Stage == SoapMessageStage.BeforeDeserialize)
    {
        StreamReader sr = new StreamReader(message.Stream);
        File.WriteAllText(@"C:\test.txt", sr.ReadToEnd());
        message.Stream.Position = 0; //Will blow up 'cause type of stream ("ConnectStream") doesn't alow seek so can't reset position
    }
}

If you look up SoapMessage.Stream, it's supposed to be a read-only stream that you can use to inspect the data at this point. This is a screw-up 'cause if you do read the stream, subsequent processing bombs with no data found errors (stream was at end) and you can't reset the position to the beginning.

Interestingly, if you do both methods, the ChainStream and the ProcessMessage ways, the ProcessMessage method will work because you changed the stream type from ConnectStream to MemoryStream in ChainStream, and MemoryStream does allow seek operations. (I tried casting the ConnectStream to MemoryStream - wasn't allow.)

So ..... Microsoft should either allow seek operations on the ChainStream type or make the SoapMessage.Stream truly a read-only copy as it's supposed to be. (Write your congressman, etc...)

One further point. After creating a way to retreive the raw HTTP response after an exception, I still didn't get the full response (as determined by a HTTP sniffer). This was because when the development web service added the HTML error messages to the beginning of the response, it didn't adjust the Content-Length header, so the Content-Length value was less than the size of the actual response body. All I got was the Content-Length value number of characters - the rest were missing. Obviously, when .Net reads the response stream, it just reads the Content-Length number of characters and doesn't allow for the Content-Length value possibily being wrong. This is as it should be; but if the Content-Length header value is wrong, the only way you'll ever get the entire response body is with a HTTP sniffer (I user HTTP Analyzer from http://www.ieinspector.com).

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

Why can't I check if a 'DateTime' is 'Nothing'?

You can also use below just simple to check:

If startDate <> Nothing Then
your logic
End If

It will check that the startDate variable of DateTime datatype is null or not.

mysqldump exports only one table

try this. There are in general three ways to use mysqldump—

in order to dump a set of one or more tables,

shell> mysqldump [options] db_name [tbl_name ...]

a set of one or more complete databases

shell> mysqldump [options] --databases db_name ...

or an entire MySQL server—as shown here:

shell> mysqldump [options] --all-databases

Where to put Gradle configuration (i.e. credentials) that should not be committed?

First answer is still valid, but the API has changed in the past. Since my edit there wasn't accepted I post it as separate answer.

The method authentication() is only used to provide the authentication method (e.g. Basic) but not any credentials.

You also shouldn't use it since it's printing the credentials plain on failure!

This his how it should look like in your build.gradle

    maven {
        credentials {
            username "$mavenUser"
            password "$mavenPassword"
        }
        url 'https://maven.yourcorp.net/'
   }

In gradle.properties in your userhome dir put:

mavenUser=admin
mavenPassword=admin123

Also ensure that the GRADLE_USER_HOME is set to ~/.gradle otherwise the properties file there won't be resolved.

See also:

https://docs.gradle.org/current/userguide/build_environment.html

and

https://docs.gradle.org/current/userguide/dependency_management.html (23.6.4.1)

How to POST the data from a modal form of Bootstrap?

You need to handle it via ajax submit.

Something like this:

$(function(){
    $('#subscribe-email-form').on('submit', function(e){
        e.preventDefault();
        $.ajax({
            url: url, //this is the submit URL
            type: 'GET', //or POST
            data: $('#subscribe-email-form').serialize(),
            success: function(data){
                 alert('successfully submitted')
            }
        });
    });
});

A better way would be to use a django form, and then render the following snippet:

<form>
    <div class="modal-body">
        <input type="email" placeholder="email"/>
        <p>This service will notify you by email should any issue arise that affects your plivo service.</p>
    </div>
    <div class="modal-footer">
        <input type="submit" value="SUBMIT" class="btn"/>
    </div>
</form>

via the context - example : {{form}}.

How can I dynamically add a directive in AngularJS?

Inspired from many of the previous answers I have came up with the following "stroman" directive that will replace itself with any other directives.

app.directive('stroman', function($compile) {
  return {
    link: function(scope, el, attrName) {
      var newElem = angular.element('<div></div>');
      // Copying all of the attributes
      for (let prop in attrName.$attr) {
        newElem.attr(prop, attrName[prop]);
      }
      el.replaceWith($compile(newElem)(scope)); // Replacing
    }
  };
});

Important: Register the directives that you want to use with restrict: 'C'. Like this:

app.directive('my-directive', function() {
  return {
    restrict: 'C',
    template: 'Hi there',
  };
});

You can use like this:

<stroman class="my-directive other-class" randomProperty="8"></stroman>

To get this:

<div class="my-directive other-class" randomProperty="8">Hi there</div>

Protip. If you don't want to use directives based on classes then you can change '<div></div>' to something what you like. E.g. have a fixed attribute that contains the name of the desired directive instead of class.

Excel: Can I create a Conditional Formula based on the Color of a Cell?

You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):

Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
End Function

Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel

In your worksheet, you can use the following: =GetFillColor(B5)

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

If you use the WEB API with Claims, you can use this:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AutorizeCompanyAttribute:  AuthorizationFilterAttribute
{
    public string Company { get; set; }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var claims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity);
        var claim = claims.Claims.Where(x => x.Type == "Company").FirstOrDefault();

        string privilegeLevels = string.Join("", claim.Value);        

        if (privilegeLevels.Contains(this.Company)==false)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario de Empresa No Autorizado");
        }
    }
}
[HttpGet]
[AutorizeCompany(Company = "MyCompany")]
[Authorize(Roles ="SuperAdmin")]
public IEnumerable MyAction()
{....
}

How to get JSON response from http.Get

The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Tracks struct {
    Toptracks []Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  []Attr_info
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []Streamable_info
    Artist     []Artist_info
    Attr       []Track_attr_info
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "&limit=1" // limit data for testing
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var data interface{} // TopTracks
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Output:

Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]

How to replace url parameter with javascript/jquery?

Nowdays that's possible with native JS

var href = new URL('https://google.com?q=cats');
href.searchParams.set('q', 'dogs');
console.log(href.toString()); // https://google.com/?q=dogs

How do I find the authoritative name-server for a domain name?

You used the singular in your question but there are typically several authoritative name servers, the RFC 1034 recommends at least two.

Unless you mean "primary name server" and not "authoritative name server". The secondary name servers are authoritative.

To find out the name servers of a domain on Unix:

  % dig +short NS stackoverflow.com
 ns52.domaincontrol.com.
 ns51.domaincontrol.com.

To find out the server listed as primary (the notion of "primary" is quite fuzzy these days and typically has no good answer):

% dig +short  SOA stackoverflow.com | cut -d' ' -f1
ns51.domaincontrol.com.

To check discrepencies between name servers, my preference goes to the old check_soa tool, described in Liu & Albitz "DNS & BIND" book (O'Reilly editor). The source code is available in http://examples.oreilly.com/dns5/

% check_soa stackoverflow.com
ns51.domaincontrol.com has serial number 2008041300
ns52.domaincontrol.com has serial number 2008041300

Here, the two authoritative name servers have the same serial number. Good.

Difference between .dll and .exe?

Both DLL and EXE are Portable Executable(PE) Formats

A Dynamic-link library (DLL) is a library and therefore can not be executed directly. If you try to run it you will get an error about a missing entry point. It needs an entry point (main function) to get executed, that entry point can be any application or exe. DLL binding occurs at run-time. That is why its called "Dynamic Link" library.

An Executable (EXE) is a program that can be executed. It has its own entry point. A flag inside the PE header indicates which type of file it is (irrelevant of file extension). The PE header has a field where the entry point for the program resides. In DLLs it isn't used (or at least not as an entry point).

There are many software available to check header information. The only difference causing both to work differently is the bit in header as shown in below diagram.

header

EXE file has only single main entry means it is isolated application, when a system launches exe, a new process is created while DLLs have many entry points so when application use it no new process started, DLL can be reused and versioned. DLL reduces storage space as different programs can use the same dll.

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

search in java ArrayList

In Java 8:

Customer findCustomerByid(int id) {
    return this.customers.stream()
        .filter(customer -> customer.getId().equals(id))
        .findFirst().get();
}

It might also be better to change the return type to Optional<Customer>.

MySQL - sum column value(s) based on row from the same table

This might be seen as a little complex but does exactly what you want

SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(pl.CashAmount) AS Cash,
  SUM(pr.CashAmount) AS `Check`,
  SUM(px.CashAmount) AS `Credit Card`,
  SUM(pl.CashAmount) + SUM(pr.CashAmount) +SUM(px.CashAmount) AS Amount
FROM
  `payments` AS p 
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Cash' GROUP BY ProductID , PaymentMethod ) AS pl 
    ON pl.`PaymentMethod` = p.`PaymentMethod` AND pl.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Check' GROUP BY ProductID , PaymentMethod) AS pr 
    ON pr.`PaymentMethod` = p.`PaymentMethod` AND pr.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID, PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Credit Card' GROUP BY ProductID , PaymentMethod) AS px 
    ON px.`PaymentMethod` = p.`PaymentMethod` AND px.ProductID = p.`ProductID`
GROUP BY p.`ProductID` ;

Output

ProductID | Cash | Check | Credit Card | Amount
-----------------------------------------------
    3     | 20   |  15   |   25        |  60
    4     | 5    |  6    |   7         |  18

SQL Fiddle Demo

How to move an entire div element up x pixels?

you can also do this

margin-top:-30px; 
min-height:40px;

this "help" to stop the div yanking everything up a bit.

How to set an environment variable from a Gradle build?

In case you're using Gradle Kotlin syntax, you also can do:

tasks.taskName {
    environment(mapOf("A" to 1, "B" to "C"))
}

So for test task this would be:

tasks.test {
    environment(mapOf("SOME_TEST_VAR" to "aaa"))
}

Removing duplicates from a list of lists

This should work.

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]

k_cleaned = []
for ele in k:
    if set(ele) not in [set(x) for x in k_cleaned]:
        k_cleaned.append(ele)
print(k_cleaned)

# output: [[1, 2], [4], [5, 6, 2], [3]]

HTTP post XML data in C#

In General:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

In your specific situation:

Instead of:

request.ContentType = "application/x-www-form-urlencoded";

use:

request.ContentType = "text/xml; encoding='utf-8'";

Also, remove:

string postData = "XMLData=" + Sendingxml;

And replace:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

with:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());

How to declare a local variable in Razor?

If you want a variable to be accessible across the entire page, it works well to define it at the top of the file. (You can use either an implicit or explicit type.)

@{
    // implicit type
    var something1 = "something";

    // explicit type
    string something2 = "something";
}

<div>@something1</div> @*display first variable*@
<div>@something2</div> @*display second variable*@

Converting string format to datetime in mm/dd/yyyy

You can change the format too by doing this

string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");

// this change the "/" for the "-"

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

A side from the very long complete accepted answer there is an important point to make about IndexOutOfRangeException compared with many other exception types, and that is:

Often there is complex program state that maybe difficult to have control over at a particular point in code e.g a DB connection goes down so data for an input cannot be retrieved etc... This kind of issue often results in an Exception of some kind that has to bubble up to a higher level because where it occurs has no way of dealing with it at that point.

IndexOutOfRangeException is generally different in that it in most cases it is pretty trivial to check for at the point where the exception is being raised. Generally this kind of exception get thrown by some code that could very easily deal with the issue at the place it is occurring - just by checking the actual length of the array. You don't want to 'fix' this by handling this exception higher up - but instead by ensuring its not thrown in the first instance - which in most cases is easy to do by checking the array length.

Another way of putting this is that other exceptions can arise due to genuine lack of control over input or program state BUT IndexOutOfRangeException more often than not is simply just pilot (programmer) error.

ssh : Permission denied (publickey,gssapi-with-mic)

First a password login has to be established to remote machine

  • Firstly make a password login

you have to enable a password login by enabling the property ie) PasswordAuthentication yes in sshd_config file.Then restart the sshd service and copy the pub key to remote server (aws ec2 in my case), key will be copied without any error

  • Without password login works if and only if password login is made first
  • copy the pub key contents to authorised keys, cat xxx.pub >> ~/.ssh/authorized_keys

SQL Server ON DELETE Trigger

INSERTED and DELETED are virtual tables. They need to be used in a FROM clause.

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    IF EXISTS (SELECT foo
               FROM database2.dbo.table2
               WHERE id IN (SELECT deleted.id FROM deleted)
               AND bar = 4)

regular expression to match exactly 5 digits

what is about this? \D(\d{5})\D

This will do on:

f 23 23453 234 2344 2534 hallo33333 "50000"

23453, 33333 50000

Understanding Bootstrap's clearfix class

The :before pseudo element isn't needed for the clearfix hack itself.

It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.

display:table is being used because display:block doesn't do the trick. Using display:block margins will collapse even with a :before element.

There is one caveat: if vertical-align:baseline is used in table cells with clearfixed <div> elements, Firefox won't align well. Then you might prefer using display:block despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.

Cloning an array in Javascript/Typescript

Try this

const returnedTarget = Object.assign(target, source);

and pass empty array to target

in case complex objects this way works for me

$.extend(true, [], originalArray) in case of array

$.extend(true, {}, originalObject) in case of object

How to config routeProvider and locationProvider in angularJS?

Following is how one can configure $locationProvider using requireBase=false flag to avoid setting base href <head><base href="/"></head>:

var app = angular.module("hwapp", ['ngRoute']);

app.config(function($locationProvider){
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    }) 
});

jQuery add class .active on menu

Use window.location.pathname and compare it with your links. You can do something like this:

$('a[href="~/' + currentSiteVar + '/"').addClass('active');

But first you have to prepare currentSiteVar to put it into selecor.

When to use DataContract and DataMember attributes?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. Many .NET Framework types also have existing data contracts.

You can find the full article here.

Git push error: "origin does not appear to be a git repository"

Your config file does not include any references to "origin" remote. That section looks like this:

[remote "origin"]
    url = [email protected]:repository.git
    fetch = +refs/heads/*:refs/remotes/origin/*

You need to add the remote using git remote add before you can use it.

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

How to clone a Date object?

_x000D_
_x000D_
var orig = new Date();
var copy = new Date(+orig);

console.log(orig, copy);
_x000D_
_x000D_
_x000D_

How can I add a line to a file in a shell script?

Use perl -i, with a command that replaces the beginning of line 1 with what you want to insert (the .bk will have the effect that your original file is backed up):

perl -i.bk -pe 's/^/column1, column2, column3\n/ if($.==1)' testfile.csv  

JPA & Criteria API - Select only specific columns

You can do something like this

Session session = app.factory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Users> root = query.from(Users.class);
query.select(root.get("firstname"));
String name = session.createQuery(query).getSingleResult();

where you can change "firstname" with the name of the column you want.

How to check String in response body with mockMvc

You can use getContentAsString method to get the response data as string.

    String payload = "....";
    String apiToTest = "....";
    
    MvcResult mvcResult = mockMvc.
                perform(post(apiToTest).
                content(payload).
                contentType(MediaType.APPLICATION_JSON)).
                andReturn();
    
    String responseData = mvcResult.getResponse().getContentAsString();

You can refer this link for test application.

How do I share a global variable between c files?

Use the extern keyword to declare the variable in the other .c file. E.g.:

extern int counter;

means that the actual storage is located in another file. It can be used for both variables and function prototypes.

Android map v2 zoom to show all the markers

I have one other way to do this same thing works perfectly. so the idea behind to show all markers on the screen we need a center lat long and zoom level. here is the function which will give you both and need all marker's Latlng objects as input.

 public Pair<LatLng, Integer> getCenterWithZoomLevel(LatLng... l) {
    float max = 0;

    if (l == null || l.length == 0) {
        return null;
    }
    LatLngBounds.Builder b = new LatLngBounds.Builder();
    for (int count = 0; count < l.length; count++) {
        if (l[count] == null) {
            continue;
        }
        b.include(l[count]);
    }

    LatLng center = b.build().getCenter();

    float distance = 0;
    for (int count = 0; count < l.length; count++) {
        if (l[count] == null) {
            continue;
        }
        distance = distance(center, l[count]);
        if (distance > max) {
            max = distance;
        }
    }

    double scale = max / 1000;
    int zoom = ((int) (16 - Math.log(scale) / Math.log(2)));
    return new Pair<LatLng, Integer>(center, zoom);
}

This function return Pair object which you can use like

Pair pair = getCenterWithZoomLevel(l1,l2,l3..); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pair.first, pair.second));

you can instead of using padding to keep away your markers from screen boundaries, you can adjust zoom by -1.

How to split a string into an array in Bash?

For multilined elements, why not something like

$ array=($(echo -e $'a a\nb b' | tr ' ' '§')) && array=("${array[@]//§/ }") && echo "${array[@]/%/ INTERELEMENT}"

a a INTERELEMENT b b INTERELEMENT

How to import a module given its name as string?

Note: imp is deprecated since Python 3.4 in favor of importlib

As mentioned the imp module provides you loading functions:

imp.load_source(name, path)
imp.load_compiled(name, path)

I've used these before to perform something similar.

In my case I defined a specific class with defined methods that were required. Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:

import imp
import os

def load_from_file(filepath):
    class_inst = None
    expected_class = 'MyClass'

    mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])

    if file_ext.lower() == '.py':
        py_mod = imp.load_source(mod_name, filepath)

    elif file_ext.lower() == '.pyc':
        py_mod = imp.load_compiled(mod_name, filepath)

    if hasattr(py_mod, expected_class):
        class_inst = getattr(py_mod, expected_class)()

    return class_inst

ImportError: No module named BeautifulSoup

Try This, Mine worked this way. To get any data of tag just replace the "a" with the tag you want.

from bs4 import BeautifulSoup as bs
import urllib

url="http://currentaffairs.gktoday.in/month/current-affairs-january-2015"

soup = bs(urllib.urlopen(url))
for link in soup.findAll('a'):
        print link.string

Html.EditorFor Set Default Value

This worked for me

In Controlle

 ViewBag.AAA = default_Value ;

In View

@Html.EditorFor(model => model.AAA, new { htmlAttributes = new { @Value = ViewBag.AAA } }

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

Quickly ran a timeit to see, if there are any differences between the np.full and np.ones version.

Answer: No

import timeit

n_array, n_test = 1000, 10000
setup = f"import numpy as np; n = {n_array};"

print(f"np.ones: {timeit.timeit('np.ones((n, n), dtype=bool)', number=n_test, setup=setup)}s")
print(f"np.full: {timeit.timeit('np.full((n, n), True)', number=n_test, setup=setup)}s")

Result:

np.ones: 0.38416870904620737s
np.full: 0.38430388597771525s


IMPORTANT

Regarding the post about np.empty (and I cannot comment, as my reputation is too low):

DON'T DO THAT. DON'T USE np.empty to initialize an all-True array

As the array is empty, the memory is not written and there is no guarantee, what your values will be, e.g.

>>> print(np.empty((4,4), dtype=bool))
[[ True  True  True  True]
 [ True  True  True  True]
 [ True  True  True  True]
 [ True  True False False]]

printf with std::string?

printf accepts a variable number of arguments. Those can only have Plain Old Data (POD) types. Code that passes anything other than POD to printf only compiles because the compiler assumes you got your format right. %s means that the respective argument is supposed to be a pointer to a char. In your case it is an std::string not const char*. printf does not know it because the argument type goes lost and is supposed to be restored from the format parameter. When turning that std::string argument into const char* the resulting pointer will point to some irrelevant region of memory instead of your desired C string. For that reason your code prints out gibberish.

While printf is an excellent choice for printing out formatted text, (especially if you intend to have padding), it can be dangerous if you haven't enabled compiler warnings. Always enable warnings because then mistakes like this are easily avoidable. There is no reason to use the clumsy std::cout mechanism if the printf family can do the same task in a much faster and prettier way. Just make sure you have enabled all warnings (-Wall -Wextra) and you will be good. In case you use your own custom printf implementation you should declare it with the __attribute__ mechanism that enables the compiler to check the format string against the parameters provided.

Android soft keyboard covers EditText field

I believe that you can make it scroll by using the trackball, which might be achieved programmatically through selection methods eventually, but it's just an idea. I know that the trackball method typically works, but as for the exact way to do this and make it work from code, I do not sure.
Hope that helps.

How to get height of Keyboard?

Update Swift 4.2

private func setUpObserver() {
    NotificationCenter.default.addObserver(self, selector: .keyboardWillShow, name: UIResponder.keyboardWillShowNotification, object: nil)
}

selector method:

@objc fileprivate func keyboardWillShow(notification:NSNotification) {
    if let keyboardRectValue = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardHeight = keyboardRectValue.height
    }
}

extension:

private extension Selector {
    static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(notification:)) 
}

Update Swift 3.0

private func setUpObserver() {
    NotificationCenter.default.addObserver(self, selector: .keyboardWillShow, name: .UIKeyboardWillShow, object: nil)
}

selector method:

@objc fileprivate func keyboardWillShow(notification:NSNotification) {
    if let keyboardRectValue = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardHeight = keyboardRectValue.height
    }
}

extension:

private extension Selector {
    static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(notification:)) 
}

Tip

UIKeyboardDidShowNotification or UIKeyboardWillShowNotification might called twice and got different result, this article explained why called twice.

In Swift 2.2

Swift 2.2 deprecates using strings for selectors and instead introduces new syntax: #selector.

Something like:

private func setUpObserver() {

    NSNotificationCenter.defaultCenter().addObserver(self, selector: .keyboardWillShow, name: UIKeyboardWillShowNotification, object: nil)
}

selector method:

@objc private func keyboardWillShow(notification:NSNotification) {

    let userInfo:NSDictionary = notification.userInfo!
    let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
    let keyboardRectangle = keyboardFrame.CGRectValue()
    let keyboardHeight = keyboardRectangle.height
    editorBottomCT.constant = keyboardHeight
}

extension:

    private extension Selector {

    static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(_:)) 
}

git am error: "patch does not apply"

What is a patch?

A patch is little more (see below) than a series of instructions: "add this here", "remove that there", "change this third thing to a fourth". That's why git tells you:

The copy of the patch that failed is found in:
c:/.../project2/.git/rebase-apply/patch

You can open that patch in your favorite viewer or editor, open the files-to-be-changed in your favorite editor, and "hand apply" the patch, using what you know (and git does not) to figure out how "add this here" is to be done when the files-to-be-changed now look little or nothing like what they did when they were changed earlier, with those changes delivered to you as a patch.

A little more

A three-way merge introduces that "little more" information than the plain "series of instructions": it tells you what the original version of the file was as well. If your repository has the original version, your git can compare what you did to a file, to what the patch says to do to the file.

As you saw above, if you request the three-way merge, git can't find the "original version" in the other repository, so it can't even attempt the three-way merge. As a result you get no conflict markers, and you must do the patch-application by hand.

Using --reject

When you have to apply the patch by hand, it's still possible that git can apply most of the patch for you automatically and leave only a few pieces to the entity with the ability to reason about the code (or whatever it is that needs patching). Adding --reject tells git to do that, and leave the "inapplicable" parts of the patch in rejection files. If you use this option, you must still hand-apply each failing patch, and figure out what to do with the rejected portions.

Once you have made the required changes, you can git add the modified files and use git am --continue to tell git to commit the changes and move on to the next patch.

What if there's nothing to do?

Since we don't have your code, I can't tell if this is the case, but sometimes, you wind up with one of the patches saying things that amount to, e.g., "fix the spelling of a word on line 42" when the spelling there was already fixed.

In this particular case, you, having looked at the patch and the current code, should say to yourself: "aha, this patch should just be skipped entirely!" That's when you use the other advice git already printed:

If you prefer to skip this patch, run "git am --skip" instead.

If you run git am --skip, git will skip over that patch, so that if there were five patches in the mailbox, it will end up adding just four commits, instead of five (or three instead of five if you skip twice, and so on).

Any way to replace characters on Swift String?

You can use this:

let s = "This is my string"
let modified = s.replace(" ", withString:"+")    

If you add this extension method anywhere in your code:

extension String
{
    func replace(target: String, withString: String) -> String
    {
       return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
    }
}

Swift 3:

extension String
{
    func replace(target: String, withString: String) -> String
    {
        return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
    }
}

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

How to "properly" print a list?

Using .format for string formatting,

mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))

Output:

[x, 3, b]

Explanation:

  1. map is used to map each element of the list to string type.
  2. The elements are joined together into a string with , as separator.
  3. We use [ and ] in the print statement to show the list braces.

Reference: .format for string formatting PEP-3101

Download file from an ASP.NET Web API method using AngularJS

Send your file as a base64 string.

 var element = angular.element('<a/>');
                         element.attr({
                             href: 'data:attachment/csv;charset=utf-8,' + encodeURI(atob(response.payload)),
                             target: '_blank',
                             download: fname
                         })[0].click();

If attr method not working in Firefox You can also use javaScript setAttribute method

How to write text in ipython notebook?

Simply Enter Esc and type m it will convert to text cell.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

Execute this code on a good server which will provide you the complete rights for PUBLIC role. Copy the output and paste to the server with the issue. Execute. Try logging in again. It fixed our problem.

SELECT  SDP.state_desc ,
        SDP.permission_name ,
        SSU.[name] AS "Schema" ,
        SSO.[name] ,
        SSO.[type]
FROM    sys.sysobjects SSO
        INNER JOIN sys.database_permissions SDP ON SSO.id = SDP.major_id
        INNER JOIN sys.sysusers SSU ON SSO.uid = SSU.uid
ORDER BY SSU.[name] ,
        SSO.[name]

Java - escape string to prevent SQL injection

If you are using PL/SQL you can also use DBMS_ASSERT it can sanitize your input so you can use it without worrying about SQL injections.

see this answer for instance: https://stackoverflow.com/a/21406499/1726419

laravel 5 : Class 'input' not found

In larvel => 6 Version:

Input no longer exists In larvel 6,7,8 Version. Use Request instead of Input.

Based on the Laravel docs, since version 6.x Input has been removed.

The Input Facade

Likelihood Of Impact: Medium

The Input facade, which was primarily a duplicate of the Request facade, has been removed. If you are using the Input::get method, you should now call the Request::input method. All other calls to the Input facade may simply be updated to use the Request facade.

use Illuminate\Support\Facades\Request;
..
..
..
 public function functionName(Request $request)
    {
        $searchInput = $request->q;
}

Proper way of checking if row exists in table in PL/SQL block

IMO code with a stand-alone SELECT used to check to see if a row exists in a table is not taking proper advantage of the database. In your example you've got a hard-coded ID value but that's not how apps work in "the real world" (at least not in my world - yours may be different :-). In a typical app you're going to use a cursor to find data - so let's say you've got an app that's looking at invoice data, and needs to know if the customer exists. The main body of the app might be something like

FOR aRow IN (SELECT * FROM INVOICES WHERE DUE_DATE < TRUNC(SYSDATE)-60)
LOOP
  -- do something here
END LOOP;

and in the -- do something here you want to find if the customer exists, and if not print an error message.

One way to do this would be to put in some kind of singleton SELECT, as in

-- Check to see if the customer exists in PERSON

BEGIN
  SELECT 'TRUE'
    INTO strCustomer_exists
    FROM PERSON
    WHERE PERSON_ID = aRow.CUSTOMER_ID;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    strCustomer_exists := 'FALSE';
END;

IF strCustomer_exists = 'FALSE' THEN
  DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
END IF;

but IMO this is relatively slow and error-prone. IMO a Better Way (tm) to do this is to incorporate it in the main cursor:

FOR aRow IN (SELECT i.*, p.ID AS PERSON_ID
               FROM INVOICES i
               LEFT OUTER JOIN PERSON p
                 ON (p.ID = i.CUSTOMER_PERSON_ID)
               WHERE DUE_DATA < TRUNC(SYSDATE)-60)
LOOP
  -- Check to see if the customer exists in PERSON

  IF aRow.PERSON_ID IS NULL THEN
    DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
  END IF;
END LOOP;

This code counts on PERSON.ID being declared as the PRIMARY KEY on PERSON (or at least as being NOT NULL); the logic is that if the PERSON table is outer-joined to the query, and the PERSON_ID comes up as NULL, it means no row was found in PERSON for the given CUSTOMER_ID because PERSON.ID must have a value (i.e. is at least NOT NULL).

Share and enjoy.

What version of Java is running in Eclipse?

try this :

public class vm
{
  public static void main(String[] args)
  {
      System.getProperty("sun.arch.data.model") 
  }
}

compile and run. it will return either 32 or 64 as per your java version . . .

Get the new record primary key ID from MySQL insert query?

If you need the value before insert a row:

CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
    RETURNS BIGINT
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN

    DECLARE Value BIGINT;

    SELECT
        AUTO_INCREMENT INTO Value
    FROM
        information_schema.tables
    WHERE
        table_name = TableName AND
        table_schema = DATABASE();

    RETURN Value;

END

You can use this in a insert:

INSERT INTO
    document (Code, Title, Body)
VALUES (                
    sha1( concat (convert ( now() , char), ' ',   getAutoincrementalNextval ('document') ) ),
    'Title',
    'Body'
);

Initializing C# auto-properties

In the default constructor (and any non-default ones if you have any too of course):

public foo() {
    Bar = "bar";
}

This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.

how to convert a string date to date format in oracle10g

You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:

SELECT TO_CHAR(
         TO_DATE('15/August/2009,4:30 PM'
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM DUAL;

15-08-2009

For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:

SELECT TO_CHAR(
         TO_DATE(MYDATESTRING
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM MYTABLE;

Trigger a keypress/keydown/keyup event in JS/jQuery?

I thought I would draw your attention that in the specific context where a listener was defined within a jQuery plugin, then the only thing that successfully simulated the keypress event for me, eventually caught by that listener, was to use setTimeout(). e.g.

setTimeout(function() { $("#txtName").keypress() } , 1000);

Any use of $("#txtName").keypress() was ignored, although placed at the end of the .ready() function. No particular DOM supplement was being created asynchronously anyway.

How do I make a burn down chart in Excel?

But why would you use excel when you could do it all online and have your boss check your dynamic link.

We are using this new tool since last week. http://www.burndown-charts.com/

What I do is I send my boss the link to my chart and he plays around with the links to see if we will be on time...

http://www.burndown-charts.com/teams/dreamteam/sprints/prototype-x

Printing the value of a variable in SQL Developer

SQL Developer seems to only output the DBMS_OUTPUT text when you have explicitly turned on the DBMS_OUTPUT window pane.

Go to (Menu) VIEW -> Dbms_output to invoke the pane.

Click on the Green Plus sign to enable output for your connection and then run the code.

EDIT: Don't forget to set the buffer size according to the amount of output you are expecting.

How to get the URL without any parameters in JavaScript?

Every answer is rather convoluted. Here:

var url = window.location.href.split('?')[0];

Even if a ? isn't present, it'll still return the first argument, which will be your full URL, minus query string.

It's also protocol-agnostic, meaning you could even use it for things like ftp, itunes.etc.

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

You can't get latitude/longitude from autocomplete API since the data generated by google from that API doesn't contain latitude and logitude field. Example:-

{
   "predictions" : [
      {
         "description" : "IIT Mumbai, Mumbai, Maharashtra, India",
         "id" : "ac3235cda973818a89b5fe21ad0f5261ac9b6723",
         "matched_substrings" : [
            {
               "length" : 10,
               "offset" : 0
            }
         ],
         "reference" : "CkQ0AAAAHWg-RSngiYHHdz_yqyFKmfSoBwT-_PW0k8qQDhsbiVrk7BlPHCyJb58OthledMUTGYS5Vhec1Zj2L7w9Rq0zDxIQrbn05RX1QgWHkSXsmTk1TRoU45APW2BBRIUsA3t6XBy_8s0BPPA",
         "terms" : [
            {
               "offset" : 0,
               "value" : "IIT Mumbai"
            },
            {
               "offset" : 12,
               "value" : "Mumbai"
            },
            {
               "offset" : 20,
               "value" : "Maharashtra"
            },
            {
               "offset" : 33,
               "value" : "India"
            }
         ],
         "types" : [ "establishment", "geocode" ]
      }
   ],
   "status" : "OK"
}

You can use the Google API to get the Longitude and Latitude from your address. As you already said, you should implement a hidden field where the result should be inserted. Then you can save the location together with the coordinates.

e.g https://maps.googleapis.com/maps/api/geocode/json?address=IIT%20Area,%20Mumbai,%20Maharashtra,%20India&sensor=false

I recently implemented this function in one of my projects:

function getLatLngFromAddress(city, country){

  var address = city +", "+ country;
  var geocoder = new google.maps.Geocoder();

  geocoder.geocode( { 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
      $('#latitude').val(results[0].geometry.location.Pa);
      $('#longitude').val(results[0].geometry.location.Qa);

    } else {
      console.log("Geocode was not successful for the following reason: " + status);
    }
  });
}

Calculating and printing the nth prime number

public class prime{
    public static void main(String ar[])
    {
      int count;
      int no=0;
      for(int i=0;i<1000;i++){
        count=0;
        for(int j=1;j<=i;j++){

        if(i%j==0){
          count++;
         }
        }
        if(count==2){
          no++;
          if(no==Integer.parseInt(ar[0])){
            System.out.println(no+"\t"+i+"\t") ;
          }
        }
      }
    }
}

assignment operator overloading in c++

#include<iostream>

using namespace std;

class employee
{
    int idnum;
    double salary;
    public:
        employee(){}

        employee(int a,int b)
        {
            idnum=a;
            salary=b;
        }

        void dis()
        {
            cout<<"1st emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl<<endl;
        }

        void operator=(employee &emp)
        {
            idnum=emp.idnum;
            salary=emp.salary;
        }

        void show()
        {
            cout<<"2nd emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl;
        }
};

main()
{
    int a;
    double b;

    cout<<"enter id num and salary"<<endl;
    cin>>a>>b;
    employee e1(a,b);
    e1.dis();
    employee e2;
    e2=e1;
    e2.show();  
}

Find duplicate values in R

You could use table, i.e.

n_occur <- data.frame(table(vocabulary$id))

gives you a data frame with a list of ids and the number of times they occurred.

n_occur[n_occur$Freq > 1,]

tells you which ids occurred more than once.

vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]

returns the records with more than one occurrence.

C++ pointer to objects

If you have defined a method inside your class as static, this is actually possible.

    class myClass
    {
    public:
        static void saySomething()
        {
            std::cout << "This is a static method!" << std::endl;
        }
    }; 

And from main, you declare a pointer and try to invoke the static method.

    myClass * pmyClass;
    pmyClass->saySomething();

/*    
Output:
This is a static method!
*/

This works fine because static methods do not belong to a specific instance of the class and they are not allocated as a part of any instance of the class.

Read more on static methods here: http://en.wikipedia.org/wiki/Static_method#Static_methods

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

shareViewPager?.setOnTouchListener(object :View.OnTouchListener{
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                for (PAGE in 0..shareViewPager.adapter!!.count){
                    if (shareViewPager.currentItem==PAGE){
                        shareViewPager.setCurrentItem(PAGE-1,false)
                        shareViewPager.setCurrentItem(PAGE,false)
                    }}
                return true
            }

        })

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

ALTER TABLE public.contract_termination_requests
ALTER COLUMN management_company_id DROP NOT NULL;

Call PHP function from Twig template

While I agree with the comments about passing in variables from your controller you can also register undefined functions when setting up the twig environment

$twig->registerUndefinedFunctionCallback(function ($name) {
        // security
        $allowed = false;
        switch ($name) {
            // example of calling a wordpress function
            case 'get_admin_page_title':
                $allowed = true;
                break;
        }

        if ($allowed && function_exists($name)) {
            return new Twig_Function_Function($name);
        }

        return false;
    });

This is from the Twig recipe page

Haven't tried calling a function on an object as the original question requested

How can I add new dimensions to a Numpy array?

I followed this approach:

import numpy as np
import cv2

ls = []

for image in image_paths:
    ls.append(cv2.imread('test.jpg'))

img_np = np.array(ls) # shape (100, 480, 640, 3)
img_np = np.rollaxis(img_np, 0, 4) # shape (480, 640, 3, 100).

Passing multiple variables to another page in url

from php.net

Warning The superglobals $_GET and $_REQUEST are already decoded. Using urldecode() on an element in $_GET or $_REQUEST could have unexpected and dangerous results.

link: http://php.net/manual/en/function.urldecode.php

be careful.

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

"FATAL: Module not found error" using modprobe

The best thing is to actually use the kernel makefile to install the module:

Here is are snippets to add to your Makefile

around the top add:

PWD=$(shell pwd)
VER=$(shell uname -r)
KERNEL_BUILD=/lib/modules/$(VER)/build
# Later if you want to package the module binary you can provide an INSTALL_ROOT
# INSTALL_ROOT=/tmp/install-root

around the end add:

install:
        $(MAKE) -C $(KERNEL_BUILD) M=$(PWD) \
           INSTALL_MOD_PATH=$(INSTALL_ROOT) modules_install

and then you can issue

    sudo make install

this will put it either in /lib/modules/$(uname -r)/extra/

or /lib/modules/$(uname -r)/misc/

and run depmod appropriately

Prevent WebView from displaying "web page not available"

Perhaps I misunderstand the question, but it sounds like you're saying you get the error received callback, and you just are asking what is the best way to not show the error? Why don't you just either remove the web view from the screen and/or show another view on top of it?

Unable to copy ~/.ssh/id_rsa.pub

This was too good of an answer not to post it here. It's from a Gilles, a fellow user from askubuntu:

The clipboard is provided by the X server. It doesn't matter whether the server is headless or not, what matters is that your local graphical session is available to programs running on the remote machine. Thanks to X's network-transparent design, this is possible.

I assume that you're connecting to the remote server with SSH from a machine running Linux. Make sure that X11 forwarding is enabled both in the client configuration and in the server configuration. In the client configuration, you need to have the line ForwardX11 yes in ~/.ssh/config to have it on by default, or pass the option -X to the ssh command just for that session. In the server configuration, you need to have the line X11Forwarding yes in /etc/ssh/sshd_config (it is present by default on Ubuntu).

To check whether X11 forwarding is enabled, look at the value of the DISPLAY environment variable: echo $DISPLAY. You should see a value like localhost:10 (applications running on the remote machine are told to connect to a display running on the same machine, but that display connection is in fact forwarded by SSH to your client-side display). Note that if DISPLAY isn't set, it's no use setting it manually: the environment variable is always set correctly if the forwarding is in place. If you need to diagnose SSH connection issues, pass the option -vvv to ssh to get a detailed trace of what's happening.

If you're connecting through some other means, you may or may not be able to achieve X11 forwarding. If your client is running Windows, PuTTY supports X11 forwarding; you'll have to run an X server on the Windows machine such as Xming.

By Gilles from askubuntu

Loading inline content using FancyBox

Just something I found for Wordpress users,

As obvious as it sounds, If your div is returning some AJAX content based on say a header that would commonly link out to a new post page, some tutorials will say to return false since you're returning the post data on the same page and the return would prevent the page from moving. However if you return false, you also prevent Fancybox2 from doing it's thing as well. I spent hours trying to figure that stupid simple thing out.

So for these kind of links, just make sure that the href property is the hashed (#) div you wish to select, and in your javascript, make sure that you do not return false since you no longer will need to.

Simple I know ^_^

Adding a Time to a DateTime in C#

Combine both. The Date-Time-Picker does support picking time, too.

You just have to change the Format-Property and maybe the CustomFormat-Property.

How do I write a Windows batch script to copy the newest file from a directory?

To allow this to work with filenames using spaces, a modified version of the accepted answer is needed:

FOR /F "delims=" %%I IN ('DIR . /B /O:-D') DO COPY "%%I" <<NewDir>> & GOTO :END
:END

Running a simple shell script as a cronjob

What directory is file.txt in? cron runs jobs in your home directory, so unless your script cds somewhere else, that's where it's going to look for/create file.txt.

EDIT: When you refer to a file without specifying its full path (e.g. file.txt, as opposed to the full path /home/myUser/scripts/file.txt) in shell, it's taken that you're referring to a file in your current working directory. When you run a script (whether interactively or via crontab), the script's working directory has nothing at all to do with the location of the script itself; instead, it's inherited from whatever ran the script.

Thus, if you cd (change working directory) to the directory the script's in and then run it, file.txt will refer to a file in the same directory as the script. But if you don't cd there first, file.txt will refer to a file in whatever directory you happen to be in when you ran the script. For instance, if your home directory is /home/myUser, and you open a new shell and immediately run the script (as scripts/test.sh or /home/myUser/scripts/test.sh; ./test.sh won't work), it'll touch the file /home/myUser/file.txt because /home/myUser is your current working directory (and therefore the script's).

When you run a script from cron, it does essentially the same thing: it runs it with the working directory set to your home directory. Thus all file references in the script are taken relative to your home directory, unless the script cds somewhere else or specifies an absolute path to the file.

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

Like many many people, I have had the same problem. Although the user is set to use mysql_native_password, and I can connect from the command line, the only way I could get mysqli() to connect is to add

default-authentication-plugin=mysql_native_password

to the [mysqld] section of, in my setup on ubuntu 19.10, /etc/mysql/mysql.conf.d/mysqld.cnf

jquery loop on Json data using $.each

getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.

How can I list ALL DNS records?

host -a works well, similar to dig any.

EG:

$ host -a google.com
Trying "google.com"
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 10403
;; flags: qr rd ra; QUERY: 1, ANSWER: 18, AUTHORITY: 0, ADDITIONAL: 0


;; QUESTION SECTION:
;google.com.            IN  ANY

;; ANSWER SECTION:
google.com.     1165    IN  TXT "v=spf1 include:_spf.google.com ip4:216.73.93.70/31 ip4:216.73.93.72/31 ~all"
google.com.     53965   IN  SOA ns1.google.com. dns-admin.google.com. 2014112500 7200 1800 1209600 300
google.com.     231 IN  A   173.194.115.73
google.com.     231 IN  A   173.194.115.78
google.com.     231 IN  A   173.194.115.64
google.com.     231 IN  A   173.194.115.65
google.com.     231 IN  A   173.194.115.66
google.com.     231 IN  A   173.194.115.67
google.com.     231 IN  A   173.194.115.68
google.com.     231 IN  A   173.194.115.69
google.com.     231 IN  A   173.194.115.70
google.com.     231 IN  A   173.194.115.71
google.com.     231 IN  A   173.194.115.72
google.com.     128 IN  AAAA    2607:f8b0:4000:809::1001
google.com.     40766   IN  NS  ns3.google.com.
google.com.     40766   IN  NS  ns4.google.com.
google.com.     40766   IN  NS  ns1.google.com.
google.com.     40766   IN  NS  ns2.google.com.

Creating a "logical exclusive or" operator in Java

Logical exclusive-or in Java is called !=. You can also use ^ if you want to confuse your friends.