text:
Q: Conditional Style can't change backcolor I'm using Jasper Report
Basically, my problem is i can't change backcolor when it's the field is null using conditional styles in Styles tag
I don't know the problem form the condition statement or the conditional style can't change when the condition is true.
so, i hope to find solution for this problem, In the following below i my Report file code :
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports
http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="FEP_ENERGY_DATA"
language="groovy" pageWidth="1333" pageHeight="1350" whenNoDataType="NoDataSection"
columnWidth="1293" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<property name="net.sf.jasperreports.style.evaluation.time.enabled" value="true"/>

<parameter name="daydate" class="java.lang.String"/>
<parameter name="metersId" class="java.util.Collection"/>
<parameter name="imagepath" class="java.lang.String"/>
<queryString>
    <![CDATA[WITH METER_ENERGY_DATA AS
      (
                 SELECT MTR_INFO.MTR_ID, MTR_INFO.MTR_SLNO AS METER_SLNO ,MTR_INFO.ACCOUNT_NO AS ACCOUNT_NO, MTR_INFO.SUB_NO AS SUB_NO,
                        CONVERT(varchar,ENERGY_TOU.TOTAL_EXP) as TOTAL_EXP, CONVERT(varchar,ENERGY_TOU.TOU1_EXP) as TOU1_KWH_EXP,
                        CONVERT(varchar,ENERGY_TOU.TOU2_EXP) as TOU2_KWH_EXP, CONVERT(varchar,ENERGY_TOU.TOU3_EXP) as TOU3_KWH_EXP,
                        CONVERT(varchar,ENERGY_TOU.TOU4_EXP) as TOU4_KWH_EXP , ROW_NUMBER() OVER (PARTITION BY
                        ENERGY_TOU.METER_ID ORDER BY ENERGY_TOU.METER_TIME DESC) ROW_NUM
                 FROM   AECMDMS_DEV.dbo.METER_INFO AS MTR_INFO
                 LEFT JOIN
                 (SELECT * FROM AECMDMS_DEV.dbo.ENERGY_WITH_TOU as ENERGY
                  WHERE ENERGY.METER_TIME BETWEEN '2014-01-10' AND '2014-01-10 23:59:59.999' ) AS ENERGY_TOU ON (ENERGY_TOU.METER_ID = MTR_INFO.MTR_ID)
                 )

                  SELECT METER_SLNO ,ACCOUNT_NO, SUB_NO,  LEFT(TOTAL_EXP,LEN(TOTAL_EXP)-2) as TOTAL_EXP, LEFT(TOU1_KWH_EXP, LEN(TOU1_KWH_EXP)-2) AS TOU1_KWH_EXP ,LEFT(TOU2_KWH_EXP, LEN(TOU2_KWH_EXP)-2) AS TOU2_KWH_EXP, LEFT(TOU3_KWH_EXP, LEN(TOU3_KWH_EXP)-2) AS TOU3_KWH_EXP, LEFT(TOU4_KWH_EXP, LEN(TOU4_KWH_EXP)-2) AS TOU4_KWH_EXP
                  FROM METER_ENERGY_DATA AS MTR_ENERGY
                  WHERE MTR_ENERGY.ROW_NUM = 1
     ]]>
</queryString>
<field name="METER_SLNO" class="java.lang.String"/>
<field name="ACCOUNT_NO" class="java.lang.String"/>
<field name="SUB_NO" class="java.lang.String"/>
<field name="TOTAL_EXP" class="java.lang.String"/>
<field name="TOU1_KWH_EXP" class="java.lang.String"/>
<field name="TOU2_KWH_EXP" class="java.lang.String"/>
<field name="TOU3_KWH_EXP" class="java.lang.String"/>
<field name="TOU4_KWH_EXP" class="java.lang.String"/>
<background>
    <band splitType="Stretch"/>
</background>
<title>
    <band height="102" splitType="Stretch">
        <image scaleImage="FillFrame">
            <reportElement positionType="Float" stretchType="RelativeToBandHeight" x="421" y="0" width="370" height="70"/>
            <imageExpression><![CDATA[$P{imagepath}]]></imageExpression>
        </image>
        <textField>
            <reportElement x="2" y="81" width="1292" height="20"/>
            <textElement textAlignment="Center">

            </textElement>
            <textFieldExpression><![CDATA["ENERGY DATA EXPORT ON "+$P{daydate}]]></textFieldExpression>
        </textField>
    </band>
</title>
<pageHeader>
    <band height="31" splitType="Stretch">
        <frame>
            <reportElement x="0" y="20" width="1292" height="10"/>
        </frame>
    </band>
</pageHeader>
<columnHeader>
    <band height="40" splitType="Stretch">
        <frame>
            <reportElement x="2" y="0" width="1294" height="40"/>
            <staticText>
                <reportElement mode="Opaque"   x="564" y="20" width="110" height="20" forecolor="#000000" backcolor="#77BCD4"/>
                <box rightPadding="5">
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[TOTAL]]></text>
            </staticText>
            <staticText>
                <reportElement mode="Opaque" style="style_TOU" x="674" y="20" width="110" height="20" forecolor="#000000" backcolor="#77BCD4"/>
                <box rightPadding="5">
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[TOU 1]]></text>
            </staticText>
            <staticText>
                <reportElement mode="Opaque" x="784" y="20" width="110" height="20" forecolor="#000000" backcolor="#77BCD4"/>
                <box rightPadding="5">
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[TOU 2]]></text>
            </staticText>
            <staticText>
                <reportElement mode="Opaque" x="894" y="20" width="110" height="20" forecolor="#000000" backcolor="#77BCD4"/>
                <box rightPadding="5">
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[TOU 3]]></text>
            </staticText>
            <staticText>
                <reportElement mode="Opaque" x="1004" y="20" width="110" height="20" forecolor="#000000" backcolor="#77BCD4"/>
                <box rightPadding="5">
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[TOU 4]]></text>
            </staticText>
            <staticText>
                <reportElement mode="Opaque" x="564" y="0" width="550" height="20" forecolor="#000000" backcolor="#77BCD4"/>
                <box>
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <bottomPen lineWidth="0.5" lineColor="#CCCCCC"/>
                    <rightPen lineWidth="0.5" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Active Energy(kWh)]]></text>
            </staticText>
            <staticText>
                <reportElement mode="Opaque" x="178" y="0" width="130" height="40" forecolor="#000000" backcolor="#77BCD4"/>
                <box leftPadding="5">
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Serial No.]]></text>
            </staticText>
            <staticText>
                <reportElement mode="Opaque" x="436" y="0" width="128" height="40" forecolor="#000000" backcolor="#77BCD4"/>
                <box rightPadding="5">
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Subscribtion No.]]></text>
            </staticText>
        </frame>
        <staticText>
            <reportElement mode="Opaque" x="310" y="0" width="128" height="40" forecolor="#000000" backcolor="#77BCD4"/>
            <box rightPadding="5">
                <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
            </box>
            <textElement textAlignment="Center" verticalAlignment="Middle">

            </textElement>
            <text><![CDATA[Account No.]]></text>
        </staticText>
    </band>
</columnHeader>
<detail>
    <band height="24" splitType="Stretch">
        <rectangle>
            <reportElement x="180" y="0" width="936" height="24" isRemoveLineWhenBlank="true" backcolor="#D0E8F0">
                <printWhenExpression><![CDATA[$V{REPORT_COUNT}.intValue() % 2 != 1]]></printWhenExpression>
            </reportElement>
            <graphicElement>
                <pen lineWidth="0.0" lineColor="#CCCCCC"/>
            </graphicElement>
        </rectangle>
        <frame>
            <reportElement x="180" y="0" width="936" height="24" backcolor="#FFFFFF"/>
            <textField pattern="###0.0">
                <reportElement mode="Transparent" x="258" y="0" width="128" height="24" backcolor="#CCCCCC"/>
                <box rightPadding="3">
                    <pen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <topPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <bottomPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <rightPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{SUB_NO}+" "]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Band">
                <reportElement mode="Transparent" style="style_TOU" x="386"  y="0" width="110" height="24"/>
                <box rightPadding="3">
                    <pen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <topPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <bottomPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <rightPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Right" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{TOTAL_EXP} ==  null ? "n/a" : $F{TOTAL_EXP} +" "]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Band">
                <reportElement mode="Transparent" style="style_TOU" x="496" y="0" width="110" height="24"/>
                <box rightPadding="3">
                    <pen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <topPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <bottomPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <rightPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Right" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{TOU1_KWH_EXP}== null ? "n/a" : $F{TOU1_KWH_EXP} +" "]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Band">
                <reportElement mode="Transparent" style="style_TOU" x="606" y="0" width="110" height="24"/>
                <box rightPadding="3">
                    <pen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <topPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <bottomPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <rightPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Right" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{TOU2_KWH_EXP} == null ? "n/a" : $F{TOU2_KWH_EXP}+" "]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Band">
                <reportElement mode="Transparent" style="style_TOU" x="716" y="0" width="110" height="24"/>
                <box rightPadding="3">
                    <pen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <topPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <bottomPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <rightPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Right" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{TOU3_KWH_EXP} == null ? "n/a" : $F{TOU3_KWH_EXP} +" "]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Band">
                <reportElement mode="Transparent" style="style_TOU" x="826" y="0" width="110" height="24"/>
                <box rightPadding="3">
                    <pen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <topPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <bottomPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <rightPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Right" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{TOU4_KWH_EXP} == null ? "n/a" : $F{TOU4_KWH_EXP} +" "]]></textFieldExpression>
            </textField>
            <textField pattern="###0.0">
                <reportElement mode="Transparent" x="130" y="0" width="126" height="24" backcolor="#CCCCCC"/>
                <box rightPadding="3">
                    <pen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <topPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <bottomPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <rightPen lineWidth="0.75" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{ACCOUNT_NO}+" "]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement mode="Transparent" x="0" y="0" width="130" height="24" backcolor="#CCCCCC"/>
                <box leftPadding="5">
                    <topPen lineWidth="0.5" lineColor="#CCCCCC"/>
                    <leftPen lineWidth="0.75" lineColor="#CCCCCC"/>
                    <bottomPen lineWidth="0.5" lineColor="#CCCCCC"/>
                    <rightPen lineWidth="0.5" lineColor="#CCCCCC"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{METER_SLNO}]]></textFieldExpression>
            </textField>
        </frame>
    </band>
