text:
Q: Nginx FPM PHP Ubuntu $_POST not being populated I have a server with NGNIX and PHP setup. The php script doesn't seem to have $_POST variable populated. I have checked the usual suspects, NGINX configuration, PHP.ini, etc. Not sure what I am doing wrong
location /ffc {
    include /etc/nginx/mime.types;
    index index.html index.php;
    root /var/www/;

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_script_name;
        fastcgi_pass_request_body on;
        fastcgi_pass_request_headers on;
        fastcgi_param REQUEST_BODY $request_body;
    }
}

<?php

   var_dump($HTTP_RAW_POST_DATA);
   var_dump($file= file_get_contents('php://input'));
   var_dump($_REQUEST);
   var_dump($GLOBALS);
   echo 'HEADERS <br/>';
   var_dump(get_headers());
?>

string(64) "fullname=test email=john@gmail.com message=dfadfsasdfas" array(0) { } array(8) { ["HTTP_RAW_POST_DATA"]=> string(64) "fullname=test email=john@gmail.com message=dfadfsasdfas" ["_GET"]=> array(0) { } ["_POST"]=> array(0) { } ["_COOKIE"]=> array(7) { ["uid"]=> string(24) "CqQw7lMQ9JNQwkpwAwMpAg==" ["_vis_opt_s"]=> string(2) "1|" ["_vis_opt_test_cookie"]=> string(1) "1" ["mp_f6e7292aa77905eaaf9137d271097d72_mixpanel"]=> string(144) "{"distinct_id": "1447a3b515f188-069aadc7a-1b10435d-1fa400-1447a3b51603ef","$initial_referrer": "$direct","$initial_referring_domain": "$direct"}" ["ip"]=> string(13) "" ["iso2"]=> string(0) "" ["iso3"]=> string(0) "" } ["_FILES"]=> array(0) { } ["GLOBALS"]=> RECURSION ["_SERVER"]=> array(41) { ["USER"]=> string(8) "www-data" ["HOME"]=> string(8) "/var/www" ["FCGI_ROLE"]=> string(9) "RESPONDER" ["QUERY_STRING"]=> string(0) "" ["REQUEST_METHOD"]=> string(4) "POST" ["CONTENT_TYPE"]=> string(10) "text/plain" ["CONTENT_LENGTH"]=> string(2) "64" ["SCRIPT_FILENAME"]=> string(34) "/var/www/test/ffc/sendmail.php" ["SCRIPT_NAME"]=> string(17) "/ffc/sendmail.php" ["REQUEST_URI"]=> string(17) "/ffc/sendmail.php" ["DOCUMENT_URI"]=> string(17) "/ffc/sendmail.php" ["DOCUMENT_ROOT"]=> string(17) "/var/www/test" ["SERVER_PROTOCOL"]=> string(8) "HTTP/1.1" ["GATEWAY_INTERFACE"]=> string(7) "CGI/1.1" ["SERVER_SOFTWARE"]=> string(12) "nginx/1.5.10" ["REMOTE_ADDR"]=> string(13) "" ["REMOTE_PORT"]=> string(4) "1572" ["SERVER_ADDR"]=> string(13) "" ["SERVER_PORT"]=> string(2) "80" ["SERVER_NAME"]=> string(12) "test.com" ["REDIRECT_STATUS"]=> string(3) "200" ["PATH_INFO"]=> string(17) "/ffc/sendmail.php" ["REQUEST_BODY"]=> string(64) "fullname=test email=john@gmail.com message=dfadfsasdfas" ["HTTP_HOST"]=> string(12) "test.com" ["HTTP_ACCEPT"]=> string(74) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8" ["HTTP_ACCEPT_ENCODING"]=> string(17) "gzip,deflate,sdch" ["HTTP_ACCEPT_LANGUAGE"]=> string(14) "en-US,en;q=0.8" ["HTTP_CACHE_CONTROL"]=> string(9) "max-age=0" ["HTTP_CONTENT_TYPE"]=> string(10) "text/plain" ["HTTP_COOKIE"]=> string(344) "uid=CqQw7lMQ9JNQwkpwAwMpAg==; _vis_opt_s=1%7C; _vis_opt_test_cookie=1; mp_f6e7292aa77905eaaf9137d271097d72_mixpanel=%7B%22distinct_id%22%3A%20%221447a3b515f188-069aadc7a-1b10435d-1fa400-1447a3b51603ef%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%7D; ip=; iso2=; iso3=" ["HTTP_ORIGIN"]=> string(19) "http://test.com" ["HTTP_REFERER"]=> string(36) "http://test.com/ffc/contact.html" ["HTTP_USER_AGENT"]=> string(120) "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36" ["HTTP_X_FORWARDED_FOR"]=> string(14) "192.195.83.183" ["HTTP_X_FORWARDED_PORT"]=> string(2) "80" ["HTTP_X_FORWARDED_PROTO"]=> string(4) "http" ["HTTP_CONTENT_LENGTH"]=> string(2) "64" ["HTTP_CONNECTION"]=> string(10) "keep-alive" ["PHP_SELF"]=> string(17) "/ffc/sendmail.php" ["REQUEST_TIME_FLOAT"]=> float(1394500698.6063) ["REQUEST_TIME"]=> int(1394500698) } ["_REQUEST"]=> array(0) { } } HEADERS
NULL POST
array(0) { }


text:
Q: Partial differentiability on a piecewise function Given $M=\{(x,x)\in\mathbb{R}^2 : x\neq 0\}$ and the function
$$f(x,y)=   \left\{\begin{matrix}
 e^x+1\;\;\;  \forall  (x,y)\in M \\
 0\;\;\;  \forall  (x,y)\notin  M.
\end{matrix}\right.$$
Prove that: $f$ is partially differentiable iff $(x,y)\notin M$.
Question: Supposing that the function is partially differentiable in $M$ as operations of partially differentiable functions (I differentiate with respect to $x$, as I've seen in many other exercises, without going by definition with the limit to see if $f$ is partially differentiable..., so I have this:) $\frac{\partial f}{\partial x}(x,x)=e^x$. But when I try going by the definition
$$\frac{\partial f}{\partial x}(x,x)= \lim\frac{f(x+h,x)-f(x,x)}{h} = \lim   \frac{(1-e^x)}{h},$$
where $h \to 0$, and that limit doesn't exist. So the first way must be wrong. But why? (I've seen exercises where a piecewise $f$ has a more complicated type and $f$ is partially differentiated with respect to a variable without the need checking the limit, it's like assuming from the start that in a set $f$ is partially differentiable. Why doesn't it work here?)

A: Your idea that "The function is partially differentiable in M as operations of partially differentiable functions" is incorrect.  You need to have an open interval in which the function is constructed from "partially differential functions" in order to use that and that that is not true here.
Your second calculation, that the partial derivatives do not exist, is correct.
Taking point $(x_0, x_0)$ in M, $f(x_0, x_0)= e^{x_0}+ 1$ while, for any positive h, $f(x_0+ h, x_)= 0$.  The partial derivative with respect to x would be given by $\lim_{h\to 0}\frac{f(x_0+h, x_0)- f(x_0,x_0)}{h}= \lim_{h\to 0}\frac{e^{x_0+ h}+1- 0}{h}$ which, as you say, does not exist.
Of course, the same argument applies to the partial derivative with respect to y.
This function is differentiable for off M (and the derivatives are 0) and is not differentiable on M.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Material Spinner (AutoCompleteTextView) - catch outside clicks When using a spinner, it's the default behaviour that clicks outside of the spinner close the spinner but are NOT handled by the view underneath the click.
When switching to TextInputLayout + AutoCompleteTextView this behaviour is different, clicking on something outside the "spinner" closes the spinner AND the view underneath the touch does get the click event as well - this is very annoying and imho unexpected.
Can I somehow disable this behaviour to get the same behaviour as I get when using an old spinner?

A: Unfortunately no chances to catch the touch outside event using setOnDismissListener or dismissDropDown(); the latter gets called when item is selected.
But that would be possible by registering OnDismissListener on the instance of the inner popup window of the AutoCompleteTextView which is of type ListPopupWindow through reflections:
private fun getPopup(): ListPopupWindow? {
    try {
        val field = AutoCompleteTextView::class.java.getDeclaredField("mPopup")
        field.isAccessible = true
        return field.get(this) as ListPopupWindow
    } catch (e: NoSuchFieldException) {
        e.printStackTrace()
    } catch (e: IllegalAccessException) {
        e.printStackTrace()
    }
    return null
}

Hopefully, the documentation can solve this to avoid this anti-pattern.
The OnDismissListener callback gets called on any type of dismissal of the menu; either clicking on items, touching outside the AutoCompleteTextView or hitting the soft keyboard back button. This can be distinguished by tagging the ACTT with the appropriate flag for each event; an enum is used for that in the below customized class):
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewTreeObserver
import android.widget.AdapterView
import android.widget.AutoCompleteTextView
import android.widget.ListPopupWindow
import androidx.appcompat.widget.AppCompatAutoCompleteTextView

class TouchOutsideAutoCompleteTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatAutoCompleteTextView(context, attrs), AdapterView.OnItemClickListener {

    init {

        super.setOnItemClickListener(this)

        viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
                    viewTreeObserver
                        .removeOnGlobalLayoutListener(this)
                else
                    viewTreeObserver
                        .removeGlobalOnLayoutListener(this)

                // Registering the mPopup window OnDismissListener
                adjustTouchOutside()
            }

        })

    }

    private var consumerListener: AdapterView.OnItemClickListener? = null

    private enum class DismissEvent {
        ON_ITEM_CLICK, // Should be set to enable the next touch dispatch event whenever the dismiss is due to a click on the menu item.
        ON_TOUCH_OUTSIDE, // Should be set to disable the next touch dispatch event whenever the dismiss is due to a touch outside the menu.
        ON_BACK_PRESSED // Should be set to enable the next touch dispatch event whenever the dismiss is due to the software keyboard back button pressed.
    }

    /*
    * Called globally on any touch on the screen to consume the event if it returns true
    * */
    fun isDismissByTouchOutside() = tag == DismissEvent.ON_TOUCH_OUTSIDE

    private fun isDismissByItemClickOrBackPressed() =
        tag == DismissEvent.ON_ITEM_CLICK || tag == DismissEvent.ON_BACK_PRESSED

    private fun setDismissToItemClick() {
        tag = DismissEvent.ON_ITEM_CLICK
    }

    private fun setDismissToTouchOutside() {
        tag = DismissEvent.ON_TOUCH_OUTSIDE
    }

    private fun setDismissToBackPressed() {
        tag = DismissEvent.ON_BACK_PRESSED
    }

    fun clearDismissEvent() {
        tag = null
    }

    @SuppressLint("DiscouragedPrivateApi")
    private fun getPopup(): ListPopupWindow? {
        try {
            val field = AutoCompleteTextView::class.java.getDeclaredField("mPopup")
            field.isAccessible = true
            return field.get(this) as ListPopupWindow
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
        return null
    }

    private fun adjustTouchOutside() {
        getPopup()?.let {
            it.setOnDismissListener {
                if (isDismissByItemClickOrBackPressed()) {// Menu dismissal Event of clicking on the menu item or hitting the software back button
                    clearDismissEvent() // Neutralize the enum to allow the next touch dispatch event & for adding a chance of next dismissal decision

                } else {  // Menu dismissal Event of touching outside the menu
                    // Don't allow the next touch dispatch event
                    setDismissToTouchOutside()
                }
            }
        }
    }

    override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
        setDismissToItemClick()
        consumerListener?.onItemClick(p0, p1, p2, p3)
    }

    override fun setOnItemClickListener(l: AdapterView.OnItemClickListener?) {
        // DO NOT CALL SUPER HERE
//        super.setOnItemClickListener(l)
        consumerListener = l
    }

    override fun onKeyPreIme(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && isPopupShowing)
            setDismissToBackPressed()
        return super.onKeyPreIme(keyCode, event)
    }

}

