Programs & Examples On #Comment conventions

How to "comment-out" (add comment) in a batch/cmd?

The :: instead of REM was preferably used in the days that computers weren't very fast. REM'ed line are read and then ingnored. ::'ed line are ignored all the way. This could speed up your code in "the old days". Further more after a REM you need a space, after :: you don't.

And as said in the first comment: you can add info to any line you feel the need to

SET DATETIME=%DTS:~0,8%-%DTS:~8,6% ::Makes YYYYMMDD-HHMMSS

As for the skipping of parts. Putting REM in front of every line can be rather time consuming. As mentioned using GOTO to skip parts is an easy way to skip large pieces of code. Be sure to set a :LABEL at the point you want the code to continue.

SOME CODE

GOTO LABEL  ::REM OUT THIS LINE TO EXECUTE THE CODE BETWEEN THIS GOTO AND :LABEL

SOME CODE TO SKIP
.
LAST LINE OF CODE TO SKIP

:LABEL
CODE TO EXECUTE

Use index in pandas to plot data

Marius's answer worked perfectly for me:

df.reset_index() sets the index as the first column, with the column label "index." You can now use the index as an axis for plotting, as described in his answer:

monthly_mean.reset_index().plot(x='index', y='A')

However, this does not change the original dataframe. The original dataframe will be unchanged unless it is set using df = df.reset_index().

example:

df.reset_index()
print(df)
        COF    TSF    PSF
3.0   0.946  0.914  0.966
4.0   0.963  0.940  0.976
6.0   0.978  0.965  0.987
8.0   0.989  0.984  0.995
10.0  1.000  1.000  1.000
12.0  1.004  1.013  1.009
15.0  1.013  1.026  1.012
17.0  1.019  1.037  1.017
20.0  1.024  1.045  1.020
25.0  1.030  1.057  1.026
30.0  1.034  1.065  1.030
35.0  1.037  1.069  1.031
40.0  1.037  1.068  1.030
60.0  1.037  1.068  1.030
df = df.reset_index()
print(df)
    index    COF    TSF    PSF
0     3.0  0.946  0.914  0.966
1     4.0  0.963  0.940  0.976
2     6.0  0.978  0.965  0.987
3     8.0  0.989  0.984  0.995
4    10.0  1.000  1.000  1.000
5    12.0  1.004  1.013  1.009
6    15.0  1.013  1.026  1.012
7    17.0  1.019  1.037  1.017
8    20.0  1.024  1.045  1.020
9    25.0  1.030  1.057  1.026
10   30.0  1.034  1.065  1.030
11   35.0  1.037  1.069  1.031
12   40.0  1.037  1.068  1.030
13   60.0  1.037  1.068  1.030

See: DataFrame.reset_index and DataFrame.set_index

How to validate a credit card number

Luhn's algorithm is used for adding validation of credit and debit card numbers. This JavaScript function should work out.

function validate_creditcardnumber(inputNum) {
    var digit, digits, flag, sum, _i, _len;
    flag = true;
    sum = 0;
    digits = (inputNum + '').split('').reverse();
    for (_i = 0, _len = digits.length; _i < _len; _i++) {
      digit = digits[_i];
      digit = parseInt(digit, 10);
      if ((flag = !flag)) {
        digit *= 2;
      }
      if (digit > 9) {
        digit -= 9;
      }
      sum += digit;
    }
    return sum % 10 === 0;
  };

Resize Cross Domain Iframe Height

Minimum crossdomain set I've used for embedding fitted single iframe on a page.

On embedding page (containing iframe):

<iframe frameborder="0" id="sizetracker" src="http://www.hurtta.com/Services/SizeTracker/DE" width="100%"></iframe>
<script type="text/javascript">
  // Create browser compatible event handler.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
  // Listen for a message from the iframe.
  eventer(messageEvent, function(e) {
    if (isNaN(e.data)) return;

    // replace #sizetracker with what ever what ever iframe id you need
    document.getElementById('sizetracker').style.height = e.data + 'px';

  }, false);
</script>

On embedded page (iframe):

<script type="text/javascript">
function sendHeight()
{
    if(parent.postMessage)
    {
        // replace #wrapper with element that contains 
        // actual page content
        var height= document.getElementById('wrapper').offsetHeight;
        parent.postMessage(height, '*');
    }
}

// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen for a message from the iframe.
eventer(messageEvent, function(e) {

    if (isNaN(e.data)) return;

    sendHeight();

}, 
false);
</script>

Reactjs convert html string to jsx

i found this js fiddle. this works like this

function unescapeHTML(html) {
    var escapeEl = document.createElement('textarea');
    escapeEl.innerHTML = html;
    return escapeEl.textContent;
}

<textarea className="form-control redactor"
                          rows="5" cols="9"
                          defaultValue={unescapeHTML(this.props.destination.description)}
                          name='description'></textarea>

jsfiddle link

Show a leading zero if a number is less than 10

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}

EDIT:

Meanwhile there is a native JS function that does that. See String#padStart

_x000D_
_x000D_
console.log(String(5).padStart(2, '0'));
_x000D_
_x000D_
_x000D_

Hook up Raspberry Pi via Ethernet to laptop without router?

No router + no screen + regular Ethernet cable + RPI 2 + Raspbian Lite 2018-11-13 + Ubuntu 18.10

First we must enable the SSH server on the Pi, which is disabled by default for security.

If you already have a shell on the Pi through a non-SSH method such as screen + keyboard or UART (see below), just run:

sudo systemctl enable ssh
sudo service sshd start

as explained at: https://raspberrypi.stackexchange.com/questions/58478/ssh-not-working-with-fresh-install This persists across boots.

Otherwise, insert he SD card on your host, and create a magic empty file named ssh file in the boot/ partition.

On Ubuntu hosts, it gets mounted automatically and you can do just:

sudo touch /media/$USER/boot/ssh

which you can confirm with:

lsblk

which contains:

mmcblk0     179:0    0  14.4G  0 disk
+-mmcblk0p1 179:1    0  43.9M  0 part /media/ciro/boot
+-mmcblk0p2 179:2    0  14.4G  0 part /media/ciro/rootfs

If you don't enable the SSHD daemon on the Pi then SSH connection will fail with:

ssh: connect to host 10.42.0.160 port 22: Connection refused

when we try it later on.

After enabling the SSH server

Next, boot the Pi, and link an Ethernet cable from your laptop directly to the Pi:

enter image description here

On Ubuntu 17.04 to work around this bug as mentioned on this answer you first need:

sudo apt-get install dnsmasq-base

On the host, open the network manager:

nm-connection-editor

And go:

  1. + sign (Add a new connection)
  2. Ethernet
  3. Create
  4. IPv4 Settings
  5. Method: Shared to other computers
  6. Set a good name for it
  7. Save

enter image description here

Find the IP of the Pi on host:

cat /var/lib/misc/dnsmasq.leases

outputs something like:

1532204957 b8:27:eb:0c:1f:69 10.42.0.160 raspberrypi 01:b8:27:eb:0c:1f:69

10.42.0.160 is the IP, then as usual:

ssh [email protected]

I also have the following in my .bashrc:

piip() ( cat /var/lib/misc/dnsmasq.leases | cut -d ' ' -f 3; )
pissh() ( sshpass -p raspberry ssh "pi@$(piip)"; )

From inside the Pi, notice that it can access the internet normally through your host's other interfaces:

ping google.com

For example on my laptop, the Pi takes up the Ethernet, but the host is also connected to the internet through WiFi.

The crossover cable is not required if the host network card supports Auto MDI-X. This is the case for most recent hardware, including for example the 2012 Lenovo T430 I tested with, which has an "Intel® 82579LM Gigabit Network Connection" which documents support for Auto MDI-X.

Now you can also:

UART serial USB converter

This is an alternative to SSH if you just want to get a shell on the Pi: https://en.wikipedia.org/wiki/Serial_port

This does not use SSH or networking itself, but rather the older, simpler, more direct, more reliable, lower bandwidth, lower distance serial interface. The Pi won't have access to the Internet with this method.

Desktop computers still have a serial port which you can connect directly wire to wire with the Pi, but these are hidden in most laptops, and so we need to buy a cheap USB adapter. Here I've used: https://www.amazon.co.uk/gp/product/B072K3Z3TL See also: https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux/367882#367882

First plug the SD card on the host, and edit the config.txt file present in the first partition to add:

enable_uart=1

as explained at: https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=141195

This first partition contains the bootloader, its configuration files and the (Linux / your) kernel, config.txt being one of them. The second partition contains the actual Linux root filesystem.

Now connect your computer to the Pi as:

enter image description here

You only need to attach 3 cables:

  • Ground to Ground
  • Tx on Pi to Rx on the USB to serial port
  • Rx on Pi to Tx on tye USB to serial port

This is also documented at: https://www.raspberrypi.org/documentation/usage/gpio/README.md

Be careful not to link the Ground to the 5V, I've already burned 2 UART to USB chips and a RPI UART by doing that!

You don't need to connect the 5V to the 5V at all. I think you can power your Pi like that, but I've read that this is a bad idea, just use the usual USB power source.

Finally, plug the USB side of the connector to your host computer, and get a shell with:

sudo apt install screen
sudo usermod -a -G dialout $USER
screen /dev/ttyUSB0 115200

Exit with Ctrl-A \.

Here is a video by Adafruit showing it: https://www.youtube.com/watch?v=zUBPeoLW16Q

See also

Similar question on RPI SE: https://raspberrypi.stackexchange.com/questions/3867/ssh-to-rpi-without-a-network-connection

Error "library not found for" after putting application in AdMob

Late for the answer but here are the list of things which I tried.So it will be in one place if anyone wants to try to fix the issue.

  1. Valid architecture = armv7 armv7s
  2. Build Active Architecture only = NO
  3. Target -> Build Settings ->Other Linker Flags = $(inherited)
  4. Target -> Build Settings ->Library Search Path = $(inherited)
  5. Product Clean
  6. Pod Update in terminal

don't fail jenkins build if execute shell fails

You can use the Text-finder Plugin. It will allow you to check the output console for an expression of your choice then mark the build as Unstable.

script to map network drive

Tomalak's answer worked great for me (+1)

I only needed to make alter it slightly for my purposes, and I didn't need a password - it's for corporate domain:

Option Explicit
Dim l: l = "Z:"
Dim s: s = "\\10.10.10.1\share"
Dim Network: Set Network = CreateObject("WScript.Network")
Dim CheckDrive: Set CheckDrive = Network.EnumNetworkDrives()
Dim DriveExists: DriveExists = False
Dim i

For i = 0 to CheckDrive.Count - 1
  If CheckDrive.Item(i) = l Then
    DriveExists = True
  End If
Next

If DriveExists = False Then
  Network.MapNetworkDrive l, s, False
Else
  MsgBox l + " Drive already mapped"
End If

Or if you want to disconnect the drive:

For i = 0 to CheckDrive.Count - 1
  If CheckDrive.Item(i) = l Then 
    WshNetwork.RemoveNetworkDrive CheckDrive.Item(i)
  End If
Next

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

You can set TextBox properties for setting negative number display and decimal places settings.

  1. Right-click the cell and then click Text Box Properties.
  2. Select Number, and in the Category field, click Currency.

enter image description here

How do I rotate the Android emulator display?

I have checked on Windows: Ctrl + F11 and Ctrl + F12 both are working to change the orientation of the Android simulator.

For other shortcut keys:

In the Eclipse toolbar go to "Help-->key Assist.. "

You can also use Ctrl + Shift + L here, so many shortcut keys of Eclipse are given.

How can I do a case insensitive string comparison?

This is not the best practice in .NET framework (4 & +) to check equality

String.Compare(x.Username, (string)drUser["Username"], 
                  StringComparison.OrdinalIgnoreCase) == 0

Use the following instead

String.Equals(x.Username, (string)drUser["Username"], 
                   StringComparison.OrdinalIgnoreCase) 

MSDN recommends:

  • Use an overload of the String.Equals method to test whether two strings are equal.
  • Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.

How to search through all Git and Mercurial commits in the repository for a certain string?

Don't know about git, but in Mercurial I'd just pipe the output of hg log to some sed/perl/whatever script to search for whatever it is you're looking for. You can customize the output of hg log using a template or a style to make it easier to search on, if you wish.

This will include all named branches in the repo. Mercurial does not have something like dangling blobs afaik.

Get SELECT's value and text in jQuery

$('select').val()  // Get's the value

$('select option:selected').val() ; // Get's the value

$('select').find('option:selected').val() ; // Get's the value

$('select option:selected').text()  // Gets you the text of the selected option

Check FIDDLE

Merge 2 DataTables and store in a new one

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);

The parameter TRUE preserve the changes.

For more details refer to MSDN.

Remove an item from an IEnumerable<T> collection

You can't. IEnumerable<T> can only be iterated.

In your second example, you can remove from original collection by iterating over a copy of it

foreach(var u in users.ToArray()) // ToArray creates a copy
{
   if(u.userId != 1233)
   {
        users.Remove(u);
   }
}

Using the GET parameter of a URL in JavaScript

You don't need to do anything special, actually. You can mix JavaScript and PHP together to get variables from PHP straight into JavaScript.

var param1val = '<?php echo $_GET['param1'] ?>';

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

Here is how i fixed it.

  1. Download https://bootstrap.pypa.io/get-pip.py
  2. Active your vitualenv
  3. Navigate to the get-pip.py file and type "python get-pip.py" without quote.