</detail>
<pageFooter>
    <band height="20" splitType="Stretch">
        <textField>
            <reportElement x="994" y="0" width="80" height="20"/>
            <textElement textAlignment="Right"/>
            <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
        </textField>
        <textField evaluationTime="Report">
            <reportElement x="1074" y="0" width="42" height="20"/>
            <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}+" "]]></textFieldExpression>
        </textField>
        <textField pattern="dd/MM/yyyy h.mm a">
            <reportElement x="182" y="0" width="100" height="20"/>
            <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
        </textField>
    </band>
</pageFooter>
<noData>
    <band height="33" splitType="Stretch">
        <staticText>
            <reportElement x="522" y="0" width="291" height="31"/>
            <textElement textAlignment="Center" verticalAlignment="Middle">

            </textElement>
            <text><![CDATA[No Data To Display]]></text>
        </staticText>
    </band>
</noData>

A: You have mode=Transparent on field level and that has higher priority then mode=Opaque at style level. Set the Transparent on style and remove it from fields, currently your conditional style sets background color on transparent fields.
Change text field from:
       <textField pattern="###0.0">
            <reportElement mode="Transparent" ...

to (1):
       <textField pattern="###0.0">
            <reportElement ...

or (2):
       <textField pattern="###0.0">
            <reportElement mode="Opaque" ...

I'm not sure which of those you can set but it should work after you change that.
Also if you want the field to be transparent when condition is not satisfied you could change style to this:


text:
Q: Python argparse : how to detect duplicated optional argument? I'm using argparse with optional parameter, but I want to avoid having something like this : script.py -a 1 -b -a 2
Here we have twice the optional parameter 'a', and only the second parameter is returned. I want either to get both values or get an error message.
How should I define the argument ?
[Edit]
This is the code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='alpha', action='store', nargs='?')
parser.add_argument('-b', dest='beta', action='store', nargs='?')

params, undefParams = self.parser.parse_known_args()

A: append action will collect the values from repeated use in a list
parser.add_argument('-a', '--alpha', action='append')

producing an args namespace like:
namespace(alpha=['1','3'], b='4')

After parsing you can check args.alpha, and accept or complain about the number of values.  parser.error('repeated -a') can be used to issue an argparse style error message.
You could implement similar functionality in a custom Action class, but that requires understanding the basic structure and operation of such a class.  I can't think anything that can be done in an Action that can't just as well be done in the appended list after.
https://stackoverflow.com/a/23032953/901925 is an answer with a no-repeats custom Action.
Why are you using nargs='?' with flagged arguments like this?  Without a const parameter this is nearly useless (see the nargs=? section in the docs).
Another similar SO: Python argparse with nargs behaviour incorrect

redpajama_set_name: RedPajamaStackExchange


text:
Q: using .Contains() with linq-to-sql I have the following query that receives a list of ints as a parameter:
public int GetMostRecent(List<int> TheIDs)
{
 ...using MyDC...

   var TheMostRecentID = (from d in MyDC.Data
                           where TheIDs.Contains(d.ID)
                           orderby d.DateTime
                           select d.ID).LastOrDefault();
}

Is this the best way to match a list within a parameter collection to data in the database or is there a better way than using the .Contains() method in linq-to-sql.
Thanks.

A: What you have is correct. This will be translated into an IN clause in SQL with the values supplied in the collection.
On an unrelated note, you should try ordering the query by date descending and use FirstOrDefault(). As it is now, you're going to bring back the entire result set and throw away every row but one.

A: You should be careful with such queries with list.Contains() inside of linq query. Because for each list element it will create a param in sql statement.
And there's a limited number of params allowed in sql statement, <= 2100.
So if your TheIDs will contains more than 2100 elements it will fail.
If you want to use in this way, you should at least check your TheIDs count and if more then 2100 dived it in pieces with less then 2100 elements.

A: This will translate into efficient SQL, so there's no need to use anything else.


text:
Q: How to Run  of php page on synchronised data-async-load call in jquery As I've successfully open a xy.php page in div id="portfolio" of the working abc.php page  without redirection. But the problem arose is that I think it is a synchronized call that is why when the xy.php page open in a div id="portfolio" than its  onload function does not call because this xy.php page is opened using synchronised method not redirect. So, On Synchronised call how to run the functions which is present inside onload="". Any Suggestions ? ?  ?
Here is my working JS Fiddle
I'm calling the next page on `

