text:
Q: Remove end-ticks from D3.js axis I'm using (the excellent) D3.js to generate some plots, and I can't find a way to remove the end ticks from the x and y axis.
Take the y-axis for example.
When the end tick value coincides with a label, I'm ok with having it.
But when the last round label is below the end of the plot, I get two ticks, one for the last rounded label and one above it at the end of the y-axis.
I don't want this end-tick visible, because I find the fact that it appears in less than the regular interval between labels distracting.
See here for an example of what I'm describing, the ticks at 0 and 15 are the end ticks:
15 ─┐
    |
10 _|
    |
5  _|
    |
0  ─┤──────

Any tips?
P.S As a response suggested, I could set the ticks explicitly. But I like the convenience of the implicit generated ticks, just don't want unlabelled ticks to pollute the axis. So an ideal solution (if exists) would also take than into account.

A: If you want to just hide the bounding values and keep the implicit behavior in the middle, you can modify the axis SVG object just after you draw it
Say, here you draw/update your axis:
g.selectAll(".x.axis").call(xAxis);

Now g will contain .tick classed objects. each of them will refer to one tick value. You can select them and set visibility attribute:
d3.select(g.selectAll(".tick")[0][0]).attr("visibility","hidden");

Alternatively, you can address any specific tick by its value d or index i
g.selectAll(".tick")
    .each(function (d, i) {
        if ( d == 0 ) {
            this.remove();
        }
    });

Be careful with .remove() though. Sometimes the first value is removed already and it removes the second value on update. Visibility hidden is more reliable.
credit to Ian & Denis at d3-js google group https://groups.google.com/forum/#!topic/d3-js/LBxR_finiME

A: Remove end ticks using something like this: note tickSize(inner, outer)
var xAxis = d3.svg.axis().scale(x).
                tickSize(3, 0).orient("bottom").tickFormat( ... );

If you put outer param to 0 in tickSize(inner, outer) you will not get the outer ticks.

A: The axis.tick* functions can help you there. You have a number of possibilities to prevent the behaviour you're describing. You could set the ticks explicitly using the tickValues() function. Or you could set the size of the end ticks to 0 using tickSize(). You can also control the underlying scale using the ticks() function.
Depending on your particular scenario, one of these options may make more sense than the others.

A: For anyone who got to this question because all you want to do is remove the two end ticks from an axis, this will do the trick:
.outerTickSize(0)

Add that to any axis call you make, such as:
d3.svg.axis().outerTickSize(0)

A: In d3.js v4.x use .tickSizeOuter(0), like:
self._leftAxis = d3.axisLeft(self._y)
      .tickSizeInner(3) // the inner ticks will be of size 3
      .tickSizeOuter(0); // the outer ones of 0 size

Note that the zero tick below is considered a inner on

This d3.js v4 doc: https://github.com/d3/d3-axis

A: I'not sure, what the outer tick size has to do with the first or last tick of an axis.

tickSize actually controls the length of the <line> element inside of the tick group. Therefore it deals with the distance between the <text> element of the tick and the axis or the length of helper lines starting at the tick positions, which depends on the orientation of the axis and where it has been moved to (via css translate()).
This is how a tick group looks like:
<g transform="translate(10,0)" style="opacity: 1;" class="tick">
   <line x2="0" y2="-15"></line>
   <text x="0" y="-18" style="text-anchor: middle;" dy="0em">0.0</text>
</g>

Now you can control the x2 and the y2 attribute of the <line> element with the tickSize method. Here I'm using tickSize(15, 0) and orientation('top') for the x axis, which has been moved to the bottom of the chart. So the lables of the ticks project into the chart in a quite messy way.

A: Working solution for D3 v5.9.2:

*

*After you declared yAxis and set the attributes, wrap it in a g and call it:
 svg.append("g").attr("id", "yAxisG").call(yAxis);

*Remove the first <path> element from the axis group:
 d3.select("g#yAxisG").select("path").remove();

A: Just remove both axis:
d3.selectAll('.axis').remove();

A: This will remove the whole axis. This does not answer the question posted.


text:
Q: libvirt: "Failed to initialize a valid firewall backend" I'm trying to set up a virtual NAT network device without DHCP for libvirt on an Arch Linux host.
What I have tried:
# virsh net-define network.xml
Network default defined from network.xml

[network.xml]:
<network>
  <name>default</name>
  <bridge name="maas0" />
  <forward mode="nat" />
  <ip address="10.137.0.1" netmask="255.255.255.0" />
</network>

My laptop outputs the following on start-up:
# virsh net-start default
error: Failed to start network default
error: internal error: Failed to initialize a valid firewall backend

All other threads concerning this topic are talking about upgrading software -- I'm using the most current versions:
$ pacman -Q ebtables dnsmasq libvirt iptables
ebtables 2.0.10_4-5
dnsmasq 2.75-1
libvirt 1.3.3-1
iptables 1.4.21-3

What could be the reason for that internal error and what can I do against?

A: Installing ebtables and dnsmasq seems to fix the problem. Don't forget to restart the libvirtd service.
The commands:
sudo pacman -Syu ebtables dnsmasq
sudo systemctl restart libvirtd