it will reinstall your pip within the environment and uninstall the previous version automatically.

now boom!! install whatever you like

MySQL - SELECT * INTO OUTFILE LOCAL ?

The path you give to LOAD DATA INFILE is for the filesystem on the machine where the server is running, not the machine you connect from. LOAD DATA LOCAL INFILE is for the client's machine, but it requires that the server was started with the right settings, otherwise it's not allowed. You can read all about it here: http://dev.mysql.com/doc/refman/5.0/en/load-data-local.html

As for SELECT INTO OUTFILE I'm not sure why there is not a local version, besides it probably being tricky to do over the connection. You can get the same functionality through the mysqldump tool, but not through sending SQL to the server.

FFmpeg: How to split video efficiently?

Didn't test ist, but this looks promising:

Basic stream segmenter

It is obviously splitting AVI into segments of same size, which implies these chunks don't loose quality or increase memory or must be recalculated.

It also uses the codec copy - does that mean it can handle very large streams ? Because this is my problem, i want to break down my avi so i could use a filter to get rid of the distorsion. But a whole avi runs for hours.

python's re: return True if string contains regex pattern

import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
  print 'matched'

How to insert a file in MySQL database?

The other answers will give you a good idea how to accomplish what you have asked for....

However

There are not many cases where this is a good idea. It is usually better to store only the filename in the database and the file on the file system.

That way your database is much smaller, can be transported around easier and more importantly is quicker to backup / restore.

What is the Maximum Size that an Array can hold?

This answer is about .NET 4.5

According to MSDN, the index for array of bytes cannot be greater than 2147483591. For .NET prior to 4.5 it also was a memory limit for an array. In .NET 4.5 this maximum is the same, but for other types it can be up to 2146435071.

This is the code for illustration:

    static void Main(string[] args)
    {
        // -----------------------------------------------
        // Pre .NET 4.5 or gcAllowVeryLargeObjects unset
        const int twoGig = 2147483591; // magic number from .NET

        var type = typeof(int);          // type to use
        var size = Marshal.SizeOf(type); // type size
        var num = twoGig / size;         // max element count

        var arr20 = Array.CreateInstance(type, num);
        var arr21 = new byte[num];

        // -----------------------------------------------
        // .NET 4.5 with x64 and gcAllowVeryLargeObjects set
        var arr451 = new byte[2147483591];
        var arr452 = Array.CreateInstance(typeof(int), 2146435071);
        var arr453 = new byte[2146435071]; // another magic number

        return;
    }

Append data frames together in a for loop

Again maRtin is correct but for this to work you have start with a dataframe that already has at least one column

model <- #some processing
df <- data.frame(col1=model)

for (i in 2:17)
{
     model <- # some processing
     nextcol <-  data.frame(model)
     colnames(nextcol) <- c(paste("col", i, sep="")) # rename the comlum
     df <- cbind(df, nextcol)
}

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

Go to Project pane> Android > Gradle Scripts and open "graddle-wrapper.properties" file check the distribution URL:

enter image description here

Go to your ".gradle/wrapper/dists/" folder and remove that file for me it was "gradle-5.6.4-all"

enter image description here

Then go back to android studio and click on File > Sync Project with Gradle Files. And it will start to download again

enter image description here

How to get response status code from jQuery.ajax?

You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts

It explains very basic knowledge that let you feel more comfortable with javascript.

You can do it with shorter version of ajax request, please see code above:

$.get("example.url.com", function(data) {
                console.log(data);
            }).done(function() {
               // TO DO ON DONE
            }).fail(function(data, textStatus, xhr) {
                 //This shows status code eg. 403
                 console.log("error", data.status);
                 //This shows status message eg. Forbidden
                 console.log("STATUS: "+xhr);
            }).always(function() {
                 //TO-DO after fail/done request.
                 console.log("ended");
            });

Example console output:

error 403 
STATUS: Forbidden 
ended

ASP.NET Core return JSON with status code

Controller action return types in ASP.NET Core web API 02/03/2020

6 minutes to read +2

By Scott Addie Link

Synchronous action

[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<Product> GetById(int id)
{
    if (!_repository.TryGetProduct(id, out var product))
    {
        return NotFound();
    }

    return product;
}

Asynchronous action

[HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<Product>> CreateAsync(Product product)
{
    if (product.Description.Contains("XYZ Widget"))
    {
        return BadRequest();
    }

    await _repository.AddProductAsync(product);

    return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}

What's the difference between the atomic and nonatomic attributes?

  • -Atomic means only one thread access the variable(static type).
  • -Atomic is thread safe.
  • -but it is slow in performance

How to declare:

As atomic is default so,

@property (retain) NSString *name;

AND in implementation file

self.name = @"sourov";

Suppose a task related to three properties are

 @property (retain) NSString *name;
 @property (retain) NSString *A;
 @property (retain) NSString *B;
 self.name = @"sourov";

All properties work parallelly (like asynchronously).

If you call "name" from thread A,

And

At the same time if you call

[self setName:@"Datta"]

from thread B,

Now If *name property is nonatomic then

  • It will return value "Datta" for A
  • It will return value "Datta" for B

Thats why non atomic is called thread unsafe But but it is fast in performance because of parallel execution

Now If *name property is atomic

  • It will ensure value "Sourov" for A
  • Then It will return value "Datta" for B

That's why atomic is called thread Safe and That's why it is called read-write safe

Such situation operation will perform serially. And Slow in performance

- Nonatomic means multiple thread access the variable(dynamic type).

- Nonatomic is thread unsafe.

- but it is fast in performance

-Nonatomic is NOT default behavior, we need to add nonatomic keyword in property attribute.

For In Swift Confirming that Swift properties are nonatomic in the ObjC sense. One reason is so you think about whether per-property atomicity is sufficient for your needs.

Reference: https://forums.developer.apple.com/thread/25642

Fro more info please visit the website http://rdcworld-iphone.blogspot.in/2012/12/variable-property-attributes-or.html

How to create a Jar file in Netbeans

Create a Java archive (.jar) file using NetBeans as follows:

  1. Right-click on the Project name
  2. Select Properties
  3. Click Packaging
  4. Check Build JAR after Compiling
  5. Check Compress JAR File
  6. Click OK to accept changes
  7. Right-click on a Project name
  8. Select Build or Clean and Build

Clean and Build will first delete build artifacts (such as .class files), whereas Build will retain any existing .class files, creating new versions necessary. To elucidate, imagine a project with two classes, A and B.

When built the first time, the IDE creates A.class and B.class. Now you delete B.java but don't clear out B.class. Executing Build should leave B.class in the build directory, and bundle it into the JAR. Selecting Clean and Build will delete B.class. Since B.java was deleted, no longer will B.class be bundled.

The JAR file is built. To view it inside NetBeans:

  1. Click the Files tab
  2. Expand Project name >> dist

Ensure files aren't being excluded when building the JAR file.

How do I create ColorStateList programmatically?

Sometimes this will be enough:

int colorInt = getResources().getColor(R.color.ColorVerificaLunes);
ColorStateList csl = ColorStateList.valueOf(colorInt);

nginx: send all requests to a single html page

Using just try_files didn't work for me - it caused a rewrite or internal redirection cycle error in my logs.

The Nginx docs had some additional details:

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

So I ended up using the following:

root /var/www/mysite;

location / {
    try_files $uri /base.html;
}

location = /base.html {
    expires 30s;
}

What is the proper way to check and uncheck a checkbox in HTML5?

In jQuery:

To check the checkbox:

$("#checkboxid").attr("checked","checked");

To uncheck the checkbox:

$("#checkboxid").removeAttr("checked");

The other answers hint at the solution and point you to documentation that after further digging will get you to this answer. Jukka K. Korpela has the reason this is the correct answer, basically I followed his link and then looked up the jQuery docs to get to that result. Just figured I'd save future people who find this article those extra steps.

What is ToString("N0") format?

Here is a good start maybe

Double.ToString()

Have a look in the examples for a number of different formating options Double.ToString(string)

Remove elements from collection while iterating

Old Timer Favorite (it still works):

List<String> list;

for(int i = list.size() - 1; i >= 0; --i) 
{
        if(list.get(i).contains("bad"))
        {
                list.remove(i);
        }
}

Benefits:

  1. It only iterates over the list once
  2. No extra objects created, or other unneeded complexity
  3. No problems with trying to use the index of a removed item, because... well, think about it!

Git checkout: updating paths is incompatible with switching branches

none of the above worked for me. My situation is slightly different, my remote branch is not at origin. but in a different repository.

git remote add remoterepo GIT_URL.git
git fetch remoterepo
git checkout -b branchname remoterepo/branchname

tip: if you don't see the remote branch in the following output git branch -v -a there is no way to check it out.

Confirmed working on 1.7.5.4

How can I see which Git branches are tracking which remote / upstream branch?

In case anyone's reading this and wanting to protect master with client-side branch protection,

git branch -vv | grep "^\*" |grep -E '\* master |origin\/master'

will return 0 if either the local checked-out branch or its upstream remote branch is master.

Just put this in your .git/hooks directory's pre-commit and update files accordingly and Bob is your father's brother.

Spring MVC: Complex object as GET @RequestParam

Since the question on how to set fields mandatory pops up under each post, I wrote a small example on how to set fields as required:

public class ExampleDTO {
    @NotNull
    private String mandatoryParam;

    private String optionalParam;
    
    @DateTimeFormat(iso = ISO.DATE) //accept Dates only in YYYY-MM-DD
    @NotNull
    private LocalDate testDate;

    public String getMandatoryParam() {
        return mandatoryParam;
    }
    public void setMandatoryParam(String mandatoryParam) {
        this.mandatoryParam = mandatoryParam;
    }
    public String getOptionalParam() {
        return optionalParam;
    }
    public void setOptionalParam(String optionalParam) {
        this.optionalParam = optionalParam;
    }
    public LocalDate getTestDate() {
        return testDate;
    }
    public void setTestDate(LocalDate testDate) {
        this.testDate = testDate;
    }
}

//Add this to your rest controller class
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String testComplexObject (@Valid ExampleDTO e){
    System.out.println(e.getMandatoryParam() + " " + e.getTestDate());
    return "Does this work?";
}

"Non-static method cannot be referenced from a static context" error

You need to correctly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference/call them you must do so via an instance. So you either want

public void loanItem() {
    this.media.setLoanItem("Yes");
}

or

public void loanItem(Media object) {
    object.setLoanItem("Yes");
}

depending on how you want to pass that instance around.

JS: Uncaught TypeError: object is not a function (onclick)

Since the behavior is kind of strange, I have done some testing on the behavior, and here's my result:

TL;DR

If you are:

  • In a form, and
  • uses onclick="xxx()" on an element
  • don't add id="xxx" or name="xxx" to that element
    • (e.g. <form><button id="totalbandwidth" onclick="totalbandwidth()">BAD</button></form> )

Here's are some test and their result:

Control sample (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

Add id to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button id="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add name to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button name="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add value to button (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <input type="button" value="totalbandwidth" onclick="totalbandwidth()" />SUCCESS
</form>
_x000D_
_x000D_
_x000D_

Add id to button, but not in a form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<button id="totalbandwidth" onclick="totalbandwidth()">SUCCESS</button>
_x000D_
_x000D_
_x000D_

Add id to another element inside the form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("The answer is no, the span will not affect button"); }
_x000D_
<form onsubmit="return false;">
<span name="totalbandwidth" >Will this span affect button? </span>
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

Display a decimal in scientific notation

from decimal import Decimal

'%.2E' % Decimal('40800000000.00000000000000')

# returns '4.08E+10'

In your '40800000000.00000000000000' there are many more significant zeros that have the same meaning as any other digit. That's why you have to tell explicitly where you want to stop.

If you want to remove all trailing zeros automatically, you can try:

def format_e(n):
    a = '%E' % n
    return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]

format_e(Decimal('40800000000.00000000000000'))
# '4.08E+10'

format_e(Decimal('40000000000.00000000000000'))
# '4E+10'

format_e(Decimal('40812300000.00000000000000'))
# '4.08123E+10'

How to resolve TypeError: can only concatenate str (not "int") to str

Change secret_string += str(chr(char + 7429146))

To secret_string += chr(ord(char) + 7429146)

ord() converts the character to its Unicode integer equivalent. chr() then converts this integer into its Unicode character equivalent.

Also, 7429146 is too big of a number, it should be less than 1114111

Is __init__.py not required for packages in Python 3.3+

Overview

@Mike's answer is correct but too imprecise. It is true that Python 3.3+ supports Implicit Namespace Packages that allows it to create a package without an __init__.py file. This is called a namespace package in contrast to a regular package which does have an __init__.py file (empty or not empty).

However, creating a namespace package should ONLY be done if there is a need for it. For most use cases and developers out there, this doesn't apply so you should stick with EMPTY __init__.py files regardless.

Namespace package use case

To demonstrate the difference between the two types of python packages, lets look at the following example:

google_pubsub/              <- Package 1
    google/                 <- Namespace package (there is no __init__.py)
        cloud/              <- Namespace package (there is no __init__.py)
            pubsub/         <- Regular package (with __init__.py)
                __init__.py <- Required to make the package a regular package
                foo.py

google_storage/             <- Package 2
    google/                 <- Namespace package (there is no __init__.py)
        cloud/              <- Namespace package (there is no __init__.py)
            storage/        <- Regular package (with __init__.py)
                __init__.py <- Required to make the package a regular package
                bar.py

google_pubsub and google_storage are separate packages but they share the same namespace google/cloud. In order to share the same namespace, it is required to make each directory of the common path a namespace package, i.e. google/ and cloud/. This should be the only use case for creating namespace packages, otherwise, there is no need for it.

It's crucial that there are no __init__py files in the google and google/cloud directories so that both directories can be interpreted as namespace packages. In Python 3.3+ any directory on the sys.path with a name that matches the package name being looked for will be recognized as contributing modules and subpackages to that package. As a result, when you import both from google_pubsub and google_storage, the Python interpreter will be able to find them.

This is different from regular packages which are self-contained meaning all parts live in the same directory hierarchy. When importing a package and the Python interpreter encounters a subdirectory on the sys.path with an __init__.py file, then it will create a single directory package containing only modules from that directory, rather than finding all appropriately named subdirectories outside that directory. This is perfectly fine for packages that don't want to share a namespace. I highly recommend taking a look at Traps for the Unwary in Python’s Import System to get a better understanding of how Python importing behaves with regular and namespace package and what __init__.py traps to watch out for.

Summary

  • Only skip __init__.py files if you want to create namespace packages. Only create namespace packages if you have different libraries that reside in different locations and you want them each to contribute a subpackage to the parent package, i.e. the namespace package.
  • Keep on adding empty __init__py to your directories because 99% of the time you just want to create regular packages. Also, Python tools out there such as mypy and pytest require empty __init__.py files to interpret the code structure accordingly. This can lead to weird errors if not done with care.

Resources

My answer only touches the surface of how regular packages and namespace packages work so take a look at the following resources for further information:

"Android library projects cannot be launched"?

With Me I had the library ticked under Eclipse>Project Properties>Android what I just did was uncheck the ticked library.

Should image size be defined in the img tag height/width attributes or in CSS?

Option a. Simple straight fwd. What you see is what you get easy to make calculations.

Option b. Too messy to do this inline unless you want to have a site that can stretch. IE if you used the with:86em however modern browsers seem to handle this functionally adequately for my purposes.. . Personally the only time that i would use something like this is if i were to create a thumbnails catalogue.

/*css*/
ul.myThumbs{}
ul.myThumbs li {float:left; width:50px;}
ul.myThumbs li img{width:50px; height:50px;border:0;}

<!--html-->
<ul><li>
<img src="~/img/products/thumbs/productid.jpg" alt="" />
</li></ul>

Option c. Too messy to maintain.

How to POST request using RestSharp

This way works fine for me:

var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
                .AddBody(BODY);

var response = Client.Execute(request);

// Handle response errors
HandleResponseErrors(response);

if (Errors.Length == 0)
{ }
else
{ }

Hope this helps! (Although it is a bit late)

Return Index of an Element in an Array Excel VBA

The only (& even though cumbersome but yet expedient / relatively quick) way I can do this, is to concatenate the any-dimensional array, and reduce it to 1 dimension, with "/[column number]//\|" as the delimiter.

& use a single-cell result multiple lookupall macro function on the this 1-d column.

& then index match to pull out the positions. (usuing multiple find match)

That way you get all matching occurrences of the element/string your looking for, in the original any-dimension array, and their positions. In one cell.

Wish I could write a macro / function for this entire process. It would save me more fuss.

How do I make a LinearLayout scrollable?

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|left"
        android:orientation="vertical">

        Your views go here...

    </LinearLayout>

</ScrollView>

Java JTextField with input hint

You could create your own:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;

public class Main {

  public static void main(String[] args) {

    final JFrame frame = new JFrame();

    frame.setLayout(new BorderLayout());

    final JTextField textFieldA = new HintTextField("A hint here");
    final JTextField textFieldB = new HintTextField("Another hint here");

    frame.add(textFieldA, BorderLayout.NORTH);
    frame.add(textFieldB, BorderLayout.CENTER);
    JButton btnGetText = new JButton("Get text");

    btnGetText.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        String message = String.format("textFieldA='%s', textFieldB='%s'",
            textFieldA.getText(), textFieldB.getText());
        JOptionPane.showMessageDialog(frame, message);
      }
    });

    frame.add(btnGetText, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.pack();
  }
}