The usage
Overriding dispatchTouchEvent() in the activity is required to consume the event for touching outside by checking isTouchOutsideDisabled(); and neutralize the dismissal event:
If the AutoCompleteTextView is in the activity then:
lateinit var autoCTV: TouchOutsideAutoCompleteTextView

override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
    if (autoCTV.isDismissByTouchOutside()) {
        autoCTV.clearDismissEvent()
        return true
    }
    return super.dispatchTouchEvent(ev)
}

If it is in some fragment, then the dispatchTouchEvent() need to have access to it:
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {

    val fragment = supportFragmentManager.findFragmentByTag("MyFragmentTag") as MyFragment

    if (fragment.autoCTV.isDismissByTouchOutside()) {
        fragment.autoCTV.clearDismissEvent()
        return true
    }
    return super.dispatchTouchEvent(ev)
}


text:
Q: Select only the most nested list item with specific class I need to select only the the deepest li.active in the ul structure. In this case that would be Další kategorie. I cannot find css only solution. Is it even possible? Thanks.

PŘEDSEDNICTVO

KOMISE

Kategorie

Další kategorie
 // I'need to select only this element (current page)

KONTAKTY

REPREZENTACE

A: When it is static structure then this selector should do the job:
.smenu > ul > li > ul > li.active {
    /* your rules */
}

A: simply
nav.smenu ul li ul li.active

A: Update:
This is currently not possible only via CSS. Children cannot affect thei parents. It will be possible once CSS4 :has() selector gets from working draft to specification and browsers starts implementing it. Current state: https://drafts.csswg.org/selectors-4/#relational

Original answer:
Ok, if it's not possible only via CSS, that's how I would do it:
$('li.active:not(:has(li.active))').addClass('deepest');

A: I'm not sure if this was available at the time of the OP, but this works just as well as the accepted answer without the :has operator:
$('.smenu').find('li.active').last().addClass('deepest')

Assuming only one nested path is active at once.