NOTE: do not forget to close and re-open your virt-manager GUI (if you're using one).
EDIT: The original answer suggested also installing firewalld. This doesn't seem to be necessary for many users, and may add an additional unwanted firewall to your system. However if you want to try it, you can add the following commands as well:
sudo pacman -Syu firewalld
sudo systemctl start firewalld
sudo systemctl enable firewalld
sudo systemctl restart libvirtd

A: This is the error that comes up if libvirtd was started without ebtables and/or dnsmasq installed. If you've got them installed and you're still having this issue, you probably need to restart the libvirtd service:
sudo systemctl restart libvirtd.service

Credit to the comments on the other answer to this question for illuminating this. I'm submitting it as a new and separate answer to the original question because installing and starting firewalld to solve the original problem is liable to cause new problems: once the firewall daemon is running, most of the services you'll want within your virtual machine, including DHCP, will be blocked by default, meaning that your VMs will not be able to reach the network on initialization.
I lost over an hour of my life trying to track down this problem, and tracing it to a firewall I had just enabled was one of the dumbest sources of a bug that I've ever run into. Don't let it take any time from yours.

A: As I am not able yet to add an additional comment to the most upvoted answer, I had to add this solution as a new answer instead.
In some cases, users might not want to replace iptables with iptables-nft as it might break existing rules.
The legacy iptables package contains ebtables-nft which is a symlink to xtables-nft-multi.
You can check this using file:
$ file $(which ebtables-nft)
/usr/bin/iptables: symbolic link to xtables-nft-multi

A simple solution is to create the missing symlinks so libvirt/virt-manager can find it without touching existing packages on your system.
$ ln -s /usr/bin/xtables-nft-multi /usr/bin/ebtables
$ ln -s /usr/bin/xtables-nft-multi /usr/bin/ebtables-save
$ ln -s /usr/bin/xtables-nft-multi /usr/bin/ebtables-restore

Restart the libvirt daemons/sockets (whatever you use) afterwards and the networks should start without the firewall backend error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex to extract key, value by brackets #2 I want to get key and value from text in a [key] value format:

*

*key is not fixed, but it will be in brakets [ ] .

*[key](there can be blank)value format

*value can not have '[', ']'

*value can have new line(\n).

*value can be null.

*last value can be only one line. (ignore 2 or more lines)

For example,
[AA] abcd 1234 !@#$ _+{}[]:"
blah blah
[abc-def] this is also value.
[BB]abcd defg
[CC]

blah blah
blah blah

In this case, I want to get below pairs.
'AA' : 'abcd 1234 !@#$ _+{}:"
    blah blah'
'abc-def' : 'this is also value.'
'BB' : 'abcd defg'
'CC' : ''
and my Python code is this:
import re

text ='''
[AA] abcd 1234 !@#$ _+{}:"
blah blah
[abc-def] this is also value.
[BB]abcd defg
[CC]

blah blah
blah blah
'''
pattern = re.compile(this is what I want)
result = {m.group('field'):m.group('value') for m in pattern.finditer(text)}

Is this possible?

A: I don't think you need regex for this.
with open('input_file.txt', 'r') as f:
    lines = f.readlines()

storage = {}
for line in lines:
    split = line.split(']')
    key = split[0][1:]
    value = split[1:]
    storage[key] = value

What we're doing here is taking each line and splitting it on the first ']' that occurs. The 0th element of that split will be '[key', so we take the 0th element, from the 1st position in that element to the end, resulting in 'key'. Then the value is just the rest of the split.


text:
Q: I2C write to Amis 30624 motor from Atsame54p20a in Atmel Studio I have been trying to write to the amis 30624 stepper motor                      (http://www.onsemi.com/pub/Collateral/AMIS-30624-D.PDF) using I2C protocol but for some reason its giving me Receive not acknowledge error. I have followed all the steps of I2C protocol mentioned in the asf4 documentation(http://ww1.microchip.com/downloads/en/DeviceDoc/50002633A.pdf) but in vain. Can someone please help me? Here is my I2c Write function:
void I2C_Write(uint8_t address_reg)
{
    gpio_set_pin_pull_mode(SDA,GPIO_PULL_OFF);
    struct io_descriptor *Asynch_master_io;
    i2c_m_async_get_io_descriptor(&Asynch_master, &Asynch_master_io);
    i2c_m_async_enable(&Asynch_master);
    i2c_m_async_register_callback(&Asynch_master, I2C_M_ASYNC_TX_COMPLETE,
                                  (FUNC_PTR)Asynch_master_tx_complete);
    i2c_m_async_set_slaveaddr(&Asynch_master, 0x60,I2C_M_SEVEN);
    uint8_t var = address_reg;
    Asynch_master_example_str[0] = var;
    io_write(Asynch_master_io, Asynch_master_example_str,1);
    i2c_m_async_send_stop(&Asynch_master);
}

The SDA and SCL have been pulled up in the initialization. SERCOM3 is used. SDA is pulled down in I2C start.

A: Update:
Following the plan in my original answer below, will lead you to a solution. However I just realised something which can be inferred from a statement in your question, and which could suggest a potential problem more quickly:

The SDA and SCL have been pulled up in the initialization.

Based on that statement, I suspect you are using the built-in pull-up resistors in the ATSAME54 MCU, since external pull-ups would not be initialised in code.
The current SAM E5x family datasheet states that the internal pull-ups will be between 20kΩ and 60kΩ, typically 40kΩ. From experience, that value range is too high for reliable I2C bus operation, except for the slowest, shortest buses.
Checking the I2C signal waveforms with an oscilloscope, as mentioned in my full answer, would allow you to check whether or not you have an issue in this area. However I would be surprised if using the internal pull-ups is not at least part of your problem(s).
If you don't have an oscilloscope, you could re-test after calculating and adding suitable external pull-up resistors to the I2C signals. However, there might be multiple problems e.g. you might fix one problem (replacing the use of internal pull-up resistors, with suitable external pull-up resistors) and still not be successful. In that case, you cannot assume that the original use of internal pull-up resistors wasn't a problem.

Original answer:
I haven't used that ASF4 software API / framework, but I'll tell you how I would approach this, if I was in your situation.
You need to see what is really happening on the I2C bus, to understand exactly what your I2C master code is sending and what (if anything) the I2C Slave is doing. Although you are getting a return code, many times I've seen return codes which don't accurately specify the problem, and they can be better viewed as saying simply "something went wrong".
If you are not 100% confident of the electrical validity of the I2C bus, then use an oscilloscope to view the analog signal characteristics e.g. voltage levels, rise/fall times, crosstalk between the signals etc.
After you are confident that the I2C bus is electrically OK, then you can use a logic analyser or equivalent (e.g. MSO), or even a standard oscilloscope again, to view and decode the I2C protocol to better understand what is happening at that level. (Cheap logic analysers capable of I2C decoding, although they have limitations, can be bought for only a few dollars and can be used with open-source Sigrok software.)
Compare the activity which you see on the I2C bus with what should happen, as shown in the I2C specification and in the documentation for that specific I2C Slave (some behaviour can vary between different I2C Slaves and is not fixed in the I2C specification alone).
That way, you can find where the I2C bus first deviates from expected behaviour, and you can focus on the h/w or s/w responsible for that specific part.


text:
Q: Vue.js: load js file based on environment I have some js file which is generated by aws cognito, and its content is different based on environment.
As I should not modify it manually, so vue's environment variables may not work for me.
How should I dynamically load the js file based on the environment?
I use following command to run my server on local

vue-cli-service serve --mode=dev

I located the file under /environment/dev/aws-exports.js
const awsmobile = {
    "aws_project_region": "ap-northeast-1",
    ... some more json...
};
export default awsmobile;

and load in the main.js
import config from "./environment/dev/aws-exports"
Amplify.configure(config);

How should I modify my code so that it can load it based on --mode?

A: I am not sure if this is exactly what you are looking for but I'll try to help:
To dynamically load the js file based on the environment you can create a function that returns an import:
function getConfig(mode) {
  return import(`./environment/${mode}/aws-exports`)  // import returns a Promise
}

Note: remember that import is a Promise so you might need to await it.


text:
Q: How to detect when user used Password AutoFill on a UITextField I've implemented all the app and server changes necessary to support Password Autofill on iOS 11, and it works well.  I'd like it to work a little better.
My username and password fields are UITextFields.  I would like to identify when a user has "autofilled" one of the two UITextFields, so I can progress to the next step.  Currently the user autofills an item, then needs to press the "Next" button on the on-screen keyboard in order to advance.  I'd like to trigger this on behalf of the user.
The WWDC2017 Password Autofill session says to use UITextFieldTextDidChange.  This works, but of course this is also triggered when a user is manually typing in those fields.
My thought has been to compare the prior version of the text with the new version of the text, and assume that if the length has increased from zero to greater than some minimal length (2 or more), the user used autofill.  That should work most of the time, but has a risk of a false trigger (fast typing on slow device perhaps).  So to me, this may be a risky assumption.
I'm curious is anyone has found a more surefire way to determine if Password Autofill has been used on a UITextField, or just thinks my worry about a false trigger is unfounded.

A: Found a solution.
When the password manager is used to autofill username + password, it will trigger didBeginEditing twice, faster than a human ever could.
So, I calculate the time between the events.  If the time is extremely fast, then I assume that autofill (e.g. FaceID or TouchID) was used to enter credentials and auto-trigger whatever UI is next -- in my case, the User tapping "Sign-in".
Obviously, you have to set up the correct delegation of the UITextFields you want to monitor, but once you do that:
var biometricAutofillTime: Date!

func textFieldDidBeginEditing(_ textField: UITextField) {
    if biometricAutofillTime != nil {
        if Date().timeIntervalSince(biometricAutofillTime) < 0.1 {
            // NOTE: Need to hesitate for a very short amount of time,
            //        because, otherwise, the second UITextField (password)
            //        won't yet be populated
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { self.didTapSignin() }
        }
        biometricAutofillTime = nil
    }
    biometricAutofillTime = Date()
}

A: This detects when user has autofilled via passwords. It may also trigger when user pastes text from their clipboard. (If textfield is empty)
You can probably handle the logic to remove user pasted cases with this link..
how to know when text is pasted into UITextView
  private var didAutofillTextfield: Bool = false {
    didSet {
      if didAutofillTextfield {
        // Fire analytics for user autofilling
      }
    }
  }

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // If the range is {0,0} and the string count > 1, then user copy paste text or used password autofill.
    didAutofillTextfield = range == NSRange(location: 0, length: 0) && string.count > 1
    return true
  }

A: Not sure if the previous answer stopped working at some point, but I can't get it to work—I only get a single didBeginEditing call when AutoFill is used.
However, I did find a way to detect AutoFill. And keep in mind that it is possible for AutoFill to be used after some characters have already been entered, for example if the user has already typed some numbers in the phone number, then they AutoFill the full number.
For Swift 4/5, add the following to the delegate of the UITextField:
private var fieldPossibleAutofillReplacementAt: Date?

private var fieldPossibleAutofillReplacementRange: NSRange?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // To detect AutoFill, look for two quick replacements. The first replaces a range with a single space
    // (or blank string starting with iOS 13.4).
    // The next replaces the same range with the autofilled content.
    if string == " " || string == "" {
        self.fieldPossibleAutofillReplacementRange = range
        self.fieldPossibleAutofillReplacementAt = Date()
    } else {
        if fieldPossibleAutofillReplacementRange == range, let replacedAt = self.fieldPossibleAutofillReplacementAt, Date().timeIntervalSince(replacedAt) < 0.1 {
            DispatchQueue.main.async {
                // Whatever you use to move forward.
                self.moveForward()
            }
        }
        self.fieldPossibleAutofillReplacementRange = nil
        self.fieldPossibleAutofillReplacementAt = nil
    }

    return true
}

A: I used this delegate method:
func textFieldDidChangeSelection(_ textField: UITextField) {
    // call when user select something
}

from documentation:

Method
textFieldDidChangeSelection(_:)
Tells the delegate when the text selection changes in the specified text field.te

A: I don't think there is a better solution.
One thing I noticed is that autofill is only enabled when the text field is empty.
So if the text field went from empty to a length greater than the minimum password/username, then it is most likely autofill/paste.
I am using shouldChangeCharactersIn to detect the change in the UITextField. I'm not for sure if there is a case where text from the keyboard could be batched together before the delegate method is called.

A:
I'd like to trigger this on behalf of the user.

If this is your primary goal, I'm doing a little different approach here.
Upon showing the login form, I first check iCloud Keychain with SecRequestSharedWebCredential. If the closure returns a credentials, which means user's intent is to login with it, then I automatically login for him/her. Otherwise, make the login text filed becomeFirstResponder().
This approach does not support third-party password manager, but most people use iCloud Keychain I believe.

A: Swift 5:
The following delegate method gets triggered every time that the user types something in the textfield. That string count is usually one, so any number great than that is either autofill or the user pasting some text into the field. I am only using this delegate on this password field.
extension LoginView: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.count > 1 {
            DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { [weak self] in
                self?.endEditing(true)
            }
        }
        return true
    }
}

A: I found another simple way.. Hope it will help who is looking for it.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Usually string is coming as single character when user hit the keyboard ..
// but at AutoFill case it will come as whole string which recieved ..
// at this moment you can replace what you currently have by what you have recieved.
// In below case I'm expecting to recieve 4 digits as OTP code .. you can change it by what you are expecting to recieve.
    if string.count == 4 {
            doWhatEverYouByAutoFillString(text: string)
            return true
        }
    }
}


text:
Q: I cannot mount my windows10 partition from Ubuntu 16.04 I have a thinkpad X270 with a dual boot win10 / Ubuntu 16.04.
Here is the output of fdisk -l:
Disk /dev/loop0: 86,6 MiB, 90828800 bytes, 177400 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop1: 86,6 MiB, 90812416 bytes, 177368 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop2: 162,6 MiB, 170479616 bytes, 332968 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop3: 162,1 MiB, 169943040 bytes, 331920 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop4: 159,5 MiB, 167231488 bytes, 326624 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/loop5: 86,6 MiB, 90759168 bytes, 177264 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/nvme0n1: 477 GiB, 512110190592 bytes, 1000215216 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: DAC31813-E9D7-4C23-A2BF-993BFA742FA8

Device             Start        End   Sectors   Size Type
/dev/nvme0n1p1      2048     534527    532480   260M EFI System
/dev/nvme0n1p2    534528     567295     32768    16M Microsoft reserved
/dev/nvme0n1p3    567296  547606527 547039232 260,9G Microsoft basic data
/dev/nvme0n1p4 998166528 1000214527   2048000  1000M Windows recovery environmen
/dev/nvme0n1p5 547606528  965101567 417495040 199,1G Linux filesystem
/dev/nvme0n1p6 965101568  998166527  33064960  15,8G Linux swap

Partition table entries are not in disk order.

So I suspect that my windows partition is /dev/nvme0n1p3, correct?
Now, here is my problem, when I try to mount this partition with:
sudo mount /dev/nvme0n1p3 /media/myusername/windows

I get the following error message:
mount: wrong fs type, bad option, bad superblock on /dev/nvme0n1p3,
   missing codepage or helper program, or other error

   In some cases useful info is found in syslog - try
   dmesg | tail or so.

Do you have any idea what the problem might be? dmesg | tail does not seem to contain any useful hint.
EDIT
In addition, as asked by  @david-foerster, here is the output of sudo lsblk -f
NAME        FSTYPE  LABEL     UUID                                  MOUNTPOINT
loop1       squashf                                                /snap/spotify
loop4       squashf                                                /snap/spotify
loop2       squashf                                                /snap/core/44
loop0       squashf                                                /snap/core/45
nvme0n1
├─nvme0n1p5 ext4              b82c7e09-ca99-4d36-a414-e27dad39ee2a /
├─nvme0n1p3
├─nvme0n1p1 vfat    SYSTEM    E274-CF83                            /boot/efi
├─nvme0n1p6 swap              6fea09e6-54ab-49b5-a792-24c14a3fc1af [SWAP]
├─nvme0n1p4 ntfs    WinRE_DRV 3C3477E53477A116
└─nvme0n1p2
loop5       squashf                                                /snap/spotify
loop3       squashf                                                /snap/core/46

A: Try this:
sudo mount -t ntfs /dev/nvme0n1p3 /media/myusername/windows

System doesn't identify the filesystem type. So you have to enter that as ntfs.  If it fails to mount Windows partition as read/write mode you have to disable fast boot mode from Windows. You can follow this guide to disable it. If you need a gui way to mount and mount at startup see this question's first answer. If still doesn't work, your PBR (Primary Boot Sector) may have corrupted. Try to run chkdsk /f from windows and try to mount it again.
Edit: Your partition name doesn't look like sdaxx because youre machine may use SSD instead of HDD hard drive.

A: Yes /dev/nvme0n1p3 seems to be the main Windows partition
Disks named like this (nvme...) are connected to the pci-express bus. Your laptop seems to run with a pci ssd drive.
Nautilus (the Ubuntu file browser) should be able to mount the Windows drives.
(Ok, you have disabled the Windows fast Startup feature)
Did you try to run (with Win10) chkdsk against your Windows drives ?
I had encounter the same issue solved by this

A: Rather than having to remember the FS type you can use the auto parameter when mounting:
mount -t auto /dev/nvme0n1p3 /media/myusername/windows

Remember in order to mount you have to create the directory first, ie:
mkdir -p /media/myusername/windows

*

*The -p or --parents switch means:

no error if existing, make parent directories as needed

A: I've been having this problem as well. This solved it for me. Turns out it was because my Windows partition was BitLocker encrypted.
Use (Windows) BitLocker-encrypted drive on Ubuntu 14.04 LTS


text:
Q: Guava CacheBuilder prevent load for specific values I have the following java code to build a Guava cache:
myCache = CacheBuilder.newBuilder()
            .build(new CacheLoader<Result, String>() {
                       @Override
                       public Result load(String s) throws Exception {
                          Result result = getResult(s);

                          // if (result == Result.INVALID) return ???

                          return result;
                       }
                   }
            );

I would like to add some code whereby if the result is a specific value then nothing is loaded into the cache.
Not sure how to do it.
Any suggestions?
Many thanks!

A: Simple answer: just throw an exception. See CacheLoader docs:
Returns:
  the value associated with key; must not be null
Throws:
  Exception - if unable to load the result

In your case it would be something like:
    myCache = CacheBuilder.newBuilder()
        .build(new CacheLoader<Result, String>() {
                   @Override
                   public Result load(String s) throws Exception {
                      Result result = getResult(s);
                      if (result == Result.INVALID) {
                          throw new InvalidResultException();
                      }
                      return result;
                   }
               }
        );

and you should use get(K) or getUnchecked(K) to handle the exception accordingly, see Guava wiki about caches.
Please note that in Caffeine, a Guava cache successor, you can return null from a CacheLoader#load(K) to indicate the value was not loaded:
Returns:
the value associated with key or null if not found
Throws:
Exception - or Error, in which case the mapping is unchanged

For more info, see Caffeine wiki about cache population.


text:
Q: How can I simulate my Metro app being terminated? VS2012's default C# "Metro style" project templates include code in App.xaml.cs (in the OnLaunched override) to restore the application state after a suspend-and-terminate. This code only runs when LaunchActivatedEventArgs.PreviousExecutionState is Terminated, i.e., "The app was terminated after being suspended."
How can I force my app to be suspended and terminated, so I can test this suspend/resume functionality in my app?
Things I've tried that don't work:

*

*If I use the "close app" gesture (drag from the top of the screen to the bottom), then the next run's PreviousExecutionState is ClosedByUser.

*If I kill the app -- either using Task Manager, or (if I was debugging) with the "stop" button on the VS toolbar -- then the next run's PreviousExecutionState is NotRunning. This is true even if Task Manager showed the app as "Suspended" before I ended task, so clearly it's more nuanced than the description of "terminated after being suspended".

*You'd think I could just switch away from my app, and then open lots of other Metro-style apps until my app eventually gets kicked out. But even if I open every single Metro-style app that ships with the Windows 8 Release Preview, that's apparently not enough memory pressure to make Windows terminate my app. (I assume Windows would be less likely to terminate an app that was being debugged, so I launched my app from the Start screen -- no debugger -- before I tried this.)

It does appear that, if I switch away from my app and type into a StackOverflow window for several minutes, that my app will eventually get terminated, so perhaps there's a time-based component to it. But if I have to wait five or ten minutes every time for my app to terminate, that's a pretty slow testing cycle.
Given that this is something developers will have to test, you'd think there would be a nice, easy way for a dev to force an app to suspend-and-terminate. Is there some kind of stress-test app that comes with Visual Studio that will force enough memory pressure? Is there some menu item in Visual Studio that will force termination of my app? How are we supposed to test this?

A: I had trouble finding the Suspend control because VS wasn't showing a second row of toolbars for me.  As it turns out, this is on the "Debug Location" toolbar.  Make sure you have this toolbar turned on and then you should be able to find the Suspend control (and it does work to solve the OP's problem).

A: If they don't show by default, go to TOOLS -> CUSTOMIZE, and under the Toolbars tab, check the box that says "Debug Location"

A: In Visual Studio 2012, when you're debugging, there are "Suspend", "Resume" and "Suspend and Shutdown" buttons.  By default, you should see the buttons while you are debugging your app. See this article for more info on debugging process lifecycle.

A: I was looking for VS 2013, just in case others came for the same reason.
Source:
http://blogs.msdn.com/b/visualstudio/archive/2012/08/23/new-visual-studio-2012-debugging-features-for-the-windows-8-app-lifecycle-model.aspx
a busy cat http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-29-92-metablogapi/2210.image_5F00_thumb_5F00_1FBA9C1E.png


text:
Q: Pendulum without friction: Are there any relative equilibria? Hopefully, my question is not too silly.
I am wondering if for the 2D-mathematical pendulum without friction, we do have any relative equilibrium: Of course, we have two equilibria (at $(0,0)$ and at $(\pi,0)$ in the $\theta-\dot{\theta}$-plane). But are there any relative equilibria?
(As far as I did understand the definition of a relative equilibrium, this is a (symmetry) group orbit which does not change under the dynamics. For the pendulum here, I would say that the symmetry group is the rotation around $2\pi$. Up to my understanding, the only group orbits which does not change then are the orbits
$$
\left\{(0+2\pi k,0): k\in\mathbb{Z}\right\}\subset\mathbb{R}^2\text{ and }\left\{(\pi+2\pi k,0): k\in\mathbb{Z}\right\}\subset\mathbb{R}^2
$$
in the $\theta$-$\dot{\theta}$-plane.
Hence I would claim that these are (the only) two relative equilibria.)


text:
Q: How do I return only the value as a string and not a collection? This eloquent collection provides this result:
$id = Model::where('s_id', $s_id)->pluck('l_id');

print_r($id)

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => 31242682774
        )

)

How do I return only the "31242682774" value as a string and not a collection?
EDIT ANSWER:
All I had to do is:
$id = Model::where('s_id', $s_id)->pluck('l_id')->first();

Any better options?

A: If you only need a single value, not multiple values, pluck isn't what you want. There is a method called value on Query Builder that returns a single value:
Model::where('s_id', $s_id)->value('l_id');

Laravel 6.x Docs - Query Builder - Retrieving Results - Retrieving A Single Row / Column From A Table value

A: It compares to when it the process you wanna do it. On the query execution or after. The most common approach would probably be.
$id = Model::where('s_id', $s_id)->first()->l_id;

This will execute after, meaning the query builder will fetch all columns in the row. In general in Laravel you don't that often work with strings and or other abstractions than your model. Model::where('s_id', $s_id)->first() will return your model and select the l_id property on it.
The approach you chosen is the database way, you only select the l_id and return it as a collection and select the first item from there. This is thou a very performance efficient way of doing it since the database does all the work and is very quick at it.
$id = Model::where('s_id', $s_id)->pluck('l_id')->first();

The reason why it is a collection, it is mainly made for selecting multiple id's, so if you query returned multiple rows multiple ids would be returned. Here you can see an example of pluck in conditional queries, where it is most often used.
$teamIds = Team::where('type', 'admin')->pluck('id');

$adminUsers = User::where('team_id', $teamIds)->get();

Your solution is perfect for what you need, just trying to bring clarity on why and a example of how it is often used.


text:
Q: Securing Azure PaaS (api apps) using NSG Trying to secure an API apps endpoint without Azure Active Directory. I have seen examples of NSG for securing SQL Server endpoints.
But with PaaS services (web apps / api apps/ logic apps) since they dont have VNETS I am bit confused as to how NSG will restrict traffic.
On Api app blade I see a "Networking" option and clicking that takes me into setting up VNET integration. When I click VNet setup starts gateway setup and configuration.
Has anyone done something similar where they secure backend api services using NSG and not API Gateway or AAD authentication.
Thanks !!

A: If you integrate the app service with a vnet, you can use NSGs to restrict the traffic, but only for the traffic connecting via the private network. vnet integration works with a vpn connection, hence the required deployment of a gateway on the vnet.
In this setup, the api app will still be accessible on the internet and that traffic will not be affected by the NSG, since it does not touch the vnet.
If you want to secure incoming traffic based on network origin you could implement that in application, but I would recommend against relying solely on that for security.


text:
Q: dynamically highlight block with highlight.js in vue app I have a VueJS where I have created a component for rendering the contents from a WYSIWYG component (tiptap).
I have the following content being returned from the backend
let x = 0;

enum A {}
function Baa() {}

I'm using highlight.js to highlight this code snippet in the following manner:
import { defineComponent, h, nextTick, onMounted, onUpdated, ref, watch } from 'vue';
// No need to use a third-party component to highlight code
// since the `@tiptap/extension-code-block-lowlight` library has highlight as a dependency
import highlight from 'highlight.js'

export const WYSIWYG = defineComponent({
  name: 'WYSIWYG',
  props: {
    content: { type: String, required: true },
  },
  setup(props) {
    const root = ref<HTMLElement>(null);

    const highlightClass = 'hljs';

    const hightlightCodes = async () => {
      console.log(root.value?.querySelectorAll('pre code')[0]);

      setTimeout(() => {
        root.value?.querySelectorAll('pre code').forEach((el: HTMLElement) => {
          highlight.highlightElement(el as HTMLElement);
        });
      }, 2000);
    }

    onMounted(hightlightCodes);
    watch(() => props.content, hightlightCodes);

    return function render() {
      return h('div', {
        class: 'WYSIWYG',
        ref: root,
        innerHTML: props.content
      });
    };
  },
});

Now, when I visit the page by typing the URL in the browser, it highlights the typescript code

Whenever I visit a different page and click on my browser's "Go back" button, it makes the code completely vanishes

What I have tried
I can see that the line root.value?.querySelectorAll('pre code') is returning the correct items and the correct code is present but the code vanishes after the 2 seconds passes - due to setTimeout.
How can I make highlight.js highlight the code parts whenever props.content changes?

A: Option 1
Use Highlight.js Vue integration (you need to setup the plugin first, check the link):
<script setup>
const props = defineProps({
  content: { type: String, required: true },
})
</script>

<template>
  <highlightjs :code="content" language="ts" />
</template>

Option 2

*

*Use computed to reactively compute highlighted HTML of props.content

*Use sync highlight(code, options) function to get the highlighted HTML

*Use HTML as-is via innerHTML prop or v-html directive

<script setup>
import { computed } from 'vue'
import highlight from 'highlight.js'

const props = defineProps({
  content: { type: String, required: true },
})

const html = computed(() => {
  const { value } = highlight.highlight(props.content, { lang: 'ts' })
  return value
})
</script>

<template>
  <div v-html="html" />
</template>


text:
Q: Overlaying two pandas Dataframes or numpy arrays and creating a key-value dictionary I have two CSV files of shape lets say 3x3.
File 1 looks like this:
-1, 2,-1
-1,-1, 3
-1, 8, 9

and File 2 like this:
-1, 56,-1
-1,-1,  73
-1, 24, 100

My aim is to overlay both arrays or DataFrames and create a dictionary of the following form:
dict = {2:56, 3:73, 8:24, 9:100}

I can create something loop-based but I am wondering if there is a way of masking or overlaying the arrays and creating the respective dictionary?

A: You can flatten the dataframes, drop the null values, and dict/zip them:
import pandas as pd

# Load the data, converting -1 to NaN
dfa = pd.read_csv('file1.csv', header=None, na_values=[-1])
dfb = pd.read_csv('file2.csv', header=None, na_values=[-1])

# Flatten the dataframes
a = dfa.values.flatten()
b = dfb.values.flatten()

# Remove null values and cast back to ints (if that matters)
# Note that both are filtered according to the key data
a = a[~np.isnan(a)].astype(int)
b = b[~np.isnan(a)].astype(int)

# Zip to pair the lists, then convert to a dict
d = dict(zip(a, b))


text:
Q: Run Intel Fortran binary with Python I am trying run a Fortran binary from within a Python script on a Mac. From the command line the Fortran binary works fine but when I run it with os.system or subprocess.open in Python then I get the following error:
dyld: Library not loaded: libimf.dylib
Referenced from: /Path/To/Binary
Reason: image not found

The Fortran binary is build with Intel Fortran. Any idea what goes wrong here?
EDIT:
I have these environmental variables set in my ~/.bash_profile which does not help:
export LD_LIBRARY_PATH="/opt/intel/compilers_and_libraries_2016.0.083/mac/compiler/lib"
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/opt/intel/compilers_and_libraries_2016.1.111/mac/compiler/lib"
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/opt/intel/compilers_and_libraries/mac/lib"
export DYLD_LIBRARY_PATH="/opt/intel/compilers_and_libraries_2016.0.083/mac/compiler/lib"
export DYLD_LIBRARY_PATH="$LD_LIBRARY_PATH:/opt/intel/compilers_and_libraries_2016.1.111/mac/compiler/lib"
export DYLD_LIBRARY_PATH="$LD_LIBRARY_PATH:/opt/intel/compilers_and_libraries/mac/lib"

I am running the python script from the terminal on my Mac. I tried printing from Python with
print os.environ['LD_LIBRARY_PATH']
print os.environ['DYLD_LIBRARY_PATH']

which both give the following error:
KeyError: 'DYLD_LIBRARY_PATH'

EDIT:
I tried running another binary with os.system in my Python code and that works fine.

A: I expect the problem is because there is no 'DYLD_LIBRARY_PATH' key in Python's os.environ dictionary; your profile setting of DYLD_LIBRARY_PATH seems fine, but Python isn't receiving it.
On my yosemite system, if I source the Intel-supplied compilervars.csh script to set DYLD_LIBRARY_PATH (resulting in a value of /opt/intel/compilers_and_libraries_2016.1.111/mac/compiler/lib:...) then the following succeeds for me
$ cat test.f90 && ifort test.f90 && python -c "import os; os.system('./a.out');"
print *, 'Hello World!'
end
 Hello World!

(From bash you would presumably utilize the compilervars.sh script instead to do this.)

A: The problem is likely the new System Integrity Protection (SIP) built into Mac El Capitan. Basically, when you run a protected process, such as a python script, DYLD_LIBRARY_PATH is not passed to the script.
The best solution is recompiling your Fortran binaries in a manner that avoids the use of dynamic libraries. Alternatively, you can prevent this problem by disabling SIP (probably not recommended) as described here:
Macworld Article
You can find more information about this issue by searching "DYLD_LIBRARY_PATH SIP"


text:
Q: Minimum Websocket Nodejs Tail Example I'm trying to create a stream of data to the browser using websocket. The data is the output of a log file. (tail -f filename)
Using node js, I've manage to log into stdout, but I haven't been able to create the server and create the client (js/html) code to create a websocket and receive all the output of this child process.
Can anyone help me?
NODE.JS SERVER OUTPUTTING TAIL TO STDOUT (as seen in http://snippets.dzone.com/posts/show/12067)
var sys = require('sys')
var spawn = require('child_process').spawn;
var filename = process.ARGV[2];

if (!filename)
  return sys.puts("Usage: node <server.js> <filename>");

var tail = spawn("tail", ["-f", filename]);
sys.puts("start tailing");

tail.stdout.on("data", function (data) {
  sys.puts(data);
});

My goal is to have the simplest stream possible. Any other simple solution is well received for this. Thanks.

A: This seems like an old question & very possibly the problem is already solved,
but in case it isn't here is a gist https://gist.github.com/867575 .
it uses socket.io
and instead of spawning "tail -f" processes(which takes more memory), fs.watchFile is used.

A: Here's a simple sample I mostly grabbed from this gist
First, switch into an empty directory
mkdir socket-tail-app; cd socket-tail-app;

Then, install what's needed
npm install socket.io

Run it like this
node server.js /path/to/file/to/tail

After it's running, open a browser at
http://localhost:8000

Here are the files you need:
server.js
var http    = require('http'),
    io      = require('socket.io'),
    fs      = require('fs');

var spawn = require('child_process').spawn;

var filename = process.argv[2];
if (!filename)
{
  console.log("Usage: node server.js filename_to_tail");
  return;
}

// -- Node.js Server ----------------------------------------------------------

server = http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/html'})
  fs.readFile(__dirname + '/index.html', function(err, data){
    res.write(data, 'utf8');
    res.end();
  });
})
server.listen(8000, '0.0.0.0');

// -- Setup Socket.IO ---------------------------------------------------------

var io = io.listen(server);

io.on('connection', function(client){
  console.log('Client connected');
  var tail = spawn("tail", ["-f", filename]);
  client.send( { filename : filename } );

  tail.stdout.on("data", function (data) {
    console.log(data.toString('utf-8'))
    client.send( { tail : data.toString('utf-8') } )
  });

});

console.log('Server running at http://0.0.0.0:8000/, connect with a browser to see tail output');

index.html
<!DOCTYPE html>

  <title>tail.js</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

A: This simple?
var sys = require('sys')
var spawn = require('child_process').spawn;
var filename = process.ARGV[2];
if (!filename)
  return sys.puts("Usage: node <server.js> <filename>");

var tail = spawn("tail", ["-f", filename]);

http = require('http');
http.createServer(function (req, res) {
  sys.puts("new connection..");
  res.writeHead(200, {'Content-Type': "text/plain;charset=UTF-8"});
  tail.stdout.on("data", function (data) {
    res.write(data);
  });
}).listen(3000);

Connect to the server and you'll get your tail. You'll have to watch for timeouts on the client side, depending on your browser, if the tail goes idle.
If you want to access this data from javascript within the browser, consider using socket.io as this will use the best method the browser has available to access the stream (websocket, long poll, flash etc.). If you need a client javascript example, I can post that too.


text:
Q: Uploading an Image using jQuery Ajax plugin not working in IE I'm using Malsup's jquery form plugin
I have this code.
$(document).ready(function() {
        jQuery("input[name=file]").change(function(e){
            if( browserType == "MSIE" ){
                jQuery("#start_campaign").ajaxForm({
                    target: '.imgPreview',
                    url: host+"/forms/campaign-image-upload.php?action=ajaxUploadImage",
                    beforeSend: function() {
                        console.log(2);
                    },
                    success: function(responseText,statusText,xhr,$form) {
                        alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
                        '\n\nThe output div should have already been updated with the responseText.');
                    }
                }).submit();
            } else {
                readURL(this);
            }
        });
    });

It's running on the beforeSend function but after that it has this kind of error:
SCRIPT3: Member not found.

jquery.form.js, line 349 character 5
LOG: [jquery.form] state = complete

This is line 349:

What's the problem with this code? I've been searching on the internet and found no answer.
Your help would be greatly appreciated and rewarded!
Thanks!

A: Same error is coming in my project also becuse i have trigger the a tag to file upload control.
If you have trigger the file upload control to other element like div or a etc if yes then please remove the trigger to file upload control and simple display file upload control in IE  then upload image it will work perfectly.
Please try this.
Sorry for my bad english

A: I answered this one by looking on this url: http://peroijanet.wordpress.com/2011/06/22/script3-member-not-found/
It seems the error is about having multiple submit buttons on your page with the same name="submit"
Make sure you only have one submit button <input type="submit" name="submit" value="Submit" />
Gosh this saved my Day! :D


text:
Q: How do I add a blur effect at the top and bottom edge of vertical scrollView in flutter I'm Trying to implement a vertical Scroll view with multiple items inside. Currently the scroll view works just fine but the edges seems to be very sharp and its cropping like this while scrolling,

instead I need to blur the top and bottom edge.
I'm looking for something similar to this answer https://stackoverflow.com/a/61151054/12890791, but this answer is for horizontal scroll.

A: Make the appBar transparent, set elevation to zero. In the scaffold, set extendBody and extend bodyBehind appBar to true


text:
Q: Why Android Studio uses Java classes instead of Kotlin I am new to kotlin. So I created a kotlin project in Android Studio and imported Fragment-ktx and Activity-ktx dependencies. So in a Fragment when I right click on the fragment and then Go To->Implementations it just opens the Fragment.java file. When using the Fragment-ktx dependency is this normal?
Any help would be great.
Here's my app.gradle file
android {
    compileSdkVersion 31
    defaultConfig {
        applicationId "com.xxxxxxx.xxxxxxxxxx"
        minSdk 23
        targetSdk 31
        versionCode 117
        versionName "3.2.11"
        vectorDrawables.generatedDensities = []
    }
    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/proguard/androidx-annotations.pro'
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        viewBinding true
    }
}

dependencies {
    implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
    implementation platform('com.google.firebase:firebase-bom:29.0.3')
    implementation 'com.google.firebase:firebase-analytics-ktx'
    implementation 'com.google.firebase:firebase-crashlytics-ktx'
    implementation 'com.google.firebase:firebase-messaging-ktx'
    implementation "androidx.core:core-ktx:1.7.0"
    implementation "androidx.activity:activity-ktx:1.4.0"
    implementation "androidx.fragment:fragment-ktx:1.4.0"
    implementation "androidx.collection:collection-ktx:1.2.0"
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
    implementation "androidx.preference:preference-ktx:1.1.1"
    implementation "androidx.biometric:biometric-ktx:1.2.0-alpha04"
    implementation 'androidx.work:work-runtime-ktx:2.7.1'
    implementation 'com.android.billingclient:billing:4.0.0'
    implementation 'com.android.volley:volley:1.2.1'
    implementation 'com.google.android.gms:play-services-ads:20.5.0'
    implementation 'com.google.android.play:core-ktx:1.8.1'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
    implementation 'com.github.lzyzsd:circleprogress:1.2.1'
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
    implementation 'com.nabinbhandari.android:permissions:3.8'
    implementation 'com.nex3z:toggle-button-group:1.2.3'
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
    implementation "io.github.iamthevoid.batteryview:batteryview:0.6.1"
}

A: There's nothing to be surprised about. Entire native SDK and most of jetpack libraries are pure java.
fragment-ktx just contains a bunch of extensions for fragment manager and viewmodels on top of inheriting androidx.fragment package.


text:
Q: How to get object of "ntSecurityDescriptor" of a active directory user I am working on a website. I have to find the value of user can't change password property of a user. I get this link
http://msdn.microsoft.com/en-us/library/aa746448(v=vs.85).aspx[^]
according to which I have to find "ntSecurityDescriptor" value of that user. They are using DirectoryEntry class to find that but in my case I am using LdapConnection class.
If I use entry class I was not able to make connectivity with server So that I change it to LdapConnection class. Now I don't know how to find value.

A: I find my solution.
 SearchResponse response = (SearchResponse)connection.SendRequest(request);
            DirectoryAttribute attribute = response.Entries[0].Attributes["ntSecurityDescriptor"];

            if (attribute != null)
            {
                const string PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}";
                const int ADS_ACETYPE_ACCESS_DENIED_OBJECT = 6;
                bool fEveryone = false;
                bool fSelf = false;

                ActiveDs.ADsSecurityUtility secUtility = new ActiveDs.ADsSecurityUtility();
                ActiveDs.IADsSecurityDescriptor sd = (IADsSecurityDescriptor)secUtility.ConvertSecurityDescriptor((byte[])attribute[0], (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_RAW, (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_IID);
                ActiveDs.IADsAccessControlList acl = (ActiveDs.IADsAccessControlList)sd.DiscretionaryAcl;

                foreach (ActiveDs.IADsAccessControlEntry ace in acl)
                {
                    if ((ace.ObjectType != null) && (ace.ObjectType.ToUpper() == PASSWORD_GUID.ToUpper()))
                    {
                        if ((ace.Trustee == "Everyone") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
                        {
                            fEveryone = true;
                        }
                        if ((ace.Trustee == @"NT AUTHORITY\SELF") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
                        {
                            fSelf = true;
                        }

                        break;
                    }
                }

                if (fEveryone || fSelf)
                {
                    return Global.RequestContants.CANT_CHANGE_PASSWORD;
                }
                else
                {
                    return string.Empty;
                }
            }


text:
Q: Why these variants of "egrep, fgrep, and rgrep" are deprecated? The description of grep, egrep, fgrep, rgrep, pgrep are shown as below:

DESCRIPTION
grep, egrep, fgrep, rgrep, pgrep - are commands in Unix-like operating
  systems that print lines matching a pattern. The grep searches the
  named input FILEs for lines containing a match to the given PATTERN.
  By default, it prints the matching lines.
In addition, the variant programs egrep, fgrep, and rgrep are the same
  as grep -E, grep -F, and grep -r, respectively. These variants are
  deprecated, but are provided for backward compatibility.

Why these variants of egrep, fgrep, and rgrep are deprecated?

A: It's answered in the Rationale for the POSIX description of grep:

This grep has been enhanced in an upwards-compatible way to provide the exact functionality of the historical egrep and fgrep commands as well. It was the clear intention of the standard developers to consolidate the three greps into a single command.
The old egrep and fgrep commands are likely to be supported for many years to come as implementation extensions, allowing historical applications to operate unmodified.
Historical implementations usually silently ignored all but one of multiply-specified -e and -f options, but were not consistent as to which specification was actually used.


text:
Q: Launching wkhtmltopdf from Runtime.getRuntime().exec(): never terminates? I'm launching wkhtmltopdf from within my Java app (part of a Tomcat server, running in debug mode within Eclipse Helios on Win7 64-bit):  I'd like to wait for it to complete, then Do More Stuff.
String cmd[] = {"wkhtmltopdf", htmlPathIn, pdfPathOut};
Process proc = Runtime.getRuntime().exec( cmd, null );

proc.waitFor();

But waitFor() never returns.  I can still see the process in the Windows Task Manager (with the command line I passed to exec(): looks fine).  AND IT WORKS.  wkhtmltopdf produces the PDF I'd expect, right where I'd expect it.  I can open it, rename it, whatever, even while the process is still running (before I manually terminate it).
From the command line, everything is fine:
c:\wrk>wkhtmltopdf C:\Temp\foo.html c:\wrk\foo.pdf
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
The process exits just fine, and life goes on.
So what is it about runtime.exec() that's causing wkhtmltopdf to never terminate?
I could grab proc.getInputStream() and look for "Done", but that's... vile.  I want something that is more general.
I've calling exec() with and without a working directory.  I've tried with and without an empty "env" array.  No joy.
Why is my process hanging, and what can I do to fix it?
PS: I've tried this with a couple other command line apps, and they both exhibit the same behavior.
Further exec woes.
I'm trying to read standard out & error, without success.  From the command line, I know there's supposed to be something remarkably like my command line experience, but when I read the input stream returned by proc.getInputStream(), I immediately get an EOL (-1, I'm using inputStream.read()).
I checked the JavaDoc for Process, and found this

The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the [b]subprocess to block, and even deadlock[/b].

Emphasis added.  So I tried that.  The first 'read()' on the Standard Out inputStream blocked until I killed the process...
WITH WKHTMLTOPDF
With the generic command line ap & no params so it should "dump usage and terminate", it sucks out the appropriate std::out, then terminates.
Interesting!
JVM version issue?  I'm using 1.6.0_23.  The latest is... v24.  I just checked the change log and don't see anything promising, but I'll try updating anyway.

Okay.  Don't let the Input Streams fill or they'll block.  Check.  .close() can also prevent this, but isn't terribly bright.
That works in general (including the generic command line apps I've tested).
In specific however, it falls down.  It appears that wkhtmltopdf is using some terminal manipulation/cursor stuff to do an ASCII-graphic progress bar.  I believe this is causing the inputStream to immediately return EOF rather than giving me the correct values.
Any ideas?  Hardly a deal-breaker, but it would definitely be Nice To Have.

A: A process has 3 streams: input, output and error. you can read both output and error stream at the same time using separate processes. see this question and its accepted answer and also this one for example.

A: You should read from the streams in a different thread.

A:     final Semaphore semaphore = new Semaphore(numOfThreads);
    final String whktmlExe = tmpwhktmlExePath;
    int doccount = 0;
    try{
        File fileObject = new File(inputDir);
        for(final File f : fileObject.listFiles()) {

            if(f.getAbsolutePath().endsWith(".html")) {
                doccount ++;
                if(doccount >500 ) {
                    LOG.info(" done with conversion of 1000 docs exiting ");
                    break;
                }
                System.out.println(" inside for before "+semaphore.availablePermits());
                semaphore.acquire();
                System.out.println(" inside for after "+semaphore.availablePermits() + " ---" +f.getName());
                new java.lang.Thread() {
                    public void run() {
                        try {
                            String F_ =  f.getName().replaceAll(".html", ".pdf") ;
                            ProcessBuilder pb = new ProcessBuilder(whktmlExe , f.getAbsolutePath(), outPutDir + F_ .replaceAll(" ", "_") );//"wkhtmltopdf.exe", htmlFilePath, pdfFilePath);
                            pb.redirectErrorStream(true);
                            Process process = pb.start();
                            BufferedReader errStreamReader = new BufferedReader(new  InputStreamReader(process.getInputStream()));
                            String line = errStreamReader.readLine();
                            while(line != null)
                            {
                                System.err.println(line); //or whatever else
                                line = errStreamReader.readLine();
                            }

                            System.out.println("after completion for ");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }finally {
                            System.out.println(" in finally releasing ");
                        semaphore.release();
                        }
                  }
                }.start();
            }
        }
    }catch (Exception ex) {
        LOG.error(" *** Error in pdf generation *** ", ex);
    }

    while (semaphore.availablePermits() < numOfThreads) {//till all threads finish
        LOG.info( " Waiting for all threads to exit "+ semaphore.availablePermits() + " --- " +( numOfThreads - semaphore.availablePermits()));
        java.lang.Thread.sleep(10000);
    }

A: I had the same exact issue as you and I solved it. Here are my findings:
For some reason, the output from wkhtmltopdf goes to STDERR of the process and NOT STDOUT. I have verified this by calling wkhtmltopdf from Java as well as perl
So, for example in java, you would have to do:
//ProcessBuilder is the recommended way of creating processes since Java 1.5
//Runtime.getRuntime().exec() is deprecated. Do not use.
ProcessBuilder pb = new ProcessBuilder("wkhtmltopdf.exe", htmlFilePath, pdfFilePath);
Process process = pb.start();

BufferedReader errStreamReader = new BufferedReader(new  InputStreamReader(process.getErrorStream()));
//not "process.getInputStream()"
String line = errStreamReader.readLine();
while(line != null)
{
    System.out.println(line); //or whatever else
    line = reader.readLine();
}

On a side note, if you spawn a process from java, you MUST read from the stdout and stderr streams (even if you do nothing with it) because otherwise the stream buffer will fill and the process will hang and never return.
To futureproof your code, just in case the devs of wkhtmltopdf decide to write to stdout, you can redirect stderr of the child process to stdout and read only one stream like this:
ProcessBuilder pb = new ProcessBuilder("wkhtmltopdf.exe", htmlFilePath, pdfFilePath);
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader inStreamReader = new BufferedReader(new  InputStreamReader(process.getInputStream()));

Actually, I do this in all the cases where I have to spawn an external process from java. That way I don't have to read two streams.
You should also read the streams of the spawned process in different threads if you dont want your main thread to block, since reading from streams is blocking.
Hope this helps.
UPDATE: I raised this issue in the project page and was replied that this is by design because wkhtmltopdf supports giving the actual pdf output in STDOUT. Please see the link for more details and java code.


text:
Q: How to get all the values from a JSON array I'm trying to get all the keys from a JSON array.
The link of the JSON is: this one
And the code I'm using is:
Imports System.Net.Http
Imports System.Text.Json.Nodes
Public Class Form1
    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Using http = New HttpClient
            Dim url = "https://api-cloud.bitmart.com/account/v1/currencies"
            Dim json = JsonNode.Parse(Await http.GetStreamAsync(url))
            Dim naming As [String] = json("currency")

            RichTextBox1.Text = json("currency")
        End Using
    End Sub
End Class

But clicking the Button doesn't populate anything. The RichTextBox stays empty,
while I want to get all the values ( es : "DFC, "$GM", "BBK" ecc)
I'm using .net6 but a framework.net solution would be appreciated.
Thanks

A: .Net Core answer
Take a look at my suggestion below. I can see that you are missing several steps in parsing the Json data as well as not getting the result of the GetStreamAsync operation.
Dim streamData As Stream = Nothing
Using http As HttpClient = New HttpClient
    Dim url As String = "https://api-cloud.bitmart.com/account/v1/currencies"

    Dim t As Task(Of Stream) = http.GetStreamAsync(url)
    streamData = t.Result
End Using

Dim jsonResponse As JsonNode = JsonNode.Parse(streamData)
Dim jsonData As JsonNode = jsonResponse("data")
Dim jsonCurrencies As JsonNode = jsonData("currencies")

Dim c As String = String.Empty
Dim n As String = String.Empty
For Each jsonCurrency As JsonNode In jsonCurrencies.AsArray()
    c += jsonCurrency("currency").ToString + " "
    n += jsonCurrency("network").ToString + " "
Next

Debug.WriteLine(c)
Debug.WriteLine(n)

This will output all of the currencies downloaded from: https://api-cloud.bitmart.com/account/v1/currencies
My test program doesn't work well with Async/Await operations so I removed the call to Await. I believe you can put it back in without issue.
This is a .Net Core answer, I believe for .Net Framework you will need to use a different Json parser, such as Newtonsoft.
.Net Framework 4.8 answer
This version makes use of Newtonsoft Json parser and is slightly different to the .Net Core version as it make use of Async/Await
Private Async Sub DownloadData()
    Dim jsonString As String
    Using http As HttpClient = New HttpClient
        Dim url As String = "https://api-cloud.bitmart.com/account/v1/currencies"

        Dim streamData As Stream = Await http.GetStreamAsync(url)

        Using sr As StreamReader = New StreamReader(streamData)
            jsonString = sr.ReadToEnd
        End Using
        streamData.Close()
    End Using

    Dim jsonResponse As JObject = JObject.Parse(jsonString)
    Dim jsonData As JObject = CType(jsonResponse("data"), JObject)
    Dim jsonCurrencies As JArray = CType(jsonData("currencies"), JArray)

    Dim c As String = String.Empty
    Dim n As String = String.Empty
    For Each jsonCurrency As JObject In jsonCurrencies
        c += jsonCurrency("currency").ToString + " "
        n += jsonCurrency("network").ToString + " "
    Next

    Debug.WriteLine(c)
    Debug.WriteLine(n)
End Sub


text:
Q: Django date format issue views.py
def calender(request):

    """"""
    settingsform = SettingsForm(instance=settings)
    if request.method == 'POST':
        reportform = ReportDateTimeForm(request.POST, instance=report)
        if reportform.is_valid():
            report = reportform.save(commit=False)
            report.user = request.user
            report.save()
    if settings and settings.date_format:
        date_format = reportform.fields['manual_date'].input_formats[1]
        createddate = report.created_date_time.strftime('%b %d %Y')
    else:
        date_format = reportform.fields['manual_date'].input_formats[0]
        createddate = report.created_date_time.strftime('%d %b %Y')
    date = report.manual_date.strftime(date_format)
    """"""
    return render_to_response('calender.html',
                               {
                                'reportform': reportform,
                                'settings': settings,
                                'settingsform':settingsform
                                 },
                                 context_instance=RequestContext(request))

forms.py
DATE_FORMAT = (
    ('0', ' dd / mm / yyyy'),
    ('1', 'mm / dd / yyyy'),
)
DATE_INPUT_FORMAT = ['%d/%m/%Y','%m/%d/%Y']

class ReportDateTimeForm(forms.ModelForm):
    manual_date = forms.DateField(input_formats = DATE_INPUT_FORMAT,
                      widget=forms.DateInput(format = '%d/%m/%Y'))

class SettingsForm(forms.ModelForm):
    date_format = forms.ChoiceField(widget=forms.RadioSelect(), choices=DATE_FORMAT, initial='0')

 def __init__(self, *args, **kwargs):
    # Get the date_format if present in parameters
    date_format = None
    if 'date_format' in kwargs:
        date_format = kwargs.pop('date_format')
    # Dynamically set input date format
    super(ReportDateTimeForm, self).__init__(*args, **kwargs)
    if date_format:
        self.fields['manual_date'].input_formats = (date_format, )

The class SettingsForm is used to save two input formats into a table. It saves an int value "1" for the %m/%d/%Y format and "0" for the %d/%m/%Y format.
If the input format is %m/%d/%Y, then on form POST, the value of the date is somehow changed and saved into the database like this: if the given date is 07/06/2013 (June, 7th 2013), it is saved in the database as 06/07/2013 (July, 6th 2013). Thus, not saving the desired and correct date.
It does works fine if the selected format is %d/%m/%Y.

A: Try this,
def calender(request):

""""""
settingsform = SettingsForm(instance=settings)

if settings and settings.date_format:
    date_format = reportform.fields['manual_date'].input_formats[1]
    createddate = report.created_date_time.strftime('%b %d %Y')
else:
    date_format = reportform.fields['manual_date'].input_formats[0]
    createddate = report.created_date_time.strftime('%d %b %Y')
date = report.manual_date.strftime(date_format)
if request.method == 'POST':
    reportform = ReportDateTimeForm(request.POST, instance=report,date_format=date_format)
    if reportform.is_valid():
        report = reportform.save(commit=False)
        report.user = request.user
        report.save()
""""""
return render_to_response('calender.html',
                           {
                            'reportform': reportform,
                            'settings': settings,
                            'settingsform':settingsform
                             },
                             context_instance=RequestContext(request))

I had made some small changes in your code,I guess it will solve your issue.
Cheers

A: In SettingsForm.__init__ your date_format is just '1' or '0'. But you should get real format. Also you should get date_format from cleaned_data and not from init args:
class SettingsForm(forms.ModelForm):
    date_format = forms.ChoiceField(widget=forms.RadioSelect(), choices=DATE_FORMAT, initial='0')
    manual_date = forms.Date....

 def clean(self, *args, **kwargs):
    super(SettingsForm, self).clean(*args, **kwargs)
    cleaned_data = self.cleaned_data
    date_format = cleaned_data['date_format']
    for (num, candidate_format) in DATE_FORMAT:
        if num == date_format:
            actual_date_format = candidate_format
            break
    else:
        raise ...ValidationError('unsupported choice!')

    # self.cleaned_data['manual_date'] already contains value parsed by "default" date_formats. So we are using raw value instead of it:
    field = self.fields['manual_date']
    field.input_formats = (actual_date_format, )
    raw_value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix('manual_date'))
    value = field.clean(raw_value)
    cleaned_data['manual_date'] = value
    return cleaned_data


text:
Q: ng-Click not working in angularjs after clicking for the first time I have a code that should display a pop-up to the center of the div when you click on it. On clicking on it the first time it pops up the Hello div but on clicking on it the second time nothing happens. Please assist me! This is my complete code.
This is the index.html
<!DOCTYPE html>

  <link rel="stylesheet" href="style.css" />

      Cover

      Hello

This is the script.js
console.clear();

var app = angular.module('myApp', ['ngAnimate']);

app.controller('MyController', function ($scope) {
  $scope.show = false;
});

This is the style.css
div#cover {
  background-color: lightblue;
  width: 90px;
  height: 30px;
  position: absolute;
  bottom: 0px;
  z-index: 10;
}
.slide {
  background-color: white;
  width: 90px;
  height: 30px;
  position: absolute;
  bottom: 30px;
  z-index: 5;
  transition: 1s ease bottom !important;
  display: block !important;
}
.slide.ng-hide {
  bottom: 0;
}

A: Remove all ng-click in your all div tags. Just copy past my below ng-clickinstead of your ng-click.
try with using ternary operators.
ng-click="show = show == false ? true : false"
Working demo : Plunker

A: I will try something like this:

 $scope.changeShow = function (){
    $scope.var = ($scope.var === false) ? true : false;
  }

      Hello

<input type="button" ng-click="changeShow()">


text:
Q: Looping inside looping with php So what I wish to accomplish is:

Surfboards _ San...

Surfboards _ San...

Surfboards _ San...

Surfboards _ San...

Surfboards _ San...

Surfboards _ San...

I have a $griditems which is a array from the database.
I would like to show 6 .product-box'es with 6
's inside  that is from this $griditems
Normally I would just have done:

<?php
$count=1;
foreach($griditems as $item)
{
  if($count == 6) { break; }
?>

.....

<?php
 $count++;
}
?>

But this will not work in this case, since I would like to have 6 of these .product-box classes, and inside each .product-box should be these 6 items, which should continue from eachother and not repeating the same first 6 that exists in the $griditems array.
How can I do this?

A: You can use array_chunk to split the array into sub-arrays of a certain maximum length.
$chunks = array_chunk($griditems, 6);
foreach($chunks as $chunk) {
    echo "

";
    foreach($chunk as $item) echo "
".$item."
";
    echo "

";
}

Incidentally, it's not great practice to use an HTML element merely to house a single, other HTML element, so your DIV may be superflous.

A: You want to use the mod operator (%) to check for every sixth item, and then close the existing box and start a new one, something like this:
?>

.....

<?php
    if ($count % 6 == 0) { ?>

<?php }
...

A: I may have misunderstood your question, but I think this will help:
$count = 0;
echo "
"
foreach($griditems as $item) {
    if (++$count % 6 == 0) {
        echo "

";
    }
    echo "
....
";
}
echo "
";


text:
Q: Implement multiple inheritance in Javascript I have observed that through the use of "prototype" property in Javascript (and indirectly setting up the prototype chain), one can implement multi-level inheritance in JavaScript. But is it possible to implement multiple inheritance in Javascript by some way? Any simple examples would be great.

A: To implement simple inheritance you usually do
MyClass.prototype = new MySuperClass();

but you could also copy the content of another "class" :
MyClass.prototype = new MySuperClass();
var myOtherSuperClass = new MyOtherSuperClass();
for (var key in myOtherSuperClass) {
     MyClass.prototype[key] = myOtherSuperClass[key];
}

Of course you could use an utility like jQuery.extend to do that, or roll your own.
A limit is that instanceof won't detect MyOtherSuperClass.

A: Just to be clear, JS doesn't have multiple inheritance.
Each object can only have one prototype.
However, since EVERYTHING is mutable, it can support "mixins", which is what the extend methods are all about. They just copy the keys of one object to another. That's not actually inheritance, though. Usually, in that scheme, the resultant object will only have the one proto, which is Object.

A: It's possible to implement multiple inheritance in JavaScript, although very few libraries does it. The only example I know is Ring.js.
Of course it doesn't rely only on prototypes, so instanceof doesn't work. But the library provides a replacement for it so it's not a big deal.


text:
Q: Edge "security certificate is not secure" since bash installation Description
I am running Windows 10 Insider - Build 14316. I managed to reproduce the issue by reverting the update and try it again to see exactly when the problem occurs.
So, I activated Ubuntu On Windows, and just at the moment I launched the bash command inside an administrator prompt (i.e. the Linux Subsystem was effectively installed), Edge started to warn me about certificates problems.
The message is (see screenshot #1) :

There is a problem connecting securely to this website. The security
  certificate presented by this website is not secure.

*

*Only secured websites were concerned but not all ;

*Facebook was concerned for example, with "Continue to this website" displayed (which actually does nothing) ;

*This Microsoft page is ironically concerned, without "Continue to this website" showed ;

*Some downloads, i.e. the Firefox setup (on Edge!), will fail with the following message which seems related to my primary question (see screenshot #2) :

The signature of this program is corrupt or invalid.

However, other downloads will work as excepted.
Note that other browsers (Chrome, Firefox) will display all websites without any error.

What I've tried so far

*

*Set correct datetime in Windows (that was already the case). Please note that the time command on bash gives incorrect hour (2 hours late) ;

*In Internet Options (inetcpl.cpl), uncheck some options relatives to certificate, signature checking and cleared SSL State ;

*From Microsoft Catalog Update, I updated root certificates. It solved the problem with Facebook, but not with the Microsoft page linked above.

*Reset IE settings ;

*Remove Linux subsystem, lxrun /uninstall /full ;

*certutil -setreg chain\minRSAPubKeyBitLength 512 ;

*sfc /scannow, etc., just in case.

None of these attempts worked.

Screenshots
#1
#2
Any help would be greatly appreciated. I hope that I've been clear, don't hesitate to ask for additional information.


text:
Q: Exception disposing memoryMappedFile in linux I'm getting an exception calling dispose on a MemoryMappedFile but only in linux.  The code is .net core 2.1 When I run the code in windows it's working fine, it's just in linux that it breaks.
Input/output error
System.IO.MemoryMappedFiles
at System.IO.MemoryMappedFiles.MemoryMappedView.Flush(UIntPtr capacity)
at System.IO.MemoryMappedFiles.MemoryMappedViewAccessor.Flush()
at System.IO.MemoryMappedFiles.MemoryMappedViewAccessor.Dispose(Boolean disposing)

The code is doing nothing special in the dispose
if (disposing)
{
     if (MyMemoryMappedViewAccessor != null)
     {
         if (MyBytePointer != null)
             MyMemoryMappedViewAccessor.SafeMemoryMappedViewHandle.ReleasePointer();

         MyMemoryMappedViewAccessor.Dispose();
     }

     if (MyMemoryMappedFile != null)
         MyMemoryMappedFile .Dispose();
}

Anyone got any good ideas?


text:
Q: Remove item level permission for specific user using powershell I want to remove the permission for each item and then want to add my unique permission
I have tried the code for giving permission. But firstly, i want to remove it and then add new permission. My code is as below:
    $clientlist.Items | ForEach-Object{
                $clientlist.BreakRoleInheritance($True)
                $userNew = $webNew.EnsureUser($user)
                $roleDefinition = $webNew.RoleDefinitions[$PermissionLevel]
                $roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($userNew)
                $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
                $clientlist.RoleAssignments.Add($roleAssignment)
                $clientlist.Update()
                Write-Host "Successfully added $PermissionLevel permission to $UserNew in $clientlist list. " -foregroundcolor Green

}

Thanks.

A: To remove permissions for a given user:
    $clientlist.RoleAssignments.RemoveById($userOld.ID)

This will remove all permissions for a given user.  You can use the same method on folders or list items.

A: Change $clientlist.BreakRoleInheritance($True) to $clientlist.BreakRoleInheritance($false) as $true in the argument of BreakRoleInheritance specifies that permissions from the parent be copied over to child. If you don't want any permissions from parent to be passed over user $false


text:
Q: topological entropy is self mapping As I know, topological dynamical system (with discrete time) is a self mapping such that $f:X\rightarrow X$ for $X$ be any arbitrary topological space. But, can we consider mapping

*

*$f:N\rightarrow R$ (as $N$ is natural number and $R$ is real number)

or

*$f:[0,1]\rightarrow (0,1]$

as topological dynamical system with discrete time?

A: To answer your question, ask yourself: do the iterated compositions of $f$ with itself make sense? In other words, are these all defined:
$$f \circ f, \quad f \circ f \circ f, \quad f \circ f \circ f \circ f, \quad \ldots \quad \text{and, by induction,} \quad f^n = f^{n-1} \circ f
$$
For a function $f : A \to B$, this is possible if $B \subset A$, whereas if $B \not\subset A$ then it may be impossible.
So for question 2, since $(0,1] \subset [0,1]$ then yes, it is a dynamical system.
And for question 1, since $R \not\subset N$ then no, it need not be a dynamical system.


text:
Q: Index out of range GridViewRow The code skips on Header as expected and enters when it becomes DataRow.. then it breaks immediately on the below error every time.  Can someone please help?
Line 252:                Button _singleClickButton = (kButton)e.Row.Cells[0].Controls[0];
 protected void Grd_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.VerticalAlign = VerticalAlign.Top;
            MonthData month = Data[e.Row.RowIndex];

            **Button _singleClickButtonNew = (Button)e.Row.Cells[e.Row.RowIndex].Controls[0];**
             string _jsSingleNew = ClientScript.GetPostBackClientHyperlink(_singleClickButtonNew, "");

                 foreach (DayData day in month.DayDatas)
                 {
                     int index = month.DayDatas.IndexOf(day) + 1;

                     SortProjectsByStartDate(day.Projects);
                     foreach (ProjectInfo project in day.Projects)
                     {
                         Button button = new Button();
                         if (day.ContainsProjectStart(project))
                         {
                             button.BackColor = Color.FromName(project.Color);
                             button.Click += btnProjectStart_Click;
                             button.CommandArgument = project.Id.ToString();
                         }
                         else if (day.ContainsProjectEnd(project))
                         {
                             button.Click += btnProjectStart_Click;
                             button.BackColor = Color.FromName(project.Color);
                             button.ToolTip = project.Name;
                         }
                         else
                         {
                             button.BackColor = Color.FromName(project.Color);
                             button.Click += btnProjectStart_Click;
                             button.CommandArgument = project.Id.ToString();
                             button.ToolTip = project.Name;
                         }

                         SortProjectsByStartDate(day.Projects);
                         button.Width = 60;
                         button.Height = 15;
                         button.ToolTip = project.Name;
                         //e.Row.Cells[index].Controls.Add(button);

                         e.Row.Cells[index].ToolTip = project.Name;

                         if (e.Row.RowIndex != -1)
                         {
                             e.Row.Cells[index].Attributes["onmouseover"] = "showContents('" + e.Row.Cells[1].Text + " " + (index - 1) + "')";
                             e.Row.Cells[index].Attributes["onmouseout"] = "hideContents()";
                             //e.Row.Attributes["onmouseover"] = "showContents('"  + (e.Row.RowIndex + 1) + "')";
                         }

                         // Add the column index as the event argument parameter
                         string js = _jsSingleNew.Insert(_jsSingleNew.Length - 2, index.ToString());
                         // Add this javascript to the onclick Attribute of the cell
                         e.Row.Cells[index].Attributes["onclick"] = js;
                         // Add a cursor style to the cells
                         e.Row.Cells[index].Attributes["style"] += "cursor:pointer;cursor:hand;";
                     }

                 }
             }

MY grid:
 <asp:GridView ID="Grd" runat="server" ShowHeaderWhenEmpty="true" AutoGenerateColumns="False"  style="table-layout:fixed;" Width="1500px" Height="800px"
                        OnRowDataBound="Grd_RowDataBound"  OnRowCommand="Grd_RowCommand"
                        CssClass="grid" BorderColor="Black" BorderStyle="Solid">
                        <Columns>
                            <asp:BoundField DataField="MonthName" HeaderText="Month"/>
                            <asp:BoundField HeaderText="1" />
                            <asp:BoundField HeaderText="2" />
                            <asp:BoundField HeaderText="3" />
                            <asp:BoundField HeaderText="4" />
                            <asp:BoundField HeaderText="5" />
                            <asp:BoundField HeaderText="6" />
                            <asp:BoundField HeaderText="7" />
                            <asp:BoundField HeaderText="8" />
                            <asp:BoundField HeaderText="9" />
                            <asp:BoundField HeaderText="10" />
                            <asp:BoundField HeaderText="11" />
                            <asp:BoundField HeaderText="12" />
                            <asp:BoundField HeaderText="13" />
                            <asp:BoundField HeaderText="14" />
                            <asp:BoundField HeaderText="15" />
                            <asp:BoundField HeaderText="16" />
                            <asp:BoundField HeaderText="17" />
                            <asp:BoundField HeaderText="18" />
                            <asp:BoundField HeaderText="19" />
                            <asp:BoundField HeaderText="20" />
                            <asp:BoundField HeaderText="21" />
                            <asp:BoundField HeaderText="22" />
                            <asp:BoundField HeaderText="23" />
                            <asp:BoundField HeaderText="24" />
                            <asp:BoundField HeaderText="25" />
                            <asp:BoundField HeaderText="26" />
                            <asp:BoundField HeaderText="27" />
                            <asp:BoundField HeaderText="28" />
                            <asp:BoundField HeaderText="29" />
                            <asp:BoundField HeaderText="30" />
                            <asp:BoundField HeaderText="31" />
                        </Columns>
                    </asp:GridView>

A: There are issues in your code
Button _singleClickButtonNew = (Button)e.Row.Cells[e.Row.RowIndex].Controls[0];

*

*You are casting ButtonField to Button

*You are accessing cell based on RowIndex (e.Row.Cells[e.Row.RowIndex]). You only have few cells and this gives Index out of range exception as there may be more rows than cells. Use defined cell number to get a particular cell.

If you want to use Button, use it in TemplateField as below
<asp:TemplateField HeaderText="header">
    <ItemTemplate>
       <asp:Button id="btn" runat="server" Text="btn" OnClick="btn_Click"/>
    </ItemTemplate>
<asp:TemplateField>

This Button is easy to find using FindControl as below,
Button btn = (e.Row.FindControl("btn") as Button);
if(btn != null)
{
   //add button related code
}


text:
Q: The jvm crashed looks like it was caused by JIT I wrote a server application in Java 8 but occasionally crashes.
running it with
java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)

gdb $JAVA_HOME/bin/java core.53164
(gdb) bt
#0  0x00007f80df3aa493 in Monitor::wait(bool, long, bool) ()
   from /data/disk01/hh_process_prod_cube_mpp/jdk1.8.0_251/jre/lib/amd64/server/libjvm.so
#1  0x00007f80def60ed2 in CompileQueue::get() () from /data/disk01/hh_process_prod_cube_mpp/jdk1.8.0_251/jre/lib/amd64/server/libjvm.so
#2  0x00007f80def6977b in CompileBroker::compiler_thread_loop() ()
   from /data/disk01/hh_process_prod_cube_mpp/jdk1.8.0_251/jre/lib/amd64/server/libjvm.so
#3  0x00007f80df55d40b in JavaThread::thread_main_inner() ()
   from /data/disk01/hh_process_prod_cube_mpp/jdk1.8.0_251/jre/lib/amd64/server/libjvm.so
#4  0x00007f80df55d711 in JavaThread::run() () from /data/disk01/hh_process_prod_cube_mpp/jdk1.8.0_251/jre/lib/amd64/server/libjvm.so
#5  0x00007f80df3eb2e2 in java_start(Thread*) () from /data/disk01/hh_process_prod_cube_mpp/jdk1.8.0_251/jre/lib/amd64/server/libjvm.so
#6  0x00007f80e02bcdd5 in start_thread () from /lib64/libpthread.so.0
#7  0x00007f80dfbc9ead in clone () from /lib64/libc.so.6


text:
Q: How to obtain all fields of an object? Disclaimer: I'm doing my first steps in python that's why the question may sound a little silly.
How to list all variables which are stored in self?

A: You might want inspect.getmembers as it'll list members of objects even if those objects have __slots__ defined as those objects do not have a __dict__.
>>> import inspect
>>> class F:
...     def __init__(self):
...             self.x = 2
...
>>> inspect.getmembers(F())
[('__doc__', None), ('__init__', <bound method F.__init__ of <__main__.F instance at 0xb7527fec>>), ('__module__', '__main__'), ('x', 2)]
>>> class F:
...     __slots__ = ('x')
...     def __init__(self):
...             self.x = 2
...
>>> inspect.getmembers(F())
[('__doc__', None), ('__init__', <bound method F.__init__ of <__main__.F instance at 0xb72d3b0c>>), ('__module__', '__main__'), ('__slots__', 'x'), ('x', 2)]

A: Every python object has a special member called __dict__ which is a dictionary containing all the instance's member.
self.__dict__.keys() lists their names
self.__dict__['foo'] gives you access to the value of the member foo
BTW, basically, writing something like self.foo = 1 is equivalent (at the basic level of things) to writing self.__dict__['foo'] = 1 that works as well.

A: If you're a beginner, you're asking a simple question so here's a simple answer: You can see all contents of a class or object, not just the variables but also the methods and other content, with the command dir. It's great when you're poking around at the python prompt. Try
dir("hello")  # examine string object
dir(str)      # examine string class
import os
dir(os)       # Examine module

And yes, from inside a class you can use it to examine self, since self is just a class object. You can use dir, type and help on the contents of a class to get more detail about them:
    dir(os.stdout)


text:
Q: "ENOENT: no such file or directory, open" when attempting to save an image through multer's storage. Symbols are not the issue For some reason if I attempt to save an image through multer's storage, I get this error:
[Error: ENOENT: no such file or directory, open 'C:\MAMP\htdocs\Chat Backend\public\images\servers\1596819056816AFKay.jpg'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'open',
  path: 'C:\\MAMP\\htdocs\\Chat Backend\\public\\images\\servers\\1596819056816AFKay.jpg',
  storageErrors: []
}

My multer setup looks like this:
var multer = require('multer');

var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/images/servers')
    },
    filename: (req, file, cb) => {
        cb(null, Date.now() + file.originalname)
    }
})

var fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg') {
        cb(null, true)
    } else {
        cb(null, false)
    }
}

app.use(multer({ storage: storage, fileFilter: fileFilter }).single('image'));

If I were to not use storage and just stick to dest, it saves the image just fine.
app.use(multer({ dest: 'public/images/servers' }).single('image'));

I've checked a lot of similar questions but their problem is usually that the name of the image contains symbols which are not allowed, whereas that is not the case with me because I've tried the simplest names (just a string for example) and I still get the error. Why might this error be happening?

A: I was facing the same issue. I am on windows OS. This helped:
new Date().toISOString().replace(/:/g, '-') + file.originalname


text:
Q: By how much does the 50/50 Joker option increase the probability of getting the correct answer? I am trying to determine by exactly how much the probability of getting the correct answer increases if we chose the 50/50 Joker option in "Who wants to be a millionare?", as compared to taking an entirely blind guess at the question.
Put formally, I (the participant) have four options, and I have zero knowledge about the question or the options given. A blind guess has a 1/4th chance of getting it correct. What are my chances of getting it correct if two incorrect options are eliminated? Is it 1/2 or higher?
I came up with the following three disjoint subsets and probabilities of winning in each:

*

*I (a) chose the incorrect option and (b) it does not get wiped out in 50/50, then (c) I will switch with 100% probability of winning $=3/4\cdot1/3\cdot1$

*I (a) chose the incorrect option and (b) it does get wiped out in 50/50, then (c) I will chose the correct answer from the remaining two with 50% probability of winning $=3/4\cdot2/3\cdot1/2$

*I (a) chose the correct option and (b) it does not get wiped out in 50/50, then (c) I retain my answer with certainty of winning $=1/4\cdot1\cdot1$
Thus the probability of winning if you use 50/50 seems to be  $=1/4+1/4+1/4=3/4$ and not $1/2$ as earlier suggested.
However, if we try to calculate probability of losing using a similar approach, we land up in trouble. Take these disjoint subsets:

*

*I (a) chose the incorrect option and (b) it does not get wiped out in 50/50, then (c) I will not switch with 100% probability of losing $=3/4\cdot1/3\cdot1$

*I (a) chose the incorrect option and (b) it does get wiped out in 50/50, then (c) I will chose the incorrect answer from the remaining two with 50% probability of winning $=3/4\cdot2/3\cdot1/2$

*I (a) chose the correct option and (b) it does not get wiped out in 50/50, then (c) I switch my answer with certainty of losing $=1/4\cdot1\cdot1$
The sum of these is also $3/4$! Therefore, the probability of winning + probability of losing appears to be $3/4+3/4=1.5$ which certainly cannot be true since they are disjoint events for the given situation.
Where then have I gone wrong in my logic exactly?

Clarifications:

*

*Do you choose an option before the two are eliminated? - yes

*Can they eliminate the one you have chosen? - yes, this is the case 2 in both lists above

*How are the two that are eliminated chosen? - randomly and uniformly. There are three incorrect options. So, you can form $^3C_2 = 3$ groups of size two. Thus, each group has a probability of $1/3$ of getting wiped out.

A: You haven't included the probabilities for choosing whether to swap your answer in cases 1 or 3. Either you have already decided, and one will have probability 1 and the other 0. Or you toss a coin when given the choice (either physically or mentally, fair or unfair coin). You can even use probability $p$ for swapping and $(1-p)$ for not swapping, if you haven't decided how you will decide yet.
Once you include that, the numbers should add up.

A: If the options to be eliminated do not depend on your original choice the two remaining options are equally likely.  You might as well not have chosen before.  Now you have $\frac 12$ of getting the right one.

A: How do you know whether to switch or not?
In the first calculations you assuming that you can magically switch to or stay on the correct answer if your first choice was not eliminated. But how would you know whether your answer is correct, i.e. whether you were in case 1 or case 3?
In the second set of calculations you similarly assume that you can magically switch to or stay on the incorrect answer if your first choice was not eliminated.
In those two sets of calculations you follow two different (magical) strategies, so it is not surprising that their resulting probabilities do not add up to 1.
To get the correct answer, first you must determine what your strategy will be. If your answer is not eliminated, will you always switch? Or will you always stay? Or will you switch with a certain fixed probability, like 50/50? For each of those strategies you can calculate the probability of winning or losing. Your strategy cannot be based on knowledge of whether your first guess is correct, because you do not have such knowledge when playing the game.


text:
Q: Why my initial variable changes even it is a copy? I'm trying to find Palindrome so I copied the list to another variable but when I use reverse function, both variables gets reversed. why is this happening?
I can use a loop and append from reverse order one by one, but I really want to know why reverse function works this way.
arr = list(input())
ar = arr
ar.reverse()
print(arr, ar)
print("YES" if arr == ar else "NO"

I expect to find palindrome.

A: It's because arr.reverse() reverses the list in place (see also help(list.reverse)).
That is, you need to make a copy of the list and then reverse that:
arr = list(input())
ar = arr.copy()
ar.reverse()
print(arr, ar)
print("YES" if arr == ar else "NO")

(Notice how I changed ar = arr to ar = arr.copy())

You could have "diagnosed" this problem yourself using the id function, which returns an unique identifier for each object:
>>> arr = list("foo bar beep boop")
>>> id(arr)
4343238976
>>> ar = arr
>>> id(ar)
4343238976
>>> copied = arr.copy()
>>> id(copied)
4341383968

Notice how id(ar) and id(arr) return the same number (4343238976 in this case), meaning they point to the same object. Meanwhile id(copied) returns a different number, meaning it's a different object.


text:
Q: Php restricting the data insertion in mysql I have a list box with two times i.e 12:00 to 2:00 and 2:00 to 4:00.I want to do that when someone submit the form (example a meeting reservation form) the timing inserted into the databse should be booked only for three times.when someone tries to insert the same time for the fourth time,it should give us message like (already booked).
help me to do this in php, mysql.
thanks

A: There is no real question here, you should start the project and when you come up against a brick wall we can help you.
Here are some good resourcesL
Start by reading up on PHP - http://www.php.net
The mysql manual is also very helpful http://dev.mysql.com/doc/refman/5.1/en/manual-info.html