class HintTextField extends JTextField implements FocusListener {

  private final String hint;
  private boolean showingHint;

  public HintTextField(final String hint) {
    super(hint);
    this.hint = hint;
    this.showingHint = true;
    super.addFocusListener(this);
  }

  @Override
  public void focusGained(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText("");
      showingHint = false;
    }
  }
  @Override
  public void focusLost(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText(hint);
      showingHint = true;
    }
  }

  @Override
  public String getText() {
    return showingHint ? "" : super.getText();
  }
}

If you're still on Java 1.5, replace the this.getText().isEmpty() with this.getText().length() == 0.

What data type to use for money in Java?

You can use Money and Currency API (JSR 354). You can use this API in, provided you add appropriate dependencies to your project.

For Java 8, add the following reference implementation as a dependency to your pom.xml:

<dependency>
    <groupId>org.javamoney</groupId>
    <artifactId>moneta</artifactId>
    <version>1.0</version>
</dependency>

This dependency will transitively add javax.money:money-api as a dependency.

You can then use the API:

package com.example.money;

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;

import java.util.Locale;

import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.MonetaryRounding;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;

import org.junit.Test;

public class MoneyTest {

    @Test
    public void testMoneyApi() {
        MonetaryAmount eurAmount1 = Monetary.getDefaultAmountFactory().setNumber(1.1111).setCurrency("EUR").create();
        MonetaryAmount eurAmount2 = Monetary.getDefaultAmountFactory().setNumber(1.1141).setCurrency("EUR").create();

        MonetaryAmount eurAmount3 = eurAmount1.add(eurAmount2);
        assertThat(eurAmount3.toString(), is("EUR 2.2252"));

        MonetaryRounding defaultRounding = Monetary.getDefaultRounding();
        MonetaryAmount eurAmount4 = eurAmount3.with(defaultRounding);
        assertThat(eurAmount4.toString(), is("EUR 2.23"));

        MonetaryAmountFormat germanFormat = MonetaryFormats.getAmountFormat(Locale.GERMAN);
        assertThat(germanFormat.format(eurAmount4), is("EUR 2,23") );
    }
}

Split comma separated column data into additional columns

You can use split function.

    SELECT 
    (select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
    (select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
    (select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
    (select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
    FROM MyTbl

Rollback one specific migration in Laravel

better to used refresh migrate

You may rollback & re-migrate a limited number of migrations by providing the step option to the refresh command. For example, the following command will rollback & re-migrate the last two migrations:

php artisan migrate:refresh --step=2

otherwise used rollback migrate

You may rollback a limited number of migrations by providing the step option to the rollback command. For example, the following command will rollback the last three migrations:

php artisan migrate:rollback --step=3

for more detail about migration see

Read data from SqlDataReader

For a single result:

if (reader.Read())
{
    Response.Write(reader[0].ToString());
    Response.Write(reader[1].ToString());
}

For multiple results:

while (reader.Read())
{
    Response.Write(reader[0].ToString());
    Response.Write(reader[1].ToString());
}

Python Create unix timestamp five minutes in the future

Just found this, and its even shorter.

import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)

How to center a (background) image within a div?

#doit {
    background: url(url) no-repeat center;
}

How do I format a number in Java?

As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).

Use Spring's Numberformatter instead, which is thread safe.

Function vs. Stored Procedure in SQL Server

Generally using stored procedures is better for perfomances. For example in previous versions of SQL Server if you put the function in JOIN condition the cardinality estimate is 1 (before SQL 2012) and 100 (after SQL 2012 and before of SQL 2017) and the engine can generate a bad execution plan.

Also if you put it in WHERE clause the SQL Engine can generate a bad execution plan.

With SQL 2017 Microsoft introduced the feature called interleaved execution in order to produce a more accurate estimate but the stored procedure remains the best solution.

For more details look the following article of Joe Sack https://techcommunity.microsoft.com/t5/sql-server/introducing-interleaved-execution-for-multi-statement-table/ba-p/385417

Can't import org.apache.http.HttpResponse in Android Studio

According to the Apache site this is the Gradle dependency you need to include, if you use Android API 23 or newer:

dependencies {
    compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}

Source: https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html

adding text to an existing text element in javascript via DOM

_x000D_
_x000D_
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");

t.appendChild(y);
_x000D_
<p id="p">This is some text</p>
_x000D_
_x000D_
_x000D_

curl_init() function not working

On Ubuntu 18.04 these two commands solve my this problem.

sudo apt-get install php5.6-curl //install curl for php 5.6
sudo service apache2 restart //restart apache

Stop setInterval call in JavaScript

setInterval() returns an interval ID, which you can pass to clearInterval():

var refreshIntervalId = setInterval(fname, 10000);

/* later */
clearInterval(refreshIntervalId);

See the docs for setInterval() and clearInterval().

How to show Snackbar when Activity starts?

You can also define a super class for all your activities and find the view once in the parent activity.

for example

AppActivity.java :

public class AppActivity extends AppCompatActivity {

    protected View content;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        changeLanguage("fa");
        content = findViewById(android.R.id.content);
    }
}

and your snacks would look like this in every activity in your app:

Snackbar.make(content, "hello every body", Snackbar.LENGTH_SHORT).show();

It is better for performance you have to find the view once for every activity.

mean() warning: argument is not numeric or logical: returning NA

The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean() function. Therefore, check your data using str(data.frame&column) function to see what data type you have, and convert it to numeric format if necessary. For example, if your data is Character convert it with as.numeric(data.frame$column), or as a factor with as.numeric(as.character(data.frame$column)). The mean function does not work with types other than numeric.

Export SQL query data to Excel

I had a similar problem but with a twist - the solutions listed above worked when the resultset was from one query but in my situation, I had multiple individual select queries for which I needed results to be exported to Excel. Below is just an example to illustrate although I could do a name in clause...

select a,b from Table_A where name = 'x'
select a,b from Table_A where name = 'y'
select a,b from Table_A where name = 'z'

The wizard was letting me export the result from one query to excel but not all results from different queries in this case.

When I researched, I found that we could disable the results to grid and enable results to Text. So, press Ctrl + T, then execute all the statements. This should show the results as a text file in the output window. You can manipulate the text into a tab delimited format for you to import into Excel.

You could also press Ctrl + Shift + F to export the results to a file - it exports as a .rpt file that can be opened using a text editor and manipulated for excel import.

Hope this helps any others having a similar issue.

Error when creating a new text file with python?

This works just fine, but instead of

name = input('Enter name of text file: ')+'.txt' 

you should use

name = raw_input('Enter name of text file: ')+'.txt'

along with

open(name,'a') or open(name,'w')

How can I generate Unix timestamps?

First of all, the Unix 'epoch' or zero-time is 1970-01-01 00:00:00Z (meaning midnight of 1st January 1970 in the Zulu or GMT or UTC time zone). A Unix time stamp is the number of seconds since that time - not accounting for leap seconds.

Generating the current time in Perl is rather easy:

perl -e 'print time, "\n"'

Generating the time corresponding to a given date/time value is rather less easy. Logically, you use the strptime() function from POSIX. However, the Perl POSIX::strptime module (which is separate from the POSIX module) has the signature:

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = 
                                     POSIX::strptime("string", "Format");

The function mktime in the POSIX module has the signature:

mktime(sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = 0)

So, if you know the format of your data, you could write a variant on:

perl -MPOSIX -MPOSIX::strptime -e \
    'print mktime(POSIX::strptime("2009-07-30 04:30", "%Y-%m-%d %H:%M")), "\n"'

How to avoid HTTP error 429 (Too Many Requests) python

As MRA said, you shouldn't try to dodge a 429 Too Many Requests but instead handle it accordingly. You have several options depending on your use-case:

1) Sleep your process. The server usually includes a Retry-after header in the response with the number of seconds you are supposed to wait before retrying. Keep in mind that sleeping a process might cause problems, e.g. in a task queue, where you should instead retry the task at a later time to free up the worker for other things.

2) Exponential backoff. If the server does not tell you how long to wait, you can retry your request using increasing pauses in between. The popular task queue Celery has this feature built right-in.

3) Token bucket. This technique is useful if you know in advance how many requests you are able to make in a given time. Each time you access the API you first fetch a token from the bucket. The bucket is refilled at a constant rate. If the bucket is empty, you know you'll have to wait before hitting the API again. Token buckets are usually implemented on the other end (the API) but you can also use them as a proxy to avoid ever getting a 429 Too Many Requests. Celery's rate_limit feature uses a token bucket algorithm.

Here is an example of a Python/Celery app using exponential backoff and rate-limiting/token bucket:

class TooManyRequests(Exception):
"""Too many requests"""

@task(
   rate_limit='10/s',
   autoretry_for=(ConnectTimeout, TooManyRequests,),
   retry_backoff=True)
def api(*args, **kwargs):
  r = requests.get('placeholder-external-api')

  if r.status_code == 429:
    raise TooManyRequests()

HTTP Request in Swift with POST method

@IBAction func btn_LogIn(sender: AnyObject) {

    let request = NSMutableURLRequest(URL: NSURL(string: "http://demo.hackerkernel.com/ios_api/login.php")!)
    request.HTTPMethod = "POST"
    let postString = "email: [email protected] & password: testtest"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data, response, error in
        guard error == nil && data != nil else{
            print("error")
            return
        }
        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200{
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }
        let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
    }
    task.resume()
}

How to prevent long words from breaking my div?

Use the style word-break:break-all;. I know it works on tables.

Getting last month's date in php

If you want to get first date of previous month , Then you can use as like following ... $prevmonth = date('M Y 1', strtotime('-1 months')); what? first date will always be 1 :D

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

I was getting this error too and the reason ended up being wrong call url. I am leaving this answer here, if someone else happens to mix the urls and getting this error. Took me hours to realize I had wrong URL.

Error I got (HTTP code 400):

{
    "error": "unsupported_grant_type",
    "error_description": "grant type not supported"
}

I was calling:

https://MY_INSTANCE.lightning.force.com

While the correct URL would have been:

https://MY_INSTANCE.cs110.my.salesforce.com

Going to a specific line number using Less in Unix

For editing this is possible in nano via +n from command line, e.g.,

nano +16 file.txt

To open file.txt to line 16.

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

How do I put an image into my picturebox using ImageLocation?

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

Does it matter what extension is used for SQLite database files?

Emacs expects one of db, sqlite, sqlite2 or sqlite3 in the default configuration for sql-sqlite mode.

How do I execute a command and get the output of the command within C++ using POSIX?

Assuming POSIX, simple code to capture stdout:

#include <sys/wait.h>
#include <unistd.h>
#include <string>
#include <vector>

std::string qx(const std::vector<std::string>& args) {
  int stdout_fds[2];
  pipe(stdout_fds);

  int stderr_fds[2];
  pipe(stderr_fds);

  const pid_t pid = fork();
  if (!pid) {
    close(stdout_fds[0]);
    dup2(stdout_fds[1], 1);
    close(stdout_fds[1]);

    close(stderr_fds[0]);
    dup2(stderr_fds[1], 2);
    close(stderr_fds[1]);

    std::vector<char*> vc(args.size() + 1, 0);
    for (size_t i = 0; i < args.size(); ++i) {
      vc[i] = const_cast<char*>(args[i].c_str());
    }

    execvp(vc[0], &vc[0]);
    exit(0);
  }

  close(stdout_fds[1]);

  std::string out;
  const int buf_size = 4096;
  char buffer[buf_size];
  do {
    const ssize_t r = read(stdout_fds[0], buffer, buf_size);
    if (r > 0) {
      out.append(buffer, r);
    }
  } while (errno == EAGAIN || errno == EINTR);

  close(stdout_fds[0]);

  close(stderr_fds[1]);
  close(stderr_fds[0]);

  int r, status;
  do {
    r = waitpid(pid, &status, 0);
  } while (r == -1 && errno == EINTR);

  return out;
}

Code contributions are welcome for more functionality:

https://github.com/ericcurtin/execxx

LIKE operator in LINQ

In native LINQ you may use combination of Contains/StartsWith/EndsWith or RegExp.

In LINQ2SQL use method SqlMethods.Like()

    from i in db.myTable
    where SqlMethods.Like(i.field, "tra%ata")
    select i

add Assembly: System.Data.Linq (in System.Data.Linq.dll) to use this feature.

Converting byte array to String (Java)

Java 7 and above

You can also pass your desired encoding to the String constructor as a Charset constant from StandardCharsets. This may be safer than passing the encoding as a String, as suggested in the other answers.

For example, for UTF-8 encoding

String bytesAsString = new String(bytes, StandardCharsets.UTF_8);

Python Error: "ValueError: need more than 1 value to unpack"

You shouldn't be doing tuple dereferencing on values that can change like your line below.

 script, user_name = argv

The line above will fail if you pass less than one argument or more than one argument. A better way of doing this is to do something like this:

 for arg in argv[1:]:
     print arg

Of cause you will do something other than print the args. Maybe put a series of 'if' statement in the 'for' loop that set variables depending on the arguments passed. An even better way is to use the getopt or optparse packages.

Python: subplot within a loop: first panel appears in wrong position

Using your code with some random data, this would work:

fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

axs = axs.ravel()

for i in range(10):

    axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
    axs[i].set_title(str(250+i))

The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).

enter image description here

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

I'd recommend raising the connection timeout time before getting the output stream, like so:

urlConnection.setConnectTimeout(1000);

Where 1000 is in milliseconds (1000 milliseconds = 1 second).

Why and when to use angular.copy? (Deep Copy)

I am just sharing my experience here, I used angular.copy() for comparing two objects properties. I was working on a number of inputs without form element, I was wondering how to compare two objects properties and based on result I have to enable and disable the save button. So I used as below.

I assigned an original server object user values to my dummy object to say userCopy and used watch to check changes to the user object.

My server API which gets me data from the server:

var req = {
    method: 'GET',
    url: 'user/profile/' + id,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
$http(req).success(function(data) {
    $scope.user = data;
    $scope.userCopy = angular.copy($scope.user);
    $scope.btnSts=true;
}).error(function(data) {
    $ionicLoading.hide();
});

//initially my save button is disabled because objects are same, once something 
//changes I am activating save button

$scope.btnSts = true;
$scope.$watch('user', function(newVal, oldVal) {
    console.log($scope.userCopy.name);

    if ($scope.userCopy.name !== $scope.user.name || $scope.userCopy.email !== $scope.user.email) {
        console.log('Changed');
        $scope.btnSts = false;
    } else {
        console.log('Unchanged');
        $scope.btnSts = true;
    }    
}, true);

I am not sure but comparing two objects was really headache for me always but with angular.copy() it went smoothly.

Select method in List<t> Collection

you can also try

var query = from p in list
            where p.Age > 18
            select p;

mysql -> insert into tbl (select from another table) and some default values

If you you want to copy a sub-set of the source table you can do:

INSERT INTO def (field_1, field_2, field3)

SELECT other_field_1, other_field_2, other_field_3 from `abc`

or to copy ALL fields from the source table to destination table you can do more simply:

INSERT INTO def 
SELECT * from `abc`

Rock, Paper, Scissors Game Java

You could insert something like this:

personPlay = "B";

while (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S")) {

    //Get player's play from input-- note that this is 
    // stored as a string 
    System.out.println("Enter your play: "); 
    personPlay = scan.next();

    //Make player's play uppercase for ease of comparison 
    personPlay = personPlay.toUpperCase();

    if (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S"))
        System.out.println("Invalid move. Try again.");

}

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

I would not use an explicit cursor to do this. Steve F. no longer advises people to use explicit cursors when an implicit cursor could be used.

The method with count(*) is unsafe. If another session deletes the row that met the condition after the line with the count(*), and before the line with the select ... into, the code will throw an exception that will not get handled.

The second version from the original post does not have this problem, and it is generally preferred.

That said, there is a minor overhead using the exception, and if you are 100% sure the data will not change, you can use the count(*), but I recommend against it.

I ran these benchmarks on Oracle 10.2.0.1 on 32 bit Windows. I am only looking at elapsed time. There are other test harnesses that can give more details (such as latch counts and memory used).

SQL>create table t (NEEDED_FIELD number, COND number);

Table created.

SQL>insert into t (NEEDED_FIELD, cond) values (1, 0);

1 row created.

declare
  otherVar  number;
  cnt number;
begin
  for i in 1 .. 50000 loop
     select count(*) into cnt from t where cond = 1;

     if (cnt = 1) then
       select NEEDED_FIELD INTO otherVar from t where cond = 1;
     else
       otherVar := 0;
     end if;
   end loop;
end;
/

PL/SQL procedure successfully completed.

Elapsed: 00:00:02.70

declare
  otherVar  number;
begin
  for i in 1 .. 50000 loop
     begin
       select NEEDED_FIELD INTO otherVar from t where cond = 1;
     exception
       when no_data_found then
         otherVar := 0;
     end;
   end loop;
end;
/

PL/SQL procedure successfully completed.

Elapsed: 00:00:03.06

Get distance between two points in canvas

i tend to use this calculation a lot in things i make, so i like to add it to the Math object:

Math.dist=function(x1,y1,x2,y2){ 
  if(!x2) x2=0; 
  if(!y2) y2=0;
  return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); 
}
Math.dist(0,0, 3,4); //the output will be 5
Math.dist(1,1, 4,5); //the output will be 5
Math.dist(3,4); //the output will be 5

Update:

this approach is especially happy making when you end up in situations something akin to this (i often do):

varName.dist=Math.sqrt( ( (varName.paramX-varX)/2-cx )*( (varName.paramX-varX)/2-cx ) + ( (varName.paramY-varY)/2-cy )*( (varName.paramY-varY)/2-cy ) );

that horrid thing becomes the much more manageable:

varName.dist=Math.dist((varName.paramX-varX)/2, (varName.paramY-varY)/2, cx, cy);

Facebook Graph API error code list

While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.

Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.

Current Subversion revision command

Nobody mention for Windows world SubWCRev, which, properly used, can substitute needed data into the needed places automagically, if script call SubWCRev in form SubWCRev WC_PATH TPL-FILE READY-FILE

Sample of my post-commit hook (part of)

SubWCRev.exe CustomLocations Builder.tpl  z:\Builder.bat
...
call z:\Builder.bat

where my Builder.tpl is

svn.exe export trunk z:\trunk$WCDATE=%Y%m%d$-r$WCREV$

as result, I have every time bat-file with variable part - name of dir - which corresponds to the metadata of Working Copy

Open a file with Notepad in C#

You can use Process.Start, calling notepad.exe with the file as a parameter.

 Process.Start(@"notepad.exe", pathToFile);

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

Let'e me give an example:

  1. client connect to server, and send 1MB data to server every 1 second.

  2. server side accept a connection, and then sleep 20 second, without recv msg from client.So the tcp send buffer in the client side will be full.

Code in client side:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define exit_if(r, ...)                                                                          \
    if (r) {                                                                                     \
        printf(__VA_ARGS__);                                                                     \
        printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
        exit(1);                                                                                 \
    }

void setNonBlock(int fd) {
    int flags = fcntl(fd, F_GETFL, 0);
    exit_if(flags < 0, "fcntl failed");
    int r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
    exit_if(r < 0, "fcntl failed");
}

void test_full_sock_buf_1(){
    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;


    int fd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(fd<0, "create socket error");

    int ret = connect(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(ret<0, "connect to server error");
    setNonBlock(fd);

    printf("connect to server success");

    const int LEN = 1024 * 1000;
    char msg[LEN];  // 1MB data
    memset(msg, 'a', LEN);

    for (int i = 0; i < 1000; ++i) {
        int len = send(fd, msg, LEN, 0);
        printf("send: %d, erron: %d, %s \n", len, errno, strerror(errno));
        sleep(1);
    }

}

int main(){
    test_full_sock_buf_1();

    return 0;
}

Code in server side:

    #include <arpa/inet.h>
    #include <sys/socket.h>
    #include <stdio.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <string.h>
    #define exit_if(r, ...)                                                                          \
        if (r) {                                                                                     \
            printf(__VA_ARGS__);                                                                     \
            printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
            exit(1);                                                                                 \
        }
void test_full_sock_buf_1(){

    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(listenfd<0, "create socket error");

    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;

    int r = ::bind(listenfd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(r<0, "bind socket error");

    r = listen(listenfd, 100);
    exit_if(r<0, "listen socket error");

    struct sockaddr_in raddr;
    socklen_t rsz = sizeof(raddr);
    int cfd = accept(listenfd, (struct sockaddr *) &raddr, &rsz);
    exit_if(cfd<0, "accept socket error");

    sockaddr_in peer;
    socklen_t alen = sizeof(peer);
    getpeername(cfd, (sockaddr *) &peer, &alen);

    printf("accept a connection from %s:%d\n", inet_ntoa(peer.sin_addr), ntohs(peer.sin_port));

    printf("but now I will sleep 15 second, then exit");
    sleep(15);
}

Start server side, then start client side.

server side may output:

accept a connection from 127.0.0.1:35764
but now I will sleep 15 second, then exit
Process finished with exit code 0

enter image description here

client side may output:

connect to server successsend: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 552190, erron: 0, Success 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 104, Connection reset by peer 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 

enter image description here

You can see, as the server side doesn't recv the data from client, so when the client side tcp buffer get full, but you still send data, so you may get Resource temporarily unavailable error.

How to update/upgrade a package using pip?

tl;dr script to update all installed packages

If you only want to upgrade one package, refer to @borgr's answer. I often find it necessary, or at least pleasing, to upgrade all my packages at once. Currently, pip doesn't natively support that action, but with sh scripting it is simple enough. You use pip list, awk (or cut and tail), and command substitution. My normal one-liner is:

for i in $(pip list -o | awk 'NR > 2 {print $1}'); do sudo pip install -U $i; done

This will ask for the root password. If you do not have access to that, the --user option of pip or virtualenv may be something to look into.

Get battery level and state in Android

one mistake in official docs, you must use double instead float. Because 0.53F * 100F = 52F

int level = batteryStatus != null ? 
batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1; int scale = 
batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1; 
double batteryPct = (double) level / (double) scale; int percent = (int) (batteryPct * 100D);

Virtualhost For Wildcard Subdomain and Static Subdomain

This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.

<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com

SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"

VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"

DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>

PHP Get Highest Value from Array

$ee = array('a' => 50, 'b' => 25, 'c' => 5, 'd' => 80, 'e' => 40, 'f' => 152, 'g' => 45, 'h' => 28);
$Acurr = '';
$Amax = 0;

foreach($ee as $key => $value) {
    $Acurr = $value;    

    if($Acurr >= $Amax) {
        $Amax = $Acurr; 
    }
}

echo "greatest number is $Amax";

MySQL - Selecting data from multiple tables all with same structure but different data

Any of the above answers are valid, or an alternative way is to expand the table name to include the database name as well - eg:

SELECT * from us_music, de_music where `us_music.genre` = 'punk' AND `de_music.genre` = 'punk'

Preferred way of loading resources in Java

I tried a lot of ways and functions that suggested above, but they didn't work in my project. Anyway I have found solution and here it is:

try {
    InputStream path = this.getClass().getClassLoader().getResourceAsStream("img/left-hand.png");
    img = ImageIO.read(path);
} catch (IOException e) {
    e.printStackTrace();
}

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

How to dynamically create CSS class in JavaScript and apply?

Found a better solution, which works across all browsers.
Uses document.styleSheet to add or replace rules. Accepted answer is short and handy but this works across IE8 and less too.

function createCSSSelector (selector, style) {
  if (!document.styleSheets) return;
  if (document.getElementsByTagName('head').length == 0) return;

  var styleSheet,mediaType;

  if (document.styleSheets.length > 0) {
    for (var i = 0, l = document.styleSheets.length; i < l; i++) {
      if (document.styleSheets[i].disabled) 
        continue;
      var media = document.styleSheets[i].media;
      mediaType = typeof media;

      if (mediaType === 'string') {
        if (media === '' || (media.indexOf('screen') !== -1)) {
          styleSheet = document.styleSheets[i];
        }
      }
      else if (mediaType=='object') {
        if (media.mediaText === '' || (media.mediaText.indexOf('screen') !== -1)) {
          styleSheet = document.styleSheets[i];
        }
      }

      if (typeof styleSheet !== 'undefined') 
        break;
    }
  }

  if (typeof styleSheet === 'undefined') {
    var styleSheetElement = document.createElement('style');
    styleSheetElement.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(styleSheetElement);

    for (i = 0; i < document.styleSheets.length; i++) {
      if (document.styleSheets[i].disabled) {
        continue;
      }
      styleSheet = document.styleSheets[i];
    }

    mediaType = typeof styleSheet.media;
  }

  if (mediaType === 'string') {
    for (var i = 0, l = styleSheet.rules.length; i < l; i++) {
      if(styleSheet.rules[i].selectorText && styleSheet.rules[i].selectorText.toLowerCase()==selector.toLowerCase()) {
        styleSheet.rules[i].style.cssText = style;
        return;
      }
    }
    styleSheet.addRule(selector,style);
  }
  else if (mediaType === 'object') {
    var styleSheetLength = (styleSheet.cssRules) ? styleSheet.cssRules.length : 0;
    for (var i = 0; i < styleSheetLength; i++) {
      if (styleSheet.cssRules[i].selectorText && styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) {
        styleSheet.cssRules[i].style.cssText = style;
        return;
      }
    }
    styleSheet.insertRule(selector + '{' + style + '}', styleSheetLength);
  }
}

Function is used as follows.

createCSSSelector('.mycssclass', 'display:none');

DataGridView changing cell background color

You can use the VisibleChanged event handler.

private void DataGridView1_VisibleChanged(object sender, System.EventArgs e)
{
    var grid = sender as DataGridView;
    grid.Rows[0].Cells[0].Style.BackColor = Color.Yellow;
}

How to get the file extension in PHP?

A better method is using strrpos + substr (faster than explode for that) :

$userfile_name = $_FILES['image']['name'];
$userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);

But, to check the type of a file, using mime_content_type is a better way : http://www.php.net/manual/en/function.mime-content-type.php

how to open a url in python

On window

import os
os.system("start \"\" https://example.com")

On macOS

import os
os.system("open \"\" https://example.com")

On Linux

import os
os.system("xdg-open \"\" https://example.com")

Cross-Platform

import webbrowser

webbrowser.open('https://example.com')

Multiple definition of ... linker error

Don't define variables in headers. Put declarations in header and definitions in one of the .c files.

In config.h

extern const char *names[];

In some .c file:

const char *names[] =
    {
        "brian", "stefan", "steve"
    };

If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.

Laravel is there a way to add values to a request array

Usually, you do not want to add anything to a Request object, it's better to use collection and put() helper:

function store(Request $request) 
{
    // some additional logic or checking
    User::create(array_merge($request->all(), ['index' => 'value']));
}

Or you could union arrays:

User::create($request->all() + ['index' => 'value']);

But, if you really want to add something to a Request object, do this:

$request->request->add(['variable' => 'value']); //add request

How to fix apt-get: command not found on AWS EC2?

please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like

AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1 

hope it helps

How to get min, seconds and milliseconds from datetime.now() in python?

What about:

datetime.now().strftime('%M:%S.%f')[:-4]

I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.

EDIT

If the %f modifier doesn't work for you, you can try something like:

now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]

Again, I'm assuming you just want to truncate the precision.

Ajax Success and Error function failure

This may not solve all of your problems, but the variable you are using inside your function (text) is not the same as the parameter you are passing in (x).

Changing:

function textreplace(x) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

To:

function textreplace(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

seems like it would do some good.

How do I find the stack trace in Visual Studio?

Using the Call Stack Window

To open the Call Stack window in Visual Studio, from the Debug menu, choose Windows>Call Stack. To set the local context to a particular row in the stack trace display, double click the first column of the row.

http://msdn.microsoft.com/en-us/library/windows/hardware/hh439516(v=vs.85).aspx

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

Uninstall Node.JS using Linux command line?

This is better to remove NodeJS and its modules manually because installation leaves a lot of files, links and modules behind and later it create problems while we reconfigure another version of NodeJS and its modules. Run the following commands.

sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* /usr/local/lib/dtrace/node.d ~/.npm ~/.node-gyp /opt/local/bin/node opt/local/include/node /opt/local/lib/node_modules 


sudo rm -rf /usr/local/lib/node*     
sudo rm -rf /usr/local/include/node*         
sudo rm -rf /usr/local/bin/node*

and this done.

A step by step guide with commands is at http://amcositsupport.blogspot.in/2016/07/to-completely-uninstall-node-js-from.html

This helped me resolve my problem.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

After updating android studio to 3.3. I faced this problem when I tried to load Firebase JobDispatcher. Adding this link on gradle.properties solved my problem

distributionUrl=https://services.gradle.org/distributions/gradle-4.1-all.zip

What is a Subclass

Subclass is to Class as Java is to Programming Language.

How to send email to multiple address using System.Net.Mail

My code to solve this problem:

private void sendMail()
{   
    //This list can be a parameter of metothd
    List<MailAddress> lst = new List<MailAddress>();

    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));


    try
    {


        MailMessage objeto_mail = new MailMessage();
        SmtpClient client = new SmtpClient();
        client.Port = 25;
        client.Host = "10.15.130.28"; //or SMTP name
        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
        objeto_mail.From = new MailAddress("[email protected]");

        //add each email adress
        foreach (MailAddress m in lst)
        {
            objeto_mail.To.Add(m);
        }


        objeto_mail.Subject = "Sending mail test";
        objeto_mail.Body = "Functional test for automatic mail :-)";
        client.Send(objeto_mail);


    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

How to get IntPtr from byte[] in C#

Not sure about getting an IntPtr to an array, but you can copy the data for use with unmanaged code by using Mashal.Copy:

IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);
// Call unmanaged code
Marshal.FreeHGlobal(unmanagedPointer);

Alternatively you could declare a struct with one property and then use Marshal.PtrToStructure, but that would still require allocating unmanaged memory.

Edit: Also, as Tyalis pointed out, you can also use fixed if unsafe code is an option for you

What does "make oldconfig" do exactly in the Linux kernel makefile?

From this page:

Make oldconfig takes the .config and runs it through the rules of the Kconfig files and produces a .config which is consistant with the Kconfig rules. If there are CONFIG values which are missing, the make oldconfig will ask for them.

If the .config is already consistant with the rules found in Kconfig, then make oldconfig is essentially a no-op.

If you were to run make oldconfig, and then run make oldconfig a second time, the second time won't cause any additional changes to be made.

Know relationships between all the tables of database in SQL Server

My solution is based on @marc_s solution, i just concatenated columns in cases that a constraint is based on more than one column:

SELECT
   FK.[name] AS ForeignKeyConstraintName
  ,SCHEMA_NAME(FT.schema_id) + '.' + FT.[name] AS ForeignTable
  ,STUFF(ForeignColumns.ForeignColumns, 1, 2, '') AS ForeignColumns
  ,SCHEMA_NAME(RT.schema_id) + '.' + RT.[name] AS ReferencedTable
  ,STUFF(ReferencedColumns.ReferencedColumns, 1, 2, '') AS ReferencedColumns
FROM
  sys.foreign_keys FK
  INNER JOIN sys.tables FT
  ON FT.object_id = FK.parent_object_id
  INNER JOIN sys.tables RT
  ON RT.object_id = FK.referenced_object_id
  CROSS APPLY
  (
    SELECT
      ', ' + iFC.[name] AS [text()]
    FROM
      sys.foreign_key_columns iFKC
      INNER JOIN sys.columns iFC
      ON iFC.object_id = iFKC.parent_object_id
        AND iFC.column_id = iFKC.parent_column_id
    WHERE
      iFKC.constraint_object_id = FK.object_id
    ORDER BY
      iFC.[name]
    FOR XML PATH('')
  ) ForeignColumns (ForeignColumns)
  CROSS APPLY
  (
    SELECT
      ', ' + iRC.[name]AS [text()]
    FROM
      sys.foreign_key_columns iFKC
      INNER JOIN sys.columns iRC
      ON iRC.object_id = iFKC.referenced_object_id
        AND iRC.column_id = iFKC.referenced_column_id
    WHERE
      iFKC.constraint_object_id = FK.object_id
    ORDER BY
      iRC.[name]
    FOR XML PATH('')
  ) ReferencedColumns (ReferencedColumns)

How do I copy the contents of one stream to another?

if you want a procdure to copy a stream to other the one that nick posted is fine but it is missing the position reset, it should be

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    long TempPos = input.Position;
    while (true)    
    {
        int read = input.Read (buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write (buffer, 0, read);
    }
    input.Position = TempPos;// or you make Position = 0 to set it at the start
}

but if it is in runtime not using a procedure you shpuld use memory stream

Stream output = new MemoryStream();
byte[] buffer = new byte[32768]; // or you specify the size you want of your buffer
long TempPos = input.Position;
while (true)    
{
    int read = input.Read (buffer, 0, buffer.Length);
    if (read <= 0)
        return;
    output.Write (buffer, 0, read);
 }
    input.Position = TempPos;// or you make Position = 0 to set it at the start

How to display string that contains HTML in twig template?

{{ word|striptags('<b>,<a>,<pre>')|raw }}

if you want to allow multiple tags

Resolve absolute path from relative path and/or file name

Files See all other answers

Directories

With .. being your relative path, and assuming you are currently in D:\Projects\EditorProject:

cd .. & cd & cd EditorProject (the relative path)

returns absolute path e.g.

D:\Projects

Math.random() versus Random.nextInt(int)

another important point is that Random.nextInt(n) is repeatable since you can create two Random object with the same seed. This is not possible with Math.random().

Add shadow to custom shape on Android

After Lots of search finally I got this

enter image description here

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

<!-- Bottom 2dp Shadow -->
<item>
    <shape  android:shape="rectangle">

        <solid android:color="#d8d8d8" />
        <corners android:radius="7dp" />

    </shape>
</item>

<!-- White Top color -->
<item android:bottom="3px">

    <shape  android:shape="rectangle">

    <solid android:color="#FFFFFF" />
    <corners android:radius="7dp" />


    </shape>

</item>


</layer-list>

Can't run Curl command inside my Docker Container

This is happening because there is no package cache in the image, you need to run:

apt-get -qq update

before installing packages, and if your command is in a Dockerfile, you'll then need:

apt-get -qq -y install curl

After that install ZSH and GIT Core:

apt-get install zsh
apt-get install git-core

Getting zsh to work in ubuntu is weird since sh does not understand the source command. So, you do this to install zsh:

wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh

and then you change your shell to zsh:

chsh -s `which zsh`

and then restart:

sudo shutdown -r 0

This problem is explained in depth in this issue.

How to determine when a Git branch was created?

First, if you branch was created within gc.reflogexpire days (default 90 days, i.e. around 3 months), you can use git log -g <branch> or git reflog show <branch> to find first entry in reflog, which would be creation event, and looks something like below (for git log -g):

Reflog: <branch>@{<nn>} (C R Eator <[email protected]>)
Reflog message: branch: Created from <some other branch>

You would get who created a branch, how many operations ago, and from which branch (well, it might be just "Created from HEAD", which doesn't help much).

That is what MikeSep said in his answer.


Second, if you have branch for longer than gc.reflogexpire and you have run git gc (or it was run automatically), you would have to find common ancestor with the branch it was created from. Take a look at config file, perhaps there is branch.<branchname>.merge entry, which would tell you what branch this one is based on.

If you know that the branch in question was created off master branch (forking from master branch), for example, you can use the following command to see common ancestor:

git show $(git merge-base <branch> master)

You can also try git show-branch <branch> master, as an alternative.

This is what gbacon said in his response.

Link entire table row?

Also it depends if you need to use a table element or not. You can imitate a table using CSS and make an A element the row

<div class="table" style="width:100%;">
  <a href="#" class="tr">
    <span class="td">
      cell 1
    </span>
    <span class="td">
      cell 2
    </span>
  </a>
</div>

css:

.table{display:table;}
.tr{display:table-row;}
.td{display:table-cell;}
.tr:hover{background-color:#ccc;}

Return anonymous type results?

You could do something like this:


public System.Collections.IEnumerable GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result.ToList();
}

How to install PHP mbstring on CentOS 6.2

As yum install php-mbstring then httpd -k restart didn't do it for me, I think these options should be compiled, as documented here:

Now, configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with Apache 2 and MySQL support.

If you built Apache from source, as described above, the below example will match your path for apxs, but if you installed Apache some other way, you'll need to adjust the path to apxs accordingly. Note that some distros may rename apxs to apxs2.

cd ../php-NN
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql --enable-mbstring
make
make install

If you decide to change your configure options after installation, you'll need to re-run the configure, make, and make install steps. You only need to restart apache for the new module to take effect. A recompile of Apache is not needed.

Note that unless told otherwise, 'make install' will also install PEAR, various PHP tools such as phpize, install the PHP CLI, and more.

Though this page says it's optional:

--enable-mbstring Allows multibyte character string support. This is optional, as slower custom code will be used if not available.

React Native Change Default iOS Simulator Device

1) Rename your simulator, If simulator with same name but different iOS version

Xcode -> Window -> Devices and Simulators -> Simulators.

enter image description here

2) Open your react native project folder

3) Edit package.json

"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "flow": "node_modules/.bin/flow",
    "start-iphone6": "react-native run-ios --simulator \"iPhone 6 11.3\""
}

4) npm run start-iphone6

SQL GROUP BY CASE statement with aggregate function

I think the answer is pretty simple (unless I'm missing something?)

SELECT    
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END AS some_product
FROM some_table
GROUP BY
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END

You can put the CASE STATEMENT in the GROUP BY verbatim (minus the alias column name)

Delete all but the most recent X files in bash

I needed an elegant solution for the busybox (router), all xargs or array solutions were useless to me - no such command available there. find and mtime is not the proper answer as we are talking about 10 items and not necessarily 10 days. Espo's answer was the shortest and cleanest and likely the most unversal one.

Error with spaces and when no files are to be deleted are both simply solved the standard way:

rm "$(ls -td *.tar | awk 'NR>7')" 2>&-

Bit more educational version: We can do it all if we use awk differently. Normally, I use this method to pass (return) variables from the awk to the sh. As we read all the time that can not be done, I beg to differ: here is the method.

Example for .tar files with no problem regarding the spaces in the filename. To test, replace "rm" with the "ls".

eval $(ls -td *.tar | awk 'NR>7 { print "rm \"" $0 "\""}')

Explanation:

ls -td *.tar lists all .tar files sorted by the time. To apply to all the files in the current folder, remove the "d *.tar" part

awk 'NR>7... skips the first 7 lines

print "rm \"" $0 "\"" constructs a line: rm "file name"

eval executes it

Since we are using rm, I would not use the above command in a script! Wiser usage is:

(cd /FolderToDeleteWithin && eval $(ls -td *.tar | awk 'NR>7 { print "rm \"" $0 "\""}'))

In the case of using ls -t command will not do any harm on such silly examples as: touch 'foo " bar' and touch 'hello * world'. Not that we ever create files with such names in real life!

Sidenote. If we wanted to pass a variable to the sh this way, we would simply modify the print (simple form, no spaces tolerated):

print "VarName="$1

to set the variable VarName to the value of $1. Multiple variables can be created in one go. This VarName becomes a normal sh variable and can be normally used in a script or shell afterwards. So, to create variables with awk and give them back to the shell:

eval $(ls -td *.tar | awk 'NR>7 { print "VarName=\""$1"\""  }'); echo "$VarName"

Is it possible to install another version of Python to Virtualenv?

Here are the options for virtualenv

$ virtualenv
You must provide a DEST_DIR
Usage: virtualenv [OPTIONS] DEST_DIR

Options:
  --version             show program's version number and exit.
  -h, --help            show this help message and exit.
  -v, --verbose         Increase verbosity.
  -q, --quiet           Decrease verbosity.
  -p PYTHON_EXE, --python=PYTHON_EXE
                        The Python interpreter to use, e.g.,
                        --python=python2.5 will use the python2.5 interpreter
                        to create the new environment.  The default is the
                        interpreter that virtualenv was installed with
                        (/usr/bin/python)
  --clear               Clear out the non-root install and start from scratch
  --no-site-packages    Don't give access to the global site-packages dir to
                        the virtual environment
  --unzip-setuptools    Unzip Setuptools or Distribute when installing it
  --relocatable         Make an EXISTING virtualenv environment relocatable.
                        This fixes up scripts and makes all .pth files
                        relative
  --distribute          Use Distribute instead of Setuptools. Set environ
                        variable VIRTUALENV_USE_DISTRIBUTE to make it the
                        default
  --prompt==PROMPT      Provides an alternative prompt prefix for this
                        environment

1) What you want to do is install python to a directory that you are able to write too.

You can follow the instructions here.

For Python 2.7.1
Python source

mkdir ~/src
mkdir ~/.localpython
cd ~/src
wget http://www.python.org/ftp/python/2.7.1/Python-2.7.1.tgz
tar -zxvf Python-2.7.1.tgz
cd Python-2.7.1

make clean
./configure --prefix=/home/${USER}/.localpython
make
make install

2) Install virtualenv
virtualenv source

cd ~/src
wget http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.5.2.tar.gz#md5=fbcefbd8520bb64bc24a560c6019a73c
tar -zxvf virtualenv-1.5.2.tar.gz
cd virtualenv-1.5.2/
~/.localpython/bin/python setup.py install

3) Create a virtualenv using your local python
virtualenv docs

mkdir /home/${USER}/virtualenvs
cd /home/${USER}/virtualenvs
~/.localpython/bin/virtualenv py2.7 --python=/home/${USER}/.localpython/bin/python2.7

4) Activate the environment

cd ~/virtualenvs/py2.7/bin
source ./activate

5) Check

(py2.7)$ python
Python 2.7.1 (r271:86832, Mar 31 2011, 15:31:37) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

(py2.7)$ deactivate
$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

tsconfig.json: Build:No inputs were found in config file

I had existing tsconfig files for 4 existing projects in my solution. After upgrading to vs2017 I experienced this problem. It was fixed by adding the (supposedly default) include and exclude sections to the files, as described by NicoJuicy.

How to read values from properties file?

You need to put a PropertyPlaceholderConfigurer bean in your application context and set its location property.

See details here : http://www.zparacha.com/how-to-read-properties-file-in-spring/

You might have to modify your property file a bit for this thing to work.

Hope it helps.

Javascript How to define multiple variables on a single line?

Specifically to what the OP has asked, if you want to initialize N variables with the same value (e.g. 0), you can use array destructuring and Array.fill to assign to the variables an array of N 0s:

_x000D_
_x000D_
let [a, b, c, d] = Array(4).fill(0);_x000D_
_x000D_
console.log(a, b, c, d);
_x000D_
_x000D_
_x000D_

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

How to set DataGrid's row Background, based on a property value using data bindings

Use a DataTrigger:

<DataGrid ItemsSource="{Binding YourItemsSource}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow"> 
            <Style.Triggers>
                <DataTrigger Binding="{Binding State}" Value="State1">
                    <Setter Property="Background" Value="Red"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding State}" Value="State2">
                    <Setter Property="Background" Value="Green"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

How to vertically align text with icon font?

You can use this property : vertical-align:middle;

.selector-class { 
    float:left;
    vertical-align:middle; 
} 

Getting the textarea value of a ckeditor textarea with javascript

I'm still having problems figuring out exactly how I find out what a user is typing into a ckeditor textarea.

Ok, this is fairly easy. Assuming your editor is named "editor1", this will give you an alert with your its contents:

alert(CKEDITOR.instances.editor1.getData());

The harder part is detecting when the user types. From what I can tell, there isn't actually support to do that (and I'm not too impressed with the documentation btw). See this article: http://alfonsoml.blogspot.com/2011/03/onchange-event-for-ckeditor.html

Instead, I would suggest setting a timer that is going to continuously update your second div with the value of the textarea:

timer = setInterval(updateDiv,100);
function updateDiv(){
    var editorText = CKEDITOR.instances.editor1.getData();
    $('#trackingDiv').html(editorText);
}

This seems to work just fine. Here's the entire thing for clarity:

<textarea id="editor1" name="editor1">This is sample text</textarea>

<div id="trackingDiv" ></div>

<script type="text/javascript">
    CKEDITOR.replace( 'editor1' );

    timer = setInterval(updateDiv,100);
    function updateDiv(){
        var editorText = CKEDITOR.instances.editor1.getData();
        $('#trackingDiv').html(editorText);
    }
</script>

Reactive forms - disabled attribute

Initialization (component) using:

public selector = new FormControl({value: '', disabled: true});

Then instead of using (template):

<ngx-select
[multiple]="true"
[disabled]="errorSelector"
[(ngModel)]="ngxval_selector"
[items]="items"
</ngx-select>

Just remove the attribute disabled:

<ngx-select
[multiple]="true"
[(ngModel)]="ngxval_selector"
[items]="items"
</ngx-select>

And when you have items to show, launch (in component): this.selector.enable();

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

I use ? and ?, but they might not work for you. I use alt 11551 for the first one and 11550 for the second one. You can always copy paste them if the ascii isnt the same for your system.

a href link for entire div in HTML/CSS

This can be done in many ways. a. Using nested inside a tag.

<a href="link1.html">
   <div> Something in the div </div>
 </a>

b. Using the Inline JavaScript Method

<div onclick="javascript:window.location.href='link1.html' "> 
  Some Text 
</div>

c. Using jQuery inside tag

HTML:

<div class="demo" > Some text here </div>

jQuery:

$(".demo").click( function() {
  window.location.href="link1.html";
 });

Replace new line/return with space using regex

You May use first split and rejoin it using white space. it will work sure.

String[] Larray = L.split("[\\n]+");
L = "";
for(int i = 0; i<Larray.lengh; i++){
   L = L+" "+Larray[i];  
}

How to pass optional arguments to a method in C++?

An important rule with respect to default parameter usage:
Default parameters should be specified at right most end, once you specify a default value parameter you cannot specify non default parameter again. ex:

int DoSomething(int x, int y = 10, int z) -----------> Not Allowed

int DoSomething(int x, int z, int y = 10) -----------> Allowed 

How to initailize byte array of 100 bytes in java with all 0's

A new byte array will automatically be initialized with all zeroes. You don't have to do anything.

The more general approach to initializing with other values, is to use the Arrays class.

import java.util.Arrays;

byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );

How to trigger SIGUSR1 and SIGUSR2?

They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2) or using the utility kill(1).

If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).

How do you set the document title in React?

As others have mentioned, you can use document.title = 'My new title' and React Helmet to update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.

If you are using create-react-app the initial document title is set in the <title> tag /public/index.html file.

You can edit this directly or use a placeholder which will be filled from environmental variables:

/.env:

REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...

If for some reason I wanted a different title in my development environment -

/.env.development:

REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...

/public/index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
         ...
         <title>%REACT_APP_SITE_TITLE%</title>
         ...
     </head>
     <body>
         ...
     </body>
</html>

This approach also means that I can read the site title environmental variable from my application using the global process.env object, which is nice:

console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!

See: Adding Custom Environment Variables

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

Android 9 and Android 11 emulators have support for arm binaries.

https://developer.android.com/studio/releases/emulator#support_for_arm_binaries_on_android_9_and_11_system_images

I had the same issue while using x86 emulator with API level 29, trying to install an apk targeting arm ABI.

I tried x86 emulator with API level 30 and it worked fine.

Change UITableView height dynamically

There isn't a system feature to change the height of the table based upon the contents of the tableview. Having said that, it is possible to programmatically change the height of the tableview based upon the contents, specifically based upon the contentSize of the tableview (which is easier than manually calculating the height yourself). A few of the particulars vary depending upon whether you're using the new autolayout that's part of iOS 6, or not.

But assuming you're configuring your table view's underlying model in viewDidLoad, if you want to then adjust the height of the tableview, you can do this in viewDidAppear:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self adjustHeightOfTableview];
}

Likewise, if you ever perform a reloadData (or otherwise add or remove rows) for a tableview, you'd want to make sure that you also manually call adjustHeightOfTableView there, too, e.g.:

- (IBAction)onPressButton:(id)sender
{
    [self buildModel];
    [self.tableView reloadData];

    [self adjustHeightOfTableview];
}

So the question is what should our adjustHeightOfTableview do. Unfortunately, this is a function of whether you use the iOS 6 autolayout or not. You can determine if you have autolayout turned on by opening your storyboard or NIB and go to the "File Inspector" (e.g. press option+command+1 or click on that first tab on the panel on the right):

enter image description here

Let's assume for a second that autolayout was off. In that case, it's quite simple and adjustHeightOfTableview would just adjust the frame of the tableview:

- (void)adjustHeightOfTableview
{
    CGFloat height = self.tableView.contentSize.height;
    CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;

    // if the height of the content is greater than the maxHeight of
    // total space on the screen, limit the height to the size of the
    // superview.

    if (height > maxHeight)
        height = maxHeight;

    // now set the frame accordingly

    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.tableView.frame;
        frame.size.height = height;
        self.tableView.frame = frame;

        // if you have other controls that should be resized/moved to accommodate
        // the resized tableview, do that here, too
    }];
}

If your autolayout was on, though, adjustHeightOfTableview would adjust a height constraint for your tableview:

- (void)adjustHeightOfTableview
{
    CGFloat height = self.tableView.contentSize.height;
    CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;

    // if the height of the content is greater than the maxHeight of
    // total space on the screen, limit the height to the size of the
    // superview.

    if (height > maxHeight)
        height = maxHeight;

    // now set the height constraint accordingly

    [UIView animateWithDuration:0.25 animations:^{
        self.tableViewHeightConstraint.constant = height;
        [self.view setNeedsUpdateConstraints];
    }];
}

For this latter constraint-based solution to work with autolayout, we must take care of a few things first:

  1. Make sure your tableview has a height constraint by clicking on the center button in the group of buttons here and then choose to add the height constraint:

    add height constraint

  2. Then add an IBOutlet for that constraint:

    add IBOutlet

  3. Make sure you adjust other constraints so they don't conflict if you adjust the size tableview programmatically. In my example, the tableview had a trailing space constraint that locked it to the bottom of the screen, so I had to adjust that constraint so that rather than being locked at a particular size, it could be greater or equal to a value, and with a lower priority, so that the height and top of the tableview would rule the day:

    adjust other constraints

    What you do here with other constraints will depend entirely upon what other controls you have on your screen below the tableview. As always, dealing with constraints is a little awkward, but it definitely works, though the specifics in your situation depend entirely upon what else you have on the scene. But hopefully you get the idea. Bottom line, with autolayout, make sure to adjust your other constraints (if any) to be flexible to account for the changing tableview height.

As you can see, it's much easier to programmatically adjust the height of a tableview if you're not using autolayout, but in case you are, I present both alternatives.

How to convert a Drawable to a Bitmap?

public static Bitmap drawableToBitmap (Drawable drawable) {
    Bitmap bitmap = null;

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if(bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
    } else {
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

Wait for all promises to resolve

Recently had this problem but with unkown number of promises.Solved using jQuery.map().

function methodThatChainsPromises(args) {

    //var args = [
    //    'myArg1',
    //    'myArg2',
    //    'myArg3',
    //];

    var deferred = $q.defer();
    var chain = args.map(methodThatTakeArgAndReturnsPromise);

    $q.all(chain)
    .then(function () {
        $log.debug('All promises have been resolved.');
        deferred.resolve();
    })
    .catch(function () {
        $log.debug('One or more promises failed.');
        deferred.reject();
    });

    return deferred.promise;
}

How do I enumerate the properties of a JavaScript object?

for (prop in obj) {
    alert(prop + ' = ' + obj[prop]);
}

How do I specify different layouts for portrait and landscape orientations?

Create a new directory layout-land, then create xml file with same name in layout-land as it was layout directory and align there your content for Landscape mode.

Note that id of content in both xml is same.

CSS Input with width: 100% goes outside parent's bound

I tried these solutions but never got a conclusive result. In the end I used proper semantic markup with a fieldset. It saved having to add any width calculations and any box-sizing.

It also allows you to set the form width as you require and the inputs remain within the padding you need for your edges.

In this example I have put a border on the form and fieldset and an opaque background on the legend and fieldset so you can see how they overlap and sit with each other.

<html>
  <head>
  <style>
    form {
      width: 300px;
      margin: 0 auto;
      border: 1px solid;
    }
    fieldset {
      border: 0;
      margin: 0;
      padding: 0 20px 10px;
      border: 1px solid blue;
      background: rgba(0,0,0,.2);
    }
    legend {
      background: rgba(0,0,0,.2);
      width: 100%;
      margin: 0 -20px;
      padding: 2px 20px;
      color: $col1;
      border: 0;
    }
    input[type="email"],
    input[type="password"],
    button {
      width: 100%;
      margin: 0 0 10px;
      padding: 0 10px;
    }
    input[type="email"],
    input[type="password"] {
      line-height: 22px;
      font-size: 16px;
    }
    button {
    line-height: 26px;
    font-size: 20px;
    }
  </style>
  </head>
  <body>
  <form>
      <fieldset>
          <legend>Log in</legend>
          <p>You may need some content here, a message?</p>
          <input type="email" id="email" name="email" placeholder="Email" value=""/>
          <input type="password" id="password" name="password" placeholder="password" value=""/>
          <button type="submit">Login</button>
      </fieldset>
  </form>
  </body>
</html>

Returning pointer from a function

Although returning a pointer to a local object is bad practice, it didn't cause the kaboom here. Here's why you got a segfault:

int *fun()
{
    int *point;
    *point=12;  <<<<<<  your program crashed here.
    return point;
}

The local pointer goes out of scope, but the real issue is dereferencing a pointer that was never initialized. What is the value of point? Who knows. If the value did not map to a valid memory location, you will get a SEGFAULT. If by luck it mapped to something valid, then you just corrupted memory by overwriting that place with your assignment to 12.

Since the pointer returned was immediately used, in this case you could get away with returning a local pointer. However, it is bad practice because if that pointer was reused after another function call reused that memory in the stack, the behavior of the program would be undefined.

int *fun()
{
    int point;
    point = 12;
    return (&point);
}

or almost identically:

int *fun()
{
    int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

Another bad practice but safer method would be to declare the integer value as a static variable, and it would then not be on the stack and would be safe from being used by another function:

int *fun()
{
    static int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

or

int *fun()
{
    static int point;
    point = 12;
    return (&point);
}

As others have mentioned, the "right" way to do this would be to allocate memory on the heap, via malloc.

Javascript Object push() function

Javascript programming language supports functional programming paradigm so you can do easily with these codes.

var data = [
    {"Id": "1", "Status": "Valid"},
    {"Id": "2", "Status": "Invalid"}
];
var isValid = function(data){
    return data.Status === "Valid";
};
var valids = data.filter(isValid);

Set default host and port for ng serve in config file

This changed in the latest Angular CLI.

The file name changed to angular.json, and the structure also changed.

This is what you should do:

"projects": {
    "project-name": {
        ...
        "architect": {
            "serve": {
                "options": {
                  "host": "foo.bar",
                  "port": 80
                }
            }
        }
        ...
    }
}

How do I put a variable inside a string?

Oh, the many, many ways...

String concatenation:

plot.savefig('hanning' + str(num) + '.pdf')

Conversion Specifier:

plot.savefig('hanning%s.pdf' % num)

Using local variable names:

plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick

Using str.format():

plot.savefig('hanning{0}.pdf'.format(num)) # Note: This is the new preferred way

Using f-strings:

plot.savefig(f'hanning{num}.pdf') # added in Python 3.6

Using string.Template:

plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))

Invoking a static method using reflection

Fromthe Javadoc of Method.invoke():

If the underlying method is static, then the specified obj argument is ignored. It may be null.

What happens when you

Class klass = ...;
Method m = klass.getDeclaredMethod(methodName, paramtypes);
m.invoke(null, args)

Get specific line from text file using just shell script

In parallel with William Pursell's answer, here is a simple construct which should work even in the original v7 Bourne shell (and thus also places where Bash is not available).

i=0
while read line; do
    i=`expr "$i" + 1`
    case $i in 5) echo "$line"; break;; esac
done <file

Notice also the optimization to break out of the loop when we have obtained the line we were looking for.

Python PDF library

Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

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

Splitting it looks like the best option in to me:

'1111342=Adam%20Franco&348572=Bob%20Jones'.split('&').map(x => x.match(/(?:&|&amp;)?([^=]+)=([^&]+)/))

How do I disable and re-enable a button in with javascript?

<script>
function checkusers()
{
   var shouldEnable = document.getElementById('checkbox').value == 0;
   document.getElementById('add_button').disabled = shouldEnable;
}
</script>

How can I determine whether a 2D Point is within a Polygon?

The answer depends on if you have the simple or complex polygons. Simple polygons must not have any line segment intersections. So they can have the holes but lines can't cross each other. Complex regions can have the line intersections - so they can have the overlapping regions, or regions that touch each other just by a single point.

For simple polygons the best algorithm is Ray casting (Crossing number) algorithm. For complex polygons, this algorithm doesn't detect points that are inside the overlapping regions. So for complex polygons you have to use Winding number algorithm.

Here is an excellent article with C implementation of both algorithms. I tried them and they work well.

http://geomalgorithms.com/a03-_inclusion.html

How does System.out.print() work?

Evidently, the compiler was made in a confusing way although the compiler developers thought they added some smartness. The true smartness they should really add is to look entire argument and interpret + operator consistently. For example, System.out.println(1+2+"hello"+3+4); should output 3hello7 instead of 3hello34

What is the first character in the sort order used by Windows Explorer?

I know there is already an answer - and this is an old question - but I was wondering the same thing and after finding this answer I did a little experimentation on my own and had (IMO) a worthwhile addition to the discussion.

The non-visible characters can still be used in a folder name - a placeholder is inserted - but the sort on ASCII value still seems to hold.

I tested on Windows7, holding down the alt-key and typing in the ASCII code using the numeric keypad. I did not test very many, but was successful creating foldernames that started with ASCII 1, ASCII 2, and ASCII 3. Those correspond with SOH, STX and ETX. Respectively it displayed happy face, filled happy face, and filled heart.

I'm not sure if I can duplicate that here - but I will type them in on the next lines and submit.

?foldername

?foldername

?foldername

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

Email Address Validation in Android on EditText

Use this method for validating your email format. Pass email as string , it returns true if format is correct otherwise false.

/**
 * validate your email address format. [email protected]
 */
public boolean emailValidator(String email) 
{
    Pattern pattern;
    Matcher matcher;
    final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    pattern = Pattern.compile(EMAIL_PATTERN);
    matcher = pattern.matcher(email);
    return matcher.matches();
}

How can I open a website in my web browser using Python?

If you want to open a specific browser (e.g. Chrome and Chromium) with command line options like full screen or kiosk mode and also want to be able to kill it later on, then this might work for you:

from threading import Timer
from time import sleep

import subprocess
import platform

# Hint 1: to enable F11 use --start-fullscreen instead of --kiosk, otherwise Alt+F4 to close the browser   
# Hint 2: fullscreen will only work if chrome is not already running

platform_browser = {
'Windows': r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://stackoverflow.com',
'Linux' : ['/usr/bin/chromium-browser', '--kiosk', 'http://stackoverflow.com']
}

browser = None
def open_browser():
    global browser

    platform_name = platform.system()

    if platform_name in  platform_browser:        
        browser = subprocess.Popen(platform_browser[platform_name])
    else:
        print(":-(")

Timer(1, open_browser).start() # delayed start, give e.g. your own web server time to launch

sleep(20) # start e.g. your python web server here instead

browser.kill()

Changing all files' extensions in a folder with one command on Windows

Rename multiple file extensions:

You want to change ringtone1.mp3, ringtone2.mp3 to ringtone1.wav, ringtone2.wav

Here is how to do that: I am in d drive on command prompt (CMD) so I use:

d:\>ren *.* *.wav 

This is just an example of file extensions, you can use any type of file extension like WAV, MP3, JPG, GIF, bmp, PDF, DOC, DOCX, TXT this depends on what your operating system.

And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.

Cannot implicitly convert type from Task<>

You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

public Task<List<int>> TestGetMethod()
{
    return GetIdList();
}    

async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

Another option

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet, it has nothing to do with the distance between the two routers. The propagation delay is the time taken by a bit to to propagate form one router to the next

What special characters must be escaped in regular expressions?

Unfortunately there really isn't a set set of escape codes since it varies based on the language you are using.

However, keeping a page like the Regular Expression Tools Page or this Regular Expression Cheatsheet can go a long way to help you quickly filter things out.

Find the location of a character in string

find the position of the nth occurrence of str2 in str1(same order of parameters as Oracle SQL INSTR), returns 0 if not found

instr <- function(str1,str2,startpos=1,n=1){
    aa=unlist(strsplit(substring(str1,startpos),str2))
    if(length(aa) < n+1 ) return(0);
    return(sum(nchar(aa[1:n])) + startpos+(n-1)*nchar(str2) )
}


instr('xxabcdefabdddfabx','ab')
[1] 3
instr('xxabcdefabdddfabx','ab',1,3)
[1] 15
instr('xxabcdefabdddfabx','xx',2,1)
[1] 0

Launch custom android application from android browser

example.php:

<?php
if(!isset($_GET['app_link'])){  ?>   
    <iframe src="example.php?app_link=YourApp://blabla" style="display:none;" scrolling="no" frameborder="0"></iframe>
    <iframe src="example.php?full_link=http://play.google.com/xyz" style="display:none;" scrolling="no" frameborder="0"></iframe>
    <?php 
}
else { ?>
    <script type="text/javascript">
    self.window.location        = '<?php echo $_GET['app_link'];?>';
    window.parent.location.href = '<?php echo $_GET['full_link'];?>';
    </script>
<?php 
}

Javascript "Uncaught TypeError: object is not a function" associativity question

Try to have the function body before the function call in your JavaScript file.

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

This is similar to some of the other answers, but is compact and avoids the conversion to dictionary if you already have a list.

Given a ComboBox "combobox" on a windows form and a class SomeClass with the string type property Name,

List<SomeClass> list = new List<SomeClass>();

combobox.DisplayMember = "Name";
combobox.DataSource = list;

Which means that combobox.SelectedItem is a SomeClass object from list, and each item in combobox will be displayed using its property Name.

You can read the selected item using

SomeClass someClass = (SomeClass)combobox.SelectedItem;

How to use radio on change event?

If the radio buttons are added dynamically, you may wish to use this

$(document).on('change', 'input[type=radio][name=bedStatus]', function (event) {
    switch($(this).val()) {
      case 'allot' :
        alert("Allot Thai Gayo Bhai");
        break;
      case 'transfer' :
        alert("Transfer Thai Gayo");
        break;
    }     
});

What is uintptr_t data type

First thing, at the time the question was asked, uintptr_t was not in C++. It's in C99, in <stdint.h>, as an optional type. Many C++03 compilers do provide that file. It's also in C++11, in <cstdint>, where again it is optional, and which refers to C99 for the definition.

In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".

Take this to mean what it says. It doesn't say anything about size.

uintptr_t might be the same size as a void*. It might be larger. It could conceivably be smaller, although such a C++ implementation approaches perverse. For example on some hypothetical platform where void* is 32 bits, but only 24 bits of virtual address space are used, you could have a 24-bit uintptr_t which satisfies the requirement. I don't know why an implementation would do that, but the standard permits it.

How to copy file from HDFS to the local file system

1.- Remember the name you gave to the file and instead of using hdfs dfs -put. Use 'get' instead. See below.

$hdfs dfs -get /output-fileFolderName-In-hdfs

difference between System.out.println() and System.err.println()

System.out.println("wassup"); refers to when you have to output a certain result pertaining to the proper input given by the user whereas System.err.println("duh, that's wrong); is a reference to show that the input provided is wrong or there is some other error.

Most of the IDEs show this in red color (System.err.print).

How do I limit the number of results returned from grep?

Using tail:

#dmesg 
...
...
...
[132059.017752] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
[132116.566238] cfg80211: Calling CRDA to update world regulatory domain
[132116.568939] cfg80211: World regulatory domain updated:
[132116.568942] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132116.568944] cfg80211:   (2402000 KHz - 2472000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568945] cfg80211:   (2457000 KHz - 2482000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568947] cfg80211:   (2474000 KHz - 2494000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
[132116.568948] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568949] cfg80211:   (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132120.288218] cfg80211: Calling CRDA for country: GB
[132120.291143] cfg80211: Regulatory domain changed to country: GB
[132120.291146] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132120.291148] cfg80211:   (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211:   (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | head 2
head: cannot open ‘2’ for reading: No such file or directory
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -2
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -5
[132120.291148] cfg80211:   (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211:   (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -6
[132120.291146] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132120.291148] cfg80211:   (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211:   (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ 

Getting "cannot find Symbol" in Java project in Intellij

I was having the same problem except that I was importing the classes for which dependencies were not resolving somehow. I refreshed maven projects, Rebuild Project. It still did not resolve. Looks like IntelliJ was caching something incorrectly. I restarted IntelliJ and that resolved the dependencies. I guess it cleared the cache somehow.

Getters \ setters for dummies

You'd use them for instance to implement computed properties.

For example:

function Circle(radius) {
    this.radius = radius;
}

Object.defineProperty(Circle.prototype, 'circumference', {
    get: function() { return 2*Math.PI*this.radius; }
});

Object.defineProperty(Circle.prototype, 'area', {
    get: function() { return Math.PI*this.radius*this.radius; }
});

c = new Circle(10);
console.log(c.area); // Should output 314.159
console.log(c.circumference); // Should output 62.832

(CodePen)

How to make a variable accessible outside a function?

$.getJSON is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.

Alternatively you could use jQuery's $.when/.then(), similar to this:

var input = "netuetamundis";  var sID;  $(document).ready(function () {     $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () {         obj = name;         sID = obj.id;         console.log(sID);     })).then(function () {         $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function (stats) {             console.log(stats);         });     }); }); 

This would be more open for future modification and separates out the responsibility for the first call to know about the second call.

The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.

How can I get the average (mean) of selected columns

Try using rowMeans:

z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)

  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

what is the basic difference between stack and queue?

To try and over-simplify the description of a stack and a queue, They are both dynamic chains of information elements that can be accessed from one end of the chain and the only real difference between them is the fact that:

when working with a stack

  • you insert elements at one end of the chain and
  • you retrieve and/or remove elements from the same end of the chain

while with a queue

  • you insert elements at one end of the chain and
  • you retrieve/remove them from the other end

NOTE: I am using the abstract wording of retrieve/remove in this context because there are instances when you just retrieve the element from the chain or in a sense just read it or access its value, but there also instances when you remove the element from the chain and finally there are instances when you do both actions with the same call.

Also the word element is purposely used in order to abstract the imaginary chain as much as possible and decouple it from specific programming language terms. This abstract information entity called element could be anything, from a pointer, a value, a string or characters, an object,... depending on the language.

In most cases, though it is actually either a value or a memory location (i.e. a pointer). And the rest are just hiding this fact behind the language jargon<

A queue can be helpful when the order of the elements is important and needs to be exactly the same as when the elements first came into your program. For instance when you process an audio stream or when you buffer network data. Or when you do any type of store and forward processing. In all of these cases you need the sequence of the elements to be output in the same order as they came into your program, otherwise the information may stop making sense. So, you could break your program in a part that reads data from some input, does some processing and writes them in a queue and a part that retrieves data from the queue processes them and stores them in another queue for further processing or transmitting the data.

A stack can be helpful when you need to temporarily store an element that is going to be used in the immediate step(s) of your program. For instance, programming languages usually use a stack structure to pass variables to functions. What they actually do is store (or push) the function arguments in the stack and then jump to the function where they remove and retrieve (or pop) the same number of elements from the stack. That way the size of the stack is dependent of the number of nested calls of functions. Additionally, after a function has been called and finished what it was doing, it leaves the stack in the exact same condition as before it has being called! That way any function can operate with the stack ignoring how other functions operate with it.

Lastly, you should know that there are other terms used out-there for the same of similar concepts. For instance a stack could be called a heap. There are also hybrid versions of these concepts, for instance a double-ended queue can behave at the same time as a stack and as a queue, because it can be accessed by both ends simultaneously. Additionally, the fact that a data structure is provided to you as a stack or as a queue it does not necessarily mean that it is implemented as such, there are instances in which a data structure can be implemented as anything and be provided as a specific data structure simply because it can be made to behave like such. In other words, if you provide a push and pop method to any data structure, they magically become stacks!

How can I generate Javadoc comments in Eclipse?

JAutoDoc:

an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers...

How can I check whether Google Maps is fully loaded?

If you're using the Maps API v3, this has changed.

In version 3, you essentially want to set up a listener for the bounds_changed event, which will trigger upon map load. Once that has triggered, remove the listener as you don't want to be informed every time the viewport bounds change.

This may change in the future as the V3 API is evolving :-)

Hash function for a string

Hash functions for algorithmic use have usually 2 goals, first they have to be fast, second they have to evenly distibute the values across the possible numbers. The hash function also required to give the all same number for the same input value.

if your values are strings, here are some examples for bad hash functions:

  1. string[0] - the ASCII characters a-Z are way more often then others
  2. string.lengh() - the most probable value is 1

Good hash functions tries to use every bit of the input while keeping the calculation time minimal. If you only need some hash code, try to multiply the bytes with prime numbers, and sum them.

Replace multiple characters in a C# string

Strings are just immutable char arrays

You just need to make it mutable:

  • either by using StringBuilder
  • go in the unsafe world and play with pointers (dangerous though)

and try to iterate through the array of characters the least amount of times. Note the HashSet here, as it avoids to traverse the character sequence inside the loop. Should you need an even faster lookup, you can replace HashSet by an optimized lookup for char (based on an array[256]).

Example with StringBuilder

public static void MultiReplace(this StringBuilder builder, 
    char[] toReplace, 
    char replacement)
{
    HashSet<char> set = new HashSet<char>(toReplace);
    for (int i = 0; i < builder.Length; ++i)
    {
        var currentCharacter = builder[i];
        if (set.Contains(currentCharacter))
        {
            builder[i] = replacement;
        }
    }
}

Edit - Optimized version

public static void MultiReplace(this StringBuilder builder, 
    char[] toReplace,
    char replacement)
{
    var set = new bool[256];
    foreach (var charToReplace in toReplace)
    {
        set[charToReplace] = true;
    }
    for (int i = 0; i < builder.Length; ++i)
    {
        var currentCharacter = builder[i];
        if (set[currentCharacter])
        {
            builder[i] = replacement;
        }
    }
}

Then you just use it like this:

var builder = new StringBuilder("my bad,url&slugs");
builder.MultiReplace(new []{' ', '&', ','}, '-');
var result = builder.ToString();

How to import a single table in to mysql database using command line

  • It would be combination of EXPORT INTO OUTFILE and LOAD DATA INFILE

  • You need to export that single table with EXPORT INTO OUTFILE, this will export table data to a file. You can import that particular table using LOAD DATA INFILE

  • Refer doc1 , doc2

AVD Manager - No system image installed for this target

you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

if not installed ARM EABI v7a System Image, you should install all.

Post parameter is always null

After some tries, I think the default behavior is correct and there is nothing to hack.

The only trick is: if your post method argument is string like below, you should send a plain string with double quotes in the body (when using ajax or postman), e.g.,

//send "{\"a\":1}" in body to me, note the outer double quotes
[HttpPost("api1")]
public String PostMethod1([FromBody]string value)
{
    return "received " + value; //  "received {\"a\":1}"
}

Otherwise if you send a json string in the post body without outer double quotes and escaped inner quotes, then it should be able to be parsed to the model class (the argument type), e.g., {"a":1, "b":2}

public class MyPoco{
    public int a;
    public int b;
}

//send {"a":1, "b":2} in body to me
[HttpPost("api2")]
public String PostMethod2([FromBody]MyPoco value)
{
    return "received " + value.ToString();  //"received your_namespace+MyPoco"
}

can't load package: package .: no buildable Go source files

Make sure you are using that command in the Go project source folder (like /Users/7yan00/Golang/src/myProject).

One alternative (similar to this bug) is to use the -d option (see go get command)

go get -d

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

See if that helps in your case.


But more generally, as described in this thread:

go get is for package(s), not for repositories.

so if you want a specific package, say, go.text/encoding, then use

go get code.google.com/p/go.text/encoding

if you want all packages in that repository, use ... to signify that:

go get code.google.com/p/go.text/...

How to revert multiple git commits?

I really wanted to avoid hard resets, this is what I came up with.

A -> B -> C -> D -> HEAD

To go back to A (which is 4 steps back):

git pull                  # Get latest changes
git reset --soft HEAD~4   # Set back 4 steps
git stash                 # Stash the reset
git pull                  # Go back to head
git stash pop             # Pop the reset 
git commit -m "Revert"    # Commit the changes

Vagrant ssh authentication failure

This the all correct steps that I followed for fix this bellow issue occurred when vagrant up command run.

These are the steps that I followed

  1. create a folder. e.g F:\projects
  2. Open this folder in git bash and run this command ssh-keygen -t rsa -b 4096 -C "[email protected]" (put a valid email address)
  3. Then generating key pair in two separate files in the project folder. e.g project(private key file), project.pub (public key file)
  4. Go to this location C:\Users\acer.vagrant.d and find file insecure_private_key
  5. Get backup of the file and copy the content of newly created private key and paste it in insecure_private_key file. Then copy insecure_private_key and paste it in this location too.
  6. Now vagrant up in your project location. after generating above issue type vagrant ssh and go inside giving username, password. (in default username and password is set as vagrant)
  7. Go inside to this location cd /home/vagrant/.ssh and type mv authorized_keys authorized_keys_bk
  8. Then type ls -al and type vi authorized_keys for open authorized_keys file vi editor.
  9. Open generated public key from notepad++ (project.pub) and copy content Then press i on git bash to enable insert mode on vi editor and right click and paste. After press escape to get out from insert mode
  10. :wq! for save the file and type ls -al
  11. Then permissions are set like bellow no need to change drwx------. 2 vagrant vagrant 4096 Feb 13 15:33 . drwx------. 4 vagrant vagrant 4096 Feb 13 14:04 .. -rw-------. 1 vagrant vagrant 743 Feb 13 14:26 authorized_keys -rw-------. 1 root root 409 Feb 13 13:57 authorized_keys_bk -rw-------. 1 vagrant vagrant 409 Jan 2 23:09 authorized_keys_originial Otherwise type chmod 600 authorized_keys and type this command too chown vagrant:vagrant authorized_keys
  12. Finally run the vagrant halt and vagrant up again.

************************THIS IS WORK FINE FOR ME*******************************

Why is my power operator (^) not working?

Instead of using ^, use 'pow' function which is a predefined function which performs the Power operation and it can be used by including math.h header file.

^ This symbol performs BIT-WISE XOR operation in C, C++.

Replace a^i with pow(a,i).