Q: What if I accidentally run command "chmod -R" on system directories (/, /etc, ...) I accidently ran
sudo chmod 755 -R /

instead of
sudo chmod 755 -R ./

I stopped it after few seconds, but now there is some problems such as
sudo: must be setuid root

How can I revert permissions back?

A: In short: you can't, reinstall your system.
I mean, Posix permissions are used and relied on heavily; there's a multitude of places in the filesystem where wrong permissions would break the OS (SUID flags) or even worse, make it exposed security-wise (/etc/ssh/ssh_host_rsa_key) while it appears to be working OK.
Hence, such a recovery is hard to do properly. Miss one thing — and you screw it up. You already screwed up your sudo chmod command (if that's your friend rather than you, she might as well learn some Linux lesson, too) — and that's a very simple of a command. Proper recovery would demand way more commands and way more vigilance. Even if you use someone's script.
So trust me, just reinstall. It's a safe bet and guaranteed to keep you out of trouble.

Finally, some tips relevant here.
First: reinstalls will be less painful if you setup your /home on a separate partition next time. Actually, they will be a breeze.
Second: consider doing crazy Linux science in a virtual machine like the VirtualBox, and do your snapshots.
Third: chmod -R . works. A dot by itself . is valid directory name. There's no real need to append that slash. You could've avoided the catastrophic risk of skipping the dot entrirely;
mere chmod: missing operand after ‘755’ VS a ruined system.

A: I would try to reinstall all packages with apt-get install --reinstall, possibly using the output of dpkg --get-selections | grep install to get a list of them.

A: Alright, I haven't tested this (so use at your own risk), but it still might work. I Will test this in a virtual machine when I get the chance to:
First, in a still working system, I did the following to get all file permissions in a list, skipping the /home/ directory:
sudo find / -not -path /home -printf "%m:%p\0" > /tmp/fileper.log

This will print the permissions and file name for each file or directory on the system, followed by a \0 character (this is needed later on to deal with weird file names such as those containing newlines).
Then, on a system where the file permissions have been compromised:
while IFS=: read -r -d '' perm file; do
    chmod "$perm" "$file"
done < /tmp/fileper.log

This will read each line of fileper.log, saving the permissions as$perm and the file name as $file and then will set the file (or directory's) permissions to whatever was listed in the fileper.log

A few things to note here:

*

*While outputting to the file: /tmp/fileper.log, you might be listing custom settings, and proc, etc.

*you might not be able to boot, or run commands,

What I would suggest is boot up a LiveCD with the Linux version you have on your disk, run the command, modify the path to where you have the local disk mounted, and run the second command!

I have tested that when booted from an Ubuntu CD/USB, I can choose not to format disk, meaning it will replace everything in the / directory, BUT skip the /home/ directory. Meaning your users will have the configuration of apps/DATA(Music,Video,Documents) still intact. And by replacing the system files, the chmod is set to there proper number.

A: You can try restoring permissions with apt-get.
If you can not run these commands with sudo you may need to boot to recovery mode and run them as root.
For booting to recovery mode see https://wiki.ubuntu.com/RecoveryMode.
From http://hyperlogos.org/page/Restoring-Permissions-Debian-System
Note: This was originally posted on the Ubuntu Forums but I can not find the original post.
Try, in order,
sudo apt-get --reinstall install `dpkg --get-selections | grep install | grep -v deinstall | cut -f1`

If that fails:
sudo apt-get --reinstall install `dpkg --get-selections | grep install | grep -v deinstall | cut -f1 | egrep -v '(package1|package2)'`

And finally, as a last resort,
sudo dpkg --get-selections | grep install | grep -v deinstall | cut -f1 | xargs apt-get --reinstall -y --force-yes install

Using apt-get
Here's the relevant snip, EDITED FOR CORRECTNESS and reformatted:

sudo apt-get --reinstall install `dpkg --get-selections | grep install | grep -v deinstall | cut -f1`

Let's say you get messages about some packages that can't be reinstalled, and the command fails. Here's one way to fix it by skipping the packages in question:
sudo apt-get --reinstall install `dpkg --get-selections | grep install | grep -v deinstall | cut -f1 | egrep -v '(package1|package2)'`

And finally, if you should somehow have so many things installed that the above command fails saying your argument list is too long, here's the fix, which will run apt-get many more times than you might like:
sudo dpkg --get-selections | grep install | grep -v deinstall | cut -f1 | xargs apt-get --reinstall -y --force-yes install

Note the -y and --force-yes options, which will stop apt-get from prompting you over and over again. These are always fun options, if you're sure you know what you're doing.

A: (I know I shouldn't comment in an answer, but not enough reputation to comment.)
blade19899's answer worked for me except for symlinks. E.g. it applied 755 to /bin/bash, but then applied 777 to the symlink /bin/rbash, effectively 777-ing /bin/bash.
As I already had the fileper.log file, I just modified the destination-end command:
while IFS=: read -r -d '' perm file; do
    if [[ ! -L "$file" ]]; then
        chmod "$perm" "$file"
    fi
done < /tmp/fileper.log

A: How to prevent future accidents
All answers here focus (predictably) on restoring the system to a working state. But no answer focuses on how to better prevent a similar accident in the future.
To completely prevent accidents like this in the future, add the following to your ~/.bashrc (or ~/.bash_aliases) file:
# set Safetynets
alias sudo='sudo '    # This allows sudo to run aliases
alias chmod='chmod --preserve-root'
alias chown='chown --preserve-root'
alias chgrp='chgrp --preserve-root'

Also, make sure the same contents are inside the ~/.bashrc (or ~/.bash_aliases) file of the root user as well (else it doesn't matter!).
In this way, you CAN NOT use these commands (even as root) recursively on the root filesystem.
Adding this to ~/.bashrc
Add the following line to your own ~/.bashrc:
echo "alias sudo='sudo '    # This allows sudo to run aliases" >> ~/.bashrc

An easy way to add lines to roots ~/.bashrc is to use a "heredoc". First switch to the root user:
sudo -s

Then run the following text block:
cat << EOT >> ~/.bashrc

# set Safetynets
alias sudo='sudo '    # This allows sudo to run aliases
alias chmod='chmod --preserve-root'
alias chown='chown --preserve-root'
alias chgrp='chgrp --preserve-root'
EOT

A: I wrote and have been using for several years a couple of Ruby scripts to rsync permissions and ownership. Script get-filesystem-acl collects all the information by recursively traversing all the files and puts it all into the file .acl. Script .acl-restore will read .acl and apply all the chown's and chmod's.
You can run get-filesystem-acl on a similar Ubuntu installation and then copy over the .acl file to your chmod-damaged box, put .acl and .acl-restore in /, and run .acl-restore.
You will need to have root so fix your sudo as Marco Ceppi suggested.
I can generate and give you the .acl file for my Ubuntu.
get-filesystem-acl
#!/usr/bin/ruby

RM   = "/bin/rm"
SORT = "/usr/bin/sort"
TMP  = "/tmp/get_acl_#{Time.now.to_i}_#{rand * 899 + 100}"

require 'find'

IGNORE = [".git"]

def numeric2human(m)
  return sprintf("%c%c%c%c%c%c%c%c%c",
            (m & 0400 == 0 ? ?- : ?r),
            (m & 0200 == 0 ? ?- : ?w),
            (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
                             (m & 04000 == 0 ? ?x : ?s)),
            (m & 0040 == 0 ? ?- : ?r),
            (m & 0020 == 0 ? ?- : ?w),
            (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
                             (m & 02000 == 0 ? ?x : ?s)),
            (m & 0004 == 0 ? ?- : ?r),
            (m & 0002 == 0 ? ?- : ?w),
            (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
                             (m & 01000 == 0 ? ?x : ?t)))
end

File.open(TMP, "w") do |acl_file|

  # TODO: Instead of the current dir, find the .git dir, which could be
  #       the same or outside of the current dir
  Find.find(".") do |path|

    next if IGNORE.collect {|ig| !!(path[2..-1] =~ /\A#{ig}/)}.include? true
    next if File.symlink?(path)

    stat = File.lstat(path)
    group_id = stat.gid
    rules    = "#{type}#{numeric2human(stat.mode)}"

    acl_file.puts "#{path} #{rules} #{owner_id} #{group_id}"
  end
end

`#{SORT} #{TMP} > .acl`
`#{RM}   #{TMP}`

.acl-restore
#!/usr/bin/ruby

# This script will only work with .acl_ids

# Restore from...
FROM  = ".acl"

MKDIR = "/bin/mkdir"
CHMOD = "/bin/chmod"
CHOWN = "/bin/chown"
known_content_missing = false

def numeric2human(m)
  return sprintf("%c%c%c%c%c%c%c%c%c",
            (m & 0400 == 0 ? ?- : ?r),
            (m & 0200 == 0 ? ?- : ?w),
            (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
                             (m & 04000 == 0 ? ?x : ?s)),
            (m & 0040 == 0 ? ?- : ?r),
            (m & 0020 == 0 ? ?- : ?w),
            (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
                             (m & 02000 == 0 ? ?x : ?s)),
            (m & 0004 == 0 ? ?- : ?r),
            (m & 0002 == 0 ? ?- : ?w),
            (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
                             (m & 01000 == 0 ? ?x : ?t)))
end

def human2chmod(mode)
  raise unless mode =~ /([r-][w-][xtsTS-])([r-][w-][xtsTS-])([r-][w-][xtsTS-])/
  triple = [$1, $2, $3]
  u,g,o = triple.collect do |i|
    i.sub('s', 'sx').sub('t', 'tx').downcase.gsub('-', '')
  end

  return "u=#{u},g=#{g},o=#{o}"
end

File.open(FROM).each do |acl|
  raise unless acl =~ /\A(([^ ]*? )+)([^ ]+) ([^ ]+) ([^ ]+)\Z/
  path, rules, owner_id, group_id = $1, $3, $4, $5
  path = path.strip
  owner_id = owner_id.to_i
  group_id = group_id.to_i

  if !File.exists?(path) and !File.symlink?(path)
    if rules =~ /\Ad/
      STDERR.puts "Restoring a missing directory: #{path}"
      STDERR.puts "Probably it was an empty directory. Git goes not track them."
      `#{MKDIR} -p '#{path}'` # Creating the any parents
    else
      known_content_missing = true
      STDERR.puts "ERROR: ACL is listed but the file is missing: #{path}"
      next
    end
  end

  s = File.lstat(path)
  t = s.ftype[0..0].sub('f', '-') # Single character for the file type
                                  # But a "-" istead of "f"

  # Actual, but not neccesarely Desired
  actual_rules    = "#{t}#{numeric2human(s.mode)}"
  actual_owner_id = s.uid
  actual_group_id = s.gid

  unless [actual_rules, actual_owner_id, actual_group_id] ==
    [rules, owner_id, group_id]

    chmod_argument = human2chmod(rules)

    # Debug
    #p chmod_argument
    #p s.mode

    ## Verbose
    puts path
    puts "Wrong: #{[actual_rules, actual_owner_id, actual_group_id].inspect}"
    puts "Fixed: #{[rules, owner_id, group_id].inspect}"
    `#{CHMOD} #{chmod_argument} '#{path}'`

    #puts
  end

end

if known_content_missing
  STDERR.puts "-" * 80
  STDERR.puts "Some files that are listed in #{FROM.inspect} are missing in " +
              "the current directory."
  STDERR.puts
  STDERR.puts "Is #{FROM.inspect} outdated?"
  STDERR.puts "(Try retrograding the current directory to an earlier version)"
  STDERR.puts
  STDERR.puts "Or is the current directory incomplete?"
  STDERR.puts "(Try to recover the current directory)"
  STDERR.puts "-" * 80
end

A: In long: you can. You'll need to mount the the file system from the a Live CD and begin reverting the permissions in the appropriate places. At a minimum to get sudo back you'll want to run sudo chmod u+s /usr/bin/sudo while in the LiveCD session - that will fix the must be setuid root.
However, it would likely be easier to simply reinstall the system.

A: There is a closed question (with a great answer) as duplicate of this one from:

*

*Set myself as owner of /etc with chown command now getting all kinds of errors
As such I will give Terdon the credit but here is my own answer based his.
During development of a new script, the variable  $TMP_DIRECTORY/ had unexpected result of /. This was followed by chmod 700 and chown -R $UDO_USER pointing to $TMP_DIRECTORY which was really /.
System slowly crashed and burned. After that it would not reboot. Everyone screams "YOU MUST REINSTALL" but that means loosing years of work. This script is a variation of Terdon's answer:
#!/bin/bash

if [[ $(id -u) != 0 ]]; then # root powers needed to call this script
    echo >&2 "$0 must be called with sudo powers"
    exit 1
fi

# Parameters blank?
[[ $1 == "" ]] && echo "Parm 1 must be source directory" && exit 1
[[ $2 == "" ]] && echo "Parm 2 must be target directory" && exit 1

# Parameters valid directories?
[[ ! -d "$1" ]] && echo "Parm 1 must be a directory" && exit 1
[[ ! -d "$2" ]] && echo "Parm 2 must be a directory" && exit 1
# [[ ! "$2" == "/mnt/"* ]] && echo "Parm 2 must start with /mnt/..." && exit 1

# shopt -s globstar     # From original
shopt -s dotglob
liveSystem="$1"
deadSystem="$2"

# Parameters must end in same subdirectory
[[ "${liveSystem##*/}" != "${deadSystem##*/}" ]] && \
    echo "subdirectory ${liveSystem##*/} not same as ${deadSystem##*/}" && \
    exit 1

cd "$deadsystem"
Count=0
NoRef=0
one() {
    path="$1"
    MountlessPath="${path##*$deadSystem/}"
    if [ -e "$liveSystem/$MountlessPath" ] ; then
        echo chown --reference "$liveSystem/$MountlessPath" "$path"
        echo chmod --reference "$liveSystem/$MountlessPath" "$path"
        (( Count++ ))
    else
        echo "No reference for: $path"
        (( NoRef++ ))
    fi
}

# From: https://stackoverflow.com/questions/51654041/loop-through-all-files-in-a-directory-and-subdirectories-using-bash
# Note typo "If" instead of "if" in above link
recurse() {
  path="$1"
  if [ -d "$path" ] ; then
#     echo "Path: $path"
     one "$path"            # Enhancement: chown of directories too
     for i in "$path/"* # "$path/."* # Enhancement: do hidden directories
     do
        # Skip over .. which gives endless loop
        [[ "$path" == *".cache/speech-dispatcher"* ]] && continue
        [[ "$path" == *"/usr/bin/X11"* ]] && continue
        BaseName=${path##*/}
        [[ "${#BaseName}" -gt 300 ]] && continue
#        [[ ${#BaseName[@]} -gt 1 ]] && continue
#        echo BaseName: $BaseName
#        [[ $BaseName == ".." || $BaseName == "*" ]] && continue
        recurse "$i"
     done
# Original code selected only files but we want links too
#  elif [ -f "$path" ] ; then
  else
    [ ! -f "$path" ] && printf "Not a file -> "
    one "$path"
  fi
}

recurse "$deadSystem"

echo "========================================================================"
echo "$Count references found for chown command to process"
echo "$NoRef files, directories and links, etc. could not be processed"
# From: https://unix.stackexchange.com/questions/193368/can-scp-create-a-directory-if-it-doesnt-exist/193372?noredirect=1#comment1111576_193372
# Original didn't have much luck?
#for file in **/*; do
#    [ -e "$liveSystem/$file" ] &&
#        echo sudo chown --reference "$liveSystem/$file" "$file"
#done

When running the script with $ sudo reset-owner /mnt/old/var /var | grep "No reference" the tail end says this:
Not a file -> No reference for: /var/tmp/systemd-private-fdbc599820b645f4a461404675af3b5d-rtkit-daemon.service-jvV8tG/tmp/*
No reference for: /var/tmp/systemd-private-fdbc599820b645f4a461404675af3b5d-systemd-timesyncd.service-vmgqTh
No reference for: /var/tmp/systemd-private-fdbc599820b645f4a461404675af3b5d-systemd-timesyncd.service-vmgqTh/tmp
Not a file -> No reference for: /var/tmp/systemd-private-fdbc599820b645f4a461404675af3b5d-systemd-timesyncd.service-vmgqTh/tmp/*
No reference for: /var/tmp/uefi.dat
No reference for: /var/tmp/uefi.dsl
========================================================================
12369 references found for chown command to process
7676 files, directories and links, etc. could not be processed

As daunting as it seems it only took an hour to work it all out. By the time I was done I was left with this:
$ sudo reset-owner /mnt/old/var /var | grep "No reference" | grep -v /var/tmp/ | grep -v /var/spool/ | grep -v '\/\*' | grep -v /var/run | grep -v /unattended | grep -v /upstart | grep -v /log/journal | grep -v /log/pm | grep -v /log/cron | grep -v /log/dpkg | grep -v /log/apt | grep -v /log/altern | grep -v /lib/u | grep -v /lib/systemd | grep -v /lib/snapd | grep -v /lib/shim | grep -v /lib/NetworkManager | grep -v /lib/lightdm | grep -v /lib/initram | grep -v /lib/dpkg | grep -v /lib/doc-base | grep -v /var/lib/dkms | grep -v /lib/blue | grep -v /lib/binfmts | grep -v /lib/apt | grep -v /lib/app-info | grep -v /lib/Accounts | grep -v /var/crash | grep -v /var/cache
No reference for: /var
No reference for: /var/lib/flashplugin-installer
No reference for: /var/lib/gems
No reference for: /var/lib/gems/2.3.0
No reference for: /var/lib/git
No reference for: /var/lib/tlp/rfkill-saved

A: For packages, the easiest, fastest, and more stable option that I know of is this Aptitude command below.
In summary, this command automatically restore a package permissions to their default. Including both all its default folder(s) & file(s). The end result is as if the package was freshly installed for the first time with its default permission. While at the same time keeping any already existing configuration file(s).
Three Steps
Step 1
Using Terminal/Console, connect into the appropriate Linux user account. This is important because in both steps 2 & 3 below all commands will be executed as this user.
Step 2
If not already done, using Terminal execute this command to install Sudo
apt install sudo

Note: For those not familiar with Sudo, allow a Linux user(s) limited super user privileges
If not already done, using Terminal execute this command to install Aptitude
sudo apt install aptitude

Note: For those not familiar with Aptitude, it is a package manager. Which is similar to Apt. Aptitude has more functionality than Apt. Aptitude includes both an interactive UI and a text-only interface/CLI. In comparison, Apt lacks an interactive UI. Aptitude is a high-level package manager while Apt is lower-level package manager.
Step 3
Choose one of the four options below. Which will reset the package permissions to their default. And keep the package(s) configuration:
Option 1: ONE package. WITHOUT Backport.

*

*Format: sudo aptitude reinstall <PACKAGE NAME>

*Example: sudo aptitude reinstall jami
Option 2: ALL packages. WITHOUT Backport.

*

*Example: sudo aptitude reinstall '~i'
Note

*

*This option above will both reinstall ALL already installed packages and reset their permissions to their default. Including your operating system (OS). Before executing this command, it is suggested to complete the appropriate actions. Such as, but not limited to, create a backup, check that you have enough available locale storage. Time needed for this command is similar to installing a new OS.

Option 3: ONE package. WITH Backport.

*

*Format: sudo aptitude -t <CODE NAME DEBIAN>-backports reinstall <PACKAGE NAME>

*Example: sudo aptitude -t buster-backports reinstall jami
Note

*

*This option above is for Debian 10 Buster. If you use Ubuntu, you would need to adapt this command. Related documentation at https://help.ubuntu.com/community/UbuntuBackports
Option 4: ALL packages. WITH Backport.

*

*Format: sudo aptitude -t <CODE NAME DEBIAN>-backports reinstall '~i'

*Example: sudo aptitude -t buster-backports reinstall '~i'
Note

*

*This option above is for Debian 10 Buster. If you use Ubuntu, you would need to adapt this command. Related documentation at https://help.ubuntu.com/community/UbuntuBackports
Note

*This option above will both reinstall ALL already installed packages and reset their permissions to their default. Including your operating system (OS). Before executing this command, it is suggested to complete the appropriate actions. Such as, but not limited to, create a backup, check that you have enough available locale storage. Time needed for this command is similar to installing a new OS.
Notes about all four options above

*

*Depending on the package, most of the time, those commands above will reset the permissions only on the package folder(s) & file(s). Other files, such as configuration file(s) may not be affected. In other words, the configuration file will remains unaffected. If needed, and if appropriate you could manually reset the permissions on the configuration file(s) only. Often those configurations file(s) are stored at a different location. For example, but not limited to, somewhere into the user home folder. If unsure, find each package documentation.

Attribution
Thanks to this Debian wiki for those options above at https://wiki.debian.org/Permissions/ResetPackagePermissions

A: I did the same thing. In short. I did not reinstall my system. When I noticed that it is running not under all files under the current directory I immediately canceled my command. Then I saw I CANNOT RUN sudo!
Whenever I try to run sudo I get below error message.
sudo: /etc/sudoers is world writable
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin

When I googled I found https://www.thegeekdiary.com/sudo-etc-sudoers-is-world-writable-how-to-correct-the-permissions-of-sudoers-file/
basically, it says to execute chmod 440 /etc/sudoers as root. How can I be root if I can't type sudo?
To do that I go into recovery mode in Ubuntu like https://askubuntu.com/a/92558/488768. From there I log in as root then I executed chmod 440 /etc/sudoers Then I can execute sudo. When I execute a command with sudo I get another warning saying sudo: /etc/sudoers.d is world writable I executed chmod 440 /etc/sudoers.d to fix that.
After that, I see many weird things such as I cannot do SSH on my machine. I deleted the "OpenSSHD" program and then reinstalled it. When I delete and reinstall I see many warnings
WARN: /etc/default/ufw is group writable!
WARN: /etc/default is group writable!
WARN: /etc is group writable!
WARN: / is group writable!
WARN: /lib/ufw/user.rules is group writable!
WARN: /lib/ufw is group writable!
WARN: /lib is group writable!
WARN: /etc/ufw/applications.d is group writable!
WARN: /etc/ufw is group writable!
WARN: /etc/ufw/after6.rules is group writable!
WARN: /lib/ufw/ufw-init is group writable!
WARN: /etc/ufw/ufw.conf is group writable!
WARN: /lib/ufw/user6.rules is group writable!
WARN: /etc/ufw/before6.rules is group writable!
WARN: /etc/ufw/after.rules is group writable!
WARN: /etc/ufw/before.rules is group writable!
WARN: /usr/sbin/ufw is group writable!
WARN: /usr/sbin is group writable!
WARN: /usr is group writable!

Then I followed the suggestions of How to fix permissions warnings in the root folder?
Then I still see my server name is changed. So set the name in "/etc/hosts" Then I still cannot SSH to the given name of my server. Then we changed the IP address back to the previous one. I don't know how IP address changed.

A: I did the same mistake by accident and with these steps my problem was solved.
I was logged out from root and I couldn't run commands with root permissions, and I was working on debian 10.
1-Start or re-start your computer and press ESC(in some machines, press and hold Shift key) to show the Grub boot menu.
2-Choose "Advanced Options for..." from menu and boot the kernel entry with(recovery mode)
3-It gives you a root shell if you have your root password, so you can run these commands
chmod -R 755 /bin /boot /dev /etc/ /home /lib /lib64
/media /mnt /opt /run /sbin /srv /usr /var
chmod -R 777 /initrd.img /vmlinuz
chmod -R 1777 /tmp
chmod -R 555 /sys
chmod -R 555 /proc
chmod -R 700 /root
4-If you get an error when you want to log in as root user, you can run chmod +s /bin/su and check the result with ls -lt /bin/su
the result should be like this -rwsr-sr-x instead of -rwxr-sr-x
I hope it helps.


Q: How to return the id of a mui datagrid row from an onClick event I'm trying to use a material-ui datagrid that's being populated by a sql database to be able to edit what's inside of the database, I want that to be done via a form instead of simply editing the rows and cells individually.
I want to pass the id of the specific row as an argument into a function that will patch that row, using the id I can actually select the row inside of the database and then use a dialog form to update the individual data columns.
I've looked into the docs and anything that it seems to say would work just doesn't. I can't import the GridApi from @mui/x-data-grid-pro or @mui/x-data-grid-premium despite those being installed to make it work, getRowId seems to be a means of setting the row id rather than getting it, and the code snippets I've been able to find don't work either
<DataGrid
onComponentMount={getComponents()} {/*Calls on the database to get the rows and places the resulting array into the rows variable using sqlalchemy and fastapi */}
rows={rows}
columns={columns} {/* contains columns id, description, stock */}
pageSize={6}
rowsPerPageOptions={[6]}
onRowClick={()=>{selectComponents(((index) => {index.api.getRowIndex(index.rows.id)}))}}
/>

A:     onRowClick={(rows)=>{selectComponents(rows.id)}}

This is the answer. Now when I click a row, it will return the row id as an argument in my function. Now I can simply click a row and use that info to open a dataform modal that comes pre-filled out with info that can change and then either be pushed to the database or canceled without saving


Q: Método para saber si está caído el servidor con Server-Sent Event Necesito algún método que me diga si está caído el servidor.
Tengo el siguiente código, por ejemplo:
var conexion       = new EventSource(server + 'config.php');
conexion.onmessage = function(e) { alert('Está conectado'); }
conexion.onerror   = function(e) { alert('Está caído.'); }

La cuestión es que la alerta que debería de aparecer cuando está caído, aparece cuando el servidor está conectado. Salen las dos alertas, pero la segunda debería salir solo en caso de haber un error.

A: Lo que te esta sucediendo es que:

*

*Cuando el servidor esta corriendo, se hace la primer llamada, lo que dispara los eventos onopen y onmessage.

*La conexión se se cierra, lo que dispara el evento onerror.

*Automáticamente se realiza una "re conexión" (aprox. cada 3 segundos), lo que provoca que vuelva a empezar el ciclo (es decir, volvemos al paso 1)

Para validar que el servidor esta caído podrías hacer lo siguiente:

*

*Crear una bandera, por ejemplo isOpen, para determinar si se pudo establecer la conexión.

*Suscribirte al evento onopen y modificar el valor de la variable isOpen a true.

*Suscribirte al evento onerror y usar dicha bandera para determinar si:

*

*El servidor esta "caído" (nunca se pudo establecer una conexión)

*O si hubo un error al intentar recibir una respuesta (se estableció un conexiona pero el contenido de la respuesta no tenia el formato esperado)

Así por ejemplo:
(function() {
    var source = new EventSource(server + 'config.php');
    var isOpen = false;

    source.addEventListener('message', function(e) {
        console.log(e.data);
    }, false);

    source.addEventListener('open', function(e) {
        // Server up
        console.log('El server esta corriendo');
        isOpen = true;
    }, false);

    source.addEventListener('error', function(e) {
        if (!isOpen && source.readyState == EventSource.CONNECTING) {
            // Server down
            console.log('El server esta caido');
        }
        else if (source.readyState == EventSource.CLOSED) {
            // Server error
            console.log('Error en el server');
        }
        isOpen = false;
    }, false);
})();

Fuente: Stream Updates with Server-Sent Events


Q: make table out of several files and combine into one matrix table I have these files (https://github.com/learnseq/RNAseqcollection.git) that I want to merge(combine) the second column of each into one table with reference name. I have two issues: how to enforce column conversion from factor to another type (because I'm getting error when I try) and how to join them with shorter code.
I want this out put (for example one row of the output):
    Geneid      MCL1.DG MCL1.DI  MCL1.DK MCL1.LA MCL1.LC MCL1.LE MCL1.DH MCL1.DJ MCL1.DL MCL1.LB MCL1.LD MCL1.LF
1   100008567     0        0        0      0       0       0       0        0       0      0       0      0

I tried this:
files = list.files(path=".", pattern="MCL")
file1 = read.table("MCL1-DG.txt", col.names=c("Geneid","MCL1-DG" ))
file2 = read.table("MCL1-DI.txt", col.names=c("Geneid","MCL1-DI" ))
file3 = read.table("MCL1-DK.txt", col.names=c("Geneid","MCL1-DK" ))
file4 = read.table("MCL1-LA.txt", col.names=c("Geneid","MCL1-LA"))
file5 = read.table("MCL1-LC.txt", col.names=c("Geneid","MCL1-LC"))
file6 = read.table("MCL1-LE.txt", col.names=c("Geneid","MCL1-LE"))
file7 = read.table("MCL1-DH.txt", col.names=c("Geneid","MCL1-DH"))
file8 = read.table("MCL1-DJ.txt", col.names=c("Geneid","MCL1-DJ"))
file9 = read.table("MCL1-DL.txt", col.names=c("Geneid","MCL1-DL"))
file10 = read.table("MCL1-LB.txt", col.names=c("Geneid","MCL1-LB"))
file11 = read.table("MCL1-LD.txt", col.names=c("Geneid","MCL1-LD"))
file12 = read.table("MCL1-LF.txt", col.names=c("Geneid","MCL1-LF"))

out.file = merge (file1, file2, by=c("Geneid"))
out.file2 <- merge(out.file, file3, by=c("Geneid"))
out.file3 <- merge(out.file2, file4, by=c("Geneid"))
out.file4 <- merge(out.file3, file5, by=c("Geneid"))
out.file5 <- merge(out.file4, file6, by=c("Geneid"))
out.file6 <- merge(out.file5, file7, by=c("Geneid"))
out.file7 <- merge(out.file6, file8, by=c("Geneid"))
out.file8 <- merge(out.file7, file9, by=c("Geneid"))
out.file9 <- merge(out.file8, file10, by=c("Geneid"))
out.file10 <- merge(out.file9, file11, by=c("Geneid"))
out.file11 <- merge(out.file10, file12, by=c("Geneid"))

A: This seems to work quite well:
files = list.files(path=".", pattern="MCL")

table_list <- lapply(X = files, FUN = read.table, header=TRUE)

combined <- Reduce(f = merge, x = table_list)

We first loop over the table names with lapply and read each one in, returning a list. By using header=TRUE we can avoid having to rename each one and instead deduce the column names from the first row of each file. Then we can use Reduce to repeatedly merge each table with the next one. merge is smart enough to assume that the shared column name is the thing we want to merge on, so we don't need to specify arguments there either.
I didn't download all the files but here's the output from running this code on the first 3:


Q: Detect if a fs writable stream is full I'm opening a writable stream to a device (e.g: /dev/disk2) with fs.createWriteStream(). Assuming I don't know the device size in advance, how could I correctly detect if the device can't receive more data (e.g: the device doesn't have any more space)?
If I simulate such scenario, I eventually get an EIO error emitted from the stream:
Error: EIO: i/o error, write
  at Error (native) errno: -5, code: 'EIO', syscall: 'write', type: 'write'

But then an EIO is too generic, and can be thrown in other situations as well.
I'm inspecting the properties of the stream object once the error is thrown but there doesn't seem to exist a flag I could use to determine this.


Q: Does passing a value type in an "out" parameter cause the variable to be boxed? I'm aware that boxing and unboxing are relatively expensive in terms of performance. What I'm wondering is:
Does passing a value type to a method's out parameter cause boxing/unboxing of the variable (and thus a performance hit)? Can the compiler optimize this away?
  int number;
  bool result = Int32.TryParse(value, out number);

A: No boxing, compiler uses the ldloca.s instruction which pushes a reference to the local variable onto the stack (http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldloca_s(VS.71).aspx)
.method private hidebysig static void Func() cil managed
{
    .maxstack 2
    .locals init (
        [0] int32 num,
        [1] bool flag)
    L_0000: nop
    L_0001: ldstr "5"
    L_0006: ldloca.s num
    L_0008: call bool [mscorlib]System.Int32::TryParse(string, int32&)
    L_000d: stloc.1
    L_000e: ret
}

A: No, there is no Boxing (required/involved).
When you do Box a variable, changes to the boxed instance do not affect the original. But that is exactly what out is supposed to do.
The compiler 'somehow' constructs a reference to the original variable.

A: As others have pointed out, there's no boxing here. When you pass a variable as an argument corresponding to an out or ref parameter, what you are doing is making an alias to the variable.  You are not doing anything to the value of the variable.  You're making two variables represent the same storage location.
Boxing only happens when a value of a value type is converted to a value of a reference type, and there's no conversion of any kind in your example. The reference type must of course be System.Object, System.ValueType, System.Enum or any interface. Usually it is pretty clear; there's an explicit or implicit conversion in the code. However, there can be circumstances where it is less clear. For example, when a not-overridden virtual method of a struct's base type is called, there's boxing. (There are also bizarre situations in which certain kinds of generic type constraints can cause unexpected boxing, but they don't usually come up in practice.)

A: There is no boxing; what the out parameter does is specifies that number must be assigned to within the TryParse method. Irrespective of this, it is still treated as an int, not an object.


Q: Test Custom Gradle plugin after Evaluate I'm developing a Gradle custom plugin and I'm having issues on how to test it.
The plugin creates an extension to receive configuration and after evaluation (project.afterEvaluate {) creates a tasks with the received configuration, those values are @Input on tasks.
Following the documentation https://docs.gradle.org/current/userguide/custom_plugins.html to create a test for the plugin, I use the following to create the project and apply the plugin
@Before fun setup() {
  project = ProjectBuilder.builder().build()
  project.pluginManager.apply("my.plugin.name")

and then test that extension got created:
assertTrue(project.extensions.findByName("name") is MyConfigType)

and the task got created:
assertTrue(project.tasks.findByName("mytask") is MyTaskType)

The issue I'm having is that the task is only created afterEvaluate, so this test is failing. As far as I understood, it has to be afterEvaluate so that it can receive the configuration values.
So the only way I could see if I could on the test force this project to be evaluated, but how?
Is there maybe a different way to receive values?

A: I posted my similar question in the gradle forums and was able to solve the issue:
https://discuss.gradle.org/t/unit-test-plugins-afterevaulate/37437/3
Apparently afterEvaluate is not the best/right place to perform the task creation. If you have a DomainObjectCollection in your extension and want to create a task for each element in the collection, task creation should be done in the all-Callback of the collection:
final MyExtension extension = project.getExtensions().create("extension", MyExtension.class);
extension.configurations.all((c) -> {
  // register task here
});

If you have simple properties in the extension that are feed to the task as input, you should use lazy configuration:
public class MyExtension {
  public final Property<String> property;
  public final NamedDomainObjectContainer<Configuration> configurations;

  @Inject
  public MyExtension(final ObjectFactory objectFactory) {
    property = objectFactory.property(String.class).convention("value");
    configurations = objectFactory.domainObjectContainer(Configuration.class);
  }
}

public abstract class MyTask extends DefaultTask {

  @Input
  private final Property<String> property = getProject().getObjects().property(String.class);

  public Property<String> getProperty() {
    return property;
  }
}

And the apply method:
public class MyPlugin implements Plugin<Project> {

  @Override
  public void apply(final Project aProject) {
    final MyExtension extension = aProject.getExtensions().create("extension", MyExtension.class);
    aProject.getTasks().register("myTask", MyTask.class).configure((t) -> {
      t.getProperty().set(extension.property);
    });
  }
}

A: You should call project.evaluationDependsOn(":"):
@Before fun setup() {
  project = ProjectBuilder.builder().build()
  project.pluginManager.apply("my.plugin.name")
  project.evaluationDependsOn(":") // <<--
  ...
}

It executes your afterEvaluate callback.


Q: Socket programming: Struct sockaddr VS struct sockaddr_in I have seen the question similar question below:
struct sockaddr_un v/s sockaddr - C(Linux)
But I am still very unclear about what the difference is between sockaddr_in and sockaddr, every socket method/function I.e bind, connect, seems to use sockaddr and not sockaddr_in, are these structures interchangeable? if only sockaddr is used then why is there the _in one? I prefer the _in seems more detailed and sorted.
Delete the post or so if I have broken any rules ;(
most of the time the 3rd parameter is the addr_len is this used to quickly differentiate between ipv4 and ipv6?

A: The sockaddr is a generic socket address. If you remember, you can create TCP/IPv4, UDP/IPv4, UNIX, TCP/IPv6, UDP/IPv6 sockets (and more!) through the same operating system API - socket().
All of these different socket types have different actual addresses - composed of different fields.
sockaddr_in is the actual IPv4 address layout (it has .sin_port and .sin_addr). A UNIX domain socket will have type sockaddr_un and will have different fields defined, specific to the UNIX socket family.
Basically sockaddr is a collection of bytes, it's size being the maximum of sizes of all supported (by the O/S) socket/address families such that it can hold all of the supported addresses.

A: Taking a look at sockaddr_in
struct sockaddr_in
  {
    __SOCKADDR_COMMON (sin_);
    in_port_t sin_port;         /* Port number.  */
    struct in_addr sin_addr;        /* Internet address.  */

    /* Pad to size of `struct sockaddr'.  */
    unsigned char sin_zero[sizeof (struct sockaddr) -
               __SOCKADDR_COMMON_SIZE -
               sizeof (in_port_t) -
               sizeof (struct in_addr)];
  };

And if we see sockaddr
* Structure describing a generic socket address.  */
struct sockaddr
  {
    __SOCKADDR_COMMON (sa_);    /* Common data: address family and length.  */
    char sa_data[14];       /* Address data.  */
  };

So actually, they are not exchangeable, but but they have the same size so you can use it with no problem and cast between those structures.
But remember you must know what you are doing or probably will get segfaults or unexpected behavior.


Q: Call function on Main Module I have a VB.NET script that creates mail accounts using smartermail webservice, i know nothing of VB.Net but i have a little knowledge of programming. I created a new project on Visual Studio 2012 and know i need to call the function that creates the accounts on the main module to run it, that's a console app project.
Main Module (Module1.vb) is as follows:
Module Module1
      Sub Main()
      End Sub
End Module*

My function is:
 Sub fnc_CriaContas_Email_Lote()

It's on the file cria_contas_lote.vb in the same directory.
Content of cria_contas_lote.vb:
Sub fnc_CriaContas_Email_Lote()

    Dim oPainelWS As PainelControle.svcSmarterMail
    Dim sRetorno As String = ""

    Try
        'oPainelWS = New PainelControle.svcSmarterMail("xxx.xxx.xxx.xxx")
    Catch ex As Exception
        Console.WriteLine("Erro ao efetuar a conexão no servidor remoto: " & ex.Message)
        Exit Sub
    End Try

    Dim sNomeArquivo As String = "C:\dir\emails.xlsx"
    Dim sSQL As String = ""

    Dim stringExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sNomeArquivo & ";Extended Properties=Excel 12.0"
    Dim oExcel As New OleDbConnection(stringExcel)

    Try
        oExcel.Open()
    Catch ex As Exception
        Console.Write("O arquivo não foi localizado ou ocorreu um erro de abertura no servidor. Arquivo: " & sNomeArquivo)
        Console.Write(vbCrLf & "================================================")
        Console.Write(vbCrLf & ex.Message)
        Console.Write(vbCrLf & "================================================")

        Exit Sub
    End Try

    Dim oDataSet As New DataSet
    Try
        Dim oExcelAdapter As New OleDbDataAdapter("select * from [contas_pop$]", oExcel)
        oExcelAdapter.Fill(oDataSet, "conteudo")
    Catch ex As Exception
        Console.Write("A tabela CONTAS_POP não foi localizada. Renomeie sua WorkSheet para CONTAS_POP")
        oExcel.Close()
        Exit Sub
    End Try
    oExcel.Close()

    Dim oDataview As DataView = oDataSet.Tables("conteudo").DefaultView

    Dim lTotal As Long = 0
    Dim lErro As Long = 0
    Dim oLinha As DataRow
    Dim iTamanhoCaixa As Integer = 1024
    Dim sComCopia As String

    For Each oLinha In oDataSet.Tables("conteudo").Rows

        If Not (Trim(oLinha("conta").ToString) = "") Then

            Console.Write("Criando [" & Trim(oLinha("conta").ToString) & "]...")
            sRetorno = ""
            sComCopia = Trim(oLinha("enviar_copia").ToString)
            iTamanhoCaixa = oLinha("tamanho_mb")

            sRetorno = CriaContaPOP(Trim(oLinha("conta").ToString), Trim(oLinha("apelidos").ToString), Trim(oLinha("password").ToString), iTamanhoCaixa, oLinha("nome").ToString, sComCopia, "admin", "password")
            'sRetorno = oPainelWS.CriaContaPOP(oLinha("conta"), Trim(oLinha("apelidos").ToString), oLinha("senha"), iTamanhoCaixa, "", sComCopia, "", "")
            Console.WriteLine("Retorno: " & sRetorno)
            'If Not (sRetorno = "OK") Then
            'Exit Sub
            'End If

            Threading.Thread.Sleep(100)

        End If

    Next

End Sub

Public Function CriaContaPOP(ByVal sConta As String, ByVal sApelidos As String, ByVal sSenha As String, ByVal iTamanhoCaixaKB As String, ByVal sNome As String, ByVal sForwardTo As String, ByVal sAdminUsuario As String, ByVal sAdminSenha As String) As String

    If Not (iTamanhoCaixaKB > 1) Then
        Return "ERRO: Tamanho da caixa postal não pode ser inferior a 1 KB"
    End If

    Dim aContaNome As String() = Split(sConta, "@")
    Dim sContaNome As String = ""
    Dim sDominio As String = ""
    sContaNome = aContaNome(0)
    sDominio = aContaNome(1)

    Dim oUsuarios As New svcUserAdmin
    Dim oUsuarioInfo As New SettingsRequestResult
    Dim oResultado As New GenericResult

    oResultado = oUsuarios.AddUser2(sAdminUsuario, sAdminSenha, sContaNome, sSenha, sDominio, sNome, "", False, iTamanhoCaixaKB)
    If (oResultado.Result = False) Then
        Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
    End If

    If Not (sForwardTo.ToString = "") Then
        Dim arrInfo(0) As String
        arrInfo(0) = "forwardaddress=" & sForwardTo.ToString
        oResultado = oUsuarios.SetRequestedUserSettings(sAdminUsuario, sAdminSenha, sConta, arrInfo)
        If (oResultado.Result = False) Then
            Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
        End If
    End If

    Return "OK"

End Function

A: What have you tried? Because as it stands it sounds like all you need to do is
Module Module1

    Sub Main()
        fnc_CriaContas_Email_Lote()
    End Sub

    Sub fnc_CriaContas_Email_Lote()
        ' Do something.
    End Sub

End Module

If "fnc_CriaContas_Email_Lote" is a class then you might have to do something like:
Module Module1

    Sub Main()
        dim email as new cria_contas_lote()

        email.fnc_CriaContas_Email_Lote()
    End Sub

End Module

Without seeing the cria_contas_lote file its hard to know.
Edit: Below is how you can call it all from just the module
    Imports System.Data.OleDb

Module Module1

Sub Main()

    fnc_CriaContas_Email_Lote()

End Sub

Sub fnc_CriaContas_Email_Lote()

    Dim oPainelWS As PainelControle.svcSmarterMail
    Dim sRetorno As String = ""

    Try
        'oPainelWS = New PainelControle.svcSmarterMail("xxx.xxx.xxx.xxx")
    Catch ex As Exception
        Console.WriteLine("Erro ao efetuar a conexão no servidor remoto: " & ex.Message)
        Exit Sub
    End Try

    Dim sNomeArquivo As String = "C:\dir\emails.xlsx"
    Dim sSQL As String = ""

    Dim stringExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sNomeArquivo & ";Extended Properties=Excel 12.0"
    Dim oExcel As New OleDbConnection(stringExcel)

    Try
        oExcel.Open()
    Catch ex As Exception
        Console.Write("O arquivo não foi localizado ou ocorreu um erro de abertura no servidor. Arquivo: " & sNomeArquivo)
        Console.Write(vbCrLf & "================================================")
        Console.Write(vbCrLf & ex.Message)
        Console.Write(vbCrLf & "================================================")

        Exit Sub
    End Try

    Dim oDataSet As New DataSet
    Try
        Dim oExcelAdapter As New OleDbDataAdapter("select * from [contas_pop$]", oExcel)
        oExcelAdapter.Fill(oDataSet, "conteudo")
    Catch ex As Exception
        Console.Write("A tabela CONTAS_POP não foi localizada. Renomeie sua WorkSheet para CONTAS_POP")
        oExcel.Close()
        Exit Sub
    End Try
    oExcel.Close()

    Dim oDataview As DataView = oDataSet.Tables("conteudo").DefaultView

    Dim lTotal As Long = 0
    Dim lErro As Long = 0
    Dim oLinha As DataRow
    Dim iTamanhoCaixa As Integer = 1024
    Dim sComCopia As String

    For Each oLinha In oDataSet.Tables("conteudo").Rows

        If Not (Trim(oLinha("conta").ToString) = "") Then

            Console.Write("Criando [" & Trim(oLinha("conta").ToString) & "]...")
            sRetorno = ""
            sComCopia = Trim(oLinha("enviar_copia").ToString)
            iTamanhoCaixa = oLinha("tamanho_mb")

            sRetorno = CriaContaPOP(Trim(oLinha("conta").ToString), Trim(oLinha("apelidos").ToString), Trim(oLinha("password").ToString), iTamanhoCaixa, oLinha("nome").ToString, sComCopia, "admin", "password")
            'sRetorno = oPainelWS.CriaContaPOP(oLinha("conta"), Trim(oLinha("apelidos").ToString), oLinha("senha"), iTamanhoCaixa, "", sComCopia, "", "")
            Console.WriteLine("Retorno: " & sRetorno)
            'If Not (sRetorno = "OK") Then
            'Exit Sub
            'End If

            Threading.Thread.Sleep(100)

        End If

    Next

End Sub

Public Function CriaContaPOP(ByVal sConta As String, ByVal sApelidos As String, ByVal sSenha As String, ByVal iTamanhoCaixaKB As String, ByVal sNome As String, ByVal sForwardTo As String, ByVal sAdminUsuario As String, ByVal sAdminSenha As String) As String

    If Not (iTamanhoCaixaKB > 1) Then
        Return "ERRO: Tamanho da caixa postal não pode ser inferior a 1 KB"
    End If

    Dim aContaNome As String() = Split(sConta, "@")
    Dim sContaNome As String = ""
    Dim sDominio As String = ""
    sContaNome = aContaNome(0)
    sDominio = aContaNome(1)

    Dim oUsuarios As New svcUserAdmin
    Dim oUsuarioInfo As New SettingsRequestResult
    Dim oResultado As New GenericResult

    oResultado = oUsuarios.AddUser2(sAdminUsuario, sAdminSenha, sContaNome, sSenha, sDominio, sNome, "", False, iTamanhoCaixaKB)
    If (oResultado.Result = False) Then
        Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
    End If

    If Not (sForwardTo.ToString = "") Then
        Dim arrInfo(0) As String
        arrInfo(0) = "forwardaddress=" & sForwardTo.ToString
        oResultado = oUsuarios.SetRequestedUserSettings(sAdminUsuario, sAdminSenha, sConta, arrInfo)
        If (oResultado.Result = False) Then
            Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
        End If
    End If

    Return "OK"

End Function

End Module

Your issue is your missing the following types:

*

*PainelControle.svcSmarterMail

*svcUserAdmin

*SettingsRequestResult

*GenericResult

These are not built in .Net types and must be defined in either another file.  Once you've found the missing classes just add them into the project and you should be good to go.

A: I think you want to make Sub Main run ENTIRE function, and DON'T EXIT as sub main is executed.
I have written answer of your question here : VB.net program with no UI
Sub Main()
    'Write whatever you want, and add this code at the END:
    Application.Run
End Sub


Q: Can an object reverse its direction of acceleration even though it continues to move in the same direction? Can anyone please explain me on this matter along with day to day examples?

A: Of course.  Acceleration is the rate of change of the velocity.
For motion in a line, if the object is slowing down, the acceleration is opposite the velocity.  If the object is speeding up, the acceleration is in the direction of the velocity.
Imagine you're pedalling a bike, gaining more and more speed and then, suddenly, stop pedalling and apply the brakes.  Your motion is still in the same direction but you suddenly change from speeding up to slowing down - your acceleration suddenly changes direction but you continue to move in the same direction.
A good example to study to get an intuitive feeling for the relationship between velocity and acceleration is the back and forth motion of a mass attached to a spring.
Try the application at this link which not only animates the motion but also plots the position, velocity, and acceleration.  When the acceleration has the opposite sign of the velocity, the acceleration is in the opposite direction of the velocity.

A: Absolutely.
Acceleration is the change in velocity, so when you say that the acceleration reverses in direction, it means that the object is transferring from either speeding up to slowing down, like a skateboard which just passed the bottom of a U-shaped ramp, or from slowing down to speeding up.  Think of the skateboard as having just crested a hill.  It was previously slowing down as it climbed the hill, then it reached the top, where its acceleration was 0, and then it began descending the hill, so its forward acceleration became positive.
Of course, this is a very general example for a very general question.  You can apply this idea to a car that has just accelerated and is now applying the brakes (positive to negative acceleration), or a person falling onto a trampoline (negative to positive).

A: A pendulum is a day to day example of this. If you watch a pendulum swinging from left to right as it passes the mid point the velocity and acceleration are:

The acceleration always point towards the mid point, so as the pendulum passes through the mid point the acceleration reverses direction but the velocity does not.

A: (Temporarily pretend you are on the second floor of a building.)  Jump up and down in one place.  After you leave the floor:

*

*your displacement is always positive (i.e., above the floor);

*your velocity is positive (rising), zero (at your highest displacement), then negative (falling back to the floor); and

*your acceleration is constant and negative -- it's gravity steering you back to the floor.

If you walk downstairs to the first floor, your displacement is always negative (unless you are capable of jumping as high as the distance between floors, you are always below where you started on the second floor), your velocity and acceleration, however follow the same pattern.
If alternatively, the floor fails and you fall to the first floor, you displacement will be initially positive and then negative.
So even though in this very simple experiment your acceleration is always negative (down), your velocity and displacement can be positive, zero, or negative in any combination.
For more examples --

*

*A bullet flying through the air has large velocity, a small drag acceleration directed (ideally) opposite to its velocity, and a smaller gravitational acceleration pointed down.  It takes a long time for the drag to overcome the initial velocity of the bullet.  For bullets fired horizontally near the surface of the Earth, the gravitational force will bring the bullet to the ground before drag will arrest its forward motion.

*A beginning roller skater (when upright and rolling) is always experiencing a little drag acceleration opposite their velocity.  Bearing aren't perfect and the gummy residue that seems to collect on wheels and rinks resists the rolling of the wheels (by not letting go when the wheel tries to roll on).

*Large ships -- you can throw it in reverse, but it's going to take a while to get all that mass to (first) stop and (then) start moving back the other way.

*During landing, there are several components applying acceleration to the rear of the plane -- for instance, the engines, having been put in reverse, which just a few minutes ago were providing enough forward thrust to keep the plane in the air, take several seconds to erase the forward velocity of the plane.

A: Get on a car, turn it on and press the accelerator! (${{a}}>0$)... then press the brake (${{a}}<0$). Until the car is steady, the situation is as you described.


Q: Jquery mobile theme on dynamic pages My theme is not being carried out on the dynamic pages that are created in the code I have below. on the first menu page it works then all other pages have the default theme not the one I have set in siteData.theme.
How can I set this?
    var siteData = build;
    $(this).find('[data-role="header"] h3').html(siteData.name);
    $.mobile.activePage.find('[data-role=header] h3').html(siteData.name);
    $('div[data-theme]', '#index').data('theme', siteData.theme);

    //reset all the buttons widgets
    $.mobile.activePage.find('.ui-btn')
        .removeClass('ui-btn-up-a ui-btn-up-b ui-btn-up-c ui-btn-up-d ui-btn-up-e ui-btn-hover-a ui-btn-hover-b ui-btn-hover-c ui-btn-hover-d ui-btn-hover-e')
        .addClass('ui-btn-up-' + $('div[data-theme]', '#index').data('theme'))
        .attr('data-theme', $('div[data-theme]', '#index').data('theme'));

    //reset the header/footer widgets
    $.mobile.activePage.find('.ui-header, .ui-footer')
        .removeClass('ui-bar-a ui-bar-b ui-bar-c ui-bar-d ui-bar-e')
        .addClass('ui-bar-' + $('div[data-theme]', '#index').data('theme'))
        .attr('data-theme', $('div[data-theme]', '#index').data('theme'));

    //reset the page widget
    $.mobile.activePage.removeClass('ui-body-a ui-body-b ui-body-c ui-body-d ui-body-e')
        .addClass('ui-body-' + $('div[data-theme]', '#index').data('theme'))
        .attr('data-theme', $('div[data-theme]', '#index').data('theme'));

    $.each(siteData["pages"], function (i, v) {

        if (!$('#' + v["id"]).length) {

            // Build nav.
            $.mobile.activePage.find('[data-role=content]').append('' +
                '' + v["name"] +
                '').trigger('create');

            var components = {};

            var newPage = $("

Back" +
                "
" + v["name"] + "
" +
                "
" +
                "
" + pagecontent +
                "
" +
                "
" +
                "
" + v["name"] + "
" +
                "
" +
                "
");

            newPage.appendTo($.mobile.pageContainer);

        }

    });

});

A: From your code it looks like siteData.theme holds the theme name i.e. 'b' so you can just add:
$('[data-role=page]').page({
        theme: siteData.theme
    });

To your script.
This will not however change the header and footer from the default theme. You could just in the newPage creation add data-theme=siteData.theme depending on whats in siteData.theme of course.


Q: How to insert array object property value into HTML? I wanted to make a simple carousel using DOM manipulation, I don't know if I can do this or not in Angular, but the idea is I created an array of objects with properties that I want to pass to the HTML using interpolation, and I don't know how to do it yet. Here's my code:

carousel

                              <fa-icon [icon]="faChevronLeft" class="mr-2"></fa-icon>

                              <fa-icon [icon]="faChevronRight" class="mr-2"></fa-icon>

{{carousel.description}}

 {{carousel.name}}, {{carousel.affiliation}}

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import {faChevronLeft, faChevronRight, IconDefinition} from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-carousel',
  templateUrl: './carousel.component.html',
  styleUrls: ['./carousel.component.scss']
})
export class CarouselComponent implements OnInit {
  faChevronLeft: IconDefinition = faChevronLeft;
  faChevronRight: IconDefinition = faChevronRight;
  carousel = [
    {
      id: 1,
      name: 'captain america',
      affiliation: 'camp lehigh',
      description: 'language!',
      image: 'http://picsum.photos/200'
    },
    {
      id: 2,
      name: 'thor',
      affiliation: 'asgard',
      description: 'i am god of thunder!',
      image: 'http://picsum.photos/200'
    },
    {
      id: 3,
      name: 'tony stark',
      affiliation: 'stark industries',
      description: 'and i....am..iron man!',
      image: 'http://picsum.photos/200'
    }
  ];

  constructor(
  ) {}

  ngOnInit() {
  }

  carouselPrev() {
     // i want to make this a control by making the id/index +1
  }

  carouselNext() {
    // i want to make this a control by making the id/index -1
  }
 }

A: You can achieve it using ngFor with index.
Live example: https://stackblitz.com/edit/angular-b5qvwy
Some code:
Basic HTML

{{list[i].name}}

<

>

Basic TS code
 export class AppComponent  {
      list = [
        {
          name: "Jhon"
        },
        {
          name: "Joe"
        },
        {
          name: "Marth"
        }
      ];

      i = 0;

      prev(){
        if(this.i > 0){
          this.i--;
        }
      }

      next(){
        if(this.i < this.list.length -1){
          this.i++;
        }
      }
    }

For your example, simply do that in the html:

carousel

                              <fa-icon [icon]="faChevronLeft" class="mr-2"></fa-icon>

                              <fa-icon [icon]="faChevronRight" class="mr-2"></fa-icon>

{{carousel[i].description}}

 {{carousel[i].name}}, {{carousel[i].affiliation}}


Q: Google Cloud : check disk space usage How to check the used disk space of Google Persistent Disk without looking into each of them?

A: I use a simple workaround for this.
Create a snapshot of your persistent disk, and look at the snapshot size:

A: You can't see it in the disk preview as Faizan said, But you could Use Google StackDriver Monitoring tool to get a nice preview of your instances status.

A: The workaround with snapshot size will work in the console.
For more precise (and quicker) detailed overview you can SSH into your instance and do:
sudo df -h

The response you get will look similar to this:
YOURUSERNAME@YOURINSTANCENAME:~$ sudo df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1       9.8G  9.3G     0 100% /
udev             10M     0   10M   0% /dev
tmpfs           743M   81M  663M  11% /run
tmpfs           1.9G     0  1.9G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/sdb        197G   60M  197G   1% /mnt/new_disk

Entries starting with /dev/ under 'Filesystem' are your disks.

A: Just install Monitoring Agents in https://console.cloud.google.com/monitoring/dashboards/resourceList/gce_instance
then check the dashboard

A: In your terminal use this command to detect files size and which directory is more bulky:
ncdu /


Q: Jammy - resolvectl domain persistent across reboots Much that I have searched AU for similar questions, I came up null for 22.04 - although maybe this is nothing to do with 22.04
I am looking to know how to make a search domain persistent across reboots.
I use the following command to set the local cloud domain
resolvectl domain eth0 organisational.cloud

It works great - until I reboot the machine..
How is one meant to add a persistent search domain?
I see something in man about /etc/systemd/network but I'm not sure that is for legacy support or not.  The resolv.conf file (and others) all say Do not edit.

A: In my Fedora 36 system, which is a fixed IPv4 address, I was also looking for how to persist the local domain DNS settings without doing sudo resolvectl domain enp5s0 haapi.org all the time. FedKad's comment has turned out to be spot-on.
I edited the [Resolve] section of /etc/systemd/resolved.conf:
[Resolve]
DNS=192.168.77.88  # my local LAN's DNS server
Domains=haapi.org  # my local domain

Then, systemctl restart systemd-resolved
as FedKad said, and it worked. Even better, it worked after a reboot, so now I can ssh to my myriad RPi4s by short name after reboots and suspends.

A: I had the exact same issue on Ubuntu 22.04. Netplan was configured to get its config from NetworkManager (Look at cat /etc/netplan/*.yaml). I ended up using nmcli like this :
$ sudo nmcli connection modify "Wired connection 1" ipv4.dns "10.24.1.119,8.8.8.8"

You can get the connection name using nmcli connection and check your modifications with nmcli connection show "Wired connection 1".
PS : Those modifications will be displayed on GUI Network settings.
Source : pimylifeup.com


Q: Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/Object in Redhat I am using Redhat 6. I am in strange problem.
I was working with java 1.6. I updated my system with yum updated automatically openjdk 1.8 got install. I removed the package fro UI.
Now when I typed java -version. I get this error
 Error occurred during initialization of VM
 java/lang/NoClassDefFoundError: java/lang/Object.

I thought my java is corrupted and I remove java using yum remove java*. Again I installed java.
I downloaded the bin file of java 1.6 and extracted it in my home folder. edited .bash_profile and gave the path.
run .bash_profile Using . .bash_profile
Now when I type
java -version I get

java version "1.6.0_45" Java(TM) SE Runtime Environment (build
  1.6.0_45-b06) Java HotSpot(TM) 64-Bit Server VM (build 20.45-b01, mixed mode)

but when i restart my system and again I type
java -version I get the same error saying
Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

How do i resolve it?


Q: Count how many arguments passed as positional If I have a function
def foo(x, y):
    pass

how can I tell, from inside the function, whether y was passed positionally or with its keyword?
I'd like to have something like
def foo(x, y):
    if passed_positionally(y):
        print('y was passed positionally!')
    else:
        print('y was passed with its keyword')

so that I get
>>> foo(3, 4)
y was passed positionally
>>> foo(3, y=4)
y was passed with its keyword

I realise I didn't originally specify this, but is it possible to do this whilst preserving type annotations? The top answer so far suggests using a decorator - however, that does not preserve the return type

A: You can create a decorator, like this:
def checkargs(func):
    def inner(*args, **kwargs):
        if 'y' in kwargs:
            print('y passed with its keyword!')
        else:
            print('y passed positionally.')
        result = func(*args, **kwargs)
        return result
    return inner

>>>  @checkargs
...: def foo(x, y):
...:     return x + y

>>> foo(2, 3)
y passed positionally.
5

>>> foo(2, y=3)
y passed with its keyword!
5

Of course you can improve this by allowing the decorator to accept arguments. Thus you can pass the parameter you want to check for. Which would be something like this:
def checkargs(param_to_check):
    def inner(func):
        def wrapper(*args, **kwargs):
            if param_to_check in kwargs:
                print('y passed with its keyword!')
            else:
                print('y passed positionally.')
            result = func(*args, **kwargs)
            return result
        return wrapper
    return inner

>>>  @checkargs(param_to_check='y')
...: def foo(x, y):
...:     return x + y

>>> foo(2, y=3)
y passed with its keyword!
5

I think adding functools.wraps would preserve the annotations, following version also allows to perform the check over all arguments (using inspect):
from functools import wraps
from inspect import signature

def checkargs(func):
    @wraps(func)
    def inner(*args, **kwargs):
        for param in signature(func).parameters:
            if param in kwargs:
                print(param, 'passed with its keyword!')
            else:
                print(param, 'passed positionally.')
        result = func(*args, **kwargs)
        return result
    return inner

>>>  @checkargs
...: def foo(x, y, z) -> int:
...:     return x + y

>>> foo(2, 3, z=4)
x passed positionally.
y passed positionally.
z passed with its keyword!
9

>>> inspect.getfullargspec(foo)
FullArgSpec(args=[], varargs='args', varkw='kwargs', defaults=None,
kwonlyargs=[], kwonlydefaults=None, annotations={'return': <class 'int'>})
                                             _____________HERE____________

Update Python 3.10
In Python 3.10+ new ParamSpec type annotation was introduced (PEP 612), for better specifying parameter types in higher-order functions. As of now, the correct way to annotate this decorator would be like this:
from functools import wraps
from inspect import signature
from typing import Callable, ParamSpec, TypeVar, TYPE_CHECKING

T = TypeVar("T")
P = ParamSpec("P")

def check_args(func: Callable[P, T]) -> Callable[P, T]:
    """
    Decorator to monitor whether an argument is passed
    positionally or with its keyword, during function call.
    """

    @wraps(func)
    def inner(*args: P.args, **kwargs: P.kwargs) -> T:
        for param in signature(func).parameters:
            if param in kwargs:
                print(param, 'passed with its keyword!')
            else:
                print(param, 'passed positionally.')
        return func(*args, **kwargs)

    return inner

Which correctly preserves type annotation:
if TYPE_CHECKING:
    reveal_type(foo(2, 3))

# ─❯ mypy check_kwd.py
# check_kwd.py:34: note: Revealed type is "builtins.int"
# Success: no issues found in 1 source file

A: Adapted from @Cyttorak 's answer, here's a way to do it which maintains the types:
from typing import TypeVar, Callable, Any, TYPE_CHECKING

T = TypeVar("T", bound=Callable[..., Any])

from functools import wraps
import inspect

def checkargs() -> Callable[[T], T]:
    def decorate(func):
        @wraps(func)
        def inner(*args, **kwargs):
            for param in inspect.signature(func).parameters:
                if param in kwargs:
                    print(param, 'passed with its keyword!')
                else:
                    print(param, 'passed positionally.')
            result = func(*args, **kwargs)
            return result
        return inner
    return decorate

@checkargs()
def foo(x, y) -> int:
    return x+y

if TYPE_CHECKING:
    reveal_type(foo(2, 3))
foo(2, 3)
foo(2, y=3)

Output is:
$ mypy t.py
t.py:27: note: Revealed type is 'builtins.int'

$ python t.py
x passed positionally.
y passed positionally.
x passed positionally.
y passed with its keyword!

A: It is not ordinarily possible. In a sense: the language is not designed to allow you to distinguish both ways.
You can design your function to take different parameters - positional, and named, and check which one was passed, in a thing like:
def foo(x, y=None, /, **kwargs):

    if y is None:
        y = kwargs.pop(y)
        received_as_positional = False
    else:
        received_as_positional = True

The problem is that, although by using positional only parameters as abov, you could get y both ways,
it would be shown not once for a user (or IDE) inspecting the
function signature.
I hav a feeling you just want to know this for the sake of knowing - if
you really intend this for design of an API, I'd suggest you'd rethink
your API - there should be no difference in the behavior, unless both
are un-ambiguously different parameters from the user point of view.
That said, the way to go would be to inspect the caller frame, and check
the bytecode around the place the function is called:

In [24]: import sys, dis

In [25]: def foo(x, y=None):
    ...:     f = sys._getframe().f_back
    ...:     print(dis.dis(f.f_code))
    ...:

In [26]: foo(1, 2)
  1           0 LOAD_NAME                0 (foo)
              2 LOAD_CONST               0 (1)
              4 LOAD_CONST               1 (2)
              6 CALL_FUNCTION            2
              8 PRINT_EXPR
             10 LOAD_CONST               2 (None)
             12 RETURN_VALUE
None

In [27]: foo(1, y=2)
  1           0 LOAD_NAME                0 (foo)
              2 LOAD_CONST               0 (1)
              4 LOAD_CONST               1 (2)
              6 LOAD_CONST               2 (('y',))
              8 CALL_FUNCTION_KW         2
             10 PRINT_EXPR
             12 LOAD_CONST               3 (None)
             14 RETURN_VALUE

So, as you can see, when y is called as named parameter, the opcode for the call is CALL_FUNCTION_KW , and the name of the parameter is loaded into the stack imediately before it.

A: You can trick the user and add another argument to the function like this:
def foo(x,y1=None,y=None):
  if y1 is not None:
    print('y was passed positionally!')
  else:
    print('y was passed with its keyword')

I don't recommend doing it but it does work

A: In foo, you can pass the call stack from traceback to positionally, which will then parse the lines, find the line where foo itself is called, and then parse the line with ast to locate positional parameter specifications (if any):
import traceback, ast, re
def get_fun(name, ast_obj):
    if isinstance(ast_obj, ast.Call) and ast_obj.func.id == name:
        yield from [i.arg for i in getattr(ast_obj, 'keywords', [])]
    for a, b in getattr(ast_obj, '__dict__', {}).items():
        yield from (get_fun(name, b) if not isinstance(b, list) else \
                        [i for k in b for i in get_fun(name, k)])

def passed_positionally(stack):
    *_, [_, co], [trace, _] = [re.split('\n\s+', i.strip()) for i in stack]
    f_name = re.findall('(?:line \d+, in )(\w+)', trace)[0]
    return list(get_fun(f_name, ast.parse(co)))

def foo(x, y):
    if 'y' in passed_positionally(traceback.format_stack()):
        print('y was passed with its keyword')
    else:
        print('y was passed positionally')

foo(1, y=2)

Output:
y was passed with its keyword

Notes:

*

*This solution does not require any wrapping of foo. Only the traceback needs to be captured.

*To get the full foo call as a string in the traceback, this solution must be run in a file, not the shell.

A: At the end, if you are going to do something like this:
def foo(x, y):
    if passed_positionally(y):
        raise Exception("You need to pass 'y' as a keyword argument")
    else:
        process(x, y)

You can do this:
def foo(x, *, y):
    pass

>>> foo(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes 1 positional argument but 2 were given

>>> foo(1, y=2) # works

Or only allow them to be passed positionally:
def foo(x, y, /):
    pass

>>> foo(x=1, y=2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got some positional-only arguments passed as keyword arguments: 'x, y'

>>> foo(1, 2) # works

See PEP 570 and PEP 3102 for more.


Q: When does the wave function collapse in the EPR paradox experiment? Shouldn't this depend on the reference frame? Suppose you have two entangled particles. Particle A, and Particle B.
If the spin of particle A is up, then the spin of particle B must be down and vice versa.
Now suppose you measure the spin of A at $(xA, tA)$, and measure the spin of B at $(xB, tB)$.
We usually say that the wave function collapsed at $t=tA$, if $tA<tB$ and at $t=tB$, if $tB<tA$.
However, in a different reference frame, if the separation between $(xA, tA)$ and $(xB, tB)$ is spacelike, $tA<tB$ or $tA>tB$ is not uniquely determined.
So, when exactly a wave function collapsed is not clear.

A: This is one of the things that shows that the collapse of the wavefunction is a problematic concept. Some say there isnt even a collapse. Its just that the measurements of both of the particles are correlated even though the individual measurements are completely random. This correlation is injected into the system when they become entangled, not when either A or B are measured. The bottom line is that the measurement on one of the particles is undetectable for some observer who only has access to the other particle. Only when the two observers exchange their information, the "spooky correlation" becomes visible.


Q: Changing from Linux Suse 11 to Win 7 x64 failed I bought a new laptop (HP ProBook 4540s, Intel Pentium B980, 4GB, DDR3 1333 MHz) which came with a Linux SUSE Enterprise. As this laptop is going to be used by a IT beginner, it has to run on Win 7.
So, for installing Win7, I did as I have done several times on my own laptop - booted from a Win7 DVD and followed the instructions it gave me. But after formatting the disks, the installing looked like it was doing fine until the first restart - then it gave a disk error ("Disk error, Press any key to restart") and when a key is pressed, it starts HP Advanced System Diagnostics, which is... useless.
I alse have tried using an USB for the installing (set the boot priorities accordingly on BIOS) but it just gave the same error.
So, if there is anyone who can help me based on this ambiguous description, I would be forever grateful :)

A: *

*Boot from the DVD again and try the following:

*Boot from the Windows 7 DVD

*Click Install Now & Accept License Agreement

*When the option is displayed to select an installation type, click (Custom Advanced)

*Click Drive Options

*Select the drives click Delete

*Click New

*Click Apply

*Click OK

*Click Format and click Next to proceed with the installation

try this & feedback here.

A: You probably want to have a look at at your partition table. You may have Windows arranged on a partition that the boot loader does not like, or possible MBR problems.
There are several LiveCD utilities with partition editors that will help you approach this. The partition editor in the Windows installer is really not a powerful tool, and hides much of the useful information.  As for a trustworthy tool, you might just want to grab an Ubuntu Live CD (64bit) and once running, fire up gparted, a partition table editor.
Posting information about your partition table will help rule out any problems there. Try removing all partitions if in doubt (remember to flush the changes before rebooting).  and then run the Windows DVD. Let the Windows installer set up the raw disk how it wants, and then maybe leave some room to put linux back on when Windows is finished.
Did you try to install Windows next to SuSe, or did you wipe the whole disk as per the Windows Installer?


Q: iOS app localization I want to localize my app. Should I create a new app in itunesconnect for each country or there is a way to automatically detect the country where user is? Actually my app is game based on Unity3d - is it possible to do it on Unity3d?

A: Before Unity starts write these lines to pass the current language into unity
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];

NSArray* languages = [defs objectForKey:@"AppleLanguages"];

NSString* preferredLang = [languages objectAtIndex:0];

[[NSUserDefaults standardUserDefaults] setObject: preferredLang forKey: @"language"];

[[NSUserDefaults standardUserDefaults] synchronize];

A: Definitely don't create a new app for each locale. iOS apps are localizable and iTunes Connect allows you to enter different metadata for each language.

A: You dont need to make a new app for each language. Try following a guide like SmoothLocalize's tutorial or This one.
Then you'll have a Localizable.strings file you need to translate. I usually use SmoothLocalize.com as my translation services, because its cheap and super easy, but you can look around for others or even try to find individual translators yourself.


Q: EF 4 - Lazy Loading Without Proxies I´ve read that proxies are used when wee need to use Lazy Loading and Change Tracking. In other words, to use Lazy Loading I must enable proxies.
So far so good.
the point is that I can use the code bellow to setup the context to not use a proxy and even yet use lazy loading.
ctx = new SchoolEntities();
ctx.ContextOptions.ProxyCreationEnabled = false;
ctx.ContextOptions.LazyLoadingEnabled = true;

Is the ProxyCreationEnabled property related only to change tracking proxy or am I missing something?
Could someone please explain this with some details?
Thanks!
EDIT1
I´m not using POCO/DbContext. I´m using a regular edmx EF model with ObjectContext. I know the importance of proxies for POCO entities regards to change tracking and lazy loading. By why to use Proxies in a regular EDMX model?

A: When using POCO entities with the built-in features of Entity Framework, proxy creation must be enabled in order to use lazy loading. So, with POCO entities, if ProxyCreationEnabled is false, then lazy loading won't happen even if LazyLoadingEnabled is set to true.
With certain types of legacy entities (notably those the derive from EntityObject) this was not the case and lazy loading would work even if ProxyCreationEnabled is set to false. But don't take that to mean you should use EntityObject entities--that will cause you more pain.
The ProxyCreationEnabled flag is normally set to false when you want to ensure that EF will never create a proxy, possibly because this will cause problems for the type of serialization you are doing.
The LazyLoadingEnabled flag is normally used to control whether or not lazy loading happens on a context-wide basis once you have decided that proxies are okay. So, for example, you might want to use proxies for change tracking, but switch off lazy loading.


Q: Custombox and modal using JS I have a modal using custombox that works using a button :

        <link href="assets/plugins/custombox/dist/custombox.min.css" rel="stylesheet">
        <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/core.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/components.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/icons.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/pages.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/menu.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/responsive.css" rel="stylesheet" type="text/css" />

                                                            Collapsible Group Item #1

                                                        test

  <button  data-toggle="modal" data-target="#accordion-modal">Accordion in Modal</button>

I am trying to initiate this modal inside jquery, inside a datatables button with no luck.
This is the part of the code in my function :
    buttons: [
      {
            text: 'My accordion Button',
            className: "btn-sm",
            action: function ( e, dt, node, config ) {
              Custombox.open({
                target: '#accordion-modal',
                effect: 'fadein'
     });
      e.preventDefault();
            }
        }
    ]

The code above works to open other simple modals but not this one. This has to do I guess with the
data-toggle="modal" data-target="#accordion-modal"

that is contained in the button. From what I understand the data-target is replaced by "target" in js, but the data-toggle is not triggered anywhere. How do I trigger it properly? I attempted to initiate it with $('#accordion-modal').modal('show') but I am not sure where exactly I should put this. If I put it in the beginning it just flashes for a second

A: Looks like I only needed :
  {
                text: 'My accordion Button',
                className: "btn-sm",
                action: function ( e, dt, node, config ) {
$('#accordion-modal').modal('show');

          e.preventDefault();
                }
            }


Q: Detecting when right mouse button was clicked only My table has 4 columns, and I only want column 1 to be allowed to be clicked. Also, this code also allows the LEFT mouse button to be used, I only want the RIGHT button.
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    int iCol = jTable1.getSelectedColumn();

    if(iCol == 1 && evt.getModifiers() == InputEvent.BUTTON3_MASK)
    {
        if(evt.getClickCount() == 2)
        {
            int iRow = jTable1.getSelectedRow();

            File iFile = new File(jTable1.getValueAt(iRow, iCol).toString());

            String iPath = iFile.getAbsolutePath();
            File iDir = new File(iPath.substring(0, iPath.lastIndexOf(File.separator)));

            if(Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().open(iDir);
                } catch (IOException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

I'm sorry if this question turned out as 2.

A: Lets start with, left button is normally represented by MouseEvent.BUTTON1, then move onto MouseEvent#getModifiers is usually used to provide information about what keys are currently pressed and we begin to see the major problems.
The method you really want is MouseEvent#getButton
Try run the following example for some ideas ;)
public class TestMouseClicked {

    public static void main(String[] args) {
        new TestMouseClicked();
    }

    public TestMouseClicked() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new MousePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MousePane extends JPanel {

        private JToggleButton leftButton;
        private JToggleButton middleButton;
        private JToggleButton rightButton;

        public MousePane() {
            setLayout(new GridBagLayout());

            leftButton = new JToggleButton("Left");
            middleButton = new JToggleButton("Middle");
            rightButton = new JToggleButton("Right");

            add(leftButton);
            add(middleButton);
            add(rightButton);

            ButtonGroup bg = new ButtonGroup();
            bg.add(leftButton);
            bg.add(middleButton);
            bg.add(rightButton);

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println(e.getButton());
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        leftButton.setSelected(true);
                    } else if (e.getButton() == MouseEvent.BUTTON2) {
                        middleButton.setSelected(true);
                    } else if (e.getButton() == MouseEvent.BUTTON3) {
                        rightButton.setSelected(true);
                    }
                }
            });

        }

    }

}

A: Concerning the clicking only of a specific column:

1. create the table using you own model.
final JTable table = new JTable( new MyTableModel(data, columnNames));

2. create the new model overriding the function you need (i.e. isCellEditable)
public class MyTableModel extends DefaultTableModel {

    private static final long serialVersionUID = -8422360723278074044L;

    MyTableModel(Object[][] data, Object[] columnNames )
    {
      super(data,columnNames);
    }

    public boolean isCellEditable(int row,int cols)
     {
       if(cols==1 ){return true;}
          return false;
     }
}