` tag

A: Ok I Did it!!!! The functions  which are called on loading or redirecting or refereshing the page is know called by  using JQuery and it works when you are loading your page by synchronisation data-async-load. Here is the code


text:
Q: How to sequence-identifier? In our old architektur we used id's like this:
/**
  * Model for each database-object
  */
public abstract class AbstractDbBase {
    @Getter
    @Setter
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(nullable = false, unique = true, updatable = false)
    private Long id;
}

But we got some issues, while changing values outside of Hibernate.
So we decide to use bigserial from postgres.
We changed our database and added for a each table a seqeunce and set it as primary key.
We have a lot of entities and all of them using the AbstractDbBase. And in AbstractDbBase is the defintion of the id.
But now we cant set Hibernate to use the sequence correctly.
We tried the following stragegies (for the @GeneratedValue()-annotation):

*

*GenerationType.IDENTITY: Throws excepetion when create records over hibnerate (no access to the sequence).

*GenerationType.SEQUENCE: Throws validation-exception (no sequence found).

*GenerationType.AUTO: Throws validation-exception (no sequence found).

My question is: How we can tell Hibernate to use the correct sequence? (Without write explicit the sequence-name for each entity)

A: I found this: hibernate could not get next sequence value
So I have to use GenerationType.IDENTITY. Now I have to solve the "no permission for the sequence"-issue.
This have I done with this question: ERROR: permission denied for sequence cities_id_seq using Postgres
It works now.


text:
Q: Adjust image saturation by color type I have the following method, which takes an array of pixel data, and then adjusts the saturation to this.adjustmentAmount currently it works! But I want to take it further by only adjusting the saturation of these colors:
red, green, blue, yellow, cyan, magenta
How can this be done?
public int[] filter(String keep){
    for(int i = 0; i < this.pixels.length; i++){
        int pixel = this.pixels[i];
        int red = Colors.red(pixel);
        int green = Colors.green(pixel);
        int blue = Colors.blue(pixel);

        float[] hsv = new float[3];
        Color.RGBtoHSB(red, green, blue, hsv);
        hsv[1] += (float)(this.adjustmentAmount * 0.01);
        if(hsv[1] > 1){
            hsv[1] = 1;
        }else if(hsv[1] < 0){
            hsv[1] = 0;
        }

        int newpixel = Color.HSBtoRGB(hsv[0], hsv[1], hsv[2]);

        red = Colors.red(newpixel);
        green = Colors.green(newpixel);
        blue = Colors.blue(newpixel);

        this.pixels[i] = Colors.rgba(red, green, blue);
    }
    return this.pixels;
}

Here is a working sscce (Just modify the file name):
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sscce;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Ryan
 */
public class Sscce extends JFrame{

    public Layer layer;

    public Sscce(){
    try{
            this.setSize(800, 600);
            this.setResizable(false);
            this.setLocationRelativeTo(null);
            this.setVisible(true);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            layer = new Layer();
            layer.setImage("http://www.prikol.ru/wp-content/gallery/october-2012/datacenter-01.jpg");
            this.add(layer);
            this.revalidate();
            Timer timer = new Timer();
            timer.schedule(new TimerTask(){
                @Override
                public void run(){
                    applySat();
                }
            }, 500);
        }catch(IOException ex){
            Logger.getLogger(Sscce.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    protected void applySat(){
        Saturation sat = new Saturation();
        sat.setAmount(-100);
        BufferedImage img = this.layer.getImage();
        int[] pixels = new int[img.getWidth() * img.getHeight()];
        this.layer.getImage().getRGB(0, 0, img.getWidth(), img.getHeight(), pixels, 0, img.getWidth());
        sat.setPixels(pixels);
        pixels = sat.filter("yellow");
        img.setRGB(0, 0, img.getWidth(), img.getHeight(), pixels, 0, img.getWidth());
        this.layer.setImage(img);
    }
    public static void main(String[] args){
        new Sscce();
    }
}

class Layer extends JPanel{

    protected BufferedImage image;

    public BufferedImage getImage(){
        return this.image;
    }

    public void setImage(BufferedImage image){
        this.image = image;
        this.repaint();
    }

    public void setImage(String filename) throws IOException{
        this.image = ImageIO.read(new URL(filename));
        this.setSize(this.image.getWidth(), this.image.getHeight());
        this.repaint();
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(this.image, 0, 0, this.image.getWidth(), this.image.getHeight(), Color.black, null);
    }
}

class Saturation{

    protected volatile int[] pixels;
    protected int adjustmentAmount = 0;

    public void setPixels(int[] pixels){
        this.pixels = pixels;
    }

    public void setAmount(int amount){
        this.adjustmentAmount = amount;
    }

    public int[] filter(String keep){
        for(int i = 0; i < this.pixels.length; i++){
            int pixel = this.pixels[i];
            int red = Colors.red(pixel);
            int green = Colors.green(pixel);
            int blue = Colors.blue(pixel);

            float[] hsv = new float[3];
            Color.RGBtoHSB(red, green, blue, hsv);
            hsv[1] += (float)(this.adjustmentAmount * 0.01);
            if(hsv[1] > 1){
                hsv[1] = 1;
            }else if(hsv[1] < 0){
                hsv[1] = 0;
            }

            int newpixel = Color.HSBtoRGB(hsv[0], hsv[1], hsv[2]);
            red = Colors.red(newpixel);
            green = Colors.green(newpixel);
            blue = Colors.blue(newpixel);

            this.pixels[i] = Colors.rgba(red, green, blue);
        }
        return this.pixels;
    }
}

class Colors{

    public static int rgba(int red, int green, int blue, Integer alpha){
        int rgba = alpha;
        rgba = (rgba << 8) + red;
        rgba = (rgba << 8) + green;
        rgba = (rgba << 8) + blue;
        return rgba;
    }

    public static int rgba(int red, int green, int blue){
        int rgba = 255;
        rgba = (rgba << 8) + red;
        rgba = (rgba << 8) + green;
        rgba = (rgba << 8) + blue;
        return rgba;
    }
    public static int[] getrgba(int color){
        int[] colors = new int[3];
        colors[0] = Colors.red(color);
        colors[1] = Colors.green(color);
        colors[2] = Colors.blue(color);
        return colors;
    }

    public static int alpha(int color){
        return color >> 24 & 0x0FF;
    }

    public static int red(int color){
        return color >> 16 & 0x0FF;
    }

    public static int green(int color){
        return color >> 8 & 0x0FF;
    }

    public static int blue(int color){
        return color & 0x0FF;
    }
}

A: You should set threshold values on RGB channels for the color you have mentioned.
For example default YELLOW color is defined as
RED: 255
GREEN : 255
BLUE : 0

But you probably want to accept little darker ones as yellow. Then you should set range on above three channel for YELLOW as below:
RED : [240 - 255]
GREEN : [240 - 255]
BLUE : [0 - 30]

You can apply this method for all colors and decide to adjust the saturation or not.


text:
Q: Swift fatal error: Can't form Range with upperBound < lowerBound I have a class that I want to add value there with for loop.
This is my class:
public class Expandable {
    public var name: String
    public var id:Int

    init(name: String, id:Int) {
        self.name = name
        self.id = id
    }

I can add manually like that :
let a = [Expandable(name:"aaa", id: 12)]

But when I try with for loop, it doesn't work at all.
for allin in items{
    sidebarMenuItem?.append(Expandable(name: allin["Code"] as! String, id: allin["Id"] as! Int))
}

Items data works perfectly, but sidebarMenuItem is getting Optional(MyProjectName.Expandable) value when I print it.
UPDATE :
I realized that I'm getting the datas well, but I get an error into expandCell function :

fatal error: Can't form Range with upperBound < lowerBound

My expandCell function :
private func expandCell(tableView: UITableView, index: Int) {
    // Expand Cell (add ExpansionCells
    if let expansions = sideBarData?[index]?.expandable {
        for i in 1...expansions.count {
            sideBarData?.insert(nil, at: index + i)
            tableView.insertRows(at: [NSIndexPath(row: index + i, section: 0) as IndexPath] , with: .top)
        }
    }
}

A: sidebarMenuItem is optional because you have declared it optional. Try this.
var sidebarMenuItem = [Expandable]()

for allin in items{
    sidebarMenuItem.append(Expandable(name: allin["Code"] as! String, id: allin["Id"] as! Int))
}

A: // swift 3.0
let k = 5
for i in stride(from: 10, through: k, by: 1) { print("i=\(i)") }
for i in stride(from: 10, to: k, by: 1) { print("i=\(i)") }

A: SWIIFT 4
To form a range from upperBound to lowerBound use stride as by this documentation page:
Generic Function stride(from:to:by:)
for i in stride(from: 10, through: 5, by: -1) { print(i) }
and stride through if you want to include the lowerBound:  Generic Function stride(from:through:by:)

A: I am not sure how is your expansions structure. But I am guessing it for some cell it might be that your expansion count is 0. That is why its giving this error when your start index is 1 and end index is 0.

A: try this:
  private func expandCell(tableView: UITableView, index: Int) {
        // Expand Cell (add ExpansionCells
        if let expansions = sideBarData?[index]?.expandable {
            //0 because your first item starts at 0
            for i in 0...expansions.count {
                sideBarData?.insert(nil, at: index + i)
                tableView.insertRows(at: [NSIndexPath(row: index + i, section: 0) as IndexPath] , with: .top)
            }
        }
    }


text:
Q: can encrypt ConnectionString in web.config on development machine and deploy on server? I am going to encrypt connection string in web.config using aspnet_regiis.exe tool.
Not sure how connection string is decrypted on server so wana ask, if I encrypt on my development machine and deploy on server, will it work ? Or it should be encrypted on same machine where it is going to be executed ?

A: If you use aspnet_regiis.exe tool, then you will need to do it on each server separately, because the encryption is married to the server where the encryption key was generated. So the short answer is, if you do this method, no your DEV encryption key will not work when you deploy to other environments.
However, if you want to be able to encrypt on one server and deploy it to other servers re-using the same key, then you need to Encrypt Configuration Sections in ASP.NET 2.0 Using RSA. This works, because you can export RSA keys. This technique is especially useful in web farm scenarios (i.e. multiple front-end web servers).


text:
Q: Crop a diagonal area from an image in WPF I want to crop from an image using user-drawn rectangles on a canvas. The rectangles can be moved, re-sized, and rotated.
When the user selects "Get Cropped Image", the area inside the rectangle should be saved in a second image location on the page, which I can do perfectly well, so long as the rectangle is not rotated. (Straight-forward use of CroppedBitmap.) However, when the rectangle is at an angle I do not know how to perform the crop.
This is what I want to do (forgive my poor MS Paint skills):

My questions are:
1) How do I correctly track or calculate the points of the rectangle?
and,
2) Once I have the points, how do I crop the rotated rectangle?
EDIT:
Thanks to user Rotem, I believe that I have the answer to the second question. Using code modified from the following answers: Answer 1, Answer 2, I am seeing good results. Unfortunately, I am still unable to track the correct location points for the rectangle, so I cannot fully test this as of yet.
public static Bitmap CropRotatedRect(Bitmap source, System.Drawing.Rectangle rect, float angle, bool HighQuality)
 {
    Bitmap result = new Bitmap((int)rect.Width, (int)rect.Height);
    using (Graphics g = Graphics.FromImage(result))
     {
        g.InterpolationMode = HighQuality ? InterpolationMode.HighQualityBicubic : InterpolationMode.Default;
        using (Matrix mat = new Matrix())
         {
            mat.Translate(-rect.Location.X, -rect.Location.Y);
            mat.RotateAt(-(angle), rect.Location);
            g.Transform = mat;
            g.DrawImage(source, new System.Drawing.Point(0, 0));
         }
     }
    return result;
 }

EDIT:
The answer to the first point is much easier than I had originally thought. You can always get the top-left corner of the rectangle by calling—
double top = Canvas.GetTop(rect);
double left = Canvas.GetLeft(rect);

You can then calculate the rest of the points using the width and the height—
Point topLeft = new Point(left, top);
Point topRight = new Point(left + rect.Width, top);
Point bottomLeft = new Point(left, top + rect.Height);
Point bottomRight = new Point(left + rect.Width, top + rect.Height);
Point centerPoint = new Point(left + (rect.Width / 2), top + (rect.Height / 2));

If your rectangle is rotated, then you have to translate these points to determine where they truly lie on the canvas—
public Point TranslatePoint(Point center, Point p, double angle)
 {
    // get the point relative to (0, 0) by subtracting the center of the rotated shape.
    Point relToOrig = new Point(p.X - center.X, p.Y - center.Y);
    double angleInRadians = angle * Math.PI / 180;
    double sinOfA = Math.Sin(angleInRadians);
    double cosOfA = Math.Cos(angleInRadians);
    Point translatedPoint = new Point(relToOrig.X * cosOfA - relToOrig.Y * sinOfA,
                                      relToOrig.X * sinOfA + relToOrig.Y * cosOfA);
    return new Point(translatedPoint.X + center.X, translatedPoint.Y + center.Y);
 }

Once you are able to translate the top-left corner, you can use Rotem's cropping method. You can also calculate the position of the rest of the rectangle, so you are able to determine if the rectangle is within the bounds of the image, if it is touching an edge, or any other thing that you might want to do in regards to the position.

A: I discovered the answer to my own question(s), and made the appropriate edits along the way. Please see above for the answer.


text:
Q: wacom tablet intuos DRAW ( CTL-490 ) FAR not work perfectly tablet name : Wacom tablet intuos DRAW small ( CTL - 490 )
current OS   : KDE Ubuntu 16.04 ( 64 bit ) ( Hungarian )
current kernel : 4.4
problem : the wacom tablet is recognize as Joystick, but work as a touchpad, so i can draw with it, senseless, and buttonless.
the things starts with Linux MINT 17.3 KDE , but my tablet is not work at all. my linux mint friends tolds me, this error is because the linux mint uses the very old kernel . so i am jumps into another KDE distro, the kde-ubuntu 16.04 ,because this is using a new kernel. the situation is much better now, the tablet works as touch pad, and a joystick ... confusing.
in the settings window, the buttons, and ALL of the sensitive stuff is out of working. inactive. the touch pad settings is see nothing , because the "synaptics backend missing. " ... so i am unable to change anything, because ALL the setting button here is gray, inactive. sadly the half of the settings screen is english, and half is hungarian

how interesting is, the synaptics are already installed.
the console told me, the synaptics is already the newest, up to date, version 1.8.2 ( all four zeros. )

the more interesting stuff is, the tablet is appears on one more tab.
The joystick section !

of course, the tablet is NOT a joystick, and the buttons surprisely appears VERY good, its means all the buttons work fine, but i am dont know why in this way.
if the question is still not clear for you, i am very sad.
( how i can put back the wacom tablet to work normally ? )

A: ( Tested on Linux mint 17.3 KDE )
Before build your castle, you will need some dependencies fixed.
++++++++++++++
type this into the Konsole / Terminal :
sudo apt-get install linux-headers-$(uname -r) build-essential
++++++++++++++
Download the wacom input 32th version ( TAR.BZ archive ) with any kind of browser.
( https://sourceforge.net/projects/linuxwacom/files/xf86-input-wacom/input-wacom/input-wacom-0.32.0.tar.bz2/download )
++++++++++++++
unpack your fresh download with TAR command (go to the location, where you want to INSTALL):
tar xjvf input-wacom-0.32.0.tar.bz2
cd input-wacom-0.32.0
++++++++++++++
and now the last step, the Build and Install
go in the fresh directory ( you remember, the folder's name is "input-wacom-0.32.0" )
and type the following lines ( and BE PATIENCE ) :
./configure
make
sudo make install
+++++++++++
and thats it. REBOOT the system, and after the system boots up, go, and CHECK the WACOM controll panel to be ensure the method is working !
remember, you will suffer a lot, if you enables any kind of 1 line eyefinity, or another single line multi monitor setting !


text:
Q: Renaming multiple files to start with a capital letter i'm trying to update my website to use CodeIgniter 3
but Starting with CodeIgniter 3.0, all class filenames (libraries, drivers, controllers and models) must be named in a Ucfirst-like manner or in other words - they must start with a capital letter.
For example, if you have the following library file:
application/libraries/mylibrary.php

... then you'll have to rename it to:
application/libraries/Mylibrary.php

The same goes for driver libraries and extensions and/or overrides of CodeIgniter's own libraries and core classes.
application/libraries/MY_email.php application/core/MY_log.php

The above files should respectively be renamed to the following:
application/libraries/MY_Email.php application/core/MY_Log.php

Controllers:
application/controllers/welcome.php -> application/controllers/Welcome.php

Models:
application/models/misc_model.php -> application/models/Misc_model.php

How i can do that with command line ?
thanks ,

A: With Bash 4, first enable additional globbing options:
shopt -s extglob

Now make sure you call this only in the folders that contain the PHP files you want to rename. It will recursively look for .php files.
for f in **/*.php; do
  fn=$(basename "$f") # remove directory name
  Fn=${fn^}           # uppercase first letter
  echo mv -- "$f" "$(dirname "$f")/$Fn"  # combine both
done

For the MY_ files, you may need another run:
for f in **/MY_*.php; do
  fn=$(basename "$f")
  Fn=${fn#MY_}     # remove MY_ from filename
  Fn="MY_${Fn^}"   # uppercase first letter and add MY_ again
  echo mv -- "$f" "$(dirname "$f")/$Fn"
done

Remove the echo from these scripts to perform the renaming.

A: Use a little utility called mmv. You can uppercase the first letter as follows:
mmv "[a-z]*\.*" "#u1#2.#3"

And for the second case you mention (MY_log.php), you could solve this as follows:
mmv "*_[a-z]*.php" "#1_#u2#3.php"

or:
mmv "*_[a-z]*" "#1_#u2#3"


text:
Q: Why operating systems are not written in java? All the operating systems till date have been written in C/C++ while there is none in Java. There are tonnes of Java applications but not an OS. Why?

A: Indeed there is a JavaOS http://en.wikipedia.org/wiki/JavaOS
And here is discuss about why there is not many OS written in java Is it possible to make an operating system using java?
In short, Java need to run on JVM. JVM need to run on an OS. writing an OS using Java is not a good choice.
OS needs to deal with hardware which is not doable using java (except using JNI). And that is because JVM only provided limited commands which can be used in Java. These command including add, call a method and so on. But deal with hardware need command to operate reg, memory, CPU, hardware drivers directly. These are not supported directly in JVM so JNI is needed. That is back to the start - it is still needed to write an OS using C/assembly.
Hope this helps.

A: One of the main benefits of using Java is that abstracts away a lot of low level details that you usually don't really need to care about. It's those details which are required when you build an OS. So while you could work around this to write an OS in Java, it would have a lot of limitations, and you'd spend a lot of time fighting with the language and its initial design principles.

A: For operating systems you need to work really low-level. And that is a pain in Java. You do need e.g. unsigned data types, and Java only has signed data types. You need struct objects that have exactly the memory alignment the driver expects (and no object header like Java adds to every object).
Even key components of Java itself are no longer written in Java.
And this is -by no means- a temporary thing. More and more does get rewritten in native code to get better performance. The HotSpot VM adds "intrinsics" for performance critical native code, and there is work underway to reduce the overall cost of native calls.
For example JavaFX: The reason why it is much faster than AWT/Swing ever were is because it contains/uses a huge amount of native code. It relies on native code for rendering, and e.g. if you add the "webview" browser component it is actually using the webkit C library to provide the browser.
There is a number of things Java does really well. It is a nicely structured language with a fantastic toolchain. Python is much more compact to write, but its toolchain is a mess, e.g. refactoring tools are disappointing. And where Java shines is at optimizing polymorphism at run-time. Where C++ compilers would need to do expensive virtual calls - because at compile time it is not known which implementation will be used - there Hotspot can aggressively inline code to get better performance. But for operating systems, you do not need this much. You can afford to manually optimize call sites and inlining.

A: Because we have operating systems already, mainly. Java isn't designed to run on bare metal, but that's not as big of a hurdle as it might seem at first. As C compilers provide intrinsic functions that compile to specific instructions, a Java compiler (or JIT, the distinction isn't meaningful in this context) could do the same thing. Handling the interaction of GC and the memory manager would be somewhat tricky also. But it could be done. The result is a kernel that's 95% Java and ready to run jars. What's next?
Now it's time to write an operating system. Device drivers, a filesystem, a network stack, all the other components that make it possible to do things with a computer. The Java standard library normally leans heavily on system calls to do the heavy lifting, both because it has to and because running a computer is a pain in the ass. Writing a file, for example, involves the following layers (at least, I'm not an OS guy so I've surely missed stuff):

*

*The filesystem, which has to find space for the file, update its directory structure, handle journaling, and finally decide what disk blocks need to be written and in what order.

*The block layer, which has to schedule concurrent writes and reads to maximize throughput while maximizing fairness.

*The device driver, which has to keep the device happy and poke it in the right places to make things happen. And of course every device is broken in its own special way, requiring its own driver.

And all this has to work fine and remain performant with a dozen threads accessing the disk, because a disk is essentially an enormous pile of shared mutable state.
At the end, you've got Linux, except it doesn't work as well because it doesn't have near as much effort invested into functionality and performance, and it only runs Java. Possibly you gain performance from having a single address space and no kernel/userspace distinction, but the gain isn't worth the effort involved.
There is one place where a language-specific OS makes sense: VMs. Let the underlying OS handle the hard parts of running a computer, and the tenant OS handles turning a VM into an execution environment. BareMetal and MirageOS follow this model. Why would you bother doing this instead of using Docker? That's a good question.

A: This answer does not mean to be exhaustive in any way, but I'd like to share my thoughts on the (very vast) topic.
Although it is theoretically possible to write some OS in pure java, there are practical matters that make this task really difficult. The main problem is that there is no (currently up to date and reliable) java compiler able to compile java to byte code. So there is no existing tool to make writing a whole OS from the ground up feasible in java, at least as far as my knowledge goes.
Java was designed to run in some implementation of the java virtual machine. There exist implementations for Windows, Mac, Linux, Android, etc. The design of the language is strongly based on the assumption that the JVM exists and will do some magic for you at runtime (think garbage collection, JIT compiler, reflection, etc.). This is most likely part of the reason why such a compiler does not exist: where would all these functionality go? Compiled down to byte code? It's possible but at this point I believe it would be difficult to do. Even Android, whose SDK is purely java based, runs Dalvik (a version of the JVM that supports a subset of the language) on a Linux Kernel.


text:
Q: selenium web-driver chrome doesn't execute code after
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

s = Service('/usr/bin/chromium-browser')
driver = webdriver.Chrome(service=s)
print("driver has started")

it will not execute  print("driver has started") or anything after

A: It is an expected behaviour as the code will be stuck on the webdriver.Chrome while the browser is open.
I suggest you do that print before starting the driver, but that really depends on what you want to do exactly. If you need to do that in parallel, at the same time, while the browser works, you would probably need threads.


text:
Q: Can the domain model and repositories be in seperate dlls? Can the domain model and the repositories be in separate dlls?
In a 3 tier architecture I guess I would put the domain model in the business layer
and the repositories in the data access layer.
I get confused as it is my understanding that the domain model uses the repositories while the repositories should return objects from the domain model, which would cause a circular dependency.
I must be misunderstanding one or more of the above concepts.
Any clarification would be greatly appreciated as this has been bothering me for a while, thanks.

A: I don't think you should let your domain assembly reference anything from your own application at all. It should be the innermost assembly, that is totally ignorant of anything on the outside. It just sits there and knows the domain logic.
Your domain model shouldn't be using the repositories, the application services should.
(If the domain entities actually needs to use a repository, it should be injected from the application services. Some people would argue, that this should not be necessary though - and I think so too).
Try looking at it this way: Your have an application service which is the primary way your client/frontend/controller can use the domain. The application services defines the operations that can be done on your application.
The application service use a repository to load the domain object that it needs to work on, call the necessary method on the domain object and returns the result (if the operations return a such). The domain know nothing about the application service or the repository.
A nice way to get started organizing your application this way, is taking a look at this series of blog posts: http://jeffreypalermo.com/blog/the-onion-architecture-part-1/
And take a look at dependency injection, it can help you solve other problems, where it seems like, you would have a circular reference.
Ask if you have any questions.


text:
Q: How to configure WSS connection on Django Azure Web App I've attempted to make an Azure Web App using Django. For the past couple days, I've mingled with Websockets for use for a real-time chat locally using the ws protocol. But, when deploying on Azure, I am forced to use the wss protocol due to the website being hosted on https. I've done some research on how to configure wss to no avail. Can anyone help?
I initiate the connection using:
if (window.location.protocol == 'https:') {
  wsProtocol = 'wss://'
} else {wsProtocol = 'ws://'}
const chatSocket = new WebSocket(wsProtocol + window.location.host + "/");

This gives: "WebSocket connection to 'wss://pharma-send.azurewebsites.net/' failed:"
I'm using django-channels.
In the Startup Command of my Azure app I've tried running the Gunicorn server with ASGI using
gunicorn pharmasend.asgi:application --bind 0.0.0.0:8000 -w 2 -k uvicorn.workers.UvicornWorker
Although, this hasn't changed anything. Do I need to run an ASGI server, like Daphne or Uvicorn? Or, does Azure's Oryx do it for me?
Thanks for helping!

A:
configure WSS connection on Django Azure Web App

Install the Channels package in the Application.
Thanks @divanov11 for the GitHub sample code which has the configuration to WebSocket.

Do I need to run an ASGI server, like Daphne or Uvicorn?

Azure Oryx will not run the ASGI server.
Yes, we need to run any of the one ASGI server either Daphne or Uvicornto configure WSS connections on Django Azure App
Thanks @channels.readthedocs for the commands.
Install the Daphne in the Application.
pip install Daphne


text:
Q: How to make a post request with REQUESTS package for Python? I am trying to use the toggl api.
I use Requests instead of Urllib2 for doing my GETs en POSTS. But i am stuck.
payload = {
    "project":{
        "name":"Another Project",
        "billable":False,
        "workspace":{
            "Name":"jorrebor's workspace",
            "id":213272
        },
        "automatically_calculate_estimated_workhours":False
    }
}

url = "https://www.toggl.com/api/v6/projects.json"
r = requests.post(url, data=json.dumps(payload), auth=HTTPBasicAuth('j_xxxxx@gmail.com', 'mypassword'))

Authentication seems to be fine, but the payload format probably isn't.
a curl command with the same parameters:
curl -v -u heremytoken:api_token -H "Content-type: application/json" -d "{\"project\":{\"billable\":true,\"workspace\":{\"id\":213272},\"name\":\"Another project\",\"automatically_calculate_estimated_workhours\":false}}" -X POST https://www.toggl.com/api/v6/projects.json

does work fine.
What wrong with my payload? The response is get is:
    ["Name can't be blank","Workspace can't be blank"]
which leads me to conclude that the authentication works but toggl cannot read my json object.

A: Seems like you should try setting the header to a JSON application, rather than the default format, and send a JSON object instead of the Python dict. Check it out here:
payload = {"project":{"name":"Another Project",
                     "billable":False,
                     "workspace":{"Name":"jorrebor's workspace",
                                  "id":213272},
                     "automatically_calculate_estimated_workhours":False
                      }   }

parameters_json = json.dumps(payload)
headers = {'Content-Type': 'application/json')
r = client.post(url, data=parameters_json, headers=headers)

which should allow the site to read the json object just fine.


text:
Q: How can I count most occuring sequences of 3 letters within a word with a bash script Indo Cheap has a sample file like
XYZAcc
ABCAccounting
Accounting firm
Accounting Aco
Accounting Acompany
Acoustical consultant

He needs to get the most occurring sequences of 3 letters within a word.
Output should be
acc = 5 aco = 3

He asks if that is possible in bash.
He says: "I got absolutely no idea how I can accomplish it with either awk, sed, grep.
Any clue how it's possible..."

A: This absolutely possible with bash, sed and awk, and here is how to do it:
#!/bin/bash

for line in $(cat sample | tr 'A-Z' 'a-z' | tr -s ' ' '\n'); do
  ll=${#line}
  for ((i = 0; i < ll - 2; i++)) ; do   # for each word
    echo ${line:i:3}                    # print all sequences of 3 letters
  done
done |
  sort |                                # sort the sequences of three letters
  uniq -c |                             # count the sequences
  sed '/^ *1 /d' |                      # filter out the not repeated sequences
  sort -n -r |                          # most frequent sequences first
  awk -F ' ' '{print $2" = "$1}' |      # format output as asked
  tr '\n' ' '                           # put all results on one line
echo                                    # add a new line at the end

And the ouput of the sample above is:
cou = 5 acc = 5 unt = 4 tin = 4 oun = 4 nti = 4 ing = 4 cco = 4 aco = 3

In case another format of output is wanted, we can easily adapt the code of the script according to the needs.


text:
Q: How to convert hex strings to a meaningful data in order of ml based classification? I have some hex strings which are represent tcp packet payload. the payloads are encrypted using TLS and I want to find a pattern for it. The problem is tcp packet classification just by using tcp payload and for that reason I used le = preprocessing.LabelEncoder() for KNN classification in order to change hex string of payload to a value. The result was 5% accuracy in classification I changed the classification to Random Forest but the result was just like before. What is your solution for encrypted payload based classification?
le = preprocessing.LabelEncoder()
df['payload'] = le.fit_transform(df['payload'])
one_hot_encoded_data = pd.get_dummies(df, columns = ['class'])
print(one_hot_encoded_data)

X = one_hot_encoded_data.iloc[:, one_hot_encoded_data.columns != 'class_1']
y = one_hot_encoded_data.class_1

#-----------------------------------------

x_train, x_test, y_train, y_test = train_test_split(X, y, train_size=0.6, random_state = 0)

model4 = RandomForestRegressor(random_state=0).fit(x_train, y_train)
print ('Random_Forest_train_accuracy:', model4.score(x_train, y_train))
print ('Random_Forest_test_accuracy:', model4.score(x_test, y_test))
y_pred4 = model4.predict(x_test)

A: Using (properly) encrypted content as a feature for machine learning makes no sense. A main property of proper encryption is that there is no statistically significant relation between original content and encrypted content. The statistic properties of encrypted content are similar to random data instead and thus provide absolutely no value as a feature in machine learning.
There are a few information which can be used though, like

*

*size of encrypted payload which is similar to the size of original payload but not not exactly the same

*timing and direction of data, which also reflect the timing and direction of the original data

*some meta information from the TLS handshake, like server name (SNI), certificate information (up to TLS 1.2), TLS client fingerprint (JA3), chosen cipher ...

There are actually lots of publications about this topic.


text:
Q: In Python Tkinter, how do I run code after mainloop window opens? I want to create a little animation where text appears on an old monochrome terminal like screen as if someone is typing it. However I constantly run into problems with trying to run code after the GUI window opens up. The text is always already there when the window opens or doesnt appear at all. Any help is very appreaciated:)
string = "Hello World this is a Test String"

import random
import time
import tkinter as tk
from tkinter import *

vid = tk.Tk()
vid.title('Terminal')

text = Text( vid, width = 100, height = 50,  highlightthickness=1, bg='black', highlightbackground="black", font=('Courier', 14), fg='green')
text.pack()

def main():
for i in string:
    text.insert(END, i)
    time.sleep(0.2)

text.after(10, main)
vid.mainloop()

This is what I came up with so far:/

A: You need to use update_idletasks()after your sleep. The following works for me, let me know if you have any other questions:
string = "Hello World this is a Test String"

import random
import time
import tkinter as tk
from tkinter import *

vid = tk.Tk()
vid.title('Terminal')

text = Text( vid, width = 100, height = 50,  highlightthickness=1, bg='black', highlightbackground="black", font=('Courier', 14), fg='green')
text.pack()

def main():
    for i in string:
        text.insert(END, i)
        time.sleep(0.2)
        vid.update_idletasks()

vid.after(10, main)
vid.mainloop()

A: It is generally not a good idea to use sleep for an event-driven program (tkinter is event-driven, as it is the case for most GUI libraries). Here, it is better to base your animation on the after method:
import random
import tkinter as tk

string = "Hello World this is a Test String"

def animate(n=0):
  text.insert(tk.END, string[n])
  n += 1
  if n == len(string): # reached end of string
    text.insert(tk.END, '\n') # insert newline
    n = 0 # and reset current char index
  text.after(200, lambda:animate(n)) # call function again in 200ms

vid = tk.Tk()
vid.title('Terminal')

text = tk.Text(vid, width=100, height=50, highlightthickness=1, bg='black',
            highlightbackground="black", font=('Courier', 14), fg='green')
text.pack()

vid.after(10, animate)
vid.mainloop()

Note: I've slightly changed your animation to create an infinite loop where the string is endlessly printed char by char, inserting a new line when the end is reached. Just for the fun...


text:
Q: dependency resolution with sbt for continuous integration I'm an open-source Scala developer who wants to minimize the hassle of dependencies when pushing to GitHub and triggering a check with continuous integration (CircleCI). I have two projects where one (A) is dependent on the other (B). B is under development at the same time (as a snapshot). My project A build.sbt file has a dependency on this (snapshot) version of B and of course all works fine on my local machine. When I push to GitHub, it naturally fails as that snapshot file is not available to CircleCI.
I have generally worked around this by putting the jar file into my lib directory (and removing the dependency from build.sbt). I believe this is known as an unmanaged dependency.
My question is this: is there any way of setting up my lib directory so that CircleCI can resolve the (managed) dependency from the lib directory? I have tried putting the ivy structure into lib starting with the top level com.phasmidsoftware, with b_2.13 under that and under that 1.0.4-SNAPSHOT and so on down. That doesn't work. I've attached the build.sbt for project A (called Numeric).
organization := "com.phasmidsoftware"

name := "Number"

version := "1.0.9"

scalaVersion := "2.13.6"

scalacOptions ++= Seq( "-target:jvm-1.8", "-encoding", "UTF-8", "-unchecked", "-deprecation", "-Ywarn-dead-code", "-Ywarn-value-discard", "-Ywarn-unused" )

val scalaTestVersion = "3.2.3"

libraryDependencies += "org.scalatest" %% "scalatest" % scalaTestVersion % "test"

resolvers += "Typesafe Repository" at "https://repo.typesafe.com/typesafe/releases/"

libraryDependencies ++= Seq(
  "com.phasmidsoftware" %% "matchers" % "1.0.4-SNAPSHOT",
  "org.scala-lang.modules" %% "scala-parser-combinators" % "1.2.0-M1",
  "org.apache.commons" % "commons-math3" % "3.6.1",
  "org.slf4j" % "slf4j-api" % "1.7.31",
  "ch.qos.logback" % "logback-classic" % "1.2.3" % "test",
  "org.scalacheck" %% "scalacheck" % "1.14.1" % "test"
)

A: The answer described in How can sbt pull dependency artifacts from git? is indeed the right answer.
I will just add a couple of caveats.

*

*Make sure that you use the git protocol in the URI of your git repository (as is shown in the other answer);

*The mechanism works by cloning the repository (the branch is defined by ...#branch) but, once you've cloned it, sbt won't fetch if appropriate -- you do have to do that explicitly yourself.

*The other thing to keep in mind is that the clone(s) are placed in ~/.sbt/1.0/staging/... where 1.0 is based on the sbt version number.

*And, of course, don't forget to remove the reference to the other project if you have it in your libraryDependencies.

Here's the relevant part of my build.sbt file:
lazy val root = (project in file(".")).dependsOn(matchers)
lazy val matchers = RootProject(uri("git://github.com/rchillyard/Matchers#V1_0_5"))


text:
Q: How to Configure Neural Network to Produce Multiple Binary Outputs in DL4J I am learning DL4J, and I would like to configure a network that can accept a tuple of double values, and produce a tuple of binary values, in which multiple of them may be set to 1, and others set to 0.  In the language of neural nets, would I cal this is multi-class one-hot encoding?
Example:
[3.5,  2.9, 15.0] -> [0, 0, 1, 0, 1]
[2.5, 12.5,  5.0] -> [1, 1, 0, 0, 1]
[5.9, 71.3,  0.7] -> [0, 1, 1, 0, 0]

etc.
I have tried this:
MultiLayerConfiguration multiLayerConfiguration =
    new NeuralNetConfiguration.Builder()
        .seed(System.nanoTime())
        .iterations(10000)
        .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
        .learningRate(0.1)
        .useDropConnect(false)
        .biasInit(0)
        .miniBatch(false)
        .updater(Updater.NESTEROVS)
        .list()
        .layer(0, new DenseLayer.Builder()
            .nIn(3)
            .nOut(8)
            .weightInit(WeightInit.XAVIER)
            .activation(Activation.SIGMOID)
            .build())
        .layer(1, new OutputLayer.Builder()
            .nIn(8)
            .nOut(5)
            .weightInit(WeightInit.XAVIER)
            .activation(Activation.SOFTMAX)
            .lossFunction(LossFunctions.LossFunction.RECONSTRUCTION_CROSSENTROPY)
            .build())
        .pretrain(false)
        .backprop(true)
        .build();

But I seem to be getting fractional values in the output as if the network is trying to evenly distribute the activation.  How do I configure the network to make it give me multiple 1's and 0's as a classification?
For example, if the output was 3 dimensional, I would want this:
[[0.00,  0.49,  0.51],
 [0.50,  0.00,  0.50],
 [0.50,  0.50,  0.00],
 [0.33,  0.33,  0.34],
 [0.00,  0.00,  1.00]]

To really be this:
[[0.00,  1.00,  1.00],
 [1.00,  0.00,  1.00],
 [1.00,  1.00,  0.00],
 [1.00,  1.00,  1.00],
 [0.00,  0.00,  1.00]]

A: You shouldn't use a softmax output for binary or multi class. You sigmoid and binary xent instead.
Also, this code looks a bit old. Make sure you are using 0.9.1. Don't use reconstruction cross entropy -> use  KL Divergence if you are doing unsupervised learning (autoencoders and the like) but for this case you shouldn't even be using recon error.
Also, the iterations knob is going away next release. Use for loops instead. That iterations knob is legacy (just leave it at 1 in the mean time)
Again, I strongly encourage you to follow our examples closer. We have everything you need in there for multi class classification or really any use case. If you can't find something try to do a keyword search in the repo. Failing that, ask on here our on our community gitter.


text:
Q: Usage of GridSplitter with WindowsFormsHost. Problem with proportional sizing (*) I've got a UserControlParent, which has a UserControlSon and a GridSplitter (All inside Grid).
GridSplitter divides UserControlParent into two parts:

*

*UserControlSon

*SomeOtherPart

UserControlSon has  a WindowsFormsHost inside, it is created dynamically.
WindowsFormsHost  has CeTe.Dynamic PDFViewer (WinForms) control as a child inside.
When I try to use GridSplitter  to change UserControlParent.Grid.Row/Column size, I got following:
UserControlSon freezes, so I can't resize UserControlSon, I can't move GridSplitter  with cursor.
I have all Grid.Row Height set as Star type (for proportional scaling) dynamically.
For example (30* and 70* so I get 30% and 70% parts of window).
Please, help!
How Can I solve this?
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <GridSplitter x:Name="splitViewArea" Height="5" Grid.ColumnSpan="2" VerticalAlignment="Bottom" HorizontalAlignment="Stretch" Grid.Row="0" Grid.Column="0" />

    <local:SomeControl x:Name="UserControlSon"/>
</Grid>


text:
Q: How to crop and rotate the video in Android using crop image and convert image libraries? I am creating an app for Android with a crop Image / Crop Video functionality. For iOS this app is already created.
For iOS is used the lib for edit the video LLVideoEditor
and the lib for the image crop and rotate TOCropViewController
For Android I found uCrop library for Image cropping and ffmpeg-for-Android library for the video cropping.
To crop video, I take the first frame of the video, and after that I crop it with uCrop library to receive the coordinates of cropping. (X, Y, Width, Height, rotate Angle).
The received coordinates I pass as command to the ffmpeg-for-Android as command line.
The command looks like:
To crop video I use the command:
ffmpeg -y -i /sdcard/video/in.mp4 -vf crop=Width:Height:X:Y /sdcard/video/out.mp4

To crop and rotate video by 90 degree ClockWise I use the command:
ffmpeg -y -i /sdcard/video/in.mp4 -vf crop=Width:Height:X:Y transpose=1 /sdcard/video/out.mp4

The issues that I have:

*

*When I choose the crop image area and press rotate image by 90 degree and press apply, the uCrop library returns me X, Y, croppedImageWidth, croppedImageHeight, Angle. In this case Y should be equals 0, but I receive Y > 0, i.e. Y = height of Black area above the image. The uCrop library does not do the correct image zooming after the crop image area is selected.

*Converting the video with ffmpeg library works very slowly. The video I convert has only 5 second lenght, so the converting should be quick. But it takes about 15 seconds. In comparison with iOS it takes very very long.

The questions are:
1. Is this way I choose to crop video is the right one?
2. Where can I find the similar libraries for Android as for iOS that will allow me to have the same functionality for Android app as iOS app already has, i.e. receive the right crop image coordinates and quick crop video?

A: You can refer https://android-arsenal.com/tag/45 it mentioned a lot of libraries for image manipulation, it's useful and very informative, qualitative libraries


text:
Q: Export the mongodump from one host to another I am having the mongodump of that collection in host A , Now i need to move that into host B.
I have used,
 mongodump --host mongodb1.example.net --port 37017 --username user --password pass /opt/backup/mongodump-2011-10-24

but its not worked for me. Any other help on this?
Thanks in advance.

A: In the terminal, in both native Linux terminal and PuTTY, the - within the file name is actually getting treated as a type of option to the command in general. Of course this throws an error when mongodump detects the wrong number of options etc which stops it from working. It seems that encapsulation using ' and " does not work either on this front.
An easy and quick fix to this is to manually specify the --out option like so:
./mongodump --host mongodb1.example.net --port 37017 --username user --password pass --out=/opt/backup/mongodump-2011-10-24


text:
Q: C++ (not C++11) Best way to release array in very large methods I have to modify a very large method with many possible execution flows. The modification involves to allocate a char array in the heap using new. I want to be sure that this array is released properly, but I want to avoid the need of do the delete[] in all the possible execution flows. In addition, I want to make something "cleaner" for this purpose to avoid future bugs.
I have thought to alloc the array with new and then wrap it into a local std::vector (but keeping the reference to the raw pointer, since the method uses this reference intensively) and let the wrapper delete the raw pointer when it is out of scope.
Here I attach an example. The purpose of this example is to show the kind of operations that are peformed with the raw pointer.
char *rawPtr = new char[1024];
std::vector wrapper(rawPtr, rawPtr + 1024); // <= Does it assure that rawPtr will be released properly?
...
for(int i = 0; i < 1024; i++)
    rawPtr[i] = ...;

rawPtr += sizeof(...);
...
rawPtr -= ...;
if(...)
    return ...;

return ...;

So, my question is if I can be sure that the rawPtr will be released properly regardless program failures, exceptions, incoming return statements etc.
PD.: I cannot use C++11, the most similar thing I have to a smart pointer is auto_ptr and this uses delete, not delete[].

A: You can create vector<char> of length 1024 and then use pointer to its first element as rawPtr. It will be no need to call new and delete[] then.

A: std::vector doesn't have a move constructor for newed pointers. What happens, is that a copy is made for std::vector's use. So you will still need to delete.


text:
Q: Having issue T-SQL stored procedure adding qty's with an If Else condition with two tables, Fails @@roucount = 0 Here's what I am trying to accomplish. This stored procedure needs to look in a table B and determine if the row exists.
If not, then the row is added from the data row in table A and also add the qty column from table A and updates table B qty column with the sum in the new row in table B.
If the row exists, simply add the qty column from table A to qty column in table B. No row needs to be inserted as it already exists.
Here's what I have so far. This does insert the new row in table B if it does not exist yet, but it fails to add table A to b if the does exist.
PROCEDURE [dbo].[xxxxxxxx]
    @VendorAccountID int,
    @pocomment text,
    @sqlident int output
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @TotalOnHand INT;  --newly declared, not assigned. NULL
    DECLARE @POLineItemQty int

    INSERT INTO [PurchaseOrder_tbl] ([POVendorID], [pocomment])
    VALUES (@VendorAccountID, @pocomment)

    SET @sqlident = SCOPE_IDENTITY()

    UPDATE [PurchaseOrderTmp_tbl]
    SET POID = @sqlident

    UPDATE [PurchaseOrder_tbl]
    SET POTicketNumber = [PartOrderTicketID]
    FROM PurchaseOrderTmp_tbl
    WHERE PurchaseOrder_tbl.POID = @sqlident

    INSERT INTO PurchaseOrderItems_tbl(POID, VendorAccountID, POTicketID, POInvItemID, POLineItemQty, PartManufPartNum, PartOrderDesc, PartOrderManufacture, PartOrderModel, POType, PODescription, POStatusID, PartRequestedBy, POGLCode)
        SELECT
            POID, VendorAccountID, PartOrderTicketID, PartInvID,
            POItemQty, PartManufPartNum, PartOrderDesc, PartOrderManufacture,
            PartOrderModel, POType, PODescription, POStatusID,
            PartRequestedBy, POGLCode
        FROM
            PurchaseOrderTmp_tbl

    IF @@Rowcount = 0
    BEGIN
        INSERT INTO InventoryMaster_tbl (InvManufacture, InvModel, InvManPartNumber, InvDescription)
            SELECT
                PartOrderManufacture, PartOrderModel, PartManufPartNum, PartOrderDesc
            FROM
                PurchaseOrderTmp_tbl

        SELECT @TotalOnHand = (SELECT SUM(TotalOnHand)
                               FROM (Values (InvTotalQtyOnOrder), (@POLineItemQty)) AS TSum(TotalOnHand))
        FROM InventoryMaster_tbl

        UPDATE [InventoryMaster_tbl]
        SET InvTotalQtyOnOrder = InvTotalQtyOnOrder + POLineItemQty
        FROM InventoryMaster_tbl
        INNER JOIN PurchaseOrderItems_tbl PartManufPartNum On PartManufPartNum = InvManPartNumber
        WHERE InvManPartNumber = PartManufPartNum
    END
    ELSE
    BEGIN
        SELECT @TotalOnHand = (SELECT SUM(TotalOnHand)
                               FROM (Values (InvTotalQtyOnOrder), (@POLineItemQty)) as TSum(TotalOnHand))
        FROM InventoryMaster_tbl

        UPDATE [InventoryMaster_tbl]
        SET InvTotalQtyOnOrder = InvTotalQtyOnOrder + POLineItemQty
        FROM InventoryMaster_tbl
        INNER JOIN PurchaseOrderItems_tbl PartManufPartNum On PartManufPartNum = InvManPartNumber
        WHERE InvManPartNumber = PartManufPartNum
    END

    DELETE PurchaseOrderTmp_tbl
END

Thanks in advance.
Version two. This does add the qty field IF the row exist but fails if row count = 0. Does not add row there for does not have anything to add.
PROCEDURE [dbo].[XXXXXXXX]
    -- Add the parameters for the stored procedure here
    @VendorAccountID int,
    @pocomment text,
    @sqlident int output

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @TotalOnHand INT;  --newly declared, not assigned. NULL
    DECLARE @POLineItemQty int

INSERT INTO [PurchaseOrder_tbl]
    ([POVendorID],[pocomment])
Values (@VendorAccountID,@pocomment)
SET @sqlident = SCOPE_IDENTITY()

UPDATE [PurchaseOrderTmp_tbl]

SET POID = @sqlident

UPDATE [PurchaseOrder_tbl]
Set POTicketNumber = [PartOrderTicketID]
From PurchaseOrderTmp_tbl
Where PurchaseOrder_tbl.POID = @sqlident

INSERT INTO PurchaseOrderItems_tbl
     (POID,VendorAccountID,POTicketID,POInvItemID,POLineItemQty,PartManufPartNum,PartOrderDesc,PartOrderManufacture,PartOrderModel,POType,PODescription,POStatusID,PartRequestedBy,POGLCode)
Select POID, VendorAccountID, PartOrderTicketID, PartInvID, POItemQty,PartManufPartNum,PartOrderDesc,PartOrderManufacture,PartOrderModel,POType,PODescription,POStatusID,PartRequestedBy,POGLCode
From PurchaseOrderTmp_tbl

SELECT  @TotalOnHand = (Select Sum(TotalOnHand)
    FROM (Values (InvTotalQtyOnOrder), (@POLineItemQty)) as TSum(TotalOnHand))
FROM InventoryMaster_tbl

UPDATE [InventoryMaster_tbl]
SET InvTotalQtyOnOrder = InvTotalQtyOnOrder + POLineItemQty
FROM InventoryMaster_tbl
INNER JOIN PurchaseOrderItems_tbl PartManufPartNum On PartManufPartNum = InvManPartNumber
WHERE InvManPartNumber = PartManufPartNum
END
BEGIN

IF @@Rowcount = 0
BEGIN
INSERT INTO InventoryMaster_tbl
    (InvManufacture, InvModel, InvManPartNumber, InvDescription)
    SELECT PartOrderManufacture, PartOrderModel, PartManufPartNum, PartOrderDesc
    From PurchaseOrderTmp_tbl

SELECT  @TotalOnHand = (Select Sum(TotalOnHand)
    FROM (Values (InvTotalQtyOnOrder), (@POLineItemQty)) as TSum(TotalOnHand))
FROM InventoryMaster_tbl

UPDATE [InventoryMaster_tbl]
SET InvTotalQtyOnOrder = InvTotalQtyOnOrder + POLineItemQty
FROM InventoryMaster_tbl
INNER JOIN PurchaseOrderItems_tbl PartManufPartNum On PartManufPartNum = InvManPartNumber
WHERE InvManPartNumber = PartManufPartNum

END

Delete PurchaseOrderTmp_tbl
END


text:
Q: Does github (twitter, stripe & co) uses oauth for its own login? Does github (twitter, stripe & co) uses OAuth for its own signin/signup forms?
All those authentications are cookie based, so is this regular web client basic auth or does it use some form of OAuth or xAuth ?
On login, a call to https://github.com/session (or https://twitter.com/sessions or https://dashboard.stripe.com/ajax/sessions) is made (with credentials given as formdata) that result in a 302 (or 200 for stripe) with Set-Cookie and a location to https://github.com (or https://twitter.com).
It does not seems that they use a client_id to get a code and exchange it with a token. All the OAuth dance seems striped. And the Bearer header too. So, what's going on here?
Thanks.

A: OAuth is a three-legged system, two-legs is sort of useless.  The whole point of using OAuth is to give other services the ability to perform actions as you without needing to specifically authenticate or pass the data yourself.  In the end you must still authenticate against some Auth service.
Since you are using these services as the Authentication mechanism for other sites, it wouldn't make sense to attempt to use it in your own.  As part of setting OAuth, the second site redirects to the first and asked to authenticate there, which means you literally need to enter your credentials.  Which means that if you are okay entering your credentials into say github, having a different authentication mechanism is useless.
OAuth allows non-github to create user accounts by trusting github with the authentication, or it allows non-github sites to make changes to github as the user once the user agrees to the interaction by logging into github to accept that policy (logging in using their credentials).

A: Sign in forms on github (and others websites as well) are simply cookie based.
Usually every direct login via the website through a browser is made with cookie based system , simply because isn't necessary to do otherwise.
A bit of theory
Every time you use a login form in a website you are calling an API, not necessarily intended for public use (so a private API)
When you put your credentials in the login form and push that login button , your credentials are being managed by some code in the server that permits you to authenticate against that website.
There is no need for the entire OAuth overhead here because the website has full control on the authentication mechanism and isn't necessary to externalize.
Why OAuth is different in this contest?
OAuth is a system designed to distribute the authentication system across different services / applications even from different vendors.
In OAuth there are multiple actors involved:

*

*the client

*the authorization server

*the resource provider

In your case all these 3 actors are the website itself and so there is no need for a decoupling system like OAuth.


text:
Q: pick the minimum value out of a list of sublists and display another value in that sublist with the minimum Say I have a list:
stuff =  [[5,3,8],[2,4,7],[14,5,9]]

where each sublist is of the form [x,y,z].
I want to find the minimum value of this list for the third entry in the sub lists, i.e. z=7. Then I want to print out the first value of that sublist, x.
ex) The minimum value of z occurs at x = 2.

A: You can use the builtin min function with the key parameter, like this
stuff = [[5,3,8],[2,4,7],[14,5,9]]
print min(stuff, key = lambda x: x[2])[0]   # 2

To make this more readable, you can unpack the values like this
print min(stuff, key = lambda (x, y, z): z)[0]

For each and every element of stuff, the function assigned to key parameter will be invoked. Now, the minimum value will be determined based on the value returned by that function only.

A: You can pass the built-in min function a key to access the third element in each sublist:
Demo
>>> stuff = [[5,3,8],[2,4,7],[14,5,9]]
>>> x, y, z = min(stuff, key=lambda arr: arr[2])
>>> x, y, z
(2, 4, 7)


text:
Q: Derivation about the clutter problem of Expectation Propagation Recently I have read the book "Pattern Recognition and Machine Learning" by Bishop, and I spent a lot of time deriving the result of the clutter problem for Expectation Propagation. But I don't know how to derive Eq.(10.217) and Eq.(10.218), as you can see in the picture:

I don't understand why variable $\rho_{n}$ suddenly apperas in Eq.(10.219). I have read a lot about EP algorithms on the Internet, such as (1),(2) and (3). But almost all of them just give these conclusions without explaining how to derive them. Can anyone help me?
(1) Introduction to Expectation Propagation
(2) Expectation Propagation for approximate Bayesian inference
(3) https://jmhldotorg.files.wordpress.com/2013/11/slidescharlesuniversityep2013.pdf

A: Well, I have found that the derivation of this problem is one of the after-class exercises in PRML, and I have found the corresponding answer in [1].
Everyone can find the details in Problem 10.39 Solution.
[1] https://github.com/zhengqigao/PRML-Solution-Manual


text:
Q: How can I detect if client has Background Sync support from the Service Worker? How can I detect whether the user's browser has Background Sync support from within the service worker?
I know how to detect for this on the app side, but not from within the service worker itself.
Basically I'm using Workbox's Background Sync and it's all working great in Chrome and Chrome Mobile.
I know Workbox has a Background Sync "fallback" for browsers that don't support Background Sync, but this not working very well, so I would rather just disable Background Sync completely for browsers which don't support it.
Here is my service worker file for reference. You can see there are 3 blocks of code that I don't want to execute if the browser doesn't support background sync (I've marked these with *** I ONLY WANT TO RUN THIS CODE IF BACKGROUND SYNC IS SUPPORTED ***):
/*
 * This file (which will be your service worker)
 * is picked up by the build system ONLY if
 * quasar.conf > pwa > workboxPluginMode is set to "InjectManifest"
 */

/*
  config
*/

workbox.setConfig({ debug: false }) // disable workbox console logs
workbox.precaching.precacheAndRoute(self.__precacheManifest || [])

/*
basic routes
*/

workbox.routing.registerRoute(
  /^https:\/\/firestore.googleapis.com/,
  new workbox.strategies.NetworkFirst(),
  'GET'
);

workbox.routing.registerRoute(
  'https://myapp.com/posts',
  new workbox.strategies.NetworkFirst(),
  'GET'
);

workbox.routing.registerRoute(
  'https://myapp.com/favorites',
  new workbox.strategies.NetworkFirst(),
  'GET'
);

workbox.routing.registerRoute(
  /^http/,
  new workbox.strategies.StaleWhileRevalidate(),
  'GET'
);

/*
posts queue
*/

// *** I ONLY WANT TO RUN THIS CODE IF BACKGROUND SYNC IS SUPPORTED ***
const postsQueue = new workbox.backgroundSync.Queue('postsQueue', {
  maxRetentionTime: 24 * 60 * 365, // Retry for max of one year
  onSync: async ({queue}) => {
    let entry;
    while (entry = await queue.shiftRequest()) {
      try {
        await fetch(entry.request);
        // console.log('Replay successful for request', entry.request);

        const clients = await self.clients.matchAll({type: 'window'});
        for (const client of clients) {
          client.postMessage({
            msg: "offline-post-uploaded"
          })
        }
      } catch (error) {
        console.error('Replay failed for request', entry.request, error);

        // Put the entry back in the queue and re-throw the error:
        await queue.unshiftRequest(entry);
        throw error;
      }
    }
    // console.log('Replay complete!');
  }
})

/*
update post queue
*/

// *** I ONLY WANT TO RUN THIS CODE IF BACKGROUND SYNC IS SUPPORTED ***
const updatePostQueue = new workbox.backgroundSync.Queue('updatePostQueue', {
  maxRetentionTime: 24 * 60 * 365, // Retry for max of one year
  onSync: async ({queue}) => {
    let entry;
    while (entry = await queue.shiftRequest()) {
      try {
        await fetch(entry.request);
        console.log('Replay successful for request', entry.request);
      } catch (error) {
        console.error('Replay failed for request', entry.request, error);

        // Put the entry back in the queue and re-throw the error:
        await queue.unshiftRequest(entry);
        throw error;
      }
    }
    // console.log('Replay complete!');
  }
})

/*
events
*/

// *** I ONLY WANT TO RUN THIS CODE IF BACKGROUND SYNC IS SUPPORTED ***
self.addEventListener('fetch', (event) => {
  // console.log('event.request.url: ', event.request.url)
  if (event.request.url == 'https://myapp.com/createPost') {
    console.log('SW fetch createPost')
    // Clone the request to ensure it's safe to read when
    // adding to the Queue.
    if (!self.navigator.onLine) {
      console.log('SW device is offline')
      const promiseChain = fetch(event.request.clone()).catch((err) => {
        return postsQueue.pushRequest({request: event.request});
      });

      event.waitUntil(promiseChain);
    }
    else {
      console.log('SW device is online')
    }
  }
  else if (event.request.url.startsWith('https://myapp.com/updatePost')) {
    // Clone the request to ensure it's safe to read when
    // adding to the Queue.

    if (!self.navigator.onLine) {
      const promiseChain = fetch(event.request.clone()).catch((err) => {
        return updatePostQueue.pushRequest({request: event.request});
      });
      event.waitUntil(promiseChain);
    }
  }
});

self.addEventListener('notificationclick', event => {
  let notification = event.notification
  let action = event.action

  event.waitUntil(
    clients.matchAll()
      .then(clis => {
        let client = clis.find(cli => {
          return cli.visibilityState === 'visible'
        })

        if (client !== undefined) {
          client.navigate(notification.data.openUrl)
          client.focus()
        }
        else {
          clients.openWindow(notification.data.openUrl)
        }
        // notification.close()
      })
  )
})

self.addEventListener('notificationclose', event => {
  console.log('Notification was closed', event)
})

self.addEventListener('push', event => {
  console.log('Push Notification received: ', event)

  if (event.data) {
    console.log('event.data: ', event.data)
    let data = JSON.parse(event.data.text())
    console.log('data: ', data)

    console.log('showNotificationYo!')
    event.waitUntil(
      self.registration.showNotification(
        data.title,
        {
          body: data.body,
          icon: 'statics/icons/icon-128x128.png',
          badge: 'statics/icons/icon-128x128.png',
          image: data.imageUrl,
          data: {
            openUrl: data.openUrl
          }
        }
      )
    )
  }
})

A: The feature detection that's used within workbox-background-sync looks like:
if ('sync' in self.registration) {
  // Background sync is natively supported.
}

You could do something similar in your own code to determine native support.


text:
Q: Guessing a number Find the number $n$ which has exactly $3$ prime divisors: $3$, $5$, and $7$, and has $4$ divisors that are powers of $5$. Moreover, $n$ has as many divisors that are powers of $3$ as there are divisors that are powers of $7$. Finally, $24$ divisors of $n$ are multiples of $3$.
What I understood is that $5$, $25$, $125$ and $625$ are the divisors of $n$. But do $7$ and $4$ have the same power in the prime factorization of $n$?

A: "$24$ divisors of $n$ are multiples of $3$".  So, $n/3$ itself has $24$ divisors which are each one third of a divisor of $n$.
To have four power of $5$ divisors and $m$ divisors apiece that are powers of $3$ and powers of $7$, the number must have the form $n=3^{m-1}×5^3×7^{m-1}$ counting $1=p^0$ as a power of each prime factor.  Then $n/3=3^{m-2}×5^3×7^{m-1}$ with $4m(m-1)$ divisors (add one to each exponent and multiply the augmented exponents).  To match this with $24$ set $m=3$ therefore $n=3^2×5^3×7^2=55 125$.


text:
Q: How to convert textField.text value to Integer and sum two Integers
Initialization of immutable value 'textfieldInt' was never used;
  consider replacing with assignment to '_' or removing it  and
  textfield2Int

I get that warning twice for textfieldInt
This is all the code I have:
class ViewController: UIViewController {

    @IBOutlet weak var textField1: UITextField!
    @IBOutlet weak var textField2: UITextField!
    @IBOutlet weak var output: UILabel!

    @IBAction func calculate(_ sender: AnyObject) {
        let textfieldInt: Int? = Int(textField1.text!)
        let textfield2Int: Int? = Int(textField2.text!)
        let convert = textField1.text! + textField2.text!
        let convertText = String(convert)
        output.text = convertText

}

A: You are receiving the warning because, as the warning tells you, you are instantiating textfieldInt and textfield2Int, but you're not using your created Integers textfieldInt and textfield2Int to be calculated as let convert, but you add the Strings textField1.text! and textField2.text! together...
I guess, you want your function to be that:
@IBAction func calculate(_ sender: AnyObject) {
    let textfieldInt: Int? = Int(textField1.text!)
    let textfield2Int: Int? = Int(textField2.text!)
    let convert = textfieldInt + textfield2Int
    let convertText = String(convert)
    output.text = convertText
}


text:
Q: Блок шириной 100% экрана посредине сайта? Допустим, у меня есть сайт шириной 1000 пикселов. И в нем две колонки. Как сделать блок, который бы шел где-то после этих двух колонок шириной, 100% от экрана, а затем снова бы шли колонки???
A: Для того блока, который в обёртке 1000px, задать position: absolute; width: 100%; position - выдернет из потока ваш внутренний блок, а ширина будет растянута на весь экран для любого монитора (не забудьте указать height для блока), остаётся только через свойство top: подогнать отступ сверху.
Так как ширина будет 100%, то никакие отступы и пэйдинги слева и справа не нужны, а значит можно подогнать блок через отступ сверху (свойство top:), если надо конечно.
И про z-index не забываем, если я Вас правильно понял.
A: Можно использовать свойство float. Делаешь как то так:

но я бы лучше использовал bootstrap

A: Выбирай:

*

*width: 100vw

*position: fixed

*position: absolute при соответствующем контексте


text:
Q: Initializing Bitmap variable with bitmap drawable from resources is not working - using ANDROID I use the following code to initialize my bitmap variable:
Bitmap bitmap = ((BitmapDrawable)this.model.gameView.context.getResources().getDrawable(R.drawable.pic1)).getBitmap();

When I try to log the width of that bitmap, the log does not even output anything for that call.
I know it's making it to that line, because I traced the code.
Also, when I try to do canvas.draw for the bitmap, nothing is drawn on the screen.
Everything I draw with rectangles works fine.
My picture resource is a PNG.
Any help is appreciated!

A: Try something like this for your bitmap class.
public class DrawBitmap extends View
{
    Bitmap bitmap;

    public DrawBitmap(Context content)
    {
        super(content);

        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic1);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawColor(Color.BLACK);//whatever color you want, make sure it's not the same as your image
        canvas.drawBitmap(bitmap, (canvas.getWidth()), 0, null);
    }
}

Main Class
public class Main extends Activity
{

    DrawBitmap myView;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myView = new DrawBitmap(this);
        setContentView(myView);
    }
}

A: Try using BitmapFactory.decodeResource
Have a look at the answer in this topic:
How to convert a Drawable to a Bitmap?

A: Just figured it out.  It had nothing to do with the method of bitmap loading I used.
It was a logical error on my part. My code accidentally reached a case where my bitmap became null, and it tried to draw the null resource on the canvas.


text:
Q: Why does recursive function return the value of the first call? I got the following helper function, which traverses through a binary tree and saves the height and position additionally. The main idea of the function is to check if two trees are exactly the same, but I am already stuck at the helper function. See input and output below for the exact issue
def isSameTree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:

    def helper(node, height, position):

        if not node:
            return None

        if node.left:
            helper(node.left, height + 1, "left")
        if node.right:
            helper(node.right, height + 1, "right")

        return (node.val, height, position)

    return helper(p, 0, "")

Example Input:
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(Solution.isSameTree(root, root2))

root2 is defined, but plays no major rule for this example. The Output of the print I expected is the very last node without any children, that is root.left.left = TreeNode(4). However, the print statement returns the root node and I cannot understand why. Should not the last recursion call, i.e. the one with no children, return first?
Bonus question: How can I fix the code in such way that I every node, with its height and position gets returned?

A: You must use the returned value of the helper function when you recurse...
Here the underlying rationale is that 2 trees are equal if their (current) root node either are both null or have same value and both left and right subtrees are equal.
The function using a recursive helper should just translate that in Python language:
def isSameTree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:

    def helper(node1, node2):
        if node1 is None and node2 is None:   // Ok if both nodes are None
            return True
        if node1 is None or node2 is None:    // not ok if one is None (both was tested above)
            return False
        if node1.value != node2.value:     // if nodes exist they must have same value
            return False
        if not helper(node1.left, node2.left): // left subtree must be equal
            return False
        return helper(node1.right, node2.right) // same for right one

    return helper(p, q)


text:
Q: How use Any object in kotlin parceable? I have to use Any Object for parseable in kotlin data model.
@Parcelize
data class TestModel(

     var data: ArrayList<Any>? = null

) : Parcelable

android studio show below error.

I add @RawValue in the data class
var data: @RawValue ArrayList<Any>? = null

but when I create a new instance from class, I get this error

anybody can help me?

A: You have to enable this feature in the gradle file:
androidExtensions {
    experimental = true
}

also make sure you applied the plugin of kotlin extension for android:
apply plugin: 'kotlin-android-extensions'

Enabling experimental features