text:
Q: How I can write a function that will display the path in the Browser Console I want to write a function that will display the path in the Browser Console when I click on a link of the menu on the sub-category, the menu looks like this (https://www.sephora.fr/) in this e-commerce website
For example : Parfum => ForMen => Cologne
How to get the path when I click on Cologne
Thanks

A: If you're just looking to get the path without the domain name, you can use this:
function getUrlWithoutDomain() {
   return window.location.pathname;
}

If the domain name is also important, this will get you the full url:
function getFullUrl() {
   return window.location.href;
}

A: Not sure if this is what you are looking for, but this will return the relative path for the website whenever an anchor tag is clicked on.
const anchors = document.querySelectorAll('a');

anchors.forEach(el => el.addEventListener('click', event => {
  console.log(event.target.getAttribute("href"));
}));

Also check out JavaScript click event listener on class for a similar question.


text:
Q: Restrict length of log output in Rails I have an API that accepts base64 encoded images. The requests come in looking like:
{
  image: "ijt41ig8ahbha8oij4j1tjletc"
}

The base64 encoded strings can be very large, sometimes 10k - 100k characters. When a request is sent with improperly formatted JSON, Active Dispatch correctly raises an error and logs the request:
ActionDispatch::ParamsParser::ParseError (765: unexpected token at '{
    "image": "iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ
    iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ
    iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ
    iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ"
}'):
actionpack (5.0.5) lib/action_dispatch/http/parameters.rb:88:in `rescue in parse_formatted_parameters'
actionpack (5.0.5) lib/action_dispatch/http/parameters.rb:82:in `parse_formatted_parameters'
actionpack (5.0.5) lib/action_dispatch/http/request.rb:354:in `block in POST'

etc

In this case the error is caused by new lines in the encoding.
My question is, what is a good way to restrict the logging to not display the sometimes 50k char long image string? This is filling up my log files and making looking through logs difficult. I do want the error logged, I just want to slice the string to maybe show the first 255 chars instead of the massive image.
I know that ActionDispatch has some nice ways of filtering attributes (for instance passwords), but that assumes that the parameters have been parsed into a hash, which in the case of a JSON error they have not.

A: I ended up creating a custom formatter and just manipulating the string directly
class CustomFormatter < Logger::Formatter

  def call(severity, time, program_name, message)
    if message =~ /"image": /
      message.gsub!(/(?<="image": )".+"/m) { |image| image[0..255]  + "_TRUNCATED_" }
    end

    super
  end

end

Then just use that formatter in your config file
  config.logger = Logger.new(STDOUT).tap do |logger|
    logger.formatter = CustomFormatter.new
  end


text:
Q: extracting substring before a random numeric value: Xpath/XSLT I have following string:  /abc/xyz/asdsd/sdfggf/10203940:40:50:/etc/oa.setup009
I need to extract string /abc/xyz/asdsd/sdfggf/  The numeric value after this string is dynamic, any possible way to iterate from left to right and moment you get number, you keep the sub-string before that.
Thanks in Advance

A: To extract the substring before the first digit in the given string, you can use:
substring-before(translate($string, '123456789', '0'), '0')

Note that if the given string contains no digits, the result will be an empty string.


text:
Q: FB api /me/accounts returns empty array on 1 website and not the other I maintain 2 websites and each company has an FB page. I'm trying to have them create events on fb from their website.
I used EXACTLY the same code for each with the exception of an include that has the ap_id, secret key, and page id. I have set up the fb ap the same except for the app domain and the url.
One works and the other gets a permission error.
When I add
$accounts = $facebook->api("/me/accounts");

and
$me = $facebook->api("/me");

and do a PRINT_R of each, the $me is exactly the same but the $accounts is empty on the site that gets the permission error.
The site that works, shows all the pages that I'm an admin for including the one that doesn't work. I can manually create an event on that fb page.
What am I missing?


text:
Q: Java Swing - Nimbus L&F overrides custom icon in JTable header after sort is applied I'm trying to create a custom cell renderer that will display an image in JTable's header cell. I've gotten the source code to work with the Metal L&F but I am encountering problems with Nimbus. Under normal circumstances, Nimbus displays the image just fine. However, when a table is sorted, Nimbus will draw the sort icon instead of the icon I've specified. This is different than the Metal L&F, as that will always draw the icon I've provided.

Does anyone know of a way to have Nimbus draw the image even if a column is sorted?
I'm using Java 6.29 & Nimbus. I can't change the Java release or the L&F.
Also, I've tried to do some other workarounds, like changing the label to use HTML and and img tag to display the image, but this produces a weird visual effect. EDIT The text and image aren't aligned well (even with a HTML align tag on the img tag) Here is a picture, notice how the text in the Temp Hi column doesn't align:

import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

public class ImageChangeDemo extends JFrame {
    public static void main(String args[]) {
        //comment out the code below to try in Metal L&F
        try {
            for(javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.
                    getInstalledLookAndFeels()) {
                if("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ImageChangeDemo().setVisible(true);
            }
        });
    }

    public ImageChangeDemo(){
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        JScrollPane pane = new javax.swing.JScrollPane();
        JTable table = new javax.swing.JTable();
        table.setAutoCreateRowSorter(true);
        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"a", "q", "h", "v"},
                {"b", "m", "l", "h"},
                {"d", "c", "a", "d"},
                {"j", "o", "y", "e"}
            },
            new String [] {
                "Col 1", "Col 2", "Col 3", "Col 4"
            }
        ) {
            Class[] types = new Class [] {
                String.class, String.class, String.class, String.class
            };
            @Override
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        pane.setViewportView(table);
        this.add(pane);

        table.getTableHeader().setDefaultRenderer(new ImageRenderer(table));

        pack();
    }

    public class ImageRenderer extends DefaultTableCellRenderer{
        TableCellRenderer orig;
        ImageIcon icon;
        ImageRenderer(JTable table){
            orig = table.getTableHeader().getDefaultRenderer();
        }
        @Override
        public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component c =
                    orig.getTableCellRendererComponent(
                        table, value, isSelected, hasFocus, row, column);
            if(c instanceof JLabel){
                if(true){
                    JLabel label = (JLabel)c;
                    label.setIcon(makeIcon());
                }
            }
            return c;
        }

        public ImageIcon makeIcon(){
            if(icon == null)
            icon = new ImageIcon(
                    ImageChangeDemo.class.getResource("/resources/green_triangle_down.png"));
            return icon;
        }
    }
}

EDIT: Here is an example scenario of what my real application should do: If the table column contains certain data (such as any strings beginning with a certain word) display a warning icon next to the column name in the table header. I've gotten this to work fine. Now, if the user sorts a column with the image, Nimbus is removing the image and replacing it with a sort icon - I still want the original warning icon to display.

A: *

*don't recreate an Icon inside Renderer, prepare that before, otherwise you'll recreating Icon in the crazy periods

*not to add Icon to the Component / JComponent / JLabel returns Renderer

*put to the Renderer
code made by Darryl or Rob
protected Icon getIcon(JTable table, int column) {
    SortKey sortKey = getSortKey(table, column);
    if (sortKey != null && table.convertColumnIndexToView(
        sortKey.getColumn()) == column) {
        switch (sortKey.getSortOrder()) {
            case ASCENDING:
                return UIManager.getIcon("Table.ascendingSortIcon");
            case DESCENDING:
                return UIManager.getIcon("Table.descendingSortIcon");
        }
    }
    return null;
}

EDIT
thank to Renderer by @trashgod, UNSORTED isn't required to override for Renderer, try & enjoy
initial view

ASCENDING

DESCENDING

UNSORTED

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.UIManager;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class ImageChangeDemo extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table = new javax.swing.JTable();

    public static void main(String args[]) {
        //comment out the code below to try in Metal L&F
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ImageChangeDemo().setVisible(true);
            }
        });
    }

    public ImageChangeDemo() {
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        JScrollPane pane = new javax.swing.JScrollPane();

        table.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                    {"a", "q", "h", "v"},
                    {"b", "m", "l", "h"},
                    {"d", "c", "a", "d"},
                    {"j", "o", "y", "e"}
                },
                new String[]{
                    "Col 1", "Col 2", "Col 3", "Col 4"
                }) {

            private static final long serialVersionUID = 1L;
            Class[] types = new Class[]{
                String.class, String.class, String.class, String.class
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }
        });
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel()) {

            @Override
            public void toggleSortOrder(int column) {
                if (column >= 0 && column < getModelWrapper().getColumnCount() && isSortable(column)) {
                    List<SortKey> keys = new ArrayList<SortKey>(getSortKeys());
                    if (!keys.isEmpty()) {
                        SortKey sortKey = keys.get(0);
                        if (sortKey.getColumn() == column && sortKey.getSortOrder() == SortOrder.DESCENDING) {
                            setSortKeys(null);
                            return;
                        }
                    }
                }
                super.toggleSortOrder(column);
            }
        };
        table.setRowSorter(sorter);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        table.setDefaultRenderer(ImageChangeDemo.class, new HeaderRenderer(table));
        pane.setViewportView(table);
        add(pane);
        pack();
    }

    class HeaderRenderer implements TableCellRenderer {

       final TableCellRenderer renderer;

        public HeaderRenderer(JTable table) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }

        @Override
        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int col) {
            return renderer.getTableCellRendererComponent(
                    table, value, isSelected, hasFocus, row, col);
        }

        public Icon getIcon(JTable table, int column) {
            for (RowSorter.SortKey sortKey : table.getRowSorter().getSortKeys()) {
                if (sortKey.getColumn() == column) {
                    switch (sortKey.getSortOrder()) {
                        case ASCENDING:
                            return (UIManager.getIcon("Table.ascendingSortIcon"));
                        case DESCENDING:
                            return (UIManager.getIcon("Table.descendingSortIcon"));
                    }
                }
            }
            return null;
        }
    }
}

EDIT 2
then to set Icon directly to the UIManager

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowSorter.SortKey;
import javax.swing.SortOrder;
import javax.swing.UIManager;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class ImageChangeDemo extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table = new javax.swing.JTable();

    public static void main(String args[]) {
        //comment out the code below to try in Metal L&F
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    UIManager.getLookAndFeelDefaults().put("Table.ascendingSortIcon", new BevelArrowIcon(BevelArrowIcon.UP, false, false));
                    UIManager.getLookAndFeelDefaults().put("Table.descendingSortIcon", new BevelArrowIcon(BevelArrowIcon.DOWN, false, false));
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ImageChangeDemo().setVisible(true);
            }
        });
    }

    public ImageChangeDemo() {
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        JScrollPane pane = new javax.swing.JScrollPane();
        //table.setAutoCreateRowSorter(true);
        table.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                    {"a", "q", "h", "v"},
                    {"b", "m", "l", "h"},
                    {"d", "c", "a", "d"},
                    {"j", "o", "y", "e"}
                },
                new String[]{
                    "Col 1", "Col 2", "Col 3", "Col 4"
                }) {

            private static final long serialVersionUID = 1L;
            Class[] types = new Class[]{
                String.class, String.class, String.class, String.class
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }
        });
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel()) {

            @Override
            public void toggleSortOrder(int column) {
                if (column >= 0 && column < getModelWrapper().getColumnCount() && isSortable(column)) {
                    List<SortKey> keys = new ArrayList<SortKey>(getSortKeys());
                    if (!keys.isEmpty()) {

                        SortKey sortKey = keys.get(0);
                        if (sortKey.getColumn() == column && sortKey.getSortOrder() == SortOrder.DESCENDING) {
                            setSortKeys(null);
                            return;
                        }
                    }
                }
                super.toggleSortOrder(column);
            }
        };
        table.setRowSorter(sorter);
        //table.getTableHeader().setDefaultRenderer(new DefaultTableHeaderCellRenderer());
        //table.setDefaultRenderer(ImageChangeDemo.class, new HeaderRenderer(table));
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        pane.setViewportView(table);
        add(pane);
        pack();
    }

   static class BevelArrowIcon implements Icon {

        public static final int UP = 0;         // direction
        public static final int DOWN = 1;
        private static final int DEFAULT_SIZE = 11;
        private Color edge1;
        private Color edge2;
        private Color fill;
        private int size;
        private int direction;

        public BevelArrowIcon(int direction, boolean isRaisedView, boolean isPressedView) {
            if (isRaisedView) {
                if (isPressedView) {
                    init(UIManager.getColor("controlLtHighlight"), UIManager.getColor("controlDkShadow"), UIManager.getColor("controlShadow"), DEFAULT_SIZE, direction);
                } else {
                    init(UIManager.getColor("controlHighlight"), UIManager.getColor("controlShadow"), UIManager.getColor("control"), DEFAULT_SIZE, direction);
                }
            } else {
                if (isPressedView) {
                    init(UIManager.getColor("controlDkShadow"), UIManager.getColor("controlLtHighlight"), UIManager.getColor("controlShadow"), DEFAULT_SIZE, direction);
                } else {
                    init(UIManager.getColor("controlShadow"), UIManager.getColor("controlHighlight"), UIManager.getColor("control"), DEFAULT_SIZE, direction);
                }
            }
        }

        public BevelArrowIcon(Color edge1, Color edge2, Color fill, int size, int direction) {
            init(edge1, edge2, fill, size, direction);
        }

        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            switch (direction) {
                case DOWN:
                    drawDownArrow(g, x, y);
                    break;
                case UP:
                    drawUpArrow(g, x, y);
                    break;
            }
        }

        @Override
        public int getIconWidth() {
            return size;
        }

        @Override
        public int getIconHeight() {
            return size;
        }

        private void init(Color edge1, Color edge2, Color fill, int size, int direction) {
            edge1 = Color.red;
            edge2 = Color.blue;
            this.edge1 = edge1;
            this.edge2 = edge2;
            this.fill = fill;
            this.size = size;
            this.direction = direction;
        }

        private void drawDownArrow(Graphics g, int xo, int yo) {
            g.setColor(edge1);
            g.drawLine(xo, yo, xo + size - 1, yo);
            g.drawLine(xo, yo + 1, xo + size - 3, yo + 1);
            g.setColor(edge2);
            g.drawLine(xo + size - 2, yo + 1, xo + size - 1, yo + 1);
            int x = xo + 1;
            int y = yo + 2;
            int dx = size - 6;
            while (y + 1 < yo + size) {
                g.setColor(edge1);
                g.drawLine(x, y, x + 1, y);
                g.drawLine(x, y + 1, x + 1, y + 1);
                if (0 < dx) {
                    g.setColor(fill);
                    g.drawLine(x + 2, y, x + 1 + dx, y);
                    g.drawLine(x + 2, y + 1, x + 1 + dx, y + 1);
                }
                g.setColor(edge2);
                g.drawLine(x + dx + 2, y, x + dx + 3, y);
                g.drawLine(x + dx + 2, y + 1, x + dx + 3, y + 1);
                x += 1;
                y += 2;
                dx -= 2;
            }
            g.setColor(edge1);
            g.drawLine(xo + (size / 2), yo + size - 1, xo + (size / 2), yo + size - 1);
        }

        private void drawUpArrow(Graphics g, int xo, int yo) {
            g.setColor(edge1);
            int x = xo + (size / 2);
            g.drawLine(x, yo, x, yo);
            x--;
            int y = yo + 1;
            int dx = 0;
            while (y + 3 < yo + size) {
                g.setColor(edge1);
                g.drawLine(x, y, x + 1, y);
                g.drawLine(x, y + 1, x + 1, y + 1);
                if (0 < dx) {
                    g.setColor(fill);
                    g.drawLine(x + 2, y, x + 1 + dx, y);
                    g.drawLine(x + 2, y + 1, x + 1 + dx, y + 1);
                }
                g.setColor(edge2);
                g.drawLine(x + dx + 2, y, x + dx + 3, y);
                g.drawLine(x + dx + 2, y + 1, x + dx + 3, y + 1);
                x -= 1;
                y += 2;
                dx += 2;
            }
            g.setColor(edge1);
            g.drawLine(xo, yo + size - 3, xo + 1, yo + size - 3);
            g.setColor(edge2);
            g.drawLine(xo + 2, yo + size - 2, xo + size - 1, yo + size - 2);
            g.drawLine(xo, yo + size - 1, xo + size, yo + size - 1);
        }
    }
}

A: So after much trial and error I was able to figure out a way to have my custom icon in the header row even if the column is sorted. Basically what I did was have the renderer return a custom panel containing 2 children, the image in a JLabel and the component that was originally produced by default renderer. (Note that this workaround is only necessary for Nimbus L&F, and the original example code works fine in the Metal L&F)
This code uses StackLayout created by Romain Guy as demonstrated in his book Filthy Rich Clients - see page p245. Here is the source for StackLayout
Here is the code I created for the renderer. Make sure to download StackLayout else this won't compile.
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

public class ImageChangeDemo extends JFrame {
    public static void main(String args[]) {
        //comment out the code below to try in Metal L&F
        try {
            for(javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.
                    getInstalledLookAndFeels()) {
                if("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ImageChangeDemo().setVisible(true);
            }
        });
    }

    public ImageChangeDemo(){
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        JScrollPane pane = new javax.swing.JScrollPane();
        JTable table = new javax.swing.JTable();
        table.setAutoCreateRowSorter(true);
        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"a", "q", "h", "v"},
                {"b", "m", "l", "h"},
                {"d", "c", "a", "d"},
                {"j", "o", "y", "e"}
            },
            new String [] {
                "Col 1", "Col 2", "Col 3", "Col 4"
            }
        ) {
            Class[] types = new Class [] {
                String.class, String.class, String.class, String.class
            };
            @Override
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        pane.setViewportView(table);
        this.add(pane);

        pack();
        //set renderer after pack so header row has correct default height
        table.getTableHeader().setDefaultRenderer(new ImageRenderer(table));

    }

    public class ImageRenderer extends DefaultTableCellRenderer{
        TableCellRenderer orig;
        private final ImageIcon icon = new ImageIcon(
                    ImageChangeDemo.class.getResource("/resources/exclamation-icon.png"));;
        private JPanel jp = new JPanel(new StackLayout());
        private final JLabel pic = new JLabel(icon);
        { //extra initialization for PIC
            pic.setHorizontalAlignment(JLabel.LEADING); //so it isn't centered in stack layout
        }

        ImageRenderer(JTable table){
            orig = table.getTableHeader().getDefaultRenderer();
        }

        @Override
        public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component c =
                    orig.getTableCellRendererComponent(
                        table, value, isSelected, hasFocus, row, column);
            if(true){
                int width  = table.getColumnModel().getColumn(column).getWidth();
                int height = table.getTableHeader().getSize().height;
                System.out.println("height"+height);

                jp.removeAll();                //clean the JPanel

                //move text in label to the left so it isn't covered by the icon
                if(c instanceof JLabel){
                    JLabel l = (JLabel) c;
                    l.setPreferredSize(new Dimension(width, height));

                    FontMetrics fontMetrics = l.getFontMetrics(l.getFont());
                    int sizeOfSpace = fontMetrics.charWidth(' ');
                    int numSpaces = (int)Math.round(icon.getIconWidth() / (double)sizeOfSpace);
                    StringBuilder sb = new StringBuilder();
                    for(int i = 0; i < numSpaces; i++)
                        sb.append(' ');

                    //account for HTML in header messages
                    if(l.getText().toLowerCase().startsWith("<html>")){
                        l.setText(  l.getText().substring(0, "<html>".length()) +
                                    sb.toString() +
                                    l.getText().substring("<html>".length()));
                    }
                    else
                        l.setText(sb.toString()+l.getText());
                }

                //Add components to the JPanel & return it.
                jp.add(c, StackLayout.BOTTOM);  //will contain modifications for spacing.
                jp.add(pic, StackLayout.TOP);
                return jp;

            }
            else
                return c;
        }
    }
}


text:
Q: Off the shelf discriminative reranking software Is there existing software for discriminative reranking, such as that used by the Charniak NLP parser, Shen, Sarkar, and Och's parser or Shen and Joshi's techniques? I'd like something that I can easily adapt for my own uses, which are similar to parse reranking.

A: Charniak-Johnson Reranking
The source code for the Charniak-Johnson (CJ) reranking parser is freely available, you can download a copy here.
The reranker is a separate code module that takes as input n-best lists of parses, so it's trivial to decouple it from the parsing front end.
SVM-rank
Alternatively, the package SVM-rank, from Thorsten Joachim's lab at Cornell, is a general purpose ranker. It might be easier to go with this package, if what you want to do deviates significantly from what's being done by the Charniak-Johnson parser.


text:
Q: Is script src=//example.com/file.js valid? Is it valid to do:
<script src="//example.com/file.js" />

instead of
<script src="http://example.com/file.js" />

or
<script src="https://example.com/file.js" />

The first is given as an example in facebook's documentation, and I'm wondering if its valid and if so, which browsers support it (all, or only the most recent, etc).

A: That's called a protocol-relative URL.
It will become HTTP or HTTPS, depending on the protocol of the current page.
It works in all browsers.

A: Yes, it's valid and it works too! This is what's called a Protocol Relative URL, which will use http:// or https:// based on the current page protocol.


text:
Q: Post slugs colliding with page links php I am working on a music blog and using htaccess for url rewriting but am having issues with page links colliding with artist links coz i want the artist link to be like https://eachamps.com/artistname. But am in a situation where even page links like http://eachamps.com/audios are being seen as artist links.
A solution to my problem shall be highly appreciated
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^([^/]*)/?$ artist.php?artist=$1 [L]

I want to stop the collision between the page links and post slugs


text:
Q: Serverless Cognito User Pool authorizer I want to use my Cognito User Pool as the authorizer for all my lambda functions deployed through the Serverless Framework and API Gateway.
The Serverless docs mention that this is possible as follows, which exposes claims at event.requestContext.authorizer.claims:
functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          authorizer:
            arn: arn:aws:cognito-idp:us-east-1:xxx:userpool/us-east-1_ZZZ
            scopes:
              - my-app/read

Or, if you want more control of which attributes are exposed as claims, use the following implementation which exposes claims at events.cognitoPoolClaims:
functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          integration: lambda
          authorizer:
            arn: arn:aws:cognito-idp:us-east-1:xxx:userpool/us-east-1_ZZZ
            claims:
              - email
              - nickname

I have a few questions about this and I'm attempting to find the answers online, but the terms are all commonly-used and it's hard to know what to search for and recognize the correct answer. The docs also seem to show a few examples, but never specifies all the available options (as far as I've seen). I'd appreciate some clarification on the following or a link to the docs where it may explain some of this in more detail:

*

*What scopes are available? (e.g. scopes: my-app/read)

*What is the difference between exposing the claims at event.requestContext.authorizer.claims vs events.cognitoPoolClaims?

*Will this implementation work with httpApi functions, instead of http like the docs show?


text:
Q: How to show alert dialog box if page is switched in bottom navigation bar in flutter Currently I am working on flutter project in which I have used bottom navigation bar and in one of the pages I have a form in which information needs to fill. In this case if the user switches to another page after filling  information and does not submit it, I want to show dialog box to user that "You have information filled leaving this page will discard the info". Please help.
I have tried WillPopScope widget but it only works when you press back button I want to show dialog box when the text fields are filled but not submitted and without submitting user tries to switch to another page.

A: In the onTap callback, check if the Navbar Item index is not equal to the Item which contains the form. If it is different, show the dialog and await its response.
  void _onItemTapped(int index) async {
   if(_selectedIndex == formItemIndex && index != formItemIndex)
    {
       // await showDialog();
    }
    setState(() {
      _selectedIndex = index;
    });
  }

BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      )


text:
Q: Trouble changing object value in page, but shows up in console log as working (angularjs) I want to change an object variable mF depending on what the user clicks, which will assign an object from an array of objects to the variable mF, and also take them to the next "page".
I am using ng-click to assign the objects to mf through a function. I'm using {{ mF.name }} to test if a new object has been assigned to mF and I keep drawing a blank (nothing outputs to page). However, when I assign the object manually within the controller and output using console.log(), it's working. Why is it not outputting to the page?
Code:
app.js:
app.controller('DeviceController', function($scope) {

$scope.showOptions = false;

var device1 = [
    {
        name: 'PC',
        os: 'Windows',
        chosen: false,
    },
  ...
  ];

var device2 = [
  {...}
  ...
];

var mF = {};

$scope.mF = mF;

console.log(mF);

function calculate (x) {
    mF = device1[x];
}

mF = device1[0];

console.log(mF.name); //outputs correctly in console - "PC"

});

HTML:

Win
    Mac test

This is the 2nd page: {{ mF.name }}

Back

A: You would need to attach the function calculate to the scope as well in order to invoke it from the view binding.
So try:
$scope.calculate = function calculate (x) {
    $scope.mF = device1[x];
}


text:
Q: How can I truncate this PHP statement? I'm trying to program more efficiently by reducing repetition.
<?php if (isset($user_school_data[0]) && trim($user_school_data[0] != "")) print($user_school_data[0]) ?>

Is there a way I can shorten the statement above?

A: You could make use of PHP's null coalescing operator (only with PHP7 onwards):
<?php if (strlen(trim($user_school_data[0] ?? ''))) print($user_school_data[0]) ?>

*

*$user_school_data[0] ?? '' basically means: evaluate to
$user_school_data[0], or if it doesn't exist (or is null), replace it with an
empty string.

*strlen then checks the length of the trimmed string.

As @Nigel Ren suggested in the comments, you can also omit the condition completely if it just prints the value:
print(trim($user_school_data[0] ?? ''));

This will only print the value if it exists and its trimmed version is not empty.


text:
Q: Can someone confirm the following bug in Office.js on macOS (Microsoft Word)? The following very simple code works fine on Word Online and Word 2016 on Windows 10.
It works the first time it is used on macOS and Word 2016, but then throws an error on any subsequent use...until the page is refreshed and then it works again.
To reproduce:

*

*Open a dialog window using the dialogAPI

*Click to close the new window

*Click on the button that triggers the opening of the dialog window

On the second attempt no window opens on Mac.
I am on Office Insider Slow running Word for Mac Version 116.13.1 (180523). I have had this issue since a previous release of Office Insider Slow.
The error thrown is:

TypeError: undefined is not an object (evaluating 'dialog.addEventHandler')

It seems that, on a Mac, the dialog object is not closed when the dialog window is closed.
Code:
dialogUrl = dialogUrl + 'qLTI.html';

Office.context.ui.displayDialogAsync(dialogUrl, {height: 90, width: 70},
  function (asyncResult) {
    dialog = asyncResult.value;
      dialog.addEventHandler(Office.EventType.DialogMessageReceived, processMessage);
  }
);

Trying to get confirmation and also flag MSFT. Thank you.

A: This was a known issue to MSFT and was fixed in a June release.
See https://github.com/OfficeDev/office-js/issues/197.


text:
Q: Best choice for handling forms in React I need help understanding what is the best choice for forms in React. We will have multiple forms in our app. I'm thinking one of these three options:

*

*Formik

*One useState object that will store info from all fields, and one event handler.

*Multiple states. For every input one state with its own handler.


text:
Q: How to resolve "mount.nfs: access denied by server" error I am trying to mount a directory from a Raspberry Pi 2 (the NFS server) from an Ubuntu 15.10 PC (the NFS client). When I try, I get the error:
mount.nfs: access denied by server while mounting 192.168.1.135:/home/pi

Here what I am doing.
On the Raspberry Pi 2 (NFS server)
Added this line to /etc/exports
/home/pi/workspace 192.168.1.*(rw,no_subtree_check,sync,root_squash)

Issued:
sudo update-rc.d rpcbind enable && sudo update-rc.d nfs-common enable

And then started the NFS server:
pi@dex ~ $ sudo service nfs-kernel-server start
[ ok ] Exporting directories for NFS kernel daemon....
[ ok ] Starting NFS kernel daemon: nfsd mountd.

On the PC (NFS client)
> showmount -e 192.168.1.135
Export list for 192.168.1.135:
/home/pi/workspace 192.168.1.*

Then I try to mount the directory, and get the error:
> sudo mount 192.168.1.135:/home/pi/workspace /home/fanta/nfs
mount.nfs: access denied by server while mounting 192.168.1.135:/home/pi/workspace

Any information I can collect to troubleshoot the issue?
Raspberry Pi 2 is running Linux dex 4.1.13-v7+, and the PC Ubuntu 15.10 64-bit.
Thanks!

A: You can only use * on its own or in domain names. Replace it with ip/numberofbits:
/home/pi/workspace 192.168.1.0/24(rw,no_subtree_check,sync,root_squash)

See man exports or debian handbook

Each machine can be identified either by its DNS name or its IP address. Whole sets of machines can also be specified using either a syntax such as *.falcot.com or an IP address range such as 192.168.0.0/255.255.255.0 or 192.168.0.0/24.


text:
Q: Как выполнять математические действия? В приложение есть 2 EditText мне нужно выполнить математическое действие 1EditText * 2EditText  и то что получится умножить на 2
binding.inputQuantity
binding.inputPrice

Нашел пример
int a = Integer.parseInt(binding.inputQuantity.getText().toString());
int b = Integer.parseInt(binding.inputPrice.getText().toString());

int res = (a * b) * 2;
binding.totalPrice.setText(String.valueOf(res));

Но срабатывает оно когда у EditText изначально добавлен какой то текст  android:text="1" + к тому же при повторном вводе данных уже нечего не работает. Мне нужно что бы оно автоматом обновлялось при вводе в EditText без каких либо обработчиков нажатий.
   <EditText
        android:id="@+id/inputQuantity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginEnd="4dp"
        android:background="@drawable/input_bg"
        android:drawableStart="@drawable/ic_view"
        android:drawablePadding="10dp"
        android:ems="10"
        android:fontFamily="@font/aldrich"
        android:text="1"
        android:hint="@string/_1"
        android:inputType="number"
        android:paddingStart="20dp"
        android:paddingTop="13dp"
        android:paddingEnd="20dp"
        android:paddingBottom="13dp"
        android:textColor="@color/colorWhite"
        android:textColorHint="@color/colorWhite"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputTitle"
        app:layout_editor_absoluteX="97dp"
        app:layout_editor_absoluteY="248dp" />

    <EditText
        android:id="@+id/inputPrice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginStart="4dp"
        android:background="@drawable/input_bg"
        android:drawableStart="@drawable/ic_price"
        android:drawablePadding="10dp"
        android:ems="10"
        android:fontFamily="@font/aldrich"
        android:text="1"
        android:hint="@string/_2"
        android:inputType="number"
        android:paddingStart="20dp"
        android:paddingTop="13dp"
        android:paddingEnd="20dp"
        android:paddingBottom="13dp"
        android:textColor="@color/colorWhite"
        android:textColorHint="@color/colorWhite"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputTitle"
        app:layout_editor_absoluteX="97dp"
        app:layout_editor_absoluteY="248dp" />

Нашел реализацию того что мне нужно но только когда из какого либо поля EditText убрать значение то приложение закрывается из за того что поле пустое, как это можно исправить?
    binding.inputPrice.addTextChangedListener(new TextWatcher() {

    public void afterTextChanged(Editable s) {
        int a = Integer.parseInt(binding.inputQuantity.getText().toString());
        int b = Integer.parseInt(binding.inputPrice.getText().toString());

        int res = (a * b) * 2;
        binding.totalPrice.setText(String.valueOf(res));
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) {}
});

binding.inputQuantity.addTextChangedListener(new TextWatcher() {

    public void afterTextChanged(Editable s) {
        int a = Integer.parseInt(binding.inputQuantity.getText().toString());
        int b = Integer.parseInt(binding.inputPrice.getText().toString());

        int res = (a * b) * 2;
        binding.totalPrice.setText(String.valueOf(res));
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) {}
});

A: Вот что помогло мне решить эту проблему, а именно исключения tey end catch!
private void gettingTotalPrice() {

    binding.inputPrice.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            try {
                int a = Integer.parseInt(binding.inputQuantity.getText().toString());
                int b = Integer.parseInt(binding.inputPrice.getText().toString());

                int res = (a * b) * 2;
                binding.totalPrice.setText(String.valueOf(res));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    binding.inputQuantity.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            try {
                int a = Integer.parseInt(binding.inputQuantity.getText().toString());
                int b = Integer.parseInt(binding.inputPrice.getText().toString());

                int res = (a * b) * 2;
                binding.totalPrice.setText(String.valueOf(res));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });
}


text:
Q: Linux not interpreting UTF8 encoded characters So, having the following file Adán-y-Eva-50x50.jpg when I try to access it, apache translates it to Ad\xc3\xa1n-y-Eva-50x50.jpg and won't find it, even though it exists.
This happens only for filenames that contain UTF8 characters.
I have already the following configuration in my /etc/httpd/conf/httpd.conf
...
AddDefaultCharset UTF-8
...
IndexOptions FancyIndexing VersionSort NameWidth=* HTMLTable +Charset=UTF-8
...

And added also this to my root .htaccess on the first line:
IndexOptions +Charset=UTF-8

All this with no effect to load those kind of files. Any suggestions?
UPDATE
Just to mention it: I'm running the websites on a CentOS server with plesk panel preconfigured

A: The problem here doesn't seem to be on your browser nor your Apache configuration.  You need to double check the locale settings of your system.
You need to check if the locale apache is running is UTF-8 enabled.  To do so you may run the command:
$ sudo su -l -c locale www-data

where www-data is the apache user.  Check if the locale returned doesn't looks like, for example, es_ES.UTF-8 it means your locale doesn't have UTF-8 enabled.
If this is the case, you may change this configuration, on a CentOS machine, at /etc/sysconfig/i18n, changing the line LANG="es_ES" to LANG="es_ES.UTF-8".  But, still, in order for this to work, your system need the locale file for this language.  To check if it existes, use locale -a to get a list of locales available.
If your system doesn't have a UTF-8 enabled locale, you may generate one using the command:
$ sudo localedef -i es_ES -f UTF-8 es_ES.utf8

and set it as your default language.
Hope this help!

A: In addition to fboaventura's answer
Check if the locale apache is running
$ sudo su -l -c locale www-data

In order to change i18n configuration at /etc/sysconfig/i18n :
Go to the CentOS system configuration directory
$ cd /etc/sysconfig

Make backup copy of your language setting file
$ cp i18n i18n.backup

Edit language setting file by using nano
$ nano i18n

Edit the file to include your configuration
For example:
LANG="en_US.utf8"
SYSFONT="latarcyrheb-sun16"
SUPPORTED="en_US.utf8:en_US:en:fr_FR.utf8:fr_FR:fr :es_ES.utf8:es_ES:es:de_DE.utf8:de_DE:de:sv_SE.utf 8:sv_SE:sv:zh_CN.utf8:
zh_CN:zh:zh_TW.utf8:zh_TW:zh:ja_JP.utf8:ja_JP:ja:k o_KR.utf8:ko_KR:ko"

Save the file and restart the system.
Additional Resources

*

*https://unix.stackexchange.com/questions/74618/how-to-change-locale-environment-variable

*How to change my commandline locale after CentOS decided to change it?


text:
Q: Pytorch CUDA out of memory despite plenty of memory left I am training a Huggingface model using their trainer Python module. To be fair, I have refactored my code a bit, but a very similar code was actually working perfectly with way larger datasets than the one I am supplying right now, as well as higher per_device_train_batch_size (now equal to 8, still crashing, 16 used to work).
However, I am getting out of memory error, which is pretty weird...
RuntimeError: CUDA out of memory. Tried to allocate 20.00 MiB (GPU 0; 8.00 GiB total capacity; 1.54 GiB already allocated; 5.06 GiB free; 1.62 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

That error is what got me wondering, because it's trying to allocate 20.00 MiB and 5.06 GiB is seemingly free, so why does it crash?
My PyTorch version is '1.12.1+cu113', after I run torch.version.cuda I get 11.3
Thanks for all the help

A: My guess is that your CUDA drive is not set up correctly.
You need to install these two correctly also as a prereq
NVIDIA CUDA 11.0 or above
NVIDIA cuDNN v7 or above


text:
Q: .Net Serialization Exception error I have a .net application running with no issues on IIS6. I am trying to make the same application work on Win 2008 R2, IIS 7 and running into following error:
The description for Event ID 1334 from source ASP.NET 2.0.50727.0 cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
An unhandled exception occurred and the process was terminated.
Application ID: DefaultDomain
Process ID: 3988
Exception: System.Runtime.Serialization.SerializationException
Message: Type 'my exception.Shared.Exceptions.DataAcquisitionException' in Assembly 'my exception.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
StackTrace:    at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
   at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
   at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.SerializeObject(Object obj, MemoryStream stm)
   at System.AppDomain.Serialize(Object o)
   at System.AppDomain.MarshalObject(Object o)
DETAILS TAB:

*

*Provider
[ Name]  ASP.NET 2.0.50727.0

*EventID 1334
[ Qualifiers]  49152
Level 2
Task 0
Keywords 0x80000000000000

*TimeCreated
[ SystemTime]  2014-03-06T17:10:07.000000000Z
EventRecordID 3324
Channel Application
Computer MY SERVER
Security

*

*EventData

An unhandled exception occurred and the process was terminated. Application ID: DefaultDomain Process ID: 3988 Exception: System.Runtime.Serialization.SerializationException Message: Type 'my exception.Shared.Exceptions.myException' in Assembly 'my exception.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable. StackTrace: at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.SerializeObject(Object obj, MemoryStream stm) at System.AppDomain.Serialize(Object o) at System.AppDomain.MarshalObject(Object o)
Any clues into fixing this would be much appreciated!!

A: Could be an environmental issue. Do you have same updates of .NET 2.0 applied on win 2003 and win 2008? Do you have any higher framework on win 2003?
Also, I found this article. The class that caused the exception is different but maybe it will help you or point you in right direction. Hope it helps.


text:
Q: How can I close the previous and currently window when opening a new window Can you help me guys, how can I close other windows if I open the dashboard window because when I use self.master.destroy() it destroys the current window and the windows that I currently opening.
from tkinter import *
from tkinter import messagebox
from tkinter.font import Font
from PIL import ImageTk, Image
import mysql.connector
from subprocess import call
 def main():
     root = Tk()
     startpage = StartPage(root)
     root.mainloop()

class StartPage:
#-----------------> ATTRIBUTES <------------------#

def __init__(self, master):
    self.master = master
    self.master.title("COVID-19 TRACKER")
    self.master.resizable(False, False)
    self.master.geometry('400x600+460+50')
    self.master.iconbitmap('Images/covid19-logo.ico')
    self.frame = Frame(self.master)
    self.frame.pack()

    #------------> BACKGROUND IMAGE <--------------#

    startpage_bg_image = PhotoImage(file='Images/covid19-bg.png')
    self.startpage_bg = startpage_bg = Label(self.frame, image=startpage_bg_image)
    startpage_bg.user_bg_image = startpage_bg_image
    startpage_bg.pack()

    #-----------------> BUTTONS <------------------#

    self.user_btn = Button(self.frame,
        text="USER",
        height=2,
        width=22,
        relief=RIDGE,
        bg="ORANGE",
        command=self.open_loginUser
        ).place(x=113, y=270)

    self.admin_btn = Button(self.frame,
        text="ADMIN",
        height=2,
        width=22,
        relief=RIDGE,
        bg="ORANGE",
        command=self.open_loginAdmin
        ).place(x=113, y=325)

    self.registration_btn = Button(self.frame,
        text="REGISTER",
        height=1,
        width=17,
        relief=RIDGE,
        bg="ORANGE",
        command=self.open_registration
        ).place(x=131, y=380)

    self.about_btn = Button(self.frame,
        text="ABOUT",
        height=1,
        width=13,
        relief=RIDGE,
        bg="ORANGE",
        command=self.open_about
        ).place(x=290, y=565)

#-----------------> METHODS <------------------#

#Open Login User
def open_loginUser(self):
    self.user_login = Toplevel(self.master)
    self.startpage = UserLogin(self.user_login)

#Open Login Admin
def open_loginAdmin(self):
    self.admin_login = Toplevel(self.master)
    self.startpage = AdminLogin(self.admin_login)

#Open Registration Form
def open_registration(self):
    self.registration_form = Toplevel(self.master)
    self.startpage = Registration(self.registration_form)

#Open About Form
def open_about(self):
    self.about_win = Toplevel(self.master)
    self.startpage = About(self.about_win)

Login Form for User
class UserLogin:
#-----------------> ATTRIBUTES <------------------#

def __init__(self, master):
    self.master = master
    self.master.title("Sign In As User")
    self.master.resizable(False, False)
    self.master.geometry('300x120+510+290')
    self.master.iconbitmap('Images/covid19-logo.ico')
    self.frame = Frame(self.master)
    self.frame.pack()

    #------------> BACKGROUND IMAGE <--------------#

    startpage_bg_image = PhotoImage(file='Images/user_login_form.png')
    self.startpage_bg = startpage_bg = Label(self.frame, image=startpage_bg_image)
    startpage_bg.user_bg_image = startpage_bg_image
    startpage_bg.pack()

    #-----------------> BUTTONS <------------------#

    self.login_btn = Button(self.frame,
        text="LOGIN",
        width=39,
        command=self.check_UserPass,
        bg="black",
        fg="white",
        borderwidth=1,
        relief=RIDGE,
        ).place(x=10, y=85)

    #-------------------> ENTRY <-------------------#

    # Declaring the entry variable as global
    # To access it to the check_UserPass method
    global varUsernameUser
    global varPasswordUser

    # Setting the entered elements as string
    varUsernameUser = StringVar()
    varPasswordUser= StringVar()

    self.username_entry = Entry(self.frame,
        textvariable = varUsernameUser,
        width=30,
        borderwidth=0,
        bg="black",
        fg="white",
        insertbackground="white"
        ).place(x=100, y=13)

    self.password_entry = Entry(self.frame,
        textvariable = varPasswordUser,
        width=30,
        borderwidth=0,
        show = '*',
        bg="black",
        fg="white",
        insertbackground="white",
        ).place(x=100, y=53)

#Check Admin's Username and Password
def check_UserPass(self):
    # Calling database
    try:
        db = mysql.connector.connect(host="localhost", user="root", password="root", database="COVID19_USER_DATABASE")
    except:
        print("You are not connected to server")
    else:
        print("Conected Successfully")

        mycursor = db.cursor()

        checkUsername = varUsernameUser.get()
        checkPassword = varPasswordUser.get()

        query = "SELECT username, password FROM COVID19_USER_RECORDS"
        mycursor.execute(query)

        #Looping the username and password from database and checks if it's equal
        for (username_x, password_y) in mycursor:
            if checkUsername == username_x and checkPassword == password_y:
                print("Success")
                break
        else:
            print("Wrong Input")
            self.open_popupwronginput()

        db.close()
        call (["python", "user_dashboard.py"])
# Pop Up: Wrong Input
def open_popupwronginput(self):
    self.popup = Toplevel(self.master)
    self.startpage = PopUpWrongInput(self.popup)

# Open User Dashboard
def open_userdashboard(self):
    self.user_dashboard = Toplevel(self.master)
    self.startpage = UserDashboard(self.user_dashboard)

Login Form for User
class AdminLogin:
def init(self, master):
self.master = master
self.master.title("Sign In As Admin")
self.master.resizable(False, False)
self.master.geometry('300x120+510+290')
self.master.iconbitmap('Images/covid19-logo.ico')
self.frame = Frame(self.master)
self.frame.pack()
    #------------> BACKGROUND IMAGE <--------------#

    startpage_bg_image = PhotoImage(file='Images/user_login_form.png')
    self.startpage_bg = startpage_bg = Label(self.frame, image=startpage_bg_image)
    startpage_bg.user_bg_image = startpage_bg_image
    startpage_bg.pack()

    #-----------------> BUTTONS <------------------#
    self.login_btn = Button(self.frame,
        text="LOGIN",
        width=39,
        command=self.check_UserPass,
        bg="black",
        fg="white",
        borderwidth=1,
        relief=RIDGE,
        ).place(x=10, y=85)

    #-------------------> ENTRY <-------------------#

    # Declaring the entry variable as global
    # To access it to the check_UserPass method
    global varUsernameAdmin
    global varPasswordAdmin

    # Setting the entered elements as string
    varUsernameAdmin = StringVar()
    varPasswordAdmin = StringVar()

    self.username_entry = Entry(self.frame,
        textvariable = varUsernameAdmin,
        width=30,
        borderwidth=0,
        bg="black",
        fg="white",
        insertbackground="white"
        ).place(x=100, y=13)

    self.password_entry = Entry(self.frame,
        textvariable = varPasswordAdmin,
        width=30,
        borderwidth=0,
        show = '*',
        bg="black",
        fg="white",
        insertbackground="white",
        ).place(x=100, y=53)

# Check Username and Password on database
# Username: covid19
# Password: covid19
def check_UserPass(self):
    username = varUsernameAdmin.get()
    password = varPasswordAdmin.get()

    #check admin username and password
    if username == 'covid19' and password == 'covid19':
        print("Success")
    else:
        self.open_popupwronginput()

    call (["python", "admin_dashboard.py"])

#Opens Admin Dashboard
def open_admindashboard(self):
    self.admin_dashboard = Toplevel(self.master)
    self.startpage = AdminDashboard(self.admin_dashboard)

#Pop up: WrongInput
def open_popupwronginput(self):
    self.popup = Toplevel(self.master)
    self.startpage = PopUpWrongInput(self.popup)

Registration Form
class Registration:
def init(self, master):
self.master = master
self.master.title("Registration Form")
self.master.resizable(False, False)
self.master.geometry('280x318+520+210')
self.master.iconbitmap('Images/covid19-logo.ico')
self.frame = Frame(self.master)
self.frame.pack()
    #------------> BACKGROUND IMAGE <--------------#

    startpage_bg_image = PhotoImage(file='Images/register_form.png')
    self.startpage_bg = startpage_bg = Label(self.frame, image=startpage_bg_image)
    startpage_bg.user_bg_image = startpage_bg_image
    startpage_bg.pack()

    #-----------------> ENTRY <------------------#

    global name_get
    global age_get
    global address_get
    global contactno_get
    global gender_get
    global username_get
    global password_get

    name_get = StringVar()
    age_get = StringVar()
    address_get = StringVar()
    contactno_get = StringVar()
    gender_get = StringVar()
    username_get = StringVar()
    password_get = StringVar()

    self.entry_name = Entry(self.frame,
        width=29,
        textvariable=name_get,
        borderwidth=0,
        bg="black",
        fg="white",
        insertbackground="white",
        ).place(x=95, y=40)

    self.entry_age = Entry(self.frame,
        width=29,
        textvariable=age_get,
        borderwidth=0,
        bg="black",
        fg="white",
        insertbackground="white",
        ).place(x=95, y=70)

    self.entry_address = Entry(self.frame,
        width=29,
        textvariable=address_get,
        borderwidth=0,
        bg="black",
        fg="white",
        insertbackground="white",
        ).place(x=95, y=100)

    self.entry_gender= Entry(self.frame,
        width=29,
        textvariable=gender_get,
        borderwidth=0,
        bg="black",
        fg="white",
        insertbackground="white",
        ).place(x=95, y=130)

    self.entry_contactno = Entry(self.frame,
        width=29,
        textvariable=contactno_get,
        borderwidth=0,
        bg="black",
        fg="white",
        insertbackground="white",
        ).place(x=95, y=160)

    self.entry_username = Entry(self.frame,
        width=29,
        textvariable=username_get,
        borderwidth=0,
        bg="black",
        fg="white",
        insertbackground="white",
        ).place(x=95, y=220)

    self.entry_password = Entry(self.frame,
        width=29,
        textvariable=password_get,
        borderwidth=0,
        bg="black",
        fg="white",
        insertbackground="white",
        ).place(x=95, y=250)

    #-----------------> BUTTONS <------------------#

    self.register_button = Button(self.frame,
        text="REGISTER",
        width=35,
        bg="black",
        fg="white",
        borderwidth=1,
        relief=RIDGE,
        command=self.add_to_database
        ).place(x=13, y=280)

def add_to_database(self):
    #check admin username and password
    try:
        db = mysql.connector.connect(host="localhost", user="root", password="root", database="COVID19_USER_DATABASE")
    except:
        print("You are not connected to server")
    else:
        global name
        global age
        global address
        global cotact_no
        global gender
        global username_g
        global password
        name = name_get.get()
        age = age_get.get()
        address = address_get.get()
        cotact_no = contactno_get.get()
        gender = gender_get.get()
        username_g = username_get.get()
        password = password_get.get()

        if name == "":
            self.open_popupsomething()
        elif address == "":
            self.open_popupsomething()
        elif cotact_no == "":
            self.open_popupsomething()
        elif gender == "":
            self.open_popupsomething()
        elif age == "":
            self.open_popupsomething()
        elif password == "":
            self.open_popupsomething()
        elif username_g == "":
            self.open_popupsomething()
        else:
            cursor = db.cursor()
            username = username_g
            sql1 = "SELECT * FROM COVID19_USER_RECORDS WHERE username = %s"
            username = (username, )
            result = cursor.execute(sql1, username)
            result = cursor.fetchall()
            if not result:
                self.add_user()
            else:
                print("Username Exist")
                self.open_popupsomething()

def add_user(self):
    try:
        db = mysql.connector.connect(host="localhost", user="root", password="root", database="COVID19_USER_DATABASE")
    except:
        print("You are not connected to server")
    else:
        mycursor = db.cursor()
        sql = "INSERT INTO COVID19_USER_RECORDS (name, age, address, cotact_no, gender, username, password) VALUES (%s, %s, %s, %s, %s, %s, %s)"
        value = (name, age, address, cotact_no, gender, username_g, password)
        mycursor.execute(sql, value)
        db.commit()
        print("Added Successfully")
        messagebox.showinfo("Console", "Successfully Added. Click 'Ok' to continue...")
        mycursor.close()
        db.close()

def open_popupsomething(self):
    self.popup = Toplevel(self.master)
    self.startpage = PopUpSomethingMissing(self.popup)

def open_popupcontinue(self):
    self.popup = Toplevel(self.master)
    self.startpage = PopUpContinue(self.popup)

class About:
def init(self, master):
self.master = master
self.master.title("About")
self.master.resizable(False, False)
self.master.geometry('270x170+520+250')
self.master.iconbitmap('Images/covid19-logo.ico')
self.frame = Frame(self.master)
self.frame.pack()
    #------------> BACKGROUND IMAGE <--------------#

    about_bg_image = PhotoImage(file='Images/about_form.png')
    self.about_bg = about_bg = Label(self.frame, image=about_bg_image)
    about_bg.user_bg_image = about_bg_image
    about_bg.pack(pady=0)

    #-----------------> BUTTONS <------------------#

    self.ok_button = Button(self.frame,
        text="OK",
        width=10,
        command=self.click,
        bg="black",
        fg="white",
        borderwidth=1,
        relief=RIDGE,
        ).place(x=180, y=135)

#-----------------> METHODS <------------------#

def click(self):
    self.master.destroy()

class UserDashboard:
def init(self, master):
self.master = master
self.master.title("User Dashboard")
self.master.resizable(False, False)
self.master.geometry('1000x600+160+50')
self.master.iconbitmap('Images/covid19-logo.ico')
self.frame = Frame(self.master)
self.frame.pack()
    #------------> BACKGROUND IMAGE <--------------#

def show_info():
    pass

def destroy_windows(self):
    self.popup = Toplevel(self.master)
    self.startpage = PopUpContinue(self.popup)

class AdminDashboard:
def init(self, master):
self.master = master
self.master.title("Admin Dashboard")
self.master.resizable(False, False)
self.master.geometry('1000x600+160+50')
self.master.iconbitmap('Images/covid19-logo.ico')
self.frame = Frame(self.master)
self.frame.pack()
    #------------> BACKGROUND IMAGE <--------------#

Notification Box: Somethings is Missing
class PopUpSomethingMissing:
def init(self, master):
self.master = master
self.master.title("Console")
self.master.resizable(False, False)
self.master.geometry('320x123+500+290')
self.master.iconbitmap('Images/covid19-logo.ico')
self.master.attributes("-topmost", True)
self.frame = Frame(self.master)
self.frame.pack()
    #------------> BACKGROUND IMAGE <--------------#

    about_bg_image = PhotoImage(file='Images/alert_box.png')
    self.about_bg = about_bg = Label(self.frame, image=about_bg_image)
    about_bg.user_bg_image = about_bg_image
    about_bg.pack()

    #-----------------> BUTTONS <------------------#

    self.ok_button = Button(self.frame,
        text="OK",
        width=10,
        command=self.click,
        relief="ridge",
        ).place(x=220, y=87)

    #-----------------> LABELS <------------------#

    self.wronginput = Label(self.frame,
        text="Something is missing. Please complete the form.",
        bg="#ffffff"
        ).place(x=57, y=29)

def click(self):
    self.master.destroy()

#Notification Box: Wrong Input
class PopUpWrongInput:
def init(self, master):
self.master = master
self.master.title("Console")
self.master.resizable(False, False)
self.master.geometry('316x123+510+290')
self.master.iconbitmap('Images/covid19-logo.ico')
self.master.attributes("-topmost", True)
self.frame = Frame(self.master)
self.frame.pack()
    #------------> BACKGROUND IMAGE <--------------#

    about_bg_image = PhotoImage(file='Images/alert_box.png')
    self.about_bg = about_bg = Label(self.frame, image=about_bg_image)
    about_bg.user_bg_image = about_bg_image
    about_bg.pack()

    #-----------------> BUTTONS <------------------#

    self.ok_button = Button(self.frame,
        text="OK",
        width=10,
        command=self.click,
        relief="ridge",
        ).place(x=220, y=87)

    #-----------------> LABELS <------------------#

    self.wronginput = Label(self.frame,
        text="Wrong input. Please recheck your entered data.",
        bg="#ffffff"
        ).place(x=57, y=29)

#-----------------> METHODS <------------------#

def click(self):
    self.master.destroy()

A: from tkinter import*
root = Tk()

def open_new_and_destroy():
    top = Tk()

    root.destroy()

btn_destroy_open = Button(root , text ="destroy and open" ,command = open_new_and_destroy).pack()

root.mainloop()

Does this solve your problem


text:
Q: Propensity Score Matching with panel data I am trying to use MatchIt to perform Propensity Score Matching (PSM) for my panel data. The data is panel data that contains multi-year observations from the same group of companies.
The data is basically describing a list of bond data and the financial data of their issuers, also the bond terms such as issued date, coupon rate, maturity, and bond type of bonds issued by them. For instance:

Firmnames
Year
ROA
Bond_type

AAPL US Equity
2015
0.3
0

AAPL US Equity
2015
0.3
1

AAPL US Equity
2016
0.3
0

AAPL US Equity
2017
0.3
0

C US Equity
2015
0.3
0

C US Equity
2016
0.3
0

C US Equity
2017
0.3
0

......
I've already known how to match the observations by the criteria I want and I use exact = Year to make sure I match observations from the same year. The problem now I am facing is that the observations from the same companies will be matched together, this is not what I want. The code I used:
matchit(Bond_type ~ Year + Amount_Issued + Cpn + Total_Assets_bf + AssetsEquityRatio_bf + Asset_Turnover_bf, data = rdata, method = "nearest", distance = "glm", exact = "Year")
However, as you can see, in the second raw of my sample, there might be two observations in one year from the same companies due to the nature of my study (the company can issue bonds more than one time a year). The only difference between them is the Bond_type. Therefore, the MathcIt function will, of course, treat them as the best control and treatment group and match these two observations together since they have the same ROA and other matching factors in that year.
I have two ways to solve this in my opinion:

*

*Remove the observations from the same year and company, however, removing the observations might lead to bias results and ruined the study.

*Preventing MatchIt function match the observations from the same company (or with the same Frimnames)
The second approach will be better since it will not lead to bias, however, I don't know if I can do this in MatchIt function. Hope someone can give me some advice on this or maybe there's any better solution to this problem, please be so kind to share with me, thanks in advance!
Note: If there's any further information or requirement I should provide, please just inform me. This is my first time raising the question here!

A: This is not possible with MatchIt at the moment (though it's an interesting idea and not hard to implement, so I may add it as a feature).
In the optmatch package, which perfroms optimal pair and full matching, there is a constraint that can be added called "anti-exact matching", which sounds exactly like what you want. Units with the same value of the anti-exact matching variable will not be matched with each other. This can be implemented using optmatch::antiExactMatch().
In the Matching package, which performs nearest neighbor and genetic matching, the restrict argument can be supplied to the matching function to restrict certain matches. You could manually create the restriction matrix by restricting all pairs of observations in the same company and then supply the matrix to Match().


text:
Q: How to submit and edit data from database of paritcular id on same page Good Evening, Everybody..
i am using php form to submit data of students in database using the below code...
    <?php

if(isset($_POST['submit1']))
{
$a1=mysql_real_escape_string($_POST['a1']);
$a2=mysql_real_escape_string($_POST['a2']);
$a3=mysql_real_escape_string($_POST['a3']);
$a=mysql_real_escape_string($_POST['a']);
$a4=mysql_real_escape_string($_POST['a4']);
$a5=mysql_real_escape_string($_POST['a5']);
$a6=mysql_real_escape_string($_POST['a6']);
$color=mysql_real_escape_string($_POST['color']);
$date=mysql_real_escape_string($_POST['date']);
$query1=mysql_query("insert into student_table values('','$a1','$a2','$a3','$a','$a4','$a5','$a6','$color','$date')");

if($query1)
{
echo "Open Updated Successfully";
}
}
?>

! STUDENT RESULTS !
! Live Result !

<?php

$query1 = "SELECT CONCAT(a1,a2,a3,' - ',a,' - ',a4,a5,a6) FROM student_table ORDER BY id DESC
LIMIT 1;";
$result = mysql_query($query1);
$data = mysql_fetch_array($result);

echo $data[0];

?>

<form method="post" action="" autocomplete="off">
DATE:<input type="text" name="date" size="6" align="absmiddle" value="<?php
$current_dayname = date("l");

echo $date = date("d/m/y",strtotime('monday this week')).'
to
 '.date("d/m/y",strtotime("sunday this week"));
?>">

Open:
<input type="text" name="a1" size="1" value="<?php echo $query2['a1']; ?>">
<input type="text" name="a2" size="1" value="<?php echo $query2['a2']; ?>">
<input type="text" name="a3" size="1" value="<?php echo $query2['a3']; ?>"> -
<input type="text" name="a" size="2" value="<?php echo $query2['a']; ?>">
<input type="submit" name="submit1">
</form>

    <?php

$query1 = "SELECT id FROM student_table ORDER BY id DESC
LIMIT 1;";
$result = mysql_query($query1);
$data = mysql_fetch_array($result);

    ?>

Now By using the above code it shows desired result....
but i want to add one more result along with previous result, due to this i have to required edit page of above result, the desired code of edit page is below...
<?php

if(isset($_GET['id']))
{
$id=$_GET['id'];
if(isset($_POST['submit2']))
{
$a1=$_POST['a1'];
$a2=$_POST['a2'];
$a3=$_POST['a3'];
$a=$_POST['a'];
$a4=$_POST['a4'];
$a5=$_POST['a5'];
$a6=$_POST['a6'];
$color=$_POST['color'];
$date=$_POST['date'];
$query3=mysql_query("update student_table set a1='$a1', a2='$a2', a3='$a3', a='$a', a4='$a4', a5='$a5', a6='$a6', color='$color', date='$date' where id='$id'");
if($query3)
{
echo "
 Close Updated Successfully";
}
}
$query1=mysql_query("select * from student_table where id='$id'");
$query2=mysql_fetch_array($query1);
?>

<form method="post" action="" autocomplete="off">

<input type="text" name="a4" size="1" value="<?php echo $query2['a4']; ?>">
<input type="text" name="a5" size="1" value="<?php echo $query2['a5']; ?>">
<input type="text" name="a6" size="1" value="<?php echo $query2['a6']; ?>">
<input type="text" name="a" size="2" value="<?php echo $query2['a']; ?>"><select type="text"  name="color" value="<?php echo $query2['color']; ?>"> <option value="#000000">Black</option><option value="#FF0000">Red</option></select>
<input type="submit" name="submit2">

DATE:<input type="text" name="date" size="5" align="absmiddle" value="<?php
$current_dayname = date("l");

echo $date = date("d/m/y",strtotime('monday this week')).'
to
 '.date("d/m/y",strtotime("sunday this week"));
?>"><input type="text" name="a1" size="1" value="<?php echo $query2['a1']; ?>">
<input type="text" name="a2" size="1" value="<?php echo $query2['a2']; ?>">
    <input type="text" name="a3" size="1" value="<?php echo $query2['a3']; ?>">

</form>

<?php
}
?>

Now my question is that....is it possible to perform both submitting of students numbers and having an option to add one more same result with editable function of previous result entry on the same page...
please refer below image...

can anybody help me in order to perform both functioning on same page with editable option


text:
Q: Why my nested form don't work? I have nested form for my GameDate model and RefereeStat model. They are connected with has_many association. Without nesting, both models are saving. But in nested form, my app won't save them. I suspect that the problem is in form, probably in association with showcase controller, but I can't figure it out.
This is output from console:

Started POST "/game_dates" for 127.0.0.1 at 2016-03-24 20:38:07 +0100
  Processing by GameDatesController#create as HTML   Parameters:
  {"utf8"=>"✓",
  "authenticity_token"=>"umpbTCZekqIU/g6uVdlde9fSubutgLk0Qrbb0e5GCdn3qj4/C0tmlxl/akxaM1Vmr6v8dNB8b88ATpRN8v1U2g==",
  "game_date"=>{"date(1i)"=>"2016", "date(2i)"=>"3", "date(3i)"=>"24",
  "referee_stats_attributes"=>{"0"=>{"games_count"=>"3",
  "showcase_id"=>"10"}}}, "commit"=>"Create Game date"}   User Load
  (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER
  BY "users"."id" ASC LIMIT 1  [["id", 1]]    (0.4ms)  BEGIN    (0.3ms)
  ROLLBACK   Showcase Load (0.8ms)  SELECT "showcases".* FROM
  "showcases"   Rendered game_dates/_form.html.haml (22.4ms)   Rendered
  game_dates/new.html.haml within layouts/application (23.9ms)
  Rendered layouts/_header.html.haml (0.7ms)   Rendered
  shared/_flash.html.haml (0.2ms) Completed 200 OK in 148ms (Views:
  138.5ms | ActiveRecord: 2.2ms)

This is GameDate model:
class GameDate < ActiveRecord::Base

  validates :date, presence: true

  has_many :referee_stats
  accepts_nested_attributes_for :referee_stats, :reject_if => :all_blank
end

Game date controller:
class GameDatesController < ApplicationController
  before_action :authenticate_user!
  before_action :user_is_admin

  def new
    @game_date = GameDate.new
    @game_date.referee_stats.build
  end

  def create
    @game_date = GameDate.new(game_date_params)
    if @game_date.save
      redirect_to showcases_path
      flash[:success] = "Game date created"
    else
      render 'new'
    end
  end

  def show
    @game_date = GameDate.find(params[:id])
  end

  def destroy
    @game_date = GameDate.find(params[:id]).destroy
    redirect_to root_url
    flash[:success] = "Game date deleted"
  end

  private

  def game_date_params
    params.require(:game_date).permit(:date, referee_stats_attributes: [ :games_count, :showcase_id ])
  end

  def user_is_admin
    unless current_user.admin?
      flash[:error] = "You don't have permission to perform this action!"
      redirect_to root_url
    end
  end
end

Referee stat model:
class RefereeStat < ActiveRecord::Base

  validates :games_count,  presence: true, numericality: {
                           only_integer: true,
                           greater_than_or_equal_to: 0 }

  validates :showcase_id,  presence: true
  validates :game_date_id, presence: true

  belongs_to :showcase
  belongs_to :game_date

end

Form:
.container
  .row
    .col-md-6.col-md-offset-3
      = simple_form_for @game_date do |f|
        = f.error_notification
        %h2.text-center Game date
        = f.input :date
        = f.simple_fields_for :referee_stats do |r|
          %h3.text-center Referee statistics
          = r.input :games_count
          = r.association :showcase, label_method: :name, value_method: :id, include_blank: false
        = f.button :submit, class: "btn btn-primary btn-sm"

A: I looked into your git code and found solution :

You are not passing game_date_id from the game_date new form and it
  failing at game_date_id presence validation and not allowing you to
  save record so, its better to use association name validation to
  ensure presence of record.

Actually, presence validator for foreign key don't care about record existence. It means that you are able to pass game_date_id from form.
Change the following line in referee_stat.rb & it will work for you :
validates :game_date_id, presence: true
   replace with
validate :game_date
    OR
validates :game_date, presence: true, if: -> {game_date_id.present?}

Validating foreign key and the association itself are explained at
  this blog.

A: Currently your referee_stats_attributes are passed like such:
"referee_stats_attributes"=>{"0"=>{"games_count"=>"3", "showcase_id"=>"10"}}

But they should be passed like this:
"referee_stats_attributes"=>[{"games_count"=>"3", "showcase_id"=>"10"}]

The id "0" is not needed; Rails magic will auto-create this for you. You only need to pass an id if you're updating, and even then, it should be passed like so:
"referee_stats_attributes"=>[{"id" => 1, "games_count"=>"3", "showcase_id"=>"10"}]

I have not used simple_form_for so can't comment on the syntax, because it looks OK... but check the HTML output, your <input> for the child objects should look like this:
<input name="referee_stats[][games_count]" ... />
<input name="referee_stats[][showcase_id]" ... />


text:
Q: GoogleMap.OnCameraIdleListener Mapbox equivalent I am looking for an GoogleMap.OnCameraIdleListener equivalent in the Mapbox Android SDK.
Usecase
When panning around the map I need to query some geojson from a server, which is to be shown on the map.
For this I need to be able to detect when the map have moved and is once again idle. Google Maps have the OnCameraIdleListener and OpenLayers have the 'moveend' event. I can't use Google Maps due to some licensing issues and I'm trying to find a native alternative to OpenLayers, which I currently use.
What I have tried
I have tried to use various listeners offered by the MapboxMap class, but all of them is called much too often. Like the following:
map.setOnCameraChangeListener(new MapboxMap.OnCameraChangeListener() {
    @Override
    public void onCameraChange(CameraPosition position) {
        Log.d("TAG", map.getProjection().getVisibleRegion().latLngBounds.toString());
    }
});

The method is called a lot of times (every 400ms I think during panning). If I were to use the method directly the server load would be much too large as well as handling the returned data.
I could make a workaround that only calls the server if no CameraChange event has occurred for 5-800ms, but it would result in some not-to-nice code.
Possible duplicates
I found the following in the MapBox github:
https://github.com/mapbox/mapbox-gl-native/issues/4746
The issue seem very similar. I have tried the proposed solutions, but without a satisfying result.
Have I missed some implementation or does someone know of a nice workaround?
Thanks in advance.

A: Functionality added in v5.1.0
https://github.com/mapbox/mapbox-gl-native/pull/8644