Programs & Examples On #Linux kernel

This tag is for questions about the internals of the Linux kernel itself - particularly about writing code that runs within the context of the kernel (like kernel modules or drivers). Questions about writing userspace code in Linux should generally be tagged [linux] instead. Since the internals of the Linux kernel are constantly changing, it is helpful to include the precise kernel version(s) that you are interested in.

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

In many linux release, you can find complier.h in /usr/linux/ , you can include it for use simply. And another opinion, unlikely() is more useful rather than likely(), because

if ( likely( ... ) ) {
     doSomething();
}

it can be optimized as well in many compiler.

And by the way, if you want to observe the detail behavior of the code, you can do simply as follow:

gcc -c test.c objdump -d test.o > obj.s

Then, open obj.s, you can find the answer.

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

Summary

As mentioned by Ignacio, it updates your .config for you after you update the kernel source, e.g. with git pull.

It tries to keep your existing options.

Having a script for that is helpful because:

  • new options may have been added, or old ones removed

  • the kernel's Kconfig configuration format has options that:

    • imply one another via select
    • depend on another via depends

    Those option relationships make manual config resolution even harder.

Let's modify .config manually to understand how it resolves configurations

First generate a default configuration with:

make defconfig

Now edit the generated .config file manually to emulate a kernel update and run:

make oldconfig

to see what happens. Some conclusions:

  1. Lines of type:

    # CONFIG_XXX is not set
    

    are not mere comments, but actually indicate that the parameter is not set.

    For example, if we remove the line:

    # CONFIG_DEBUG_INFO is not set
    

    and run make oldconfig, it will ask us:

    Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
    

    When it is over, the .config file will be updated.

    If you change any character of the line, e.g. to # CONFIG_DEBUG_INFO, it does not count.

  2. Lines of type:

    # CONFIG_XXX is not set
    

    are always used for the negation of a property, although:

    CONFIG_XXX=n
    

    is also understood as the negation.

    For example, if you remove # CONFIG_DEBUG_INFO is not set and answer:

    Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
    

    with N, then the output file contains:

    # CONFIG_DEBUG_INFO is not set
    

    and not:

    CONFIG_DEBUG_INFO=n
    

    Also, if we manually modify the line to:

    CONFIG_DEBUG_INFO=n
    

    and run make oldconfig, then the line gets modified to:

    # CONFIG_DEBUG_INFO is not set
    

    without oldconfig asking us.

  3. Configs whose dependencies are not met, do not appear on the .config. All others do.

    For example, set:

    CONFIG_DEBUG_INFO=y
    

    and run make oldconfig. It will now ask us for: DEBUG_INFO_REDUCED, DEBUG_INFO_SPLIT, etc. configs.

    Those properties did not appear on the defconfig before.

    If we look under lib/Kconfig.debug where they are defined, we see that they depend on DEBUG_INFO:

    config DEBUG_INFO_REDUCED
        bool "Reduce debugging information"
        depends on DEBUG_INFO
    

    So when DEBUG_INFO was off, they did not show up at all.

  4. Configs which are selected by turned on configs are automatically set without asking the user.

    For example, if CONFIG_X86=y and we remove the line:

    CONFIG_ARCH_MIGHT_HAVE_PC_PARPORT=y
    

    and run make oldconfig, the line gets recreated without asking us, unlike DEBUG_INFO.

    This happens because arch/x86/Kconfig contains:

    config X86
        def_bool y
        [...]
        select ARCH_MIGHT_HAVE_PC_PARPORT
    

    and select forces that option to be true. See also: https://unix.stackexchange.com/questions/117521/select-vs-depends-in-kernel-kconfig

  5. Configs whose constraints are not met are asked for.

    For example, defconfig had set:

    CONFIG_64BIT=y
    CONFIG_RCU_FANOUT=64
    

    If we edit:

    CONFIG_64BIT=n
    

    and run make oldconfig, it will ask us:

    Tree-based hierarchical RCU fanout value (RCU_FANOUT) [32] (NEW)
    

    This is because RCU_FANOUT is defined at init/Kconfig as:

    config RCU_FANOUT
        int "Tree-based hierarchical RCU fanout value"
        range 2 64 if 64BIT
        range 2 32 if !64BIT
    

    Therefore, without 64BIT, the maximum value is 32, but we had 64 set on the .config, which would make it inconsistent.

Bonuses

make olddefconfig sets every option to their default value without asking interactively. It gets run automatically on make to ensure that the .config is consistent in case you've modified it manually like we did. See also: https://serverfault.com/questions/116299/automatically-answer-defaults-when-doing-make-oldconfig-on-a-kernel-tree

make alldefconfig is like make olddefconfig, but it also accepts a config fragment to merge. This target is used by the merge_config.sh script: https://stackoverflow.com/a/39440863/895245

And if you want to automate the .config modification, that is not too simple: How do you non-interactively turn on features in a Linux kernel .config file?

Selecting a Linux I/O Scheduler

As documented in /usr/src/linux/Documentation/block/switching-sched.txt, the I/O scheduler on any particular block device can be changed at runtime. There may be some latency as the previous scheduler's requests are all flushed before bringing the new scheduler into use, but it can be changed without problems even while the device is under heavy use.

# cat /sys/block/hda/queue/scheduler
noop deadline [cfq]
# echo anticipatory > /sys/block/hda/queue/scheduler
# cat /sys/block/hda/queue/scheduler
noop [deadline] cfq

Ideally, there would be a single scheduler to satisfy all needs. It doesn't seem to exist yet. The kernel often doesn't have enough knowledge to choose the best scheduler for your workload:

  • noop is often the best choice for memory-backed block devices (e.g. ramdisks) and other non-rotational media (flash) where trying to reschedule I/O is a waste of resources
  • deadline is a lightweight scheduler which tries to put a hard limit on latency
  • cfq tries to maintain system-wide fairness of I/O bandwidth

The default was anticipatory for a long time, and it received a lot of tuning, but was removed in 2.6.33 (early 2010). cfq became the default some while ago, as its performance is reasonable and fairness is a good goal for multi-user systems (and even single-user desktops). For some scenarios -- databases are often used as examples, as they tend to already have their own peculiar scheduling and access patterns, and are often the most important service (so who cares about fairness?) -- anticipatory has a long history of being tunable for best performance on these workloads, and deadline very quickly passes all requests through to the underlying device.

Finding which process was killed by Linux OOM killer

Try this out:

grep -i 'killed process' /var/log/messages

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

Finaly, my service provider answered :

This is a limitation of the virtualization system we use (OpenVZ), basic iptables rules are possible but not those who use the nat table.

If this really is a problem, we can offer you to migrate to a other system virtualization (KVM) as we begin to offer our customers.

SO I had to migrate my server to the new system...

Is bool a native C type?

No such thing, probably just a macro for int

Read/write files within a Linux kernel module

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:

Includes:

#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

Opening a file (similar to open):

struct file *file_open(const char *path, int flags, int rights) 
{
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    set_fs(get_ds());
    filp = filp_open(path, flags, rights);
    set_fs(oldfs);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    }
    return filp;
}

Close a file (similar to close):

void file_close(struct file *file) 
{
    filp_close(file, NULL);
}

Reading data from a file (similar to pread):

int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_read(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}   

Writing data to a file (similar to pwrite):

int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

Syncing changes a file (similar to fsync):

int file_sync(struct file *file) 
{
    vfs_fsync(file, 0);
    return 0;
}

[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.

What is the difference between the kernel space and the user space?

The really simplified answer is that the kernel runs in kernel space, and normal programs run in user space. User space is basically a form of sand-boxing -- it restricts user programs so they can't mess with memory (and other resources) owned by other programs or by the OS kernel. This limits (but usually doesn't entirely eliminate) their ability to do bad things like crashing the machine.

The kernel is the core of the operating system. It normally has full access to all memory and machine hardware (and everything else on the machine). To keep the machine as stable as possible, you normally want only the most trusted, well-tested code to run in kernel mode/kernel space.

The stack is just another part of memory, so naturally it's segregated right along with the rest of memory.

What is ":-!!" in C code?

It's creating a size 0 bitfield if the condition is false, but a size -1 (-!!1) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1 bitfield is created, of course).

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

"FATAL: Module not found error" using modprobe

The best thing is to actually use the kernel makefile to install the module:

Here is are snippets to add to your Makefile

around the top add:

PWD=$(shell pwd)
VER=$(shell uname -r)
KERNEL_BUILD=/lib/modules/$(VER)/build
# Later if you want to package the module binary you can provide an INSTALL_ROOT
# INSTALL_ROOT=/tmp/install-root

around the end add:

install:
        $(MAKE) -C $(KERNEL_BUILD) M=$(PWD) \
           INSTALL_MOD_PATH=$(INSTALL_ROOT) modules_install

and then you can issue

    sudo make install

this will put it either in /lib/modules/$(uname -r)/extra/

or /lib/modules/$(uname -r)/misc/

and run depmod appropriately

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

IOCTL Linux device driver

An ioctl, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.

An alternative is the sysfs interface, where you set up a file under /sys/ and read/write that to get information from and to the driver. An example of how to set this up:

static ssize_t mydrvr_version_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
    return sprintf(buf, "%s\n", DRIVER_RELEASE);
}

static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);

And during driver setup:

device_create_file(dev, &dev_attr_version);

You would then have a file for your device in /sys/, for example, /sys/block/myblk/version for a block driver.

Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl or libnl3 libraries.

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

I just came across this problem when I replaced a failing disk. I had copied over the system files to the new disk, and was good about replacing the old disk's UUID entry with the new disk's UUID in fstab.

However I had not replaced the UUID in the grub.conf (sometimes menu.lst) file in /boot/grub. So check your grub.conf file, and if the "kernel" line has something like

kernel ... root=UUID=906eaa97-f66a-4d39-a39d-5091c7095987 

it likely has the old disk's UUID. Replace it with the new disk's UUID and run grub-install (if you're in a live CD rescue you may need to chroot or specify the grub directory).

What is the difference between vmalloc and kmalloc?

What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call? Is there any reason I couldn't just use vmalloc?

From Google's "I'm Feeling Lucky" on vmalloc:

kmalloc is the preferred way, as long as you don't need very big areas. The trouble is, if you want to do DMA from/to some hardware device, you'll need to use kmalloc, and you'll probably need bigger chunk. The solution is to allocate memory as soon as possible, before memory gets fragmented.

How do I delete virtual interface in Linux?

Have you tried:

ifconfig 10:35978f0 down

As the physical interface is 10 and the virtual aspect is after the colon :.

See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

The most useful thing you can do here is display/i $pc, before using stepi as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi command.

(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

To fix this problem, you have to install OpenSSL development package, which is available in standard repositories of all modern Linux distributions.

To install OpenSSL development package on Debian, Ubuntu or their derivatives:

$ sudo apt-get install libssl-dev

To install OpenSSL development package on Fedora, CentOS or RHEL:

$ sudo yum install openssl-devel 

Edit : As @isapir has pointed out, for Fedora version>=22 use the DNF package manager :

dnf install openssl-devel

Increasing the maximum number of TCP/IP connections in Linux

In an application level, here are something a developer can do:

From server side:

  1. Check if load balancer(if you have),works correctly.

  2. Turn slow TCP timeouts into 503 Fast Immediate response, if you load balancer work correctly, it should pick the working resource to serve, and it's better than hanging there with unexpected error massages.

Eg: If you are using node server, u can use toobusy from npm. Implementation something like:

var toobusy = require('toobusy');
app.use(function(req, res, next) {
  if (toobusy()) res.send(503, "I'm busy right now, sorry.");
  else next();
});

Why 503? Here are some good insights for overload: http://ferd.ca/queues-don-t-fix-overload.html

We can do some work in client side too:

  1. Try to group calls in batch, reduce the traffic and total requests number b/w client and server.

  2. Try to build a cache mid-layer to handle unnecessary duplicates requests.

How do you use MySQL's source command to import large files in windows

For importing a large SQL file using the command line in MySQL.

First go to file path at the command line. Then,

Option 1:

mysql -u {user_name} -p{password} {database_name}  < your_file.sql

It's give a warning mesaage : Using a password on the command line interface can be insecure.

Done.Your file will be imported.

Option 2:

mysql -u {user_name} -p {database_name}  < your_file.sql

in this you are not provide sql password then they asked for password just enter password and your file will be imported.

Increasing nesting function calls limit

Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.

I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.

E: Unable to locate package mongodb-org

sudo apt-get install -y mongodb 

it works for 32-bit ubuntu, try it.best of luck.

Correct way to push into state array

Using Functional Components and React Hooks

const [array,setArray] = useState([]);

Push value at the end:

setArray(oldArray => [...oldArray,newValue] );

Push value at the begging:

setArray(oldArray => [newValue,...oldArrays] );

Multiple "order by" in LINQ

Add "new":

var movies = _db.Movies.OrderBy( m => new { m.CategoryID, m.Name })

That works on my box. It does return something that can be used to sort. It returns an object with two values.

Similar, but different to sorting by a combined column, as follows.

var movies = _db.Movies.OrderBy( m => (m.CategoryID.ToString() + m.Name))

How to open VMDK File of the Google-Chrome-OS bundle 2012?

VMDK is a virtual disk file, what you need is a VMX file. Cruise on over to EasyVMX and have it create one for you, then just replace the VMDK file it gives you with the Cnrome OS one.

EasyVMX is good since VMWare Player has no VM creation stuff in it (at least in version 2, not sure about 3). You had to use one of VMWare's other products to do that.

SimpleXml to string

You can use ->child to get a child element named child.

This element will contain the text of the child element.

But if you try var_dump() on that variable, you will see it is not actually a PHP string.

The easiest way around this is to perform a strval(xml->child); That will convert it to an actual PHP string.

This is useful when debugging when looping your XML and using var_dump() to check the result.

So $s = strval($xml->child);.

EditorFor() and html properties

The problem is, your template can contain several HTML elements, so MVC won't know to which one to apply your size/class. You'll have to define it yourself.

Make your template derive from your own class called TextBoxViewModel:

public class TextBoxViewModel
{
  public string Value { get; set; }
  IDictionary<string, object> moreAttributes;
  public TextBoxViewModel(string value, IDictionary<string, object> moreAttributes)
  {
    // set class properties here
  }
  public string GetAttributesString()
  {
     return string.Join(" ", moreAttributes.Select(x => x.Key + "='" + x.Value + "'").ToArray()); // don't forget to encode
  }

}

In the template you can do this:

<input value="<%= Model.Value %>" <%= Model.GetAttributesString() %> />

In your view you do:

<%= Html.EditorFor(x => x.StringValue) %>
or
<%= Html.EditorFor(x => new TextBoxViewModel(x.StringValue, new IDictionary<string, object> { {'class', 'myclass'}, {'size', 15}}) %>

The first form will render default template for string. The second form will render the custom template.

Alternative syntax use fluent interface:

public class TextBoxViewModel
{
  public string Value { get; set; }
  IDictionary<string, object> moreAttributes;
  public TextBoxViewModel(string value, IDictionary<string, object> moreAttributes)
  {
    // set class properties here
    moreAttributes = new Dictionary<string, object>();
  }

  public TextBoxViewModel Attr(string name, object value)
  {
     moreAttributes[name] = value;
     return this;
  }

}

   // and in the view
   <%= Html.EditorFor(x => new TextBoxViewModel(x.StringValue).Attr("class", "myclass").Attr("size", 15) %>

Notice that instead of doing this in the view, you may also do this in controller, or much better in the ViewModel:

public ActionResult Action()
{
  // now you can Html.EditorFor(x => x.StringValue) and it will pick attributes
  return View(new { StringValue = new TextBoxViewModel(x.StringValue).Attr("class", "myclass").Attr("size", 15) });
}

Also notice that you can make base TemplateViewModel class - a common ground for all your view templates - which will contain basic support for attributes/etc.

But in general I think MVC v2 needs a better solution. It's still Beta - go ask for it ;-)

Get current AUTO_INCREMENT value for any table

Even though methai's answer is correct if you manually run the query, a problem occurs when 2 concurrent transaction/connections actually execute this query at runtime in production (for instance).

Just tried manually in MySQL workbench with 2 connections opened simultaneously:

CREATE TABLE translation (
  id BIGINT PRIMARY KEY AUTO_INCREMENT
);
# Suppose we have already 20 entries, we execute 2 new inserts:

Transaction 1:

21 = SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES
     WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'translation';

insert into translation (id) values (21);

Transaction 2:

21 = SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES
     WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'translation';

insert into translation (id) values (21);

# commit transaction 1;
# commit transaction 2;

Insert of transaction 1 is ok: Insert of transaction 2 goes in error: Error Code: 1062. Duplicate entry '21' for key 'PRIMARY'.

A good solution would be jvdub's answer because per transaction/connection the 2 inserts will be:

Transaction 1:

insert into translation (id) values (null);
21 = SELECT LAST_INSERT_ID();

Transaction 2:

insert into translation (id) values (null);
22 = SELECT LAST_INSERT_ID();

# commit transaction 1;
# commit transaction 2;

But we have to execute the last_insert_id() just after the insert! And we can reuse that id to be inserted in others tables where a foreign key is expected!

Also, we cannot execute the 2 queries as following:

insert into translation (id) values ((SELECT AUTO_INCREMENT FROM
    information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()
    AND TABLE_NAME='translation'));

because we actually are interested to grab/reuse that ID in other table or to return!

How to change working directory in Jupyter Notebook?

I have did it on windows machine. Detail mentioned below 1. From windows start menu open “Anaconda Prompt enter image description here 2. Find .jupyter folder file path . In command prompt just type enter image description here or enter image description here to find the .jupyter path

  1. After find the .jupyter folder, check there has “jupyter_notebook_config” file or not. If it is not there then run below command enter image description here After run the command it will create "jupyter_notebook_config.py"

if do not have administrator permission then Some time you could not find .jupyter folder . Still you can open config file from any of the text editor

  1. Open “jupyter_notebook_config.py” file from the the “.jypyter” folder.
  2. After open the file need to update the directory is use for notebooks and kernel. There are so many line in config file so find “#c.NotebookApp.notebook_dir” and update the path enter image description here After: enter image description here Save the file
  3. Now try to create or read some file from the location you set

Populate a datagridview with sql query results

Here's your code fixed up. Next forget bindingsource

 var select = "SELECT * FROM tblEmployee";
 var c = new SqlConnection(yourConnectionString); // Your Connection String here
 var dataAdapter = new SqlDataAdapter(select, c); 

 var commandBuilder = new SqlCommandBuilder(dataAdapter);
 var ds = new DataSet();
 dataAdapter.Fill(ds);
 dataGridView1.ReadOnly = true; 
 dataGridView1.DataSource = ds.Tables[0];

What is the Difference Between read() and recv() , and Between send() and write()?

I just noticed recently that when I used write() on a socket in Windows, it almost works (the FD passed to write() isn't the same as the one passed to send(); I used _open_osfhandle() to get the FD to pass to write()). However, it didn't work when I tried to send binary data that included character 10. write() somewhere inserted character 13 before this. Changing it to send() with a flags parameter of 0 fixed that problem. read() could have the reverse problem if 13-10 are consecutive in the binary data, but I haven't tested it. But that appears to be another possible difference between send() and write().

How do I compile the asm generated by GCC?

If you have main.s file. you can generate object file by GCC and also as

# gcc -c main.s
# as main.s -o main.o

check this link, it will help you learn some binutils of GCC http://www.thegeekstuff.com/2017/01/gnu-binutils-commands/

Unzip All Files In A Directory

for file in 'ls *.zip'; do unzip "${file}" -d "${file:0:-4}"; done

How can I check if an element exists in the visible DOM?

A simple solution with jQuery:

$('body').find(yourElement)[0] != null

How to iterate over a column vector in Matlab?

In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.

Thus you can write

for elm = list
%# do something with the element
end

Note that Matlab iterates through the columns of list, so if list is a nx1 vector, you may want to transpose it.

Check status of one port on remote host

I think you're looking for Hping (http://www.hping.org/), which has a Windows version.

"The interface is inspired to the ping(8) unix command, but hping isn't only able to send ICMP echo requests. It supports TCP, UDP, ICMP..."

It's also very useful if you want to see where along a route that a TCP port is being blocked (like by a firewall), where ICMP might not be.

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

How to change font-color for disabled input?

It is the solution that I found for this problem:

//If IE

inputElement.writeAttribute("unselectable", "on");

//Other browsers

inputElement.writeAttribute("disabled", "disabled");

By using this trick, you can add style sheet to your input element that works in IE and other browsers on your not-editable input box.

Iterating through map in template

Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:

{{ range $key, $value := . }}
   <li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}

replace anchor text with jquery

To reference an element by id, you need to use the # qualifier.

Try:

alert($("#link1").text());

To replace it, you could use:

$("#link1").text('New text');

The .html() function would work in this case too.

Object of custom type as dictionary key

You need to add 2 methods, note __hash__ and __eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

Filter output in logcat by tagname

Here is how I create a tag:

private static final String TAG = SomeActivity.class.getSimpleName();
 Log.d(TAG, "some description");

You could use getCannonicalName

Here I have following TAG filters:

  • any (*) View - VERBOSE
  • any (*) Activity - VERBOSE
  • any tag starting with Xyz(*) - ERROR
  • System.out - SILENT (since I am using Log in my own code)

Here what I type in terminal:

$  adb logcat *View:V *Activity:V Xyz*:E System.out:S

Getting Raw XML From SOAPMessage in Java

It is pretty old thread but recently i had a similar issue. I was calling a downstream soap service, from a rest service, and I needed to return the xml response coming from the downstream server as is.

So, i ended up adding a SoapMessageContext handler to get the XML response. Then i injected the response xml into servlet context as an attribute.

public boolean handleMessage(SOAPMessageContext context) {

            // Get xml response
            try {

                ServletContext servletContext =
                        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext();

                SOAPMessage msg = context.getMessage();

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                msg.writeTo(out);
                String strMsg = new String(out.toByteArray());

                servletContext.setAttribute("responseXml", strMsg);

                return true;
            } catch (Exception e) {
                return false;
            }
        }

Then I have retrieved the xml response string in the service layer.

ServletContext servletContext =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext();

        String msg = (String) servletContext.getAttribute("responseXml");

Didn't have chance to test it yet but this approach must be thread safe since it is using the servlet context.

php - push array into array - key issue

I think you have to go for

$arrayname[indexname] = $value;

JSON datetime between Python and JavaScript

Not much to add to the community wiki answer, except for timestamp!

Javascript uses the following format:

new Date().toJSON() // "2016-01-08T19:00:00.123Z"

Python side (for the json.dumps handler, see the other answers):

>>> from datetime import datetime
>>> d = datetime.strptime('2016-01-08T19:00:00.123Z', '%Y-%m-%dT%H:%M:%S.%fZ')
>>> d
datetime.datetime(2016, 1, 8, 19, 0, 0, 123000)
>>> d.isoformat() + 'Z'
'2016-01-08T19:00:00.123000Z'

If you leave that Z out, frontend frameworks like angular can not display the date in browser-local timezone:

> $filter('date')('2016-01-08T19:00:00.123000Z', 'yyyy-MM-dd HH:mm:ss')
"2016-01-08 20:00:00"
> $filter('date')('2016-01-08T19:00:00.123000', 'yyyy-MM-dd HH:mm:ss')
"2016-01-08 19:00:00"

Slide right to left?

$(function() {
  $('.button').click(function() {
    $(this).toggleClass('active');
    $('.yourclass').toggle("slide", {direction: "right"}, 1000);
  });
});

How do I find out what License has been applied to my SQL Server installation?

SQL Server does not track licensing. Customers are responsible for tracking the assignment of licenses to servers, following the rules in the Licensing Guide.

Jquery select this + class

What you are looking for is this:

$(".subclass", this).css("visibility","visible");

Add the this after the class $(".subclass", this)

How do I change the language of moment.js?

Fastest method: Install with Bower

I just installed moment with bower and linked de.js as javascript resource in my html project.

bower install moment --save

You can also manually download the moment.js and de.js.

Link 'de.js' in your project

Linking the de.js in my main project file automatically changed the locale for all accesses to the moment class and its methods.

There will be no need anymore to do a moment.locale("de"). or moment.lang("de"). in the source code.

Just link your desired locale like this:

<script src="/bower_components/moment/moment.js"></script>
<script src="/bower_components/moment/locale/de.js"></script>

Or you can link the libraries without the bower_components path, if you downloaded moment.js 1990ies-style via right-click, which still works fine in most scenarios.

How does one reorder columns in a data frame?

As mentioned in this comment, the standard suggestions for re-ordering columns in a data.frame are generally cumbersome and error-prone, especially if you have a lot of columns.

This function allows to re-arrange columns by position: specify a variable name and the desired position, and don't worry about the other columns.

##arrange df vars by position
##'vars' must be a named vector, e.g. c("var.name"=1)
arrange.vars <- function(data, vars){
    ##stop if not a data.frame (but should work for matrices as well)
    stopifnot(is.data.frame(data))

    ##sort out inputs
    data.nms <- names(data)
    var.nr <- length(data.nms)
    var.nms <- names(vars)
    var.pos <- vars
    ##sanity checks
    stopifnot( !any(duplicated(var.nms)), 
               !any(duplicated(var.pos)) )
    stopifnot( is.character(var.nms), 
               is.numeric(var.pos) )
    stopifnot( all(var.nms %in% data.nms) )
    stopifnot( all(var.pos > 0), 
               all(var.pos <= var.nr) )

    ##prepare output
    out.vec <- character(var.nr)
    out.vec[var.pos] <- var.nms
    out.vec[-var.pos] <- data.nms[ !(data.nms %in% var.nms) ]
    stopifnot( length(out.vec)==var.nr )

    ##re-arrange vars by position
    data <- data[ , out.vec]
    return(data)
}

Now the OP's request becomes as simple as this:

table <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))
table
##  Time In Out Files
##1    1  2   3     4
##2    2  3   4     5

arrange.vars(table, c("Out"=2))
##  Time Out In Files
##1    1   3  2     4
##2    2   4  3     5

To additionally swap Time and Files columns you can do this:

arrange.vars(table, c("Out"=2, "Files"=1, "Time"=4))
##  Files Out In Time
##1     4   3  2    1
##2     5   4  3    2

400 vs 422 response to POST of data

You should actually return "200 OK" and in the response body include a message about what happened with the posted data. Then it's up to your application to understand the message.

The thing is, HTTP status codes are exactly that - HTTP status codes. And those are meant to have meaning only at the transportation layer, not at the application layer. The application layer should really never even know that HTTP is being used. If you switched your transportation layer from HTTP to Homing Pigeons, it should not affect your application layer in any way.

Let me give you a non-virtual example. Let's say you fall in love with a girl and she loves you back but her family moves to a completely different country. She gives you her new snail-mail address. Naturally, you decide to send her a love letter. So you write your letter, put it into an envelope, write her address on the envelope, put a stamp on it and send it. Now let's consider these scenarios

  1. You forgot to write a street name. You will receive an unopened letter back with a message written on it saying that the address is malformed. You screwed up the request and the receiving post office is unable to handle it. That's the equivalent of receiving "400 Bad Request".
  2. So you fix the address and send the letter again. But due to some bad luck you totaly misspelled the name of the street. You will get the letter back again with a message saying, that the address doesn't exist. That's the equivalent of receiving "404 Not Found".
  3. You fix the address again and this time you manage to write the address correctly. Your girl receives the letter and writes you back. It's the equivalent of receiving "200 OK". However, this does not mean that you will like what she wrote in her letter. It simply means that she received your message and has a response for you. Until you open the envelope and read her letter you cannot know whether she misses you dearly or wants to break up with you.

In short: Returning "200 OK" doesn't mean that the server app has good news for you. It only means that it has some news.

PS: The 422 status code has a meaning only in the context of WebDAV. If you're not working with WebDAV, then 422 has exactly the same standard meaning as any other non-standard code = which is none.

c - warning: implicit declaration of function ‘printf’

the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..

It might either be a header file or your own function Declaration..

String field value length in mongoDB

Queries with $where and $expr are slow if there are too many documents.

Using $regex is much faster than $where, $expr.

db.usercollection.find({ 
  "name": /^[\s\S]{40,}$/, // name.length >= 40
})

or 

db.usercollection.find({ 
  "name": { "$regex": "^[\s\S]{40,}$" }, // name.length >= 40
})

This query is the same meaning with

db.usercollection.find({ 
  "$where": "this.name && this.name.length >= 40",
})

or

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gte": [ { "$strLenCP": "$name" }, 40 ] } 
})

I tested each queries for my collection.

# find
$where: 10529.359ms
$expr: 5305.801ms
$regex: 2516.124ms

# count
$where: 10872.006ms
$expr: 2630.155ms
$regex: 158.066ms

SMTPAuthenticationError when sending mail using gmail and python

I have just sent an email with gmail through Python. Try to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.

So, you may get a chance with:

server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(gmail_user, password)
server.sendmail(gmail_user, TO, BODY)

As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.

How to send a simple email from a Windows batch file?

$emailSmtpServerPort = "587"
$emailSmtpUser = "username"
$emailSmtpPass = 'password'
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "[From email address]"
$emailMessage.To.Add( "[Send to email address]" )
$emailMessage.Subject = "Testing e-mail"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = @"
<p>Here is a message that is <strong>HTML formatted</strong>.</p>
<p>From your friendly neighborhood IT guy</p>
"@
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )

Angular - res.json() is not a function

You can remove the entire line below:

 .map((res: Response) => res.json());

No need to use the map method at all.

SQL update query using joins

UPDATE im
SET mf_item_number = gm.SKU --etc
FROM item_master im
JOIN group_master gm
    ON im.sku = gm.sku 
JOIN Manufacturer_Master mm
    ON gm.ManufacturerID = mm.ManufacturerID
WHERE im.mf_item_number like 'STA%' AND
      gm.manufacturerID = 34

To make it clear... The UPDATE clause can refer to an table alias specified in the FROM clause. So im in this case is valid

Generic example

UPDATE A
SET foo = B.bar
FROM TableA A
JOIN TableB B
    ON A.col1 = B.colx
WHERE ...

Adding a guideline to the editor in Visual Studio

For those who use Visual Assist, vertical guidelines can be enabled from Display section in Visual Assist's options:

enter image description here

Selenium C# WebDriver: Wait until element is present

// Wait up to 5 seconds with no minimum for a UI element to be found
WebDriverWait wait = new WebDriverWait(_pagedriver, TimeSpan.FromSeconds(5));
IWebElement title = wait.Until<IWebElement>((d) =>
{
    return d.FindElement(By.ClassName("MainContentHeader"));
});

How to query as GROUP BY in django?

The document says that you can use values to group the queryset .

class Travel(models.Model):
    interest = models.ForeignKey(Interest)
    user = models.ForeignKey(User)
    time = models.DateTimeField(auto_now_add=True)

# Find the travel and group by the interest:

>>> Travel.objects.values('interest').annotate(Count('user'))
<QuerySet [{'interest': 5, 'user__count': 2}, {'interest': 6, 'user__count': 1}]>
# the interest(id=5) had been visited for 2 times, 
# and the interest(id=6) had only been visited for 1 time.

>>> Travel.objects.values('interest').annotate(Count('user', distinct=True)) 
<QuerySet [{'interest': 5, 'user__count': 1}, {'interest': 6, 'user__count': 1}]>
# the interest(id=5) had been visited by only one person (but this person had 
#  visited the interest for 2 times

You can find all the books and group them by name using this code:

Book.objects.values('name').annotate(Count('id')).order_by() # ensure you add the order_by()

You can watch some cheet sheet here.

Get class name using jQuery

This is to get the second class into multiple classes using into a element

var class_name = $('#videobuttonChange').attr('class').split(' ')[1];

How to install and run Typescript locally in npm?

It took me a while to figure out the solution to this problem - it's in the original question. You need to have a script that calls tsc in your package.json file so that you can run:

npm run tsc 

Include -- before you pass in options (or just include them in the script):

npm run tsc -- -v

Here's an example package.json:

{
  "name": "foo",
  "scripts": {
    "tsc": "tsc"
  },
  "dependencies": {
    "typescript": "^1.8.10"
  }
}

How to remove focus around buttons on click

I've noticed the same and even though it really annoys me, I believe there is no proper way of handling this.

I would recommend against all the other solutions given because they kill the accessibility of the button completely, so now, when you tab to the button, you won't get the expected focus.

This should be avoided!

.btn:focus {
  outline: none;
}

Fastest way to convert a dict's keys & values from `unicode` to `str`?

>>> d = {u"a": u"b", u"c": u"d"}
>>> d
{u'a': u'b', u'c': u'd'}
>>> import json
>>> import yaml
>>> d = {u"a": u"b", u"c": u"d"}
>>> yaml.safe_load(json.dumps(d))
{'a': 'b', 'c': 'd'}

How to get response from S3 getObject in Node.js?

Based on the answer by @peteb, but using Promises and Async/Await:

const AWS = require('aws-sdk');

const s3 = new AWS.S3();

async function getObject (bucket, objectKey) {
  try {
    const params = {
      Bucket: bucket,
      Key: objectKey 
    }

    const data = await s3.getObject(params).promise();

    return data.Body.toString('utf-8');
  } catch (e) {
    throw new Error(`Could not retrieve file from S3: ${e.message}`)
  }
}

// To retrieve you need to use `await getObject()` or `getObject().then()`
getObject('my-bucket', 'path/to/the/object.txt').then(...);

Execution failed for task :':app:mergeDebugResources'. Android Studio

In My case, I've written below code in build.gradle

android {
// ...
aaptOptions.cruncherEnabled = false
aaptOptions.useNewCruncher = false
// ...
}

It's work for me!...

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

I needed this peace of code as a subquery with some data filter before aggregation based on the outer most query but I wasn't able to do this using the chosen answer code because this filter should go in the inner most select (third level query) and the filter params was in the outer most select (first level query), which gave me the error ORA-00904: "TB_OUTERMOST"."COL": invalid identifier as the ANSI SQL states that table references (correlation names) are scoped to just one level deep.

I needed a solution with no levels of subquery and this one below worked great for me:

with

demotable as
(
  select 1 group_id, 'David'   name from dual union all
  select 1 group_id, 'John'    name from dual union all
  select 1 group_id, 'Alan'    name from dual union all
  select 1 group_id, 'David'   name from dual union all
  select 2 group_id, 'Julie'   name from dual union all
  select 2 group_id, 'Charlie' name from dual
)

select distinct 
  group_id, 
  listagg(name, ',') within group (order by name) over (partition by group_id) names
from demotable
-- where any filter I want
group by group_id, name
order by group_id;

Android Studio is slow (how to speed up)?

The best way to boost up android studio runtime performance is to use SSD Drive. It will boost the performance as very much. I did all the above things and felt I should go for new laptop, but suddenly I came to know about SSD Drive and I tried it. Its Much Much better.....

How to have image and text side by side

HTML

<div class='containerBox'>
    <div>
       <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails'>
       <div>
       <h4>Facebook</h4>  
       <div style="font-size:.6em;float:left; margin-left:5px;color:white;">fine location, GPS, coarse location</div>
       <div style="float:right;font-size:.6em; margin-right:5px; color:white;">0 mins ago</div>
       </div>
   </div> 
</div>

CSS

 .iconDetails {
 margin-left:2%;
 float:left; 
 height:40px;
 width:40px;
 } 

.containerBox {
width:300px;
height:60px;
padding:1px;
background-color:#303030;
}
h4{
margin:0px;
margin-top:3%;
margin-left:50px;
color:white;
}

res.sendFile absolute path

An alternative that hasn't been listed yet that worked for me is simply using path.resolve with either separate strings or just one with the whole path:

// comma separated
app.get('/', function(req, res) {
    res.sendFile( path.resolve('src', 'app', 'index.html') );
});

Or

// just one string with the path
app.get('/', function(req, res) {
    res.sendFile( path.resolve('src/app/index.html') );
});

(Node v6.10.0)

Idea sourced from https://stackoverflow.com/a/14594282/6189078

What's the difference between commit() and apply() in SharedPreferences

The difference between commit() and apply()

We might be confused by those two terms, when we are using SharedPreference. Basically they are probably the same, so let’s clarify the differences of commit() and apply().

1.Return value:

apply() commits without returning a boolean indicating success or failure. commit() returns true if the save works, false otherwise.

  1. Speed:

apply() is faster. commit() is slower.

  1. Asynchronous v.s. Synchronous:

apply(): Asynchronous commit(): Synchronous

  1. Atomic:

apply(): atomic commit(): atomic

  1. Error notification:

apply(): No commit(): Yes

How to check if PHP array is associative or sequential?

Unless PHP has a builtin for that, you won't be able to do it in less than O(n) - enumerating over all the keys and checking for integer type. In fact, you also want to make sure there are no holes, so your algorithm might look like:

for i in 0 to len(your_array):
    if not defined(your-array[i]):
        # this is not an array array, it's an associative array :)

But why bother? Just assume the array is of the type you expect. If it isn't, it will just blow up in your face - that's dynamic programming for you! Test your code and all will be well...

How to do parallel programming in Python?

You can use the multiprocessing module. For this case I might use a processing pool:

from multiprocessing import Pool
pool = Pool()
result1 = pool.apply_async(solve1, [A])    # evaluate "solve1(A)" asynchronously
result2 = pool.apply_async(solve2, [B])    # evaluate "solve2(B)" asynchronously
answer1 = result1.get(timeout=10)
answer2 = result2.get(timeout=10)

This will spawn processes that can do generic work for you. Since we did not pass processes, it will spawn one process for each CPU core on your machine. Each CPU core can execute one process simultaneously.

If you want to map a list to a single function you would do this:

args = [A, B]
results = pool.map(solve1, args)

Don't use threads because the GIL locks any operations on python objects.

CSS3 Fade Effect

It's possible, use the structure below:

<li><a><span></span></a></li>
<li><a><span></span></a></li>

etc...

Where the <li> contains an <a> anchor tag that contains a span as shown above. Then insert the following css:

  • LI get position: relative;
  • Give <a> tag a height, width
  • Set <span> width & height to 100%, so that both <a> and <span> have same dimensions
  • Both <a> and <span> get position: relative;.
  • Assign the same background image to each element
  • <a> tag will have the 'OFF' background-position, and the <span> will have the 'ON' background-poisiton.
  • For 'OFF' state use opacity 0 for <span>
  • For 'ON' :hover state use opacity 1 for <span>
  • Set the -webkit or -moz transition on the <span> element

You'll have the ability to use the transition effect while still defaulting to the old background-position swap. Don't forget to insert IE alpha filter.

What is com.sun.proxy.$Proxy

What are they?

Nothing special. Just as same as common Java Class Instance.

But those class are Synthetic proxy classes created by java.lang.reflect.Proxy#newProxyInstance

What is there relationship to the JVM? Are they JVM implementation specific?

Introduced in 1.3

http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection

It is a part of Java. so each JVM should support it.

How are they created (Openjdk7 source)?

In short : they are created using JVM ASM tech ( defining javabyte code at runtime )

something using same tech:

What happens after calling java.lang.reflect.Proxy#newProxyInstance

  1. reading the source you can see newProxyInstance call getProxyClass0 to obtain a `Class

    `

  2. after lots of cache or sth it calls the magic ProxyGenerator.generateProxyClass which return a byte[]
  3. call ClassLoader define class to load the generated $Proxy Class (the classname you have seen)
  4. just instance it and ready for use

What happens in magic sun.misc.ProxyGenerator

  1. draw a class(bytecode) combining all methods in the interfaces into one
  2. each method is build with same bytecode like

    1. get calling Method meth info (stored while generating)
    2. pass info into invocation handler's invoke()
    3. get return value from invocation handler's invoke()
    4. just return it
  3. the class(bytecode) represent in form of byte[]

How to draw a class

Thinking your java codes are compiled into bytecodes, just do this at runtime

Talk is cheap show you the code

core method in sun/misc/ProxyGenerator.java

generateClassFile

/**
 * Generate a class file for the proxy class.  This method drives the
 * class file generation process.
 */
private byte[] generateClassFile() {

    /* ============================================================
     * Step 1: Assemble ProxyMethod objects for all methods to
     * generate proxy dispatching code for.
     */

    /*
     * Record that proxy methods are needed for the hashCode, equals,
     * and toString methods of java.lang.Object.  This is done before
     * the methods from the proxy interfaces so that the methods from
     * java.lang.Object take precedence over duplicate methods in the
     * proxy interfaces.
     */
    addProxyMethod(hashCodeMethod, Object.class);
    addProxyMethod(equalsMethod, Object.class);
    addProxyMethod(toStringMethod, Object.class);

    /*
     * Now record all of the methods from the proxy interfaces, giving
     * earlier interfaces precedence over later ones with duplicate
     * methods.
     */
    for (int i = 0; i < interfaces.length; i++) {
        Method[] methods = interfaces[i].getMethods();
        for (int j = 0; j < methods.length; j++) {
            addProxyMethod(methods[j], interfaces[i]);
        }
    }

    /*
     * For each set of proxy methods with the same signature,
     * verify that the methods' return types are compatible.
     */
    for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
        checkReturnTypes(sigmethods);
    }

    /* ============================================================
     * Step 2: Assemble FieldInfo and MethodInfo structs for all of
     * fields and methods in the class we are generating.
     */
    try {
        methods.add(generateConstructor());

        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
            for (ProxyMethod pm : sigmethods) {

                // add static field for method's Method object
                fields.add(new FieldInfo(pm.methodFieldName,
                    "Ljava/lang/reflect/Method;",
                     ACC_PRIVATE | ACC_STATIC));

                // generate code for proxy method and add it
                methods.add(pm.generateMethod());
            }
        }

        methods.add(generateStaticInitializer());

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    if (methods.size() > 65535) {
        throw new IllegalArgumentException("method limit exceeded");
    }
    if (fields.size() > 65535) {
        throw new IllegalArgumentException("field limit exceeded");
    }

    /* ============================================================
     * Step 3: Write the final class file.
     */

    /*
     * Make sure that constant pool indexes are reserved for the
     * following items before starting to write the final class file.
     */
    cp.getClass(dotToSlash(className));
    cp.getClass(superclassName);
    for (int i = 0; i < interfaces.length; i++) {
        cp.getClass(dotToSlash(interfaces[i].getName()));
    }

    /*
     * Disallow new constant pool additions beyond this point, since
     * we are about to write the final constant pool table.
     */
    cp.setReadOnly();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        /*
         * Write all the items of the "ClassFile" structure.
         * See JVMS section 4.1.
         */
                                    // u4 magic;
        dout.writeInt(0xCAFEBABE);
                                    // u2 minor_version;
        dout.writeShort(CLASSFILE_MINOR_VERSION);
                                    // u2 major_version;
        dout.writeShort(CLASSFILE_MAJOR_VERSION);

        cp.write(dout);             // (write constant pool)

                                    // u2 access_flags;
        dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
                                    // u2 this_class;
        dout.writeShort(cp.getClass(dotToSlash(className)));
                                    // u2 super_class;
        dout.writeShort(cp.getClass(superclassName));

                                    // u2 interfaces_count;
        dout.writeShort(interfaces.length);
                                    // u2 interfaces[interfaces_count];
        for (int i = 0; i < interfaces.length; i++) {
            dout.writeShort(cp.getClass(
                dotToSlash(interfaces[i].getName())));
        }

                                    // u2 fields_count;
        dout.writeShort(fields.size());
                                    // field_info fields[fields_count];
        for (FieldInfo f : fields) {
            f.write(dout);
        }

                                    // u2 methods_count;
        dout.writeShort(methods.size());
                                    // method_info methods[methods_count];
        for (MethodInfo m : methods) {
            m.write(dout);
        }

                                     // u2 attributes_count;
        dout.writeShort(0); // (no ClassFile attributes for proxy classes)

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    return bout.toByteArray();
}

addProxyMethod

/**
 * Add another method to be proxied, either by creating a new
 * ProxyMethod object or augmenting an old one for a duplicate
 * method.
 *
 * "fromClass" indicates the proxy interface that the method was
 * found through, which may be different from (a subinterface of)
 * the method's "declaring class".  Note that the first Method
 * object passed for a given name and descriptor identifies the
 * Method object (and thus the declaring class) that will be
 * passed to the invocation handler's "invoke" method for a given
 * set of duplicate methods.
 */
private void addProxyMethod(Method m, Class fromClass) {
    String name = m.getName();
    Class[] parameterTypes = m.getParameterTypes();
    Class returnType = m.getReturnType();
    Class[] exceptionTypes = m.getExceptionTypes();

    String sig = name + getParameterDescriptors(parameterTypes);
    List<ProxyMethod> sigmethods = proxyMethods.get(sig);
    if (sigmethods != null) {
        for (ProxyMethod pm : sigmethods) {
            if (returnType == pm.returnType) {
                /*
                 * Found a match: reduce exception types to the
                 * greatest set of exceptions that can thrown
                 * compatibly with the throws clauses of both
                 * overridden methods.
                 */
                List<Class<?>> legalExceptions = new ArrayList<Class<?>>();
                collectCompatibleTypes(
                    exceptionTypes, pm.exceptionTypes, legalExceptions);
                collectCompatibleTypes(
                    pm.exceptionTypes, exceptionTypes, legalExceptions);
                pm.exceptionTypes = new Class[legalExceptions.size()];
                pm.exceptionTypes =
                    legalExceptions.toArray(pm.exceptionTypes);
                return;
            }
        }
    } else {
        sigmethods = new ArrayList<ProxyMethod>(3);
        proxyMethods.put(sig, sigmethods);
    }
    sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                   exceptionTypes, fromClass));
}

Full code about gen the proxy method

    private MethodInfo generateMethod() throws IOException {
        String desc = getMethodDescriptor(parameterTypes, returnType);
        MethodInfo minfo = new MethodInfo(methodName, desc,
            ACC_PUBLIC | ACC_FINAL);

        int[] parameterSlot = new int[parameterTypes.length];
        int nextSlot = 1;
        for (int i = 0; i < parameterSlot.length; i++) {
            parameterSlot[i] = nextSlot;
            nextSlot += getWordsPerType(parameterTypes[i]);
        }
        int localSlot0 = nextSlot;
        short pc, tryBegin = 0, tryEnd;

        DataOutputStream out = new DataOutputStream(minfo.code);

        code_aload(0, out);

        out.writeByte(opc_getfield);
        out.writeShort(cp.getFieldRef(
            superclassName,
            handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));

        code_aload(0, out);

        out.writeByte(opc_getstatic);
        out.writeShort(cp.getFieldRef(
            dotToSlash(className),
            methodFieldName, "Ljava/lang/reflect/Method;"));

        if (parameterTypes.length > 0) {

            code_ipush(parameterTypes.length, out);

            out.writeByte(opc_anewarray);
            out.writeShort(cp.getClass("java/lang/Object"));

            for (int i = 0; i < parameterTypes.length; i++) {

                out.writeByte(opc_dup);

                code_ipush(i, out);

                codeWrapArgument(parameterTypes[i], parameterSlot[i], out);

                out.writeByte(opc_aastore);
            }
        } else {

            out.writeByte(opc_aconst_null);
        }

        out.writeByte(opc_invokeinterface);
        out.writeShort(cp.getInterfaceMethodRef(
            "java/lang/reflect/InvocationHandler",
            "invoke",
            "(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
                "[Ljava/lang/Object;)Ljava/lang/Object;"));
        out.writeByte(4);
        out.writeByte(0);

        if (returnType == void.class) {

            out.writeByte(opc_pop);

            out.writeByte(opc_return);

        } else {

            codeUnwrapReturnValue(returnType, out);
        }

        tryEnd = pc = (short) minfo.code.size();

        List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
        if (catchList.size() > 0) {

            for (Class<?> ex : catchList) {
                minfo.exceptionTable.add(new ExceptionTableEntry(
                    tryBegin, tryEnd, pc,
                    cp.getClass(dotToSlash(ex.getName()))));
            }

            out.writeByte(opc_athrow);

            pc = (short) minfo.code.size();

            minfo.exceptionTable.add(new ExceptionTableEntry(
                tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));

            code_astore(localSlot0, out);

            out.writeByte(opc_new);
            out.writeShort(cp.getClass(
                "java/lang/reflect/UndeclaredThrowableException"));

            out.writeByte(opc_dup);

            code_aload(localSlot0, out);

            out.writeByte(opc_invokespecial);

            out.writeShort(cp.getMethodRef(
                "java/lang/reflect/UndeclaredThrowableException",
                "<init>", "(Ljava/lang/Throwable;)V"));

            out.writeByte(opc_athrow);
        }

Jquery Setting Value of Input Field

This should work.

$(".formData").val("valuesgoeshere")

For empty

$(".formData").val("")

If this does not work, you should post a jsFiddle.

Demo:

_x000D_
_x000D_
$(function() {_x000D_
  $(".resetInput").on("click", function() {_x000D_
    $(".formData").val("");_x000D_
  });_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" class="formData" value="yoyoyo">_x000D_
_x000D_
_x000D_
<button class="resetInput">Click Here to reset</button>
_x000D_
_x000D_
_x000D_

Creating a Custom Event

Yes you can do like this :

Creating advanced C# custom events

or

The Simplest C# Events Example Imaginable

public class Metronome
{
    public event TickHandler Tick;
    public EventArgs e = null;
    public delegate void TickHandler(Metronome m, EventArgs e);
    public void Start()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(3000);
            if (Tick != null)
            {
                Tick(this, e);
            }
        }
    }
}
public class Listener
{
    public void Subscribe(Metronome m)
    {
        m.Tick += new Metronome.TickHandler(HeardIt);
    }

    private void HeardIt(Metronome m, EventArgs e)
    {
        System.Console.WriteLine("HEARD IT");
    }
}
class Test
{
    static void Main()
    {
        Metronome m = new Metronome();
        Listener l = new Listener();
        l.Subscribe(m);
        m.Start();
    }
}

Is there any way to call a function periodically in JavaScript?

Old question but.. I also needed a periodical task runner and wrote TaskTimer. This is also useful when you need to run multiple tasks on different intervals.

// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);

// Add task(s) based on tick intervals.
timer.add({
    id: 'job1',       // unique id of the task
    tickInterval: 5,    // run every 5 ticks (5 x interval = 5000 ms)
    totalRuns: 10,      // run 10 times only. (set to 0 for unlimited times)
    callback(task) {
        // code to be executed on each run
        console.log(task.id + ' task has run ' + task.currentRuns + ' times.');
    }
});

// Start the timer
timer.start();

TaskTimer works both in browser and Node. See documentation for all features.

How to make Git "forget" about a file that was tracked but is now in .gitignore?

In my case here, I had several .lock files in several directories that I needed to remove. I ran the following and it worked without having to go into each directory to remove them:

git rm -r --cached **/*.lock

Doing this went into each folder under the 'root' of where I was at and excluded all files that matched the pattern.

Hope this helps others!

Searching for Text within Oracle Stored Procedures

If you use UPPER(text), the like '%lah%' will always return zero results. Use '%LAH%'.

Python csv string to array

The official doc for csv.reader() https://docs.python.org/2/library/csv.html is very helpful, which says

file objects and list objects are both suitable

import csv

text = """1,2,3
a,b,c
d,e,f"""

lines = text.splitlines()
reader = csv.reader(lines, delimiter=',')
for row in reader:
    print('\t'.join(row))

How to add image for button in android?

The new MaterialButton from the Material Components can include an icon:

<com.google.android.material.button.MaterialButton
    android:id="@+id/material_icon_button"
    style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/icon_button_label_enabled"
    app:icon="@drawable/icon_24px"/>

You can also customize some icon properties like iconSize and iconGravity.

Reference here.

Function to convert timestamp to human date in javascript

why not simply

new Date (timestamp);

A date is a date, the formatting of it is a different matter.

How to clear a notification in Android

If you're using NotificationCompat.Builder (a part of android.support.v4) then simply call its object's method setAutoCancel

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true);

Some guys were reporting that setAutoCancel() did not work for them, so you may try this way as well

builder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;

Note that the method getNotification() has been deprecated!!!

How to create folder with PHP code?

You can create it easily:

$structure = './depth1/depth2/depth3/';
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

Removing rounded corners from a <select> element in Chrome/Webkit

well i got the solution. hope it may help you :)

_x000D_
_x000D_
select{_x000D_
      border-image: url(http://www.w3schools.com/cssref/border.png) 30 stretch;_x000D_
      width: 120px;_x000D_
      height: 36px;_x000D_
      color: #999;_x000D_
  }
_x000D_
<select>_x000D_
  <option value="1">Hi</option>_x000D_
  <option value="2">Bye</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Getting GET "?" variable in laravel

Take a look at the $_GET and $_REQUEST superglobals. Something like the following would work for your example:

$start = $_GET['start'];
$limit = $_GET['limit'];

EDIT

According to this post in the laravel forums, you need to use Input::get(), e.g.,

$start = Input::get('start');
$limit = Input::get('limit');

See also: http://laravel.com/docs/input#input

Checking if a collection is empty in Java: which is the best method?

A good example of where this matters in practice is the ConcurrentSkipListSet implementation in the JDK, which states:

Beware that, unlike in most collections, the size method is not a constant-time operation.

This is a clear case where isEmpty() is much more efficient than checking whether size()==0.

You can see why, intuitively, this might be the case in some collections. If it's the sort of structure where you have to traverse the whole thing to count the elements, then if all you want to know is whether it's empty, you can stop as soon as you've found the first one.

Why use static_cast<int>(x) instead of (int)x?

It's about how much type-safety you want to impose.

When you write (bar) foo (which is equivalent to reinterpret_cast<bar> foo if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.

When you write static_cast<bar> foo you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.


EDIT 2014-02-26

I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!

How to read a config file using python

A convenient solution in your case would be to include the configs in a yaml file named **your_config_name.yml** which would look like this:

path1: "D:\test1\first"
path2: "D:\test2\second"
path3: "D:\test2\third"

In your python code you can then load the config params into a dictionary by doing this:

import yaml
with open('your_config_name.yml') as stream:
    config = yaml.safe_load(stream)

You then access e.g. path1 like this from your dictionary config:

config['path1']

To import yaml you first have to install the package as such: pip install pyyaml into your chosen virtual environment.

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

My case was that the server didn't accept the connection from this IP. The server is a SQL server from Google Apps Engine, and you have to configure allowed remote hosts that can connect to the server.

Adding the (new) host to the GAE admin page solved the issue.

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

If given no. of Nodes are N Then.

Different No. of BST=Catalan(N)
Different No. of Structurally Different Binary trees are = Catalan(N)

Different No. of Binary Trees are=N!*Catalan(N)

NULL values inside NOT IN clause

In A, 3 is tested for equality against each member of the set, yielding (FALSE, FALSE, TRUE, UNKNOWN). Since one of the elements is TRUE, the condition is TRUE. (It's also possible that some short-circuiting takes place here, so it actually stops as soon as it hits the first TRUE and never evaluates 3=NULL.)

In B, I think it is evaluating the condition as NOT (3 in (1,2,null)). Testing 3 for equality against the set yields (FALSE, FALSE, UNKNOWN), which is aggregated to UNKNOWN. NOT ( UNKNOWN ) yields UNKNOWN. So overall the truth of the condition is unknown, which at the end is essentially treated as FALSE.

Repeat a task with a time delay?

In my case, I had to execute a process if one of these conditions were true: if a previous process was completed or if 5 seconds had already passed. So, I did the following and worked pretty well:

private Runnable mStatusChecker;
private Handler mHandler;

class {
method() {
  mStatusChecker = new Runnable() {
            int times = 0;
            @Override
            public void run() {
                if (times < 5) {
                    if (process1.isRead()) {
                        executeProcess2();
                    } else {
                        times++;
                        mHandler.postDelayed(mStatusChecker, 1000);
                    }
                } else {
                    executeProcess2();
                }
            }
        };

        mHandler = new Handler();
        startRepeatingTask();
}

    void startRepeatingTask() {
       mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }


}

If process1 is read, it executes process2. If not, it increments the variable times, and make the Handler be executed after one second. It maintains a loop until process1 is read or times is 5. When times is 5, it means that 5 seconds passed and in each second, the if clause of process1.isRead() is executed.

How to initialize static variables

That's too complex to set in the definition. You can set the definition to null though, and then in the constructor, check it, and if it has not been changed - set it:

private static $dates = null;
public function __construct()
{
    if (is_null(self::$dates)) {  // OR if (!is_array(self::$date))
         self::$dates = array( /* .... */);
    }
}

Passing array in GET for a REST call

I think it's a better practice to serialize your REST call parameters, usually by JSON-encoding them:

/appointments?users=[id1,id2]

or even:

/appointments?params={users:[id1,id2]}

Then you un-encode them on the server. This is going to give you more flexibility in the long run.

Just make sure to URLEncode the params as well before you send them!

Why is jquery's .ajax() method not sending my session cookie?

Using

xhrFields: { withCredentials:true }

as part of my jQuery ajax call was only part of the solution. I also needed to have the headers returned in the OPTIONS response from my resource:

Access-Control-Allow-Origin : http://www.wombling.com
Access-Control-Allow-Credentials : true

It was important that only one allowed "origin" was in the response header of the OPTIONS call and not "*". I achieved this by reading the origin from the request and populating it back into the response - probably circumventing the original reason for the restriction, but in my use case the security is not paramount.

I thought it worth explicitly mentioning the requirement for only one origin, as the W3C standard does allow for a space separated list -but Chrome doesn't! http://www.w3.org/TR/cors/#access-control-allow-origin-response-header NB the "in practice" bit.

How to getText on an input in protractor

You have to use Promise to print or store values of element.

 var ExpectedValue:string ="AllTestings.com";
          element(by.id("xyz")).getAttribute("value").then(function (Text) {

                        expect(Text.trim()).toEqual("ExpectedValue", "Wrong page navigated");//Assertion
        console.log("Text");//Print here in Console

                    });

How to save Excel Workbook to Desktop regardless of user?

You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.

Public Sub SaveToDesktop()
    ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _ 
    FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub

I'm not sure whether this would be a requirement, but may help!

How to implement a secure REST API with node.js

If you want to secure your application, then you should definitely start by using HTTPS instead of HTTP, this ensures a creating secure channel between you & the users that will prevent sniffing the data sent back & forth to the users & will help keep the data exchanged confidential.

You can use JWTs (JSON Web Tokens) to secure RESTful APIs, this has many benefits when compared to the server-side sessions, the benefits are mainly:

1- More scalable, as your API servers will not have to maintain sessions for each user (which can be a big burden when you have many sessions)

2- JWTs are self contained & have the claims which define the user role for example & what he can access & issued at date & expiry date (after which JWT won't be valid)

3- Easier to handle across load-balancers & if you have multiple API servers as you won't have to share session data nor configure server to route the session to same server, whenever a request with a JWT hit any server it can be authenticated & authorized

4- Less pressure on your DB as well as you won't have to constantly store & retrieve session id & data for each request

5- The JWTs can't be tampered with if you use a strong key to sign the JWT, so you can trust the claims in the JWT that is sent with the request without having to check the user session & whether he is authorized or not, you can just check the JWT & then you are all set to know who & what this user can do.

Many libraries provide easy ways to create & validate JWTs in most programming languages, for example: in node.js one of the most popular is jsonwebtoken

Since REST APIs generally aims to keep the server stateless, so JWTs are more compatible with that concept as each request is sent with Authorization token that is self contained (JWT) without the server having to keep track of user session compared to sessions which make the server stateful so that it remembers the user & his role, however, sessions are also widely used & have their pros, which you can search for if you want.

One important thing to note is that you have to securely deliver the JWT to the client using HTTPS & save it in a secure place (for example in local storage).

You can learn more about JWTs from this link

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

if you are using nvm node version manager, use this command to create a symlink:

sudo ln -s "$(which node)" /usr/bin/node
sudo ln -s "$(which npm)" /usr/bin/npm
  • The first command creates a symlink for node
  • The second command creates a symlink for npm

Xcopy Command excluding files and folders

Like Andrew said /exclude parameter of xcopy should be existing file that has list of excludes.

Documentation of xcopy says:

Using /exclude

List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

Example:

xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

and list-of-excluded-files.txt should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:

exclusion.txt

How to rearrange Pandas column sequence?

Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.

In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]: 
    x  y  a  b
0   3 -1  1  2
1   6 -2  2  4
2   9 -3  3  6
3  12 -4  4  8

Multi column forms with fieldsets

I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.

<div class="form-group">
    <div class="col-sm-12">
        <label for="user_login">Username</label>
        <input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
    </div>
</div>

Check out this demo.

Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.

<form action="#" method="post" class="form-horizontal">

Check out this demo.

When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.

Disabling Chrome cache for website development

In addition to the disable cache option (which you get to via a button in the lower right corner of the developer tools window -- Tools | Developer Tools, or Ctrl + Shift + I), on the network pane of the developer tools you can now right click and choose "Clear Cache" from the popup menu.

DataTables fixed headers misaligned with columns in wide tables

Add table-layout: fixed to your table's style (css or style attribute).

The browser will stop applying its custom algorithm to solve size constraints.

Search the web for infos about handling column widths in a fixed table layout (here are 2 simple SO questions : here and here)

Obviously: the downside will be that your columns' width won't adapt to their content.


[Edit] My answer worked when I used the FixedHeader plugin, but a post on the datatable's forum seem to indicate that other problems arise when using the sScrollX option :

bAutoWidth and sWidth ignored when sScrollX is set (v1.7.5)

I'll try to find a way to go around this.

How do I create a Java string from the contents of a file?

There is a variation on the same theme that uses a for loop, instead of a while loop, to limit the scope of the line variable. Whether it's "better" is a matter of personal taste.

for(String line = reader.readLine(); line != null; line = reader.readLine()) {
    stringBuilder.append(line);
    stringBuilder.append(ls);
}

Call multiple functions onClick ReactJS

this onclick={()=>{ f1(); f2() }} helped me a lot if i want two different functions at the same time. But now i want to create an audiorecorder with only one button. So if i click first i want to run the StartFunction f1() and if i click again then i want to run StopFunction f2().

How do you guys realize this?

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

How can one change the timestamp of an old commit in Git?

Each commit is associated with two dates, the committer date and the author date. You can view these dates with:

git log --format=fuller

If you want to change the author date and the committer date of the last 6 commits, you can simply use an interactive rebase :

git rebase -i HEAD~6

.

pick c95a4b7 Modification 1
pick 1bc0b44 Modification 2
pick de19ad3 Modification 3
pick c110e7e Modification 4
pick 342256c Modification 5
pick 5108205 Modification 6

# Rebase eadedca..5108205 onto eadedca (6 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit

For all commits where you want to change the date, replace pick by edit (or just e), then save and quit your editor.

You can now amend each commit by specifying the author date and the committer date in ISO-8601 format:

GIT_COMMITTER_DATE="2017-10-08T09:51:07" git commit --amend --date="2017-10-08T09:51:07"

The first date is the commit date, the second one is the author date.

Then go to the next commit with :

git rebase --continue

Repeat the process until you amend all your commits. Check your progression with git status.

What causes a TCP/IP reset (RST) flag to be sent?

Run a packet sniffer (e.g., Wireshark) also on the peer to see whether it's the peer who's sending the RST or someone in the middle.

Sort array by firstname (alphabetically) in Javascript

If compared strings contain unicode characters you can use localeCompare function of String class like the following:

users.sort(function(a,b){
    return a.firstname.localeCompare(b.firstname);
})

Difference between & and && in Java?

'&' performs both tests, while '&&' only performs the 2nd test if the first is also true. This is known as shortcircuiting and may be considered as an optimization. This is especially useful in guarding against nullness(NullPointerException).

if( x != null && x.equals("*BINGO*") {
  then do something with x...
}

Can't use SURF, SIFT in OpenCV

for debian users its 'easy' to create their own libopencv-nonfree package.

i followed the opencv tutorial for python, but in my debian the SIFT and SURF modules were missing. And there is no non-free package available for debian including SIFT and SURF etc.

They were stripped from the package due to license issues....

i never created a package for debian before (adding a new module etc) but i followed some small steps in the debian tutorials and tried and guessed around a bit, and after 1 day, voila... i got working a libopencv-nonfree2.4 deb package and a python module with correct bindings.

(i dont know if i also needed to install the newly built python-opencv package or only the nonfree... i re-installed both and got a working python opencv library with all necessary nonfree modules!)

ok, here it is:

!this is for libopencv 2.4!

!you can do all steps except installing as a normal user!

we need the built essesntials and some tools from debian repository to compile and create a new package:

sudo apt-get install build-essential fakeroot devscripts

create a directory in your home and change to that directory:

cd ~ && mkdir opencv-debian
cd opencv-debian

download the needed packages:

apt-get source libopencv-core2.4

and download all needed dependency packages to build the new opencv

apt-get build-dep libopencv-core2.4

this will download the neeeded sources and create a directory called "opencv-2.4.9.1+dfsg"

change to that directory:

cd opencv-2.4.9.1+dfsg

now you can test if the package will built without modifications by typing:

fakeroot debian/rules binary

this will take a long time! this step should finish without errors you now have a lot of .deb packages in your opencv-debian directory

now we make some modifications to the package definition to let debian buld the nonfree modules and package!

change to the opencv-debian directory and download the correct opencv source.. in my case opencv 2.4.9 or so

i got mine from https://github.com/Itseez/opencv/releases

wget https://codeload.github.com/Itseez/opencv/tar.gz/2.4.9

this will download opencv-2.4.9.tar.gz

extract the archive:

tar -xzvf opencv-2.4.9.tar.gz

this will unpack the original source to a directory called opencv-2.4.9

now copy the nonfree modules from original source to the debian source:

cp -rv opencv-2.4.9/modules/nonfree opencv-2.4.9.1+dfsg/modules/

ok, now we have the source of the nonfree modules, but thats not enough for debian... we need to modify 1 file and create a new one

we have to edit the debian control file and add a new section at end of file: (i use mcedit as an editor here)

mcedit opencv-2.4.9.1+dfsg/debian/control

or use any other editor of your choice

and add this section:

Package: libopencv-nonfree2.4
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: OpenCV Nonfree Modules like SIFT and SURF
 This package contains nonfree modules for the OpenCV (Open Computer Vision)
 library.
 .
 The Open Computer Vision Library is a collection of algorithms and sample
 code for various computer vision problems. The library is compatible with
 IPL (Intel's Image Processing Library) and, if available, can use IPP
 (Intel's Integrated Performance Primitives) for better performance.
 .
 OpenCV provides low level portable data types and operators, and a set
 of high level functionalities for video acquisition, image processing and
 analysis, structural analysis, motion analysis and object tracking, object
 recognition, camera calibration and 3D reconstruction.

now we create a new file called libopencv-nonfree2.4.install

touch opencv-2.4.9.1+dfsg/debian/libopencv-nonfree2.4.install

and edit:

mcedit opencv-2.4.9.1+dfsg/debian/libopencv-nonfree2.4.install

and add the following content:

usr/lib/*/libopencv_nonfree.so.*

ok, thats it, now create the packages again:

cd opencv-2.4.9.1+dfsg

first a clean up:

fakeroot debian/rules clean

and build:

fakeroot debian/rules binary

et voila... after a while you have a fresh built and a new package libopencv-nonfree2.4.deb!

now install as root:

dpkg -i libopencv-nonfree2.4.deb
dpkg -i python-opencv.deb

and test!

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

sift = cv2.SIFT()
kp = sift.detect(gray,None)
img=cv2.drawKeypoints(gray,kp)

corners = cv2.goodFeaturesToTrack(gray,16,0.05,10)
corners = np.int0(corners)

for i in corners:
    x,y = i.ravel()
    cv2.circle(img,(x,y),90,255,3)

plt.imshow(img),plt.show()

have fun!

How do I mock a service that returns promise in AngularJS Jasmine unit test?

I found that useful, stabbing service function as sinon.stub().returns($q.when({})):

this.myService = {
   myFunction: sinon.stub().returns( $q.when( {} ) )
};

this.scope = $rootScope.$new();
this.angularStubs = {
    myService: this.myService,
    $scope: this.scope
};
this.ctrl = $controller( require( 'app/bla/bla.controller' ), this.angularStubs );

controller:

this.someMethod = function(someObj) {
   myService.myFunction( someObj ).then( function() {
        someObj.loaded = 'bla-bla';
   }, function() {
        // failure
   } );   
};

and test

const obj = {
    field: 'value'
};
this.ctrl.someMethod( obj );

this.scope.$digest();

expect( this.myService.myFunction ).toHaveBeenCalled();
expect( obj.loaded ).toEqual( 'bla-bla' );

How to select the rows with maximum values in each group with dplyr?

You can use top_n

df %>% group_by(A, B) %>% top_n(n=1)

This will rank by the last column (value) and return the top n=1 rows.

Currently, you can't change the this default without causing an error (See https://github.com/hadley/dplyr/issues/426)

How to fire a button click event from JavaScript in ASP.NET

I can make things work this way:

inside javascript junction that is executed by the html button:

document.getElementById("<%= Button2.ClientID %>").click();

ASP button inside div:

<div id="submitBtn" style="display: none;">
   <asp:Button ID="Button2" runat="server" Text="Submit" ValidationGroup="AllValidators" OnClick="Button2_Click" />
</div>

Everything runs from the .cs file except that the code below doesn't execute. There is no message box and redirect to the same page (refresh all boxes):

 int count = cmd.ExecuteNonQuery();
 if (count > 0)
 {
   cmd2.CommandText = insertSuperRoster;
   cmd2.Connection = con;
   cmd2.ExecuteNonQuery();
   string url = "VaccineRefusal.aspx";
   ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Data Inserted Successfully!');window.location.href = '" + url + "';", true);
  }

Any ideas why these lines won't execute?

This view is not constrained

You just have to right-click on the widget and choose "center" -> "horizontally" and do it again then choose ->"vertically" This worked for me...

Get login username in java

I tested in linux centos

Map<String, String> env = System.getenv();   
for (String envName : env.keySet()) { 
 System.out.format("%s=%s%n", envName, env.get(envName)); 
}

System.out.println(env.get("USERNAME")); 

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Some things to check:

Can you change to unrestricted?

Set-ExecutionPolicy Unrestricted

Is the group policy set?

  • Computer Configuration\Administrative Templates\Windows Components\Windows PowerShell
  • User Configuration\Administrative Templates\Windows Components\Windows PowerShell

Also, how are you calling Script.ps1?

Does this allow it to run?

powershell.exe -executionpolicy bypass -file .\Script.ps1

How to call another components function in angular2

First, what you need to understand the relationships between components. Then you can choose the right method of communication. I will try to explain all the methods that I know and use in my practice for communication between components.

What kinds of relationships between components can there be?

1. Parent > Child

enter image description here

Sharing Data via Input

This is probably the most common method of sharing data. It works by using the @Input() decorator to allow data to be passed via the template.

parent.component.ts

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

@Component({
  selector: 'parent-component',
  template: `
    <child-component [childProperty]="parentProperty"></child-component>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent{
  parentProperty = "I come from parent"
  constructor() { }
}

child.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'child-component',
  template: `
      Hi {{ childProperty }}
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  @Input() childProperty: string;

  constructor() { }

}

This is a very simple method. It is easy to use. We can also catch changes to the data in the child component using ngOnChanges.

But do not forget that if we use an object as data and change the parameters of this object, the reference to it will not change. Therefore, if we want to receive a modified object in a child component, it must be immutable.

2. Child > Parent

enter image description here

Sharing Data via ViewChild

ViewChild allows one component to be injected into another, giving the parent access to its attributes and functions. One caveat, however, is that child won’t be available until after the view has been initialized. This means we need to implement the AfterViewInit lifecycle hook to receive the data from the child.

parent.component.ts

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from "../child/child.component";

@Component({
  selector: 'parent-component',
  template: `
    Message: {{ message }}
    <child-compnent></child-compnent>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {

  @ViewChild(ChildComponent) child;

  constructor() { }

  message:string;

  ngAfterViewInit() {
    this.message = this.child.message
  }
}

child.component.ts

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

@Component({
  selector: 'child-component',
  template: `
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message = 'Hello!';

  constructor() { }

}

Sharing Data via Output() and EventEmitter

Another way to share data is to emit data from the child, which can be listed by the parent. This approach is ideal when you want to share data changes that occur on things like button clicks, form entries, and other user events.

parent.component.ts

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

@Component({
  selector: 'parent-component',
  template: `
    Message: {{message}}
    <child-component (messageEvent)="receiveMessage($event)"></child-component>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  constructor() { }

  message:string;

  receiveMessage($event) {
    this.message = $event
  }
}

child.component.ts

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child-component',
  template: `
      <button (click)="sendMessage()">Send Message</button>
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message: string = "Hello!"

  @Output() messageEvent = new EventEmitter<string>();

  constructor() { }

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}

3. Siblings

enter image description here

Child > Parent > Child

I try to explain other ways to communicate between siblings below. But you could already understand one of the ways of understanding the above methods.

parent.component.ts

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

@Component({
  selector: 'parent-component',
  template: `
    Message: {{message}}
    <child-one-component (messageEvent)="receiveMessage($event)"></child1-component>
    <child-two-component [childMessage]="message"></child2-component>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  constructor() { }

  message: string;

  receiveMessage($event) {
    this.message = $event
  }
}

child-one.component.ts

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child-one-component',
  template: `
      <button (click)="sendMessage()">Send Message</button>
  `,
  styleUrls: ['./child-one.component.css']
})
export class ChildOneComponent {

  message: string = "Hello!"

  @Output() messageEvent = new EventEmitter<string>();

  constructor() { }

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}

child-two.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'child-two-component',
  template: `
       {{ message }}
  `,
  styleUrls: ['./child-two.component.css']
})
export class ChildTwoComponent {

  @Input() childMessage: string;

  constructor() { }

}

4. Unrelated Components

enter image description here

All the methods that I have described below can be used for all the above options for the relationship between the components. But each has its own advantages and disadvantages.

Sharing Data with a Service

When passing data between components that lack a direct connection, such as siblings, grandchildren, etc, you should be using a shared service. When you have data that should always be in sync, I find the RxJS BehaviorSubject very useful in this situation.

data.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

first.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'first-componennt',
  template: `
    {{message}}
  `,
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {

  message:string;

  constructor(private data: DataService) {
      // The approach in Angular 6 is to declare in constructor
      this.data.currentMessage.subscribe(message => this.message = message);
  }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}

second.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'second-component',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./second.component.css']
})
export class SecondComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.changeMessage("Hello from Second Component")
  }

}

Sharing Data with a Route

Sometimes you need not only pass simple data between component but save some state of the page. For example, we want to save some filter in the online market and then copy this link and send to a friend. And we expect it to open the page in the same state as us. The first, and probably the quickest, way to do this would be to use query parameters.

Query parameters look more along the lines of /people?id= where id can equal anything and you can have as many parameters as you want. The query parameters would be separated by the ampersand character.

When working with query parameters, you don’t need to define them in your routes file, and they can be named parameters. For example, take the following code:

page1.component.ts

import {Component} from "@angular/core";
import {Router, NavigationExtras} from "@angular/router";

@Component({
    selector: "page1",
  template: `
    <button (click)="onTap()">Navigate to page2</button>
  `,
})
export class Page1Component {

    public constructor(private router: Router) { }

    public onTap() {
        let navigationExtras: NavigationExtras = {
            queryParams: {
                "firstname": "Nic",
                "lastname": "Raboy"
            }
        };
        this.router.navigate(["page2"], navigationExtras);
    }

}

In the receiving page, you would receive these query parameters like the following:

page2.component.ts

import {Component} from "@angular/core";
import {ActivatedRoute} from "@angular/router";

@Component({
    selector: "page2",
    template: `
         <span>{{firstname}}</span>
         <span>{{lastname}}</span>
      `,
})
export class Page2Component {

    firstname: string;
    lastname: string;

    public constructor(private route: ActivatedRoute) {
        this.route.queryParams.subscribe(params => {
            this.firstname = params["firstname"];
            this.lastname = params["lastname"];
        });
    }

}

NgRx

The last way, which is more complicated but more powerful, is to use NgRx. This library is not for data sharing; it is a powerful state management library. I can't in a short example explain how to use it, but you can go to the official site and read the documentation about it.

To me, NgRx Store solves multiple issues. For example, when you have to deal with observables and when responsibility for some observable data is shared between different components, the store actions and reducer ensure that data modifications will always be performed "the right way".

It also provides a reliable solution for HTTP requests caching. You will be able to store the requests and their responses so that you can verify that the request you're making does not have a stored response yet.

You can read about NgRx and understand whether you need it in your app or not:

Finally, I want to say that before choosing some of the methods for sharing data you need to understand how this data will be used in the future. I mean maybe just now you can use just an @Input decorator for sharing a username and surname. Then you will add a new component or new module (for example, an admin panel) which needs more information about the user. This means that may be a better way to use a service for user data or some other way to share data. You need to think about it more before you start implementing data sharing.

Catch checked change event of a checkbox

use the click event for best compatibility with MSIE

$(document).ready(function() {
    $("input[type=checkbox]").click(function() {
        alert("state changed");
    });
});

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

Taken from this link:

Build means compile and link only the source files that have changed since the last build, while Rebuild means compile and link all source files regardless of whether they changed or not. Build is the normal thing to do and is faster. Sometimes the versions of project target components can get out of sync and rebuild is necessary to make the build successful. In practice, you never need to Clean.

How can I disable mod_security in .htaccess file?

It is possible to do this, but most likely your host implemented mod_security for a reason. Be sure they approve of you disabling it for your own site.

That said, this should do it;

<IfModule mod_security.c>
  SecFilterEngine Off
  SecFilterScanPOST Off
</IfModule>

How to remove a package in sublime text 2

go to package control by pressing Ctrl + Shift + p

type "remove package"

and type your package/plugin to uninstall and remove it

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

The rem command is indeed for comments. It doesn't inherently update anyone after running the script. Some script authors might use it that way instead of echo, though, because by default the batch interpreter will print out each command before it's processed. Since rem commands don't do anything, it's safe to print them without side effects. To avoid printing a command, prefix it with @, or, to apply that setting throughout the program, run @echo off. (It's echo off to avoid printing further commands; the @ is to avoid printing that command prior to the echo setting taking effect.)

So, in your batch file, you might use this:

@echo off
REM To skip the following Python commands, put "REM" before them:
python foo.py
python bar.py

How do I open workbook programmatically as read-only?

Check out the language reference:

http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

Parsing JSON from XmlHttpRequest.responseJSON

New ways I: fetch

TL;DR I'd recommend this way as long as you don't have to send synchronous requests or support old browsers.

A long as your request is asynchronous you can use the Fetch API to send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch() to send a request and ResponseBody.json() to parse the response:

fetch(url)
  .then(function(response) {
    return response.json();
  })
  .then(function(jsonResponse) {
    // do something with jsonResponse
  });

Compatibility: The Fetch API is not supported by IE11 as well as Edge 12 & 13. However, there are polyfills.

New ways II: responseType

As Londeren has written in his answer, newer browsers allow you to use the responseType property to define the expected format of the response. The parsed response data can then be accessed via the response property:

var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = req.response;
   // do something with jsonResponse
};
req.send(null);

Compatibility: responseType = 'json' is not supported by IE11.

The classic way

The standard XMLHttpRequest has no responseJSON property, just responseText and responseXML. As long as bitly really responds with some JSON to your request, responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse():

var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = JSON.parse(req.responseText);
   // do something with jsonResponse
};
req.send(null);

Compatibility: This approach should work with any browser that supports XMLHttpRequest and JSON.

JSONHttpRequest

If you prefer to use responseJSON, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSON property. All you have to change in your code would be the first line:

var req = new JSONHttpRequest();

JSONHttpRequest also provides functionality to easily send JavaScript objects as JSON. More details and the code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/.

Full disclosure: I'm the owner of Pixels|Bytes. I thought that my script was a good solution for the original question, but it is rather outdated today. I do not recommend to use it anymore.

How to center a View inside of an Android Layout?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center">
    <ProgressBar
        android:id="@+id/ProgressBar01"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"></ProgressBar>
    <TextView
        android:layout_below="@id/ProgressBar01"
        android:text="@string/please_wait_authenticating"
        android:id="@+id/txtText"
        android:paddingTop="30px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></TextView>
</RelativeLayout>

How can I scroll a div to be visible in ReactJS?

With reacts Hooks:

  1. Import
import ReactDOM from 'react-dom';
import React, {useRef} from 'react';
  1. Make new hook:
const divRef = useRef<HTMLDivElement>(null);
  1. Add new Div
<div ref={divRef}/>
  1. Scroll function:
const scrollToDivRef  = () => {
    let node = ReactDOM.findDOMNode(divRef.current) as Element;
    node.scrollIntoView({block: 'start', behavior: 'smooth'});
}

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

Get button click inside UITableViewCell

If you want to pass parameter value from cell to UIViewController using closure then

//Your Cell Class
class TheCell: UITableViewCell {

    var callBackBlockWithParam: ((String) -> ()) = {_ in }

//Your Action on button
    @IBAction func didTap(_ sender: Any) {
        callBackBlockWithParam("Your Required Parameter like you can send button as sender or anything just change parameter type. Here I am passing string")
    }
}

//Your Controller
extension TheController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: TheCell.identifier, for: indexPath) as! TheCell {
            cell.callBackBlockWithParam = { (passedParamter) in 

             //you will get string value from cell class
                print(passedParamter)     
      }
            return cell
    }
}

How to validate an email address in JavaScript

I have found this to be the best solution:

/^[^\s@]+@[^\s@]+\.[^\s@]+$/

It allows the following formats:

1.  [email protected]
2.  [email protected]
3.  [email protected]
4.  [email protected]
9.  #!$%&'*+-/=?^_`{}|[email protected]
6.  "()[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org
7.  " "@example.org (space between the quotes)
8.  üñîçøðé@example.com (Unicode characters in local part)
9.  üñîçøðé@üñîçøðé.com (Unicode characters in domain part)
10. Pelé@example.com (Latin)
11. d???µ?@pa??de??µa.d???µ? (Greek)
12. ??@??.?? (Chinese)
13. ??@??.?? (Japanese)
14. ?????????@????-?-???????????.?? (Cyrillic)

It's clearly versatile and allows the all-important international characters, while still enforcing the basic [email protected] format. It will block spaces which are technically allowed by RFC, but they are so rare that I'm happy to do this.

Getting a random value from a JavaScript array

A generic way to get random element(s):

_x000D_
_x000D_
let some_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];_x000D_
let months = random_elems(some_array, 3);_x000D_
_x000D_
console.log(months);_x000D_
_x000D_
function random_elems(arr, count) {_x000D_
  let len = arr.length;_x000D_
  let lookup = {};_x000D_
  let tmp = [];_x000D_
_x000D_
  if (count > len)_x000D_
    count = len;_x000D_
_x000D_
  for (let i = 0; i < count; i++) {_x000D_
    let index;_x000D_
    do {_x000D_
      index = ~~(Math.random() * len);_x000D_
    } while (index in lookup);_x000D_
    lookup[index] = null;_x000D_
    tmp.push(arr[index]);_x000D_
  }_x000D_
_x000D_
  return tmp;_x000D_
}
_x000D_
_x000D_
_x000D_

Force overwrite of local file with what's in origin repo?

This worked for me:

git reset HEAD <filename>

'str' object has no attribute 'decode'. Python 3 error?

Other answers sort of hint at it, but the problem may arise from expecting a bytes object. In Python 3, decode is valid when you have an object of class bytes. Running encode before decode may "fix" the problem, but it is a useless pair of operations that suggest the problem us upstream.

DateTime.TryParse issue with dates of yyyy-dd-MM format

From DateTime on msdn:

Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.

onclick go full screen

If you want to switch the whole tab to fullscreen (just like F11 keypress) document.documentElement is the element you are looking for:

function go_full_screen(){
    var elem = document.documentElement;
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.msRequestFullscreen) {
      elem.msRequestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
      elem.webkitRequestFullscreen();
    }
}

CSS Margin: 0 is not setting to 0

It's very simple. just add this to the body -

body{
margin:0;
padding:0;
overflow:hidden;
}

How to check whether input value is integer or float?

Also:

(value % 1) == 0

would work!

How to generate random positive and negative numbers in Java

(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))

How to open the terminal in Atom?

There are a number of Atom packages which give you access to the terminal from within Atom. Try a few out to find the best option for you.

Some recommendations which work in Ubuntu (with their primary keyboard shortcuts):

Open a terminal in Atom:

Edit: recommended plugin changed as terminal-plus is no longer maintained. Thanks for the head's-up, @MorganRodgers.

If you want to open a terminal panel in Atom, try atom-ide-terminal. Use the keyboard shortcut ctrl-` to open a new terminal instance.

Open an external terminal from Atom:

If you just want a shortcut to open your external terminal from within Atom, try atom-terminal (this is what I use). You can use ctrl-shift-t to open your external terminal in the current file's directory, or alt-shift-t to open the terminal in the project's root directory.

Percentage width in a RelativeLayout

Just put your two textviews host and port in an independant linearlayout horizontal and use android:layout_weight to make the percentage

Calling Scalar-valued Functions in SQL

Are you sure it's not a Table-Valued Function?

The reason I ask:

CREATE FUNCTION dbo.chk_mgr(@mgr VARCHAR(50)) 
RETURNS @mgr_table TABLE (mgr_name VARCHAR(50))
AS
BEGIN 
  INSERT @mgr_table (mgr_name) VALUES ('pointy haired boss') 
  RETURN
END 
GO

SELECT dbo.chk_mgr('asdf')
GO

Result:

Msg 4121, Level 16, State 1, Line 1
Cannot find either column "dbo" or the user-defined function 
or aggregate "dbo.chk_mgr", or the name is ambiguous.

However...

SELECT * FROM dbo.chk_mgr('asdf') 

mgr_name
------------------
pointy haired boss

$(document).click() not working correctly on iPhone. jquery

Adding in the following code works.

The problem is iPhones dont raise click events. They raise "touch" events. Thanks very much apple. Why couldn't they just keep it standard like everyone else? Anyway thanks Nico for the tip.

Credit to: http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript

$(document).ready(function () {
  init();
  $(document).click(function (e) {
    fire(e);
  });
});

function fire(e) { alert('hi'); }

function touchHandler(event)
{
    var touches = event.changedTouches,
        first = touches[0],
        type = "";

    switch(event.type)
    {
       case "touchstart": type = "mousedown"; break;
       case "touchmove":  type = "mousemove"; break;        
       case "touchend":   type = "mouseup"; break;
       default: return;
    }

    //initMouseEvent(type, canBubble, cancelable, view, clickCount, 
    //           screenX, screenY, clientX, clientY, ctrlKey, 
    //           altKey, shiftKey, metaKey, button, relatedTarget);

    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                          first.screenX, first.screenY, 
                          first.clientX, first.clientY, false, 
                          false, false, false, 0/*left*/, null);

    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init() 
{
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);    
}

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

As it was said already @INC is an array and you're free to add anything you want.

My CGI REST script looks like:

#!/usr/bin/perl
use strict;
use warnings;
BEGIN {
    push @INC, 'fully_qualified_path_to_module_wiht_our_REST.pm';
}
use Modules::Rest;
gone(@_);

Subroutine gone is exported by Rest.pm.

Determine the process pid listening on a certain port

netstat -nlp should tell you the PID of what's listening on which port.

Maven error: Not authorized, ReasonPhrase:Unauthorized

The issue may happen while fetching dependencies from a remote repository. In my case, the repository did not need any authentication and it has been resolved by removing the servers section in the settings.xml file:

<servers>
    <server>
      <id>SomeRepo</id>
      <username>SomeUN</username>
      <password>SomePW</password>
    </server>
</servers>

ps: I guess your target is mvn clean install instead of maven install clean

Representing EOF in C code?

There is the constant EOF of type int, found in stdio.h. There is no equivalent character literal specified by any standard.

How to make a simple rounded button in Storyboard?

Follow the screenshot below. It works when you run the simulator (won't see it on preview)

Adding UIView rounded border

C# Collection was modified; enumeration operation may not execute

The error tells you EXACTLY what the problem is (and running in the debugger or reading the stack trace will tell you exactly where the problem is):

C# Collection was modified; enumeration operation may not execute.

Your problem is the loop

foreach (KeyValuePair<int, int> kvp in rankings) {
    //
}

wherein you modify the collection rankings. In particular, the offensive line is

rankings[kvp.Key] = rankings[kvp.Key] + 4;

Before you enter the loop, add the following line:

var listOfRankingsToModify = new List<int>();

Replace the offending line with

listOfRankingsToModify.Add(kvp.Key);

and after you exit the loop

foreach(var key in listOfRankingsToModify) {
    rankings[key] = rankings[key] + 4;
}

That is, record what changes you need to make, and make them without iterating over the collection that you need to modify.

HTTP GET Request in Node.js Express

Request and Superagent are pretty good libraries to use.

note: request is deprecated, use at your risk!

Using request:

var request=require('request');

request.get('https://someplace',options,function(err,res,body){
  if(err) //TODO: handle err
  if(res.statusCode === 200 ) //etc
  //TODO Do something with response
});

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

As I think, It's not best way to using UIGestureRecognizer-based cells.

First, you'll not have any options to use CoreGraphics.

Perfect solution, will UIResponder or one UIGestureRecognizer for whole table view. Not for every UITableViewCell. It will make you app stuck.

How do I replicate a \t tab space in HTML?

&nbsp;&nbsp;&nbsp;&nbsp; would be a work around if you're only after the spacing.

Nullable DateTime conversion

Make sure those two types are nullable DateTime

var lastPostDate = reader[3] == DBNull.Value ?
                                        null : 
                                   (DateTime?) Convert.ToDateTime(reader[3]);
  • Usage of DateTime? instead of Nullable<DateTime> is a time saver...
  • Use better indent of the ? expression like I did.

I have found this excellent explanations in Eric Lippert blog:

The specification for the ?: operator states the following:

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

  • If X and Y are the same type, then this is the type of the conditional expression.

  • Otherwise, if an implicit conversion exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

  • Otherwise, if an implicit conversion exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

  • Otherwise, no expression type can be determined, and a compile-time error occurs.

The compiler doesn't check what is the type that can "hold" those two types.

In this case:

  • null and DateTime aren't the same type.
  • null doesn't have an implicit conversion to DateTime
  • DateTime doesn't have an implicit conversion to null

So we end up with a compile-time error.

Passing just a type as a parameter in C#

You can use an argument of type Type - iow, pass typeof(int). You can also use generics for a (probably more efficient) approach.

Rendering HTML inside textarea

With an editable div you can use the method document.execCommand (more details) to easily provide the support for the tags you specified and for some other functionality..

_x000D_
_x000D_
#text {_x000D_
    width : 500px;_x000D_
 min-height : 100px;_x000D_
 border : 2px solid;_x000D_
}
_x000D_
<div id="text" contenteditable="true"></div>_x000D_
<button onclick="document.execCommand('bold');">toggle bold</button>_x000D_
<button onclick="document.execCommand('italic');">toggle italic</button>_x000D_
<button onclick="document.execCommand('underline');">toggle underline</button>
_x000D_
_x000D_
_x000D_

assigning column names to a pandas series

If you have a pd.Series object x with index named 'Gene', you can use reset_index and supply the name argument:

df = x.reset_index(name='count')

Here's a demo:

x = pd.Series([2, 7, 1], index=['Ezh2', 'Hmgb', 'Irf1'])
x.index.name = 'Gene'

df = x.reset_index(name='count')

print(df)

   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1

What does 'super' do in Python?

Doesn't all of this assume that the base class is a new-style class?

class A:
    def __init__(self):
        print("A.__init__()")

class B(A):
    def __init__(self):
        print("B.__init__()")
        super(B, self).__init__()

Will not work in Python 2. class A must be new-style, i.e: class A(object)

How to change dot size in gnuplot

Use the pointtype and pointsize options, e.g.

plot "./points.dat" using 1:2 pt 7 ps 10  

where pt 7 gives you a filled circle and ps 10 is the size.

See: Plotting data.

Test file upload using HTTP PUT method

If you're using PHP you can test your PUT upload using the code below:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

Change Project Namespace in Visual Studio

Instead of Find & Replace, you can right click the namespace in code and Refactor -> Rename.

Thanks to @Jimmy for this.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

pass $connect as your first parameter in mysqli_real_escape_string for this first make connection then do rest.read here http://php.net/manual/en/mysqli.real-escape-string.php

How can I make Bootstrap 4 columns all the same height?

You just have to use class="row-eq-height" with your class="row" to get equal height columns for previous bootstrap versions.

but with bootstrap 4 this comes natively.

check this link --http://getbootstrap.com.vn/examples/equal-height-columns/

Why doesn't Mockito mock static methods?

I think the reason may be that mock object libraries typically create mocks by dynamically creating classes at runtime (using cglib). This means they either implement an interface at runtime (that's what EasyMock does if I'm not mistaken), or they inherit from the class to mock (that's what Mockito does if I'm not mistaken). Both approaches do not work for static members, since you can't override them using inheritance.

The only way to mock statics is to modify a class' byte code at runtime, which I suppose is a little more involved than inheritance.

That's my guess at it, for what it's worth...

Using a list as a data source for DataGridView

First, I don't understand why you are adding all the keys and values count times, Index is never used.

I tried this example :

        var source = new BindingSource();
        List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"),  new MyStruct("c","d") };
        source.DataSource = list;
        grid.DataSource = source;

and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.

    class MyStruct
   {
    public string Name { get; set; }
    public string Adres { get; set; }


    public MyStruct(string name, string adress)
    {
        Name = name;
        Adres = adress;
    }
  }

Try to build a type that takes one key and value, and add it one by one. Hope this helps.

How to center an iframe horizontally?

If you are putting a video in the iframe and you want your layout to be fluid, you should look at this webpage: Fluid Width Video

Depending on the video source and if you want to have old videos become responsive your tactics will need to change.

If this is your first video, here is a simple solution:

_x000D_
_x000D_
<div class="videoWrapper">_x000D_
    <!-- Copy & Pasted from YouTube -->_x000D_
    <iframe width="560" height="349" src="http://www.youtube.com/embed/n_dZNLr2cME?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And add this css:

_x000D_
_x000D_
.videoWrapper {_x000D_
 position: relative;_x000D_
 padding-bottom: 56.25%; /* 16:9 */_x000D_
 padding-top: 25px;_x000D_
 height: 0;_x000D_
}_x000D_
.videoWrapper iframe {_x000D_
 position: absolute;_x000D_
 top: 0;_x000D_
 left: 0;_x000D_
 width: 100%;_x000D_
 height: 100%;_x000D_
}
_x000D_
_x000D_
_x000D_

Disclaimer: none of this is my code, but I've tested it and was happy with the results.

Escape double quotes in a string

In C# you can use the backslash to put special characters to your string. For example, to put ", you need to write \". There are a lot of characters that you write using the backslash: Backslash with a number:

  • \000 null
  • \010 backspace
  • \011 horizontal tab
  • \012 new line
  • \015 carriage return
  • \032 substitute
  • \042 double quote
  • \047 single quote
  • \134 backslash
  • \140 grave accent

Backslash with othe character

  • \a Bell (alert)
  • \b Backspace
  • \f Formfeed
  • \n New line
  • \r Carriage return
  • \t Horizontal tab
  • \v Vertical tab
  • \' Single quotation mark
  • \" Double quotation mark
  • \ Backslash
  • \? Literal question mark
  • \ ooo ASCII character in octal notation
  • \x hh ASCII character in hexadecimal notation
  • \x hhhh Unicode character in hexadecimal notation if this escape sequence is used in a wide-character constant or a Unicode string literal. For example, WCHAR f = L'\x4e00' or WCHAR b[] = L"The Chinese character for one is \x4e00".

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.

In Python 3.x True and False are keywords and will always be equal to 1 and 0.

Under normal circumstances in Python 2, and always in Python 3:

False object is of type bool which is a subclass of int:

object
   |
 int
   |
 bool

It is the only reason why in your example, ['zero', 'one'][False] does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__ method (thanks mark-dickinson).

Edit:

It is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say:

There are two types of integers: [...] Integers (int) [...] Booleans (bool)

and in the boolean subsection:

Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

There is also, for Python 2:

In numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively.

So booleans are explicitly considered as integers in Python 2 and 3.

So you're safe until Python 4 comes along. ;-)

BLOB to String, SQL Server

Can you try this:

select convert(nvarchar(max),convert(varbinary(max),blob_column)) from table_name

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

ImportError: DLL load failed: %1 is not a valid Win32 application

Or you have to rebuild the cv2 module for win 64bit.

Construct a manual legend for a complicated plot

In case you were struggling to change linetypes, the following answer should be helpful. (This is an addition to the solution by Andy W.)

We will try to extend the learned pattern:

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) +           #red
  geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) +           #blue
  scale_colour_manual(name="Error Bars",values=cols, 
                  guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_linetype_manual(values=line_types)+
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

However, what we get is the following result: manual without name

The problem is that the linetype is not merged in the main legend. Note that we did not give any name to the method scale_linetype_manual. The trick which works here is to give it the same name as what you used for naming scale_colour_manual. More specifically, if we change the corresponding line to the following we get the desired result:

scale_linetype_manual(name="Error Bars",values=line_types)

manual with the same name

Now, it is easy to change the size of the line with the same idea.

Note that the geom_bar has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.

How to center links in HTML

The <p> will show up on a new line. Try wrapping all of your links in one single <p> tag:

<p style="text-align:center;"><a href="http//www.google.com">Search</a><a href="Contact Us">Contact Us</a></p>

Checkboxes in web pages – how to make them bigger?

Here's a trick that works in most recent browsers (IE9+) as a CSS only solution that can be improved with javascript to support IE8 and below.

<div>
  <input type="checkbox" id="checkboxID" name="checkboxName" value="whatever" />
  <label for="checkboxID"> </label>
</div>

Style the label with what you want the checkbox to look like

#checkboxID
{
  position: absolute fixed;
  margin-right: 2000px;
  right: 100%;
}
#checkboxID + label
{
  /* unchecked state */
}
#checkboxID:checked + label
{
  /* checked state */
}

For javascript, you'll be able to add classes to the label to show the state. Also, it would be wise to use the following function:

$('label[for]').live('click', function(e){
  $('#' + $(this).attr('for') ).click();
  return false;
});

EDIT to modify #checkboxID styles

How can I return the sum and average of an int array?

Though the answers above all are different flavors of correct, I'd like to offer the following solution, which includes a null check:

decimal sum = (customerssalary == null) ? 0 : customerssalary.Sum();
decimal avg = (customerssalary == null) ? 0 : customerssalary.Average();

Merging Cells in Excel using C#

Try it.

ws.Range("A1:F2").Merge();

Application_Start not firing?

I hade the same problem, couldn't catch Application_Start. And the reason was that it was not firing do to a missmatch in the markup file. The markup file Global.asax was inheriting another class...

How to set selectedIndex of select element using display text?

Try this:

function SelectAnimal() {
    var sel = document.getElementById('Animals');
    var val = document.getElementById('AnimalToFind').value;
    for(var i = 0, j = sel.options.length; i < j; ++i) {
        if(sel.options[i].innerHTML === val) {
           sel.selectedIndex = i;
           break;
        }
    }
}

what is the differences between sql server authentication and windows authentication..?

Ideally, Windows authentication must be used when working in an Intranet type of an environment.

Whereas, SQL Server authentication can be used in all the other type of cases.

Here is a link which might help.

Windows Authentication vs. SQL Server Authentication

Forwarding port 80 to 8080 using NGINX

You can define an upstream and use it in proxy_pass

http://rohanambasta.blogspot.com/2016/02/redirect-nginx-request-to-upstream.html

server {  
   listen        8082;

   location ~ /(.*) {  
       proxy_pass  test_server;  
       proxy_set_header Host $host;  
       proxy_set_header X-Real-IP $remote_addr;  
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
       proxy_set_header X-Forwarded-Proto $scheme;  
       proxy_redirect    off;  
   }  

}   

  upstream test_server  
     {  
         server test-server:8989  
}  

How do I find the caller of a method using stacktrace or reflection?

This method does the same thing but a little more simply and possibly a little more performant and in the event you are using reflection, it skips those frames automatically. The only issue is it may not be present in non-Sun JVMs, although it is included in the runtime classes of JRockit 1.4-->1.6. (Point is, it is not a public class).

sun.reflect.Reflection

    /** Returns the class of the method <code>realFramesToSkip</code>
        frames up the stack (zero-based), ignoring frames associated
        with java.lang.reflect.Method.invoke() and its implementation.
        The first frame is that associated with this method, so
        <code>getCallerClass(0)</code> returns the Class object for
        sun.reflect.Reflection. Frames associated with
        java.lang.reflect.Method.invoke() and its implementation are
        completely ignored and do not count toward the number of "real"
        frames skipped. */
    public static native Class getCallerClass(int realFramesToSkip);

As far as what the realFramesToSkip value should be, the Sun 1.5 and 1.6 VM versions of java.lang.System, there is a package protected method called getCallerClass() which calls sun.reflect.Reflection.getCallerClass(3), but in my helper utility class I used 4 since there is the added frame of the helper class invocation.

How do I resolve "Cannot find module" error using Node.js?

I had this issue using live-server (using the Fullstack React book):

I kept getting:

Error: Cannot find module './disable-browser-cache.js' 
...

I had to tweak my package.json

  • From:

    "scripts": { ... "server": "live-server public --host=localhost --port=3000 --middleware=./disable-browser-cache.js" ... } "scripts": {

  • To:

    ... "server": "live-server public --host=localhost --port=3000 --middleware=../../disable-browser-cache.js" ... }

Notice relative paths seem broken/awkward... ./ becomes ../../

I found the issue here

Also if anyone follows along with that book:

  1. change devDependencies in packages.json to:

"live-server": "https://github.com/tapio/live-server/tarball/master"

Currently that upgrades from v1.2.0 to v1.2.1

  1. It's good to use nvm.
  2. It's best to install v13.14 of Node (*v14+ creates other headaches) nvm install v13.14.0
  3. nvm alias default v13.14.0
  4. Update npm with npm i -g [email protected]
  5. run: npm update
  6. you can use npm list to see the hierarchy of dependencies too. (For some reason node 15 + latest npm defaults to only showing first level of depth - a la package.json. That renders default command pointless! You can append --depth=n) to make command more useful again).
  7. you can use npm audit too. There issues requiring (update of chokidar and some others packages) to newer versions. live-server hasn't been updated to support the newer corresponding node v 14 library versions.

See similar post here


Footnote: Another thing when you get to the JSX section, check out my answer here: https://stackoverflow.com/a/65430910/495157

When you get to:

  • Advanced Component Configuration with props, state, and children. P182+, node version 13 isn't supported for some of the dependencies there.
  • Will add findings for that later too.

Replace CRLF using powershell

Below is my script for converting all files recursively. You can specify folders or files to exclude.

$excludeFolders = "node_modules|dist|.vs";
$excludeFiles = ".*\.map.*|.*\.zip|.*\.png|.*\.ps1"

Function Dos2Unix {
    [CmdletBinding()]
    Param([Parameter(ValueFromPipeline)] $fileName)

    Write-Host -Nonewline "."

    $fileContents = Get-Content -raw $fileName
    $containsCrLf = $fileContents | %{$_ -match "\r\n"}
    If($containsCrLf -contains $true)
    {
        Write-Host "`r`nCleaing file: $fileName"
        set-content -Nonewline -Encoding utf8 $fileName ($fileContents -replace "`r`n","`n")
    }
}

Get-Childitem -File "." -Recurse |
Where-Object {$_.PSParentPath -notmatch $excludeFolders} |
Where-Object {$_.PSPath -notmatch $excludeFiles} |
foreach { $_.PSPath | Dos2Unix }

Matplotlib/pyplot: How to enforce axis range?

Calling p.plot after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling xlim() or ylim() after your plot command.

I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is backwards (ie. brighter stars have a smaller magnitude) so I usually swap the limits with

lims = xlim()
xlim([lims[1], lims[0]]) 

Pad left or right with string.format (not padleft or padright) with arbitrary string

Simple:



    dim input as string = "SPQR"
    dim format as string =""
    dim result as string = ""

    'pad left:
    format = "{0,-8}"
    result = String.Format(format,input)
    'result = "SPQR    "

    'pad right
    format = "{0,8}"
    result = String.Format(format,input)
    'result = "    SPQR"


How to downgrade Node version

In Mac there is a fast method with brew:

brew search node

You see some version, for example: node@10 node@12 ... Then

brew unlink node

And now select a before version for example node@12

brew link --overwrite --force node@12

Ready, you have downgraded you node version.

Can't import javax.servlet.annotation.WebServlet

Add library 'Server Runtime' to your java build path, and it shall resolve the issue.

Max retries exceeded with URL in requests

just import time and add :

time.sleep(6)

somewhere in the for loop, to avoid sending too many request to the server in a short time. the number 6 means: 6 seconds. keep testing numbers starting from 1, until you reach the minimum seconds that will help to avoid the problem.

Pull request vs Merge request

As mentioned in previous answers, both serve almost same purpose. Personally I like git rebase and merge request (as in gitlab). It takes burden off of the reviewer/maintainer, making sure that while adding merge request, the feature branch includes all of the latest commits done on main branch after feature branch is created. Here is a very useful article explaining rebase in detail: https://git-scm.com/book/en/v2/Git-Branching-Rebasing

Saving a Excel File into .txt format without quotes

I was using Write #1 "Print my Line" instead I tried Print #1, "Print my Line" and it give me all the data without default Quote(")

Dim strFile_Path As String
strFile_Path = ThisWorkbook.Path & "\" & "XXXX" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".txt"
Open strFile_Path For Output As #1

Dim selectedFeature As String

For counter = 7 To maxNumberOfColumn

        selectedFeature = "X"
        Print #1, selectedFeature
        'Write #1, selectedFeature

Next counter
Close #1

TypeError: unsupported operand type(s) for -: 'list' and 'list'

You can't subtract a list from a list.

>>> [3, 7] - [1, 2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'

Simple way to do it is using numpy:

>>> import numpy as np
>>> np.array([3, 7]) - np.array([1, 2])
array([2, 5])

You can also use list comprehension, but it will require changing code in the function:

>>> [a - b for a, b in zip([3, 7], [1, 2])]
[2, 5]

>>> import numpy as np
>>>
>>> def Naive_Gauss(Array,b):
...     n = len(Array)
...     for column in xrange(n-1):
...         for row in xrange(column+1, n):
...             xmult = Array[row][column] / Array[column][column]
...             Array[row][column] = xmult
...             #print Array[row][col]
...             for col in xrange(0, n):
...                 Array[row][col] = Array[row][col] - xmult*Array[column][col]
...             b[row] = b[row]-xmult*b[column]
...     print Array
...     print b
...     return Array, b  # <--- Without this, the function will return `None`.
...
>>> print Naive_Gauss(np.array([[2,3],[4,5]]),
...                   np.array([[6],[7]]))
[[ 2  3]
 [-2 -1]]
[[ 6]
 [-5]]
(array([[ 2,  3],
       [-2, -1]]), array([[ 6],
       [-5]]))

How to do URL decoding in Java?

This has been answered before (although this question was first!):

"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."

As URL class documentation states:

The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL().

The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396.

Basically:

String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());

will give you:

https://mywebsite/docs/english/site/mybook.do?request_type

How to access Winform textbox control from another class?

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

private System.Windows.Forms.TextBox textBox1;

by this

public System.Windows.Forms.TextBox textBox1;

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

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

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

Modifiers

Select box arrow style

in Firefox 39 I've found that setting a border to the select element will render the arrow as (2). No border set, will render the arrow as (1). I think it's a bug.

Pandas get topmost n records within each group

Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:

g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)

What is a stored procedure?

A stored procedure is a group of SQL statements that has been created and stored in the database. A stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. A stored procedures will reduce network traffic and increase the performance. If we modify a stored procedure all the clients will get the updated stored procedure.

Sample of creating a stored procedure

CREATE PROCEDURE test_display
AS
    SELECT FirstName, LastName
    FROM tb_test;

EXEC test_display;

Advantages of using stored procedures

  • A stored procedure allows modular programming.

    You can create the procedure once, store it in the database, and call it any number of times in your program.

  • A stored procedure allows faster execution.

    If the operation requires a large amount of SQL code that is performed repetitively, stored procedures can be faster. They are parsed and optimized when they are first executed, and a compiled version of the stored procedure remains in a memory cache for later use. This means the stored procedure does not need to be reparsed and reoptimized with each use, resulting in much faster execution times.

  • A stored procedure can reduce network traffic.

    An operation requiring hundreds of lines of Transact-SQL code can be performed through a single statement that executes the code in a procedure, rather than by sending hundreds of lines of code over the network.

  • Stored procedures provide better security to your data

    Users can be granted permission to execute a stored procedure even if they do not have permission to execute the procedure's statements directly.

    In SQL Server we have different types of stored procedures:

    • System stored procedures
    • User-defined stored procedures
    • Extended stored Procedures
  • System-stored procedures are stored in the master database and these start with a sp_ prefix. These procedures can be used to perform a variety of tasks to support SQL Server functions for external application calls in the system tables

    Example: sp_helptext [StoredProcedure_Name]

  • User-defined stored procedures are usually stored in a user database and are typically designed to complete the tasks in the user database. While coding these procedures don’t use the sp_ prefix because if we use the sp_ prefix first, it will check the master database, and then it comes to user defined database.

  • Extended stored procedures are the procedures that call functions from DLL files. Nowadays, extended stored procedures are deprecated for the reason it would be better to avoid using extended stored procedures.

Center image horizontally within a div

Use positioning. The following worked for me... (Horizontally and Vertically Centered)

With zoom to the center of the image (image fills the div):

div{
    display:block;
    overflow:hidden;
    width: 70px; 
    height: 70px;  
    position: relative;
}
div img{
    min-width: 70px; 
    min-height: 70px;
    max-width: 250%; 
    max-height: 250%;    
    top: -50%;
    left: -50%;
    bottom: -50%;
    right: -50%;
    position: absolute;
}

Without zoom to the center of the image (image does not fill the div):

   div{
        display:block;
        overflow:hidden;
        width: 100px; 
        height: 100px;  
        position: relative;
    }
    div img{
        width: 70px; 
        height: 70px; 
        top: 50%;
        left: 50%;
        bottom: 50%;
        right: 50%;
        position: absolute;
    }

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Scala best way of turning a Collection into a Map-by-key?

Another solution (might not work for all types)

import scala.collection.breakOut
val m:Map[P, T] = c.map(t => (t.getP, t))(breakOut)

this avoids the creation of the intermediary list, more info here: Scala 2.8 breakOut

What's the difference between eval, exec, and compile?

exec is for statement and does not return anything. eval is for expression and returns value of expression.

expression means "something" while statement means "do something".

Bootstrap modal link

A Simple Approach will be to use a normal link and add Bootstrap modal effect to it. Just make use of my Code, hopefully you will get it run.

 <div class="container">
        <div class="row">
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="addContact" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><b style="color:#fb3600; font-weight:700;">X</b></button><!--&times;-->
                            <h4 class="modal-title text-center" id="addContact">Add Contact</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <ul class="nav nav-tabs">
                                    <li class="active">
                                        <a data-toggle="tab" style="background-color:#f5dfbe" href="#contactTab">Contact</a>
                                    </li>
                                    <li>
                                        <a data-toggle="tab" style="background-color:#a6d2f6" href="#speechTab">Speech</a>
                                    </li>
                                </ul>
                                <div class="tab-content">
                                    <div id="contactTab" class="tab-pane in active"><partial name="CreateContactTag"></div>
                                    <div id="speechTab" class="tab-pane fade in"><partial name="CreateSpeechTag"></div>
                                </div>

                            </div>
                        </div>
                        <div class="modal-footer">
                            <a class="btn btn-info" data-dismiss="modal">Close</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

how to add script inside a php code?

You could use PHP's file_get_contents();

<?php

   $script = file_get_contents('javascriptFile.js');
   echo "<script>".$script."</script>";

?>

For more information on the function:

http://php.net/manual/en/function.file-get-contents.php

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.

How to interactively (visually) resolve conflicts in SourceTree / git

When the Resolve Conflicts->Content Menu are disabled, one may be on the Pending files list. We need to select the Conflicted files option from the drop down (top)

hope it helps

Bluetooth pairing without user confirmation

Short answer: When I send files between devices with OBEX I am almost never prompted to pair, so it is certainly possible.

1) An application and the device itself can each be set to need/not-need authentication modes, so often there was no requirement for pairing. For instance most OBEX (OPP) servers don't need any authentication at all so there is not need for pairing/bonding.

Presumably "Wireless Designs"'s answer was covering that case.

2) Then if pairing was required by the device/app:

2.1) Prior to v2.1 for pairing then the two devices needed to have matching passphrase/PINs. So this either needed user involvement (to enter the PINs) or knowledge in the softwareto know the PIN: either defined in the app if pin callback send pin="1234", or smarts in the OS like BlueZ and Win7 (see Slide 20 at my Bluetooth in Windows 7 doc) which has logic like: if(remotedevice=headset) then expectedPin ="0000". Don't know what Android does

2.2) In v2.1 Secure Simple Pairing (SSP) was added. Which changes pairing to:

if (either is pre-v2.1) then
   Legacy
else if (Out-Of-Band channel) then
   OutOfBand
else if (neither have "Man-in-the-Middle Protection Required") then
   (i.e. both have "Man-in-the-Middle Protection _Not_ Required")
   Just-Works
else
   Depending on the two devices' "IO Capabilities", either NumericComparison or Passkey.
   Passkey is used when one device has KeyboardOnly -- and the peer device _isn't_ NoInputNoOutput.
endif

From 32feet.NET's BluetoothWin32Authentication user guide, see also the SSP sections in [1]

So to have pairing be unprompted needs either "JustWorks" or "Out-of-Band" eg your NFC suggestion.

Hope that helps...

Open files in 'rt' and 'wt' modes

t indicates for text mode

https://docs.python.org/release/3.1.5/library/functions.html#open

on linux, there's no difference between text mode and binary mode, however, in windows, they converts \n to \r\n when text mode.

http://www.cygwin.com/cygwin-ug-net/using-textbinary.html

How to change a text with jQuery

This should work fine (using .text():

$("#toptitle").text("New word");

Setting different color for each series in scatter plot on matplotlib

An easy fix

If you have only one type of collections (e.g. scatter with no error bars) you can also change the colours after that you have plotted them, this sometimes is easier to perform.

import matplotlib.pyplot as plt
from random import randint
import numpy as np

#Let's generate some random X, Y data X = [ [frst group],[second group] ...]
X = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
Y = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
labels = range(1,len(X)+1)

fig = plt.figure()
ax = fig.add_subplot(111)
for x,y,lab in zip(X,Y,labels):
        ax.scatter(x,y,label=lab)

The only piece of code that you need:

#Now this is actually the code that you need, an easy fix your colors just cut and paste not you need ax.
colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired  
colorst = [colormap(i) for i in np.linspace(0, 0.9,len(ax.collections))]       
for t,j1 in enumerate(ax.collections):
    j1.set_color(colorst[t])


ax.legend(fontsize='small')

The output gives you differnent colors even when you have many different scatter plots in the same subplot.

enter image description here

"Could not find bundler" error

The command is bundle update (there is no "r" in the "bundle").

To check if bundler is installed do : gem list bundler or even which bundle and the command will list either the bundler version or the path to it. If nothing is shown, then install bundler by typing gem install bundler.

How to install maven on redhat linux

I made the following script:

#!/bin/bash

# Target installation location
MAVEN_HOME="/your/path/here"

# Link to binary tar.gz archive
# See https://maven.apache.org/download.cgi?html_a_name#Files
MAVEN_BINARY_TAR_GZ_ARCHIVE="http://www.trieuvan.com/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz"

# Configuration parameters used to start up the JVM running Maven, i.e. "-Xms256m -Xmx512m"
# See https://maven.apache.org/configure.html
MAVEN_OPTS="" # Optional (not needed)

if [[ ! -d $MAVEN_HOME ]]; then
  # Create nonexistent subdirectories recursively
  mkdir -p $MAVEN_HOME

  # Curl location of tar.gz archive & extract without first directory
  curl -L $MAVEN_BINARY_TAR_GZ_ARCHIVE | tar -xzf - -C $MAVEN_HOME --strip 1

  # Creating a symbolic/soft link to Maven in the primary directory of executable commands on the system
  ln -s $MAVEN_HOME/bin/mvn /usr/bin/mvn

  # Permanently set environmental variable (if not null)
  if [[ -n $MAVEN_OPTS ]]; then
    echo "export MAVEN_OPTS=$MAVEN_OPTS" >> ~/.bashrc
  fi

  # Using MAVEN_HOME, MVN_HOME, or M2 as your env var is irrelevant, what counts
  # is your $PATH environment.
  # See http://stackoverflow.com/questions/26609922/maven-home-mvn-home-or-m2-home
  echo "export PATH=$MAVEN_HOME/bin:$PATH" >> ~/.bashrc
else
  # Do nothing if target installation directory already exists
  echo "'$MAVEN_HOME' already exists, please uninstall existing maven first."
fi

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

Your module and your class AthleteList have the same name. The line

import AthleteList

imports the module and creates a name AthleteList in your current scope that points to the module object. If you want to access the actual class, use

AthleteList.AthleteList

In particular, in the line

return(AthleteList(templ.pop(0), templ.pop(0), templ))

you are actually accessing the module object and not the class. Try

return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))

Change navbar text color Bootstrap

For changing the text color in navbar you can use inline css as;

<a style="color: #3c6afc" href="#">

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

Compress images on client side before uploading

I'm late to the party, but this solution worked for me quite well. Based on this library, you can use a function lik this - setting the image, quality, max-width, and output format (jepg,png):

function compress(source_img_obj, quality, maxWidth, output_format){
    var mime_type = "image/jpeg";
    if(typeof output_format !== "undefined" && output_format=="png"){
        mime_type = "image/png";
    }

    maxWidth = maxWidth || 1000;
    var natW = source_img_obj.naturalWidth;
    var natH = source_img_obj.naturalHeight;
    var ratio = natH / natW;
    if (natW > maxWidth) {
        natW = maxWidth;
        natH = ratio * maxWidth;
    }

    var cvs = document.createElement('canvas');
    cvs.width = natW;
    cvs.height = natH;

    var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0, natW, natH);
    var newImageData = cvs.toDataURL(mime_type, quality/100);
    var result_image_obj = new Image();
    result_image_obj.src = newImageData;
    return result_image_obj;
}