text:
Q: User Activation Code doesn't activate after submitting an Update query I'm working on a project using ZEND
A very strange and non-logical thing keeps on happening.
When user registers it generates an activation code an writes to DB:
//Generate Activation Code;
$activation_code = date('YmdHis');
$activation_code .= substr(number_format(time() * rand(),0,'',''),0,10);

in the database i get for ex. code like this: 201212301653302670595490
User should go to link  /user/activation/201212301653302670595490
I get this param with the controller:
public function activateAction() {

$activation_code = htmlentities(trim($this->_getParam('activation_code', 0)));
$activation_code = preg_replace("/[^0-9]/","", $activation_code);

    $usersModel = new Users_Model_DbTable_Users();
    $result = $usersModel->activUser($activation_code);

    if($result) {

        $this->view->message = 'Your account is activated. You may now Login.';

    } else {

        $this->view->message = 'Something went wrong.';

    }
}

this action calls a function in my models:
public function activUser($activation_code) {

    $data = array(
        'status' => 2
    );

    if($this->update($data, 'activation_code = '. $activation_code)) {
        return true;
    }

}

this is the custom rout in my Bootstrap:
$activateUserRoute = new Zend_Controller_Router_Route("user/activate/:activation_code", array(
   'module' => 'users',
   'controller' => 'manage',
   'action' => 'activate'
));

$router->addRoute('activateUserRoute', $activateUserRoute);

my cell activation_code in DB table is VARCHAR with Length of 24 ('cuz the generated code in 24 symbols in length).
The awkward moment
it keeps failing the activation process. it always returns false;
if I go to DB, replace generated code with any number 1, 1231231231234 or even the generated code itself (201212301653302670595490) it does the activation.
Maybe you can tell me what's going wrong in here? any practice?

A: Try http://framework.zend.com/manual/1.12/en/zend.db.profiler.html to see SQL that is generated.

A: I gotta aske this one first:
What is the point of: $activation_code = preg_replace("/[^0-9]/","", $activation_code); it looks like you are replacing all of the values in your activation code with nothing.
The way you passed the activation code to the $where parameter has been deprecated. In some places that syntax may still work in others it doesn't.
public function activUser($activation_code) {

    $data = array(
        'status' => 2
    );
    $where = $this->getAdapter()->quoteInto('activation_code = ?', $activation_code);
    //update() returns number of rows updated,
    if($this->update($data, $where) === 0) {
        return false;
    } else {
        return true;
    }
}

Because update() returns the number of rows updated any untrue condition in your current if() statement would be inaccurate. IT may work correctly most of the time...
It would be even better if you tested for exactly the number of rows that are supposed to be updated and fail if that number is not returned.
htmlentities() may not be the best choice to filter your input parameter. You may be much better off filtering for the type of data that you know is there. Zend_Filter_Input has filters and validators that can be very useful.


text:
Q: parsley js updateConstraint method I'm trying to do a updateConstraint in Parsley.js.
el.parsley( 'updateConstraint', { cardcheck: "true" }, "MESSAGE NOW" );
According to the plugin it has a method called updateConstraint. That has 2 paramaters. The first one works but the second one the most important one to change the message does not.
When I pass it in after the constraint object it always shows as undefined. Am I passing it incorrectly.
   /**
    * Dynamically update an existing constraint to a field.
    * Simple API: { name: requirements }
    *
    * @method updtConstraint
    * @param {Object} constraint
    */
    , updateConstraint: function ( constraint, message ) {
          console.log(" updateConstraint = ", constraint, "   message = ",message);
      for ( var name in constraint ) {
        this.updtConstraint( { name: name, requirements: constraint[ name ], valid: null }, message );
      }
    }

A: For a quick and easy answer, see what guillaumpotier posted. Destroy parsley, modify the inputs, then initialize parsley again; here is his code:
// destroy
$('#myForm').parsley('destroy');
// change attribute
$('#myTestField').data('minlength', 2);
// assign parsley to do the job
$('#myForm').parsley();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Non Editable Edit Field highlight issue I have a non editable edit field in my screen. In order to differentiate between editable and non editable field i have set the background of the non-editable field to light gray as in the code below:
  Border nonEditableBorder=BorderFactory.createRoundedBorder(new XYEdges(5, 5, 5, 5),Color.LIGHTGRAY,Border.STYLE_FILLED|Border.STYLE_TRANSPARENT);
  EditField textField=new EditField(EditField.NO_NEWLINE|EditField.FOCUSABLE|DrawStyle.RIGHT);
  textField.setBorder(nonEditableBorder);

Now on the non-editable field when i scroll the trackball to the right or left the text gets highlighted in white as shown in the image below:

I do not want the text to get highlighted. Can someone please help me with this. Thanks in advance.

A: In addition to setting the border i also set the background to the same color as the border and that solved my problem.


text:
Q: Finite dimensional counterexample for the cancellation law of the direct sum of vector spaces I am reading 'Linear Algebra and Group Lectures' written by I. Lee. By 7.5.14. of this book, the cancellation of the direct sum does NOT hold:
Let $U, W_1, W_2 \le V$ be subspaces of $V$. $U \oplus W_1 = U \oplus W_2$ does not imply $W_1 = W_2$.
The author says that only finite dimensional vector spaces will be considered in the book. However I cannot imagine a counterexample for finite $V$. Is there a 'finite' counterexample of the cancellation law of the direct sum of two vector spaces?

A: Take $U$ to be the $x$ axis in the plane, $W_1$ to be the $y$ axis, and $W_2$ to be the span of the vector $(1,1)$.
Then your direct sums are both equal to the plane $\mathbb{R}^2$, but $W_1\neq W_2$.


text:
Q: How to create multiple ec2 instance across different subnets and Az zones with private ip address I have a slight issue. I have 3 subnet cidr blocks with 3 different az groups. I am passing a list of static Ip address for these instance to get assigned in order. My code however is throwing "ip address is out of range for the subnet" which makes sense because it's just going from ip 0 to the N instance how can i properly make sure the instance gets placed in the proper subnet. I hope my question makes sense and is clear please see the code below thank you all for the help! The code belows creates the instance
  ### Start of Radient FID Server ###
resource "aws_instance" "FID" {
  depends_on = [aws_kms_key.aws-wm-wmad-prod]
  disable_api_termination     = false

   count =  var.How_many_FID

  ami                         = var.windows_dc_ami_2016
  availability_zone           = element(var.availability_zones, count.index)
  ebs_optimized               = var.windows_dc_ebs_optimized
  instance_type               = var.windows_dc_instance_type_FID
  key_name                    = var.Key_Pair_Ec2
  monitoring                  = true
 vpc_security_group_ids       = [aws_security_group.Private01.id]
  subnet_id                   = element(aws_subnet.private_subnet_cidr_blocks_Apps, count.index).id
  private_ip                  = "${lookup(var.ips,count.index)}"
  associate_public_ip_address = false

  tags = merge(
    {
      Name        = element(var.Radiant_FID_Server_Tags, count.index)
      Project     = var.project,
      Environment = var.environment
    },
    var.tags
  )

I have a variables file which i'm passing the private Ip addresses:
variable "ips" {
    default = {
        "0" = "10.7.90.79"
        "1" = "10.7.90.80"
        "2" = "10.7.90.81"
        "3" = "10.7.90.82"
        "4" = "10.7.90.90"
        "5" = "10.7.90.84"
        "6" = "10.7.90.85"
        "7" = "10.7.90.86"
        "8" = "10.7.90.87"
        "9" = "10.7.90.88"

    }
}

##how i create my subnets
resource "aws_subnet" "private_subnet_cidr_blocks_AD" {
  count = length(var.private_subnet_cidr_blocks_AD) # count = 3

  vpc_id            = aws_vpc.default.id #id34odfjdf
  cidr_block        = var.private_subnet_cidr_blocks_AD[count.index]
  availability_zone = var.availability_zones[count.index]

  tags = merge(
    {
      Name     = element(var.private_subnet_cidr_blocks_AD_NameTag, count.index),
      Project     = var.project,
      Environment = var.environment
    },
    var.tags
  )
}

A: So let's say you have the following CIDR block list defined:
private_subnet_cidr_blocks_AD = ["10.7.90.64/27", "10.7.90.96/27","10.7.90.160/27"]

Then you could define your IP list like this:
variable "ips" {
    default = [
        { subnet=0, ip="10.7.90.79" },
        { subnet=0, ip="10.7.90.80" },
        { subnet=0, ip="10.7.90.81" },

        # etc...

        { subnet=1, ip="10.7.90.100" },
        { subnet=1, ip="10.7.90.101" },

        # etc...

        { subnet=2, ip="10.7.90.170" },
        { subnet=2, ip="10.7.90.171" },
    ]
}

Each subnet number being the index in the private_subnet_cidr_blocks_AD list that corresponds to the CIDR block that the IP belongs to.
Then your instance definition could look like this:
resource "aws_instance" "FID" {
  for_each = toset( var.ips )

  subnet_id  = aws_subnet.private_subnet_cidr_blocks_Apps[each.value.subnet].id
  private_ip = each.value.ip


text:
Q: User's Post count from specific category [Wordpress] I want to show user's post count from specific category. Currently, I can only be able to query all posts. My code is like this
<?php $userpost_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type ='post' AND post_author = '".$curauth->ID."'");?>
<?php echo "Total post: ".$userpost_count.""?>

I know that, I need to join two table which is post table and term_relationships, but i don't know how to get it. Please kindly help me with that. Thank you.

A: Use your CATEGORY_ID below and try this:
<?php $userpost_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->term_taxonomy.term_id = CATEGORY_ID
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->posts.post_status = 'publish'
AND post_author = '".$curauth->ID."'");?>


text:
Q: Format dynamically created Radio buttons in Columns in c# I am creating radio buttons programatically for each element in an array/list and place them in a windows form.
Right now every new radio button is place under the previous one. How can i manage to start a new column after e.g. 4/5 radio buttons? The new column should appear on the right side of the previous radio-buttons.
This is my code so far:
for (int i = 0; i < startShapes.Count; i++)
{
    RadioButton rdb = new RadioButton();
    rdb.Text = startShapes.Values.ElementAt(i).Equals("") ? startShapes.Keys.ElementAt(i) : startShapes.Values.ElementAt(i);
    rdb.Size = new Size(100, 30);
    this.Controls.Add(rdb);
    rdb.Location = new Point(45, 70 + 35 * i);
    rdb.CheckedChanged += (s, ee) =>
    {
        var r = s as RadioButton;
        if (r.Checked)
            this.selectedString = r.Text;
    };
}

A: How about using TableLayoutPanel?
        Dictionary<string, string> startShapes = new Dictionary<string, string>();
        for(int i=0;i<20;i++)
            startShapes.Add("Shape " +i, "Shape " +i);
        int row = 0;
        int col = 0;
        tableLayoutPanel1.RowStyles.Clear();
        tableLayoutPanel1.ColumnStyles.Clear();
        tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
        tableLayoutPanel1.RowCount= 0;
        tableLayoutPanel1.ColumnCount = 1;

        foreach (var kvp in startShapes)
        {
            tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            tableLayoutPanel1.RowCount++;
            RadioButton rdb = new RadioButton();
            rdb.Text = string.IsNullOrEmpty(kvp.Value) ? kvp.Key : kvp.Value;
            rdb.Size = new Size(100, 30);
            rdb.CheckedChanged += (s, ee) =>
            {
                var r = s as RadioButton;
                if (r.Checked)
                    this.selectedString = r.Text;
            };
            tableLayoutPanel1.Controls.Add(rdb, col, row);
            row++;
            if (row == 5)
            {
                col++;
                row = 0;
                tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
                tableLayoutPanel1.ColumnCount++;
            }
        }

And if you really need your solution:
int left = 45;
int idx = 0;
for (int i = 0; i < startShapes.Count; i++)
{
    RadioButton rdb = new RadioButton();
    rdb.Text = startShapes.Values.ElementAt(i).Equals("") ? startShapes.Keys.ElementAt(i) : startShapes.Values.ElementAt(i);
    rdb.Size = new Size(100, 30);
    this.Controls.Add(rdb);
    rdb.Location = new Point(left, 70 + 35 * idx++);
    if (idx == 5)
    {
        idx = 0; // reset row
        left += rdb.Width + 5; // move to next column
    }
    rdb.CheckedChanged += (s, ee) =>
    {
        var r = s as RadioButton;
        if (r.Checked)
            this.selectedString = r.Text;
    };
}


text:
Q: Problema na definição de onClick em runtime com Pascal (Delphi/Lazarus) Preciso usar a procedure ClicaItem(Sender: TObject); em um OnClick criado em tempo de execução pela chamada da procedure CriaItem(nome:String);.
Porém, em todas as minhas tentativas, não consegui atribuir item.OnClick à procedure ClicaItem. Como devo proceder se sucede erro referente aos tipos incompativeis?

Error: Incompatible types: got address of
  procedure(TObject);Register" expected "procedure variable type of
  procedure(TObject) of object;Register>"

Peço para me esclarecerem a criação da procedure ao tipo aceito pelo OnClick, além de como devo fazer essa atribuição no evento OnClick.
OBS: O item é criado normalmente em runtime (tempo de execução), porém a linha referente ao OnClick está comentada devido ao erro antes de compilar.

A: Sua procedure ClicaItem tem que pertencer a uma instancia de uma classe (objecto);
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
     procedure ClicaItem(Sender: TObject);
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
   Button1.Click := ClicaItem;
end;

procedure TForm1.ClicaItem(Sender: TObject);
begin
   ShowMessage('ClicaItem');
end;

end.


text:
Q: Only the last x label got displayed after setting ScaleDraw? I have implemented ScaleDraw like this:
class ScaleDraw: public QwtScaleDraw {
    public:
        ScaleDraw(const std::vector<std::string> &labels) :
                labels(labels) {
            setTickLength(QwtScaleDiv::MinorTick, 4);
            setTickLength(QwtScaleDiv::MediumTick,6);
            setTickLength(QwtScaleDiv::MajorTick, 8);

            enableComponent(QwtScaleDraw::Backbone, false);

            setLabelRotation(-90.0);

            setLabelAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        }

        virtual QwtText label(double value) const QWT_OVERRIDE
        {
            QwtText lbl;

            const int index = qRound(value);
            if (index >= 0 && index < labels.size()) {
                lbl = QwtText(QString::fromStdString(labels[index]));
            }

            return lbl;
        }

    private:
        const std::vector<std::string> labels;
};

and set Scale Draw like this:
void setXLabels(const std::vector<std::string> &labels) {
    int axis = QwtAxis::XBottom;
    setAxisMaxMinor(axis, 3);
    setAxisScaleDraw(axis, new ScaleDraw(labels));
    replot();
}

and my labels has 100 values like this:
1.000016 18.000511 35.001006 52.001501 69.001996 86.002491 103.002986 120.003481 137.003977 154.004472 171.004967 188.005462 205.005957 222.006452 239.006947 256.007442 273.007937 290.008432 307.008927 324.009423 341.009918 358.010413 375.010908 392.011403 409.011898 426.012393 443.012888 460.013383 477.013878 494.014373 511.014869 528.015364 545.015859 562.016354 579.016849 596.017344 613.017839 630.018334 647.018829 664.019324 681.019819 698.020315 715.020810 732.021305 749.021800 766.022295 783.022790 800.023285 817.023780 834.024275 851.024770 868.025265 885.025761 902.026256 919.026751 936.027246 953.027741 970.028236 987.028731 1004.029226 1021.029721 1038.030216 1055.030711 1072.031207 1089.031702 1106.032197 1123.032692 1140.033187 1157.033682 1174.034177 1191.034672 1208.035167 1225.035662 1242.036157 1259.036653 1276.037148 1293.037643 1310.038138 1327.038633 1344.039128 1361.039623 1378.040118 1395.040613 1412.041108 1429.041603 1446.042099 1463.042594 1480.043089 1497.043584 1514.044079 1531.044574 1548.045069 1565.045564 1582.046059 1599.046554 1616.047049 1633.047545 1650.048040 1667.048535 1684.049030 1701.049525

and all of them has been converted to string.
And before setting ScaleDraw,plot likes this:

After setting ScaleDraw,plot becomes likes this:

As you can,only the first label: 1.000016 got displayed as the last label in the plot.


text:
Q: How to use JSTL var in Jquery selector I am using following Jquery selector
$("#selectedQuery td input:radio").attr('checked', true);

Where selectedQuery is a JSTL variable declared as
<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />

I tested the selector with hard coded values and it's working fine but no luck when used with selectedQuery.
How can we use JSTL <c:set> var in Jquery ? Is there any work around ?

A: In a JSP:
<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />

<script>
    $("#${selectedQuery} td input:radio").attr('checked', true);
</script>

A: I do stuff like that all the time.  The JSP parser doesn't know or care about the difference between the contents of a <script> tag (whether using jQuery or not) and any other content in the JSP page.
It should work fine if you do:
<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />

...

<script>
    $("#${selectedQuery} td input:radio").attr('checked', true);
</script>

Note that this requires that the <script> element with your jQuery selector be inside of the same page/JSP scope as your <c:set>.  If they aren't in the same scope then of course this will not work.

A: Mixing JSTL code in with the JavaScript can cause your code to become really jumbled. If it's unavoidable, I have all my JSTL variables set to JavaScript variables in one place:
<c:set var="selectedQuery" value="${dataRequestForm.queryMasterId}" />
<script type="text/javascript">
    //NOTE: we are sure 'selectedQuery' does not contain any double-quotes,
    // but most values will need to be escaped before doing this.
    var selectedQuery = "${selectedQuery}";

    // etc.
</script>

...

<script type="text/javascript">
    $("#" + selectedQuery + " td input:radio").attr('checked', true);
</script>


text:
Q: C# DateTime Extension Method I was asked to extend the type DateTime by Extension Method.
Then i need to create a method that will check if the month value added is my birth day, and if not it will tell me how many months left till my birth day.
I tried to create the following class for the DateTime extention, with the extension method inside.
I just got lost with the birth day month calculation inside that method
Should be something like:
public static class MyDateTimeExtension
{
    public static DateTime Month(this DateTime DiffDT)
    {
        DateTime BirthdayMonth;
        DateTime CurrentMonth;
        return DiffDT = BirthdayMonth - CurrentMonth;
    }
}

or something like
        return DiffDT.AddMonths = BirthdayMonth.AddMonths - CurrentMonth.AddMonths;

But ofcourse this code can't compile.
After creating the extension methos i should call the method from the main class with new DateTime variable
 DateTime DT;
 Console.WriteLine(DT.Month());

Hope this helps to understand

A: To implement this logic, I made the extension method as shown below, check it out,if it may be helpful for you.
class Program
{
    static void Main()
    {
        string date = "1987/7/2";
        DateTime dt = Convert.ToDateTime(date);

        string diffDate =  MyDateTimeExtension.GetDiffDate(dt);
        string[] words = diffDate.Split('/');

        if (Convert.ToInt32(words[1])== 0 && Convert.ToInt32(words[2])== 0)
        {
            Console.WriteLine("Today is your Birthday");
        }
        else
        {
            Console.WriteLine("You are " + words[0] + " Year/s " +  words[1] + " Month/s " +  words[2] + " Day/s");
        }
    }
}

public static class MyDateTimeExtension
{
    public static string GetDiffDate(this DateTime dtt)
    {
       int intYear, intMonth, intDay;

        DateTime td = DateTime.Now;
        int leapYear = 0;
        for (int i = dtt.Year; i < td.Year; i++)
        {
            if (DateTime.IsLeapYear(i))
            {
                ++leapYear;
            }
        }

        TimeSpan timespan = td.Subtract(dtt);

        intDay = timespan.Days - leapYear;
        int intResult = 0;

        intYear = Math.DivRem(intDay, 365, out intResult);
        intMonth = Math.DivRem(intResult, 30, out intResult);
        intDay = intResult;

        string dateFormat= String.Format(intYear.ToString() + "/" + intMonth + "/" + intDay);
        return dateFormat;
    }
}

A: To implement this logic, I made the extension method check if the month is later in the year, and if so, add 12 to the difference for the wrap around logic. Here is the extension method:
public static int DateTimeMonth(this DateTime dt, DateTime birthday)
{
    int difference = birthday.Month - dt.Month;
    if (difference < 0)
    {
        difference += 12;
    }
    return difference;
}

And here is the code in main to use this method:
DateTime today = DateTime.Now;
DateTime birthday = new DateTime(1985, 03, 22);
int monthDifference = today.DateTimeMonth(birthday);
if (monthDifference == 0)
{
   Console.WriteLine("It is your birthday month this month!");
}
else
{
   Console.WriteLine("It will be your birthday in " + monthDifference + " months.");
}

The extension method returns an integer that can be used in the caller, but if you just want the string that says what is being printed in the WriteLines, you can have the extension method perform this logic instead and return that string.


text:
Q: How to get data generated by script on HTML page using VBA? I am trying to parse a Website using VBA. My goal is to extract the data of the company (The name, website, location, investors, date of investment, amount of investment etc.) and to store it in an excel sheet. My function to extract the HTML source is the following (it works, at least on my computer...). I use late binding to have a better portability.
Private Sub getHTMLFromURL()

    Dim objHTTP As Object
    Dim html As Object
    Dim implTmp As Object

    Set objHTTP = VBA.CreateObject("MSXML2.XMLHTTP")
    Set html = CreateObject("htmlfile")

    on error GoTo endProgram

    With objHTTP
        .Open "GET", URLStr, False
        .send

        If .READYSTATE = 4 And .Status = 200 Then
            html.Open
            html.write .responseText
            html.Close
        Else
            Debug.Print "Error" & vbNewLine & "Ready state: " & .READYSTATE & _
            vbNewLine & "HTTP request status: " & .Status
            GoTo endProgram
        End If

    End With

endProgram:
    Set html = Nothing
    Set objHTTP = Nothing
    If Err <> 0 Then
        Debug.Print "Error in getHTMLFromURL " & Err.Number & " - " & Err.Description
    End If

End Sub

My problem is that the HTML is one huge SCRIPT tag in which the data are hidden. For example, I guess the Headquarter location of the company is in this line of code:
{"key":"hqLocations","name":"Location","sortable":false,"getText":"function getText(c) {\n    return getHQCity(c.hqLocations);\n  }"}

I humbly admit that I have absolutely no clue on how to get these data. I have searched a lot in multiple forums without finding a fitting answer. I tried to adapt this method without success. Thus I have several questions linked to my issue:

*

*Is using MSXML2.XMLHTTP the best way to do so?

*Do I have to fish for each variable or is there a way to directly interpret the script to have an HTML with all the data (which would be much easier then)?

*Otherwise, how can I extract all the data (single data and arrays)?

Thanks a lot

A: Try the below script. When you run it, you should get the required data you have requested in your post:
Sub Fetch_Data()
    Dim IE As New InternetExplorer, HTML As HTMLDocument
    Dim posts As Object, post As Object, hdata As Object
    Dim elem As Object, trow As Object

    With IE
        .Visible = False
        .navigate "http://app.startupeuropeclub.eu/companies/pld_space"
        While .Busy = True Or .readyState < 4: DoEvents: Wend
        Set HTML = .document
    End With

    ''the following line is let the scraper wait until the data is completely loaded
    Do: Set hdata = HTML.getElementsByClassName("field"): DoEvents: Loop Until hdata.Length > 1

    For Each post In hdata
        With post.getElementsByClassName("title")
            If .Length Then R = R + 1: Cells(R, 1) = .Item(0).innerText
        End With
        With post.getElementsByClassName("description")
            If .Length Then Cells(R, 2) = .Item(0).innerText
        End With
    Next post

    ''avoiding hardcoded delay and wait until the data is completely loaded
    Do: Set posts = HTML.querySelector(".card-content.with-padding table.simple-table"): DoEvents: Loop While posts Is Nothing

    For Each elem In posts.Rows
        For Each trow In elem.Cells
            C = C + 1: Cells(I + 10, C) = trow.innerText
        Next trow
        C = 0
        I = I + 1
    Next elem
    IE.Quit
End Sub

Reference to add to the library:
Microsoft Internet Controls
Microsoft HTML Object Library


text:
Q: Create a dropdown 'panel' area from a WPF ribbon? The WPF ribbon (System.Windows.Controls.Ribbon) includes a number of controls which you can add to your ribbon having "dropdown" style behavior where clicking the control's main button shows you a new area.
Examples: RibbonMenuButton, RibbonSplitButton, RibbonMenuButton, RibbonGallery, etc.
However, as far as I can see all of them are designed to show you a list of things from which the user makes a selection. But instead, is there any way to display a 'panel' area that is non-selectable, upon which other controls could be placed?
As an example, here is a screenshot from MS Outlook:

The upper red area is NOT itself a selection in a list. Instead it has a custom control (the table size-picker thing).
But the blue items ARE selectable items which function like a traditional menu.
Its the red area I'm interested in understanding.
(I don't know if Outlook was coded using the WPF Ribbon, and that doesn't matter at all - I'm just using it as an illustration of what I'm looking for.)

Note - I'm not trying to replicate this Outlook table-picker specifically, its just an example of the ways in which you might use a non-selectable 'panel' area within the dropdown region.

A: Microsoft RibbonMenuButton / RibbonSplitButton wont support custom controls in dropdown.
Even if we manage to do that by changing the Content of RibbonMenuItem / RibbonGalleryItem, we will still get selection decoration around those controls on mouse hover
Best way is to use the combination of RibbonToggleButton and Popup Control as below
Then you can place whatever custom control you want inside that popup Control
<StackPanel Orientation="Vertical">
<RibbonToggleButton
            x:Name="yAxis"
            Label="Y Axis"
            SmallImageSource="..\Images\ChartYAxis16.png"
            LargeImageSource="..\Images\ChartYAxis32.png"
            RibbonTwoLineText.HasTwoLines="True"
            RibbonTwoLineText.PathData="M 0 0 L 2.5 3 L 5 0 Z">
        </RibbonToggleButton>
        <Popup
            IsOpen="{Binding IsChecked, ElementName=yAxis}">
            <mycontrols:AnyControl/>
        </Popup>
    </StackPanel>

Of course you may need to handle the dropdown closing programmatically by unchecking the togglebutton whenever user clicks outside the togglebutton or dropdown popup

A: You can put anything you like inside a ribbonmenubutton.
For example:
    <Ribbon>
        <RibbonMenuButton Label="Button One">
            <Grid Height="100" Width="200">
                <TextBlock VerticalAlignment="Top" Text="AAAA"/>
                <TextBlock VerticalAlignment="Bottom" Text="ZZZZ"/>
            </Grid>
        </RibbonMenuButton>
    </Ribbon>

You'd want to extract and change the ribbonmenubutton template to avoid the gap at the left.

A: For prosperity, it's not currently possible.  It appears that the RibbonMenuButton uses a private Popup to display the dropdown content.
Source:  https://github.com/dotnet/wpf/blob/main/src/Microsoft.DotNet.Wpf/src/System.Windows.Controls.Ribbon/Microsoft/Windows/Controls/Ribbon/RibbonMenuButton.cs
Lines 1309 and 1335.


text:
Q: Question related to textbox used to keyin password I am developing a c# winform application. The application will minimize to the system tray, and there are two options for the user to choose from, show and exit . Both are working well. Right now i need to implement a function whereby when the user chooses exit, I need to display a textbox for the user to key in his/her password just above the system tray. The inputbox must mask the character type by the user as the user will be typing his/her password. I want to know whether there are any other way other than creating a new form with a textbox to fulfill this feature.
I tried to import use the visual basic textbox to perform this but unfortunately, I cannot mask the characters typed by the user. Are there any other way to do so other than creating a new form?

A: You're looking for the Textbox.UseSystemPasswordChar property.

A: http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.passwordchar.aspx

A: There's no out-of-the-box solution for what you're trying to do, but the .NET Framework makes available to you all the components to easily make it happen.

*

*The bad news: you need to create a new form that contains the input fields you want to display to users.

*The good news: you can use a standard TextBox, and set it so it will hide the password characters.

There are two parts to showing a password TextBox:

*

*Set the TextBox to hide password characters

*Choose the character to display for passwords


text:
Q: How to reliably access root tag's namespace declarations and attributes using lxml? In the following example, is there a way to either:

*

*only print the root REQ-IF tags's complete attributes without having lxml to print the whole XML document
or

*to enumerate the root tag's namespaces and attributes in the same order as they appear in an XML document?

My goal is to get precisely this string and nothing else:
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20101201" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd reqif.xsd http://www.w3.org/1999/xhtml driver.xsd">

In the code below, I can either print the whole XML document or access independently the nsmap and attrib properties. I can also imagine making a deep copy of a document tree, removing the children nodes and calling tostring() on that parent node only but I was wondering if there was a more elegant solution to just get the exact XML string of the parent tag without accessing its child tags or hacking on the tree structure?
import io

from lxml import etree

reqif_content = """<?xml version="1.0" encoding="UTF-8"?>
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20101201" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd reqif.xsd http://www.w3.org/1999/xhtml driver.xsd">
  <THE-HEADER>
    <REQ-IF-HEADER IDENTIFIER="3dd1a60c-59d1-11da-86ca-4bda04a730ce">
      <COMMENT>Embedded OLE object with multiple representation forms.</COMMENT>
      <CREATION-TIME>2005-05-23T12:00:00+02:00</CREATION-TIME>
      <SOURCE-TOOL-ID>Manually written</SOURCE-TOOL-ID>
      <TITLE>Test data RIF72</TITLE>
    </REQ-IF-HEADER>
  </THE-HEADER>
</REQ-IF>
"""

xml_reqif_root = etree.parse(
    io.BytesIO(bytes(reqif_content, "UTF-8"))
)

print(etree.tostring(xml_reqif_root.getroot(), pretty_print=True).decode("utf8"))
print("nsmap:")
print(xml_reqif_root.getroot().nsmap)
print("attrib:")
print(xml_reqif_root.getroot().attrib)

In the output, it is clear that I get a full XML which I don't want and I get some non-identical representation of the namespaces and attributes:
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20101201" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd reqif.xsd http://www.w3.org/1999/xhtml driver.xsd">
  <THE-HEADER>
    <REQ-IF-HEADER IDENTIFIER="3dd1a60c-59d1-11da-86ca-4bda04a730ce">
      <COMMENT>Embedded OLE object with multiple representation forms.</COMMENT>
      <CREATION-TIME>2005-05-23T12:00:00+02:00</CREATION-TIME>
      <SOURCE-TOOL-ID>Manually written</SOURCE-TOOL-ID>
      <TITLE>Test data RIF72</TITLE>
    </REQ-IF-HEADER>
  </THE-HEADER>
</REQ-IF>
nsmap:
{None: 'http://www.omg.org/spec/ReqIF/20101201', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance'}
attrib:
{'{http://www.w3.org/2001/XMLSchema-instance}schemaLocation': 'http://www.omg.org/spec/ReqIF/20110401/reqif.xsd reqif.xsd http://www.w3.org/1999/xhtml driver.xsd'}


text:
Q: How to specify the text size of a vertex index in a 3D mesh using Labeled My code takes a list of {x, y, z} vertices and displays a convex hull with each vertex labeled by its index in the list.  Here is a minimal working example of the problem,
pts = RandomReal[{-1, 1}, {4, 3}];
chull = ConvexHullMesh[pts];
HighlightMesh[chull, Labeled[0, "Index"]]

However, the size of the vertex labels is tiny and I have been unable to find any method to make the text larger. Labeling the axes etc. and changing the text there is straightforward. Does anyone have an idea how to do specify the size of the vertex text. Same issue if I want the edges labeled or the faces of the triangles. I am showing a simple icosahedron.

A: This was difficult to find, but I think this is how you do it, using MeshCellLabel and MeshCellMarker
ConvexHullMesh[pts,
 MeshCellLabel -> {0 -> "Marker"},
 MeshCellMarker ->
  Table[{0, n} -> Style[n, 25], {n, 1, 4}]]

Or you can use HighlightMesh if you've already created the ConvexHullMesh as below.  You can apply any Style elements,
HighlightMesh[chull, Labeled[0, "Marker"],
 MeshCellMarker ->
  Table[{0, n} ->
    Style[n, 25, Hue[n/4],
     FontFamily -> "Comic Sans MS"], {n, 1, 4}]]

I don't see how to use Labeled to label different cell specs, but you can use MeshCellLabel in this way,
ConvexHullMesh[pts,
  MeshCellLabel -> {0 -> "Marker", 1 -> "Marker", 2 -> "Marker"},
  MeshCellMarker -> Join[
      Table[{0, n} ->
          Style[n, 25, Red,
            FontFamily -> "Comic Sans MS"], {n, 1, 4}],
      Table[{1, n} ->
          Style[n, 35, Blue,
            FontFamily -> "Courier"], {n, 1, 6}],
      Table[{2, n} -> Style[n, 35, Purple,
            FontFamily -> "Times New Roman"], {n, 1, 4}]
      ]]


text:
Q: HD in caddy seems inactive and blocks application this is the premise:
Recently I removed from my mbp 15 (2012) the internal Superdrive and replaced it with a caddy + 1 Tb hard disk.
I already replaced the original HD with an SSD. Since I'm a programmer and I work intensively with my mac, I thought installing the caddy+HD was a good idea: this allows me to have intense write/read session over the HD rather than the ssd. Furthermore I moved all the general purpose files on the HD (music, documents and so on) by just copying it.
This said here is the strange thing. When I import music into iTunes from the HD it takes so long that the most times it start the color wheel and it blocks iTunes. Or while I'm working on a text file or source file it gets blocked while saving.
To me it looks like the hard disk goes to sleep from time to time (randomly????) and it blocks all the applications that are using it. The most obvious and tangible problem is given by the music player (that's why I spotted this problem). Sometime for example it is playing the music and by skipping from one song another it blocks for a while (keep in mind that I don't import things in the iTunes library cause this means a raw copy of the same things.. ).
Any clue is appreciated in spotting any problem or misconfiguration or whatever..

A: In system preferences -> energy saving you can disable putting HDDs to sleep. If that doesn't help my first guess would be a faulty cable or caddy.


text:
Q: cargar dropzone dentro de un div (dinámico) que pasa por ajax Hola amigos estoy tratando de incorporar dropzone que viene de un archivo externo que pasa por ajax, pero no me funciona :/, si lo pongo en la página principal fuera de la sección dinámica (que utilizo para cargar contenido por ajax) funciona perfecto.

 Aquí es donde cargo mi contenido dinámico

este es el código que viene en mi archivo externo
mediante un botón muestro una tabla con contenido y dentro de la tabla viene el formulario
no tengo idea de como realizar la selección dentro del contenido que viene por ajax.

echo'

      Código
      Evidencia
      Tipo
      Archivo
      Estado

';

if($resultEvidencias){
     while ($evidencia = $resultEvidencias->fetch_array()){
     echo'

      '.$evidencia['codigoEvidencia'].'
      '.$evidencia['nombreEvidencia'].'
      '.$evidencia['tipoEvidencia'].'
      ';
      if(empty($evidencia['archivoEvidencia'])){

        echo'<form action="upload.php" class="dropzone" id="dropzonewidget"></form>';

       }else{
         echo $evidencia['archivoEvidencia'];
        }
      echo '
';
  }

echo'

';

[![dropzone][1]][1]
[1]: https://i.stack.imgur.com/8oT2d.png
muchas gracias por su apoyo

A: Te recomiendo que uses arquitectura por capas (Modelo, Vista, Controlador o similar) en lugar de lanzar los echo para pintar tu página. Es decir, usar archivos separados para tu vista en HTML, javascript, css y tu código en PHP para que tengas desacoplado el backend del frontend. Ésta práctica te permitirá tener un mejor control en lo que pasa en tu código.
Dicho esto, lo que puedes hacer es tener un archivo HTML (junto con su(s) CSS y .js) con todo lo que requieras y que no depende para nada del back y en tu archivo .php usar el comando $_POST (ejemplo) para obtener todo lo que tu front envíe al back.


text:
Q: Program that groups numbers/letters with how many times it iterates, and puts it into array So I'm trying to make a program that checks an Array(Array2) to see if it contains numbers from another Array(Array1), and groups them along with the numbers or letters that it's connected with. With the data I put below, I was hoping for it to return something like (14T,6in,4s,3aegr,2o,1ESTfhlmpx), instead it returns 14T,6i,4s,3a,2o,1e. It seems like it's not wanting to iterate all of the other letters and numbers in the array. I tried putting it into a string instead of changing the array to add the numbers which have it, and it showed that the for loop iterated through all of the letters/numbers, but it just won't add it to the array. I've been stuck on this for multiple hours now, and was just curious if someone could help me out with this.
Array1[0] = "14";
Array1[1] = "6";
Array1[2] = "4";
Array1[3] = "3";
Array1[4] = "2";
Array1[5] = "1";

String[] Array2 = new String[18];
Array2[0] = "E1";
Array2[1] = "S1";
Array2[2] = "T14";
Array2[3] = "a3";
Array2[4] = "e3";
Array2[5] = "f1";
Array2[6] = "g3";
Array2[7] = "h1";
Array2[8] = "i6";
Array2[9] = "l1";
Array2[10] = "m1";
Array2[11] = "n6";
Array2[12] = "o2";
Array2[13] = "p1";
Array2[14] = "r3";
Array2[15] = "s4";
Array2[16] = "t4";
Array2[17] = "x1";

for(int a = 0; a < Array1.length; a++){
   for(int x = 0; x < Array2.length; x++){
       String checkers = Array2[x].substring(1);
       // ^^ Gets the letter after exp.
       if(checkers.equals(Array1[a])){
            Array1[a] += Array2[x].substring(0,1);
        }
        else{

          }
        }
    }
    System.out.println(Arrays.toString(Array1));
  }
}

A: This comparison checkers.equals(Array1[a]) will not be true after the first appending to Array1[a].  To resolve this, it's beter to provide a temporary variable before the nested loop String num = Array1[a]; and compare to this variable:
for (int a = 0; a < Array1.length; a++) {
    String num = Array1[a];
    for (int x = 0; x < Array2.length; x++) {
        String checkers = Array2[x].substring(1);
        if (num.equals(checkers)) {
            Array1[a] += Array2[x].substring(0,1);
        }
    }
}

System.out.println(Arrays.toString(Array1));

Output:
[14T, 6in, 4st, 3aegr, 2o, 1ESfhlmpx]

A: This is because by the time you run if(checkers.equals(Array1[a])) to update Array1[a] a second time (like in the case for "6"), Array1[a] has already been updated with one of its letters (so for "6", Array1[a] becomes "6i"), and although checkers may equal "6", Array[1] now equals "6i". This is what stands in the way of continuously updating Array1[a]. To get around this, you can create a third array Array3 that has all the initial values of Array1. This third array will be used in comparison to checkers.
Replace if(checkers.equals(Array1[a])) with:
if(Array3[a].equals(checkers)).

A: First of all, never use captial letters for your objects. These should only be used for class definitions.
Now to the case. Use regex and create a dictionary of arrays of the second array. The keys will be the numbers and the values will be the letters connected to those numbers. After that you can write out this info however you want:
import re

match_dict = {}

# Construct the match dict
for letter_digit in array2:
    # Use regex for string matching
    match_obj = re.match( r'([a-zA-Z]+)([0-9]+)', letter_digit, re.M|re.I)
    letter = match_obj.group(1)
    digit = match_obj.group(2)

    if digit in match_dict:
        match_dict[digit].append(letter)
    else:
        match_dict[digit] = [letter]

# Get only letters that match with array1
array1_matches = {}
for digit in array1:
    if digit in match_dict:
        array1_matches[digit] = match_dict[digit]
    else:
        # No idea what you want to do if there's no match
        array1_matches[digit] = None

# Print everything
for key, value in array1_matches.items():
    if value is not None:
        print(key, end='')
        for letter in value:
            print(letter, end='')
        print(",", end='')

I haven't tested the code myself, but it should do what you're after.


text:
Q: Python: Pandas merge 2 dataframes using a common column How can I merge 2 dataframes df1 and df2 using a common column 'ADD' into df3?
Both df1 and df2 have a common column 'ADD'.
I want to use df2 as a mapping table for covert ADD into a ST value.
I have tried to convert df2 into Series or Dictionary, but nether seems work.
 df1 =

    Name    ADD
 1  A       12
 2  B       54
 3  C       34
 4  D       756
 5  E       43

 df2 =

    ADD     ST
 1  12      CA
 2  54      CA
 3  34      TX

 df3 =

    Name    ADD     ST
 1  A       12      CA
 2  B       54      CA
 3  C       34      TX
 4  D       756     nan
 5  E       43      nan

A: You have to do an outer merge (join):
In [11]: df1.merge(df2, how='outer')
Out[11]:
  Name  ADD   ST
0    A   12   CA
1    B   54   CA
2    C   34   TX
3    D  756  NaN
4    E   43  NaN


text:
Q: How to implement custom URL handler to access JS modal content? I maintain a wordpress site that is javascript heavy and includes a lot of content in modals created with the the Tingle Modal library. The site is designed as a single-column site for the main page, with hash based navigation to take users up and down the page. What I would like to achieve, is to make the modal content accessible by url, so that external users can be directed to the content.
The modals themselves pull in info from a custom content type and are triggered by a jquery function called by clicking a url on the mainpage. I assume to get the functionality I want I would need to implement some sort of custom URL handler which would trigger the modal function submission, but I'm not sure what the best way to implement this would be ( .htaccess, PHP script, Jquery, combination?). Anyway, I wanted to know if anyone has dealt with something like this and had suggestions?

A: You could try with javascript, the following logic:

*

*On page load check if a hash exist in the url with something like:

var hash = decodeURIComponent(location.hash.substr(1));

*

*Then you would have two tables (one for team and one for advisors) with names matching the urls of your modals (e.g.: https://greentec-capital.com/team/peter-grouev/) like:

var teamHashes = ['peter-grouev', 'erick-yong'];

*

*After that you will check if the hash is inside of one of your tables*:

if teamHashes.indexOf(hash) !== -1 { //show modal logic }
*if hash not in teamHashes table, then check the advisorsHashes table.
Now inside the above if, to show the modal, we need to declare the $modal like in your code and construct the url and make the ajax call to it, like:
if teamHashes.indexOf(hash) !== -1 {
    var $teamModal = new tingle.modal({
        footer: true,
        stickyFooter: false,
        closeMethods: ['overlay', 'escape'],
        closeLabel: "Close",
        cssClass: ['team-modal'],
        onOpen: function() {
            console.log('modal open');
        },
        onClose: function() {
            console.log('modal closed');
            $modal.setContent("");
        },

    var teamUrl = "https://greentec-capital.com/team/"+hash+"/";

    $.ajax({
           type: "POST",
           url: teamUrl,
           data: {},
           success: function(result){
               $modal.setContent(result);
               $modal.open();
           }
        });
});

That should do it.


text:
Q: My breakpoints located after an http request does not work, how can I fix it? I work on the PhpStorm IDE and I use Xdebug.
The process_upgrade_membership() function displays a form to register to my website (currently on my localhost). When I place a breakpoint on this function, it triggers.
The recurring_payment_confirm() function is triggered by an http request from Stripe when a payment has been made ([200] POST http://localhost/mySite/index.php?option=com_osmembership&task=recurring_payment_confirm&payment_method=os_stripe [evt_1KYoa4HVMmgjDnLE4gsKXE5c]). When I place a breakpoint on this function, the breakpoint is ignored. I also tried to put breakpoints in the functions used by recurring_payment_confirm() without success. I made sure that the function is used by testing it with a dd().
These two functions are in the same file.
Can you help me debug what's after the http request?
xdebug_info() :
`Version    3.1.3
Support Xdebug on Patreon, GitHub, or as a business
Enabled Features
(through 'xdebug.mode' setting)
Feature Enabled/Disabled    Docs
Development Helpers ✘ disabled
Coverage    ✘ disabled
GC Stats    ✘ disabled
Profiler    ✘ disabled
Step Debugger   ✔ enabled
Tracing ✘ disabled
Optional Features
Compressed File Support no
Clock Source    GetSystemTimePreciseAsFileTime
Diagnostic Log
No messages
Step Debugging  Docs
Debugger    Active
Connected Client    localhost:9003
DBGp Settings
Max Children    100
Max Data    1024
Max Depth   1
Show Hidden Properties  Yes
Extended Properties Yes
Notifications   Yes
Resolved Breakpoints    Yes
Breakpoint Details  No
PHP
Build Configuration
Version (Run Time)  7.2.3
Version (Compile Time)  7.2.34
Debug Build no
Thread Safety   enabled
Settings
Configuration File (php.ini) Path   C:\WINDOWS
Loaded Configuration File   D:\xampp\php\php.ini
Scan this dir for additional .ini files (none)
Additional .ini files parsed    (none)
Directive   Local Value Master Value    Docs
xdebug.mode debug   debug
xdebug.start_with_request   default default
xdebug.start_upon_error default default
xdebug.output_dir   C:\Windows\Temp C:\Windows\Temp
xdebug.use_compression  0   0
xdebug.trigger_value    no value    no value
xdebug.file_link_format no value    no value
xdebug.filename_format  no value    no value
xdebug.log  no value    no value
xdebug.log_level    7   7
xdebug.var_display_max_children 128 128
xdebug.var_display_max_data 512 512
xdebug.var_display_max_depth    3   3
xdebug.max_nesting_level    256 256
xdebug.cli_color    0   0
xdebug.force_display_errors Off Off
xdebug.force_error_reporting    0   0
xdebug.halt_level   0   0
xdebug.max_stack_frames -1  -1
xdebug.show_error_trace Off Off
xdebug.show_exception_trace Off Off
xdebug.show_local_vars  Off Off
xdebug.dump.COOKIE  no value    no value
xdebug.dump.ENV no value    no value
xdebug.dump.FILES   no value    no value
xdebug.dump.GET no value    no value
xdebug.dump.POST    no value    no value
xdebug.dump.REQUEST no value    no value
xdebug.dump.SERVER  no value    no value
xdebug.dump.SESSION no value    no value
xdebug.dump_globals On  On
xdebug.dump_once    On  On
xdebug.dump_undefined   Off Off
xdebug.profiler_output_name cachegrind.out.%p   cachegrind.out.%p
xdebug.profiler_append  Off Off
xdebug.cloud_id no value    no value
xdebug.client_host  localhost   localhost
xdebug.client_port  9003    9003
xdebug.discover_client_host Off Off
xdebug.client_discovery_header  no value    no value
xdebug.idekey   no value    no value
xdebug.connect_timeout_ms   200 200
xdebug.scream   Off Off
xdebug.gc_stats_output_name gcstats.%p  gcstats.%p
xdebug.trace_output_name    trace.%c    trace.%c
xdebug.trace_format 0   0
xdebug.trace_options    0   0
xdebug.collect_assignments  Off Off
xdebug.collect_return   Off Off
xdebug.remote_autostart (setting renamed in Xdebug 3)   (setting renamed in Xdebug 3)
xdebug.remote_enable    (setting renamed in Xdebug 3)   (setting renamed in Xdebug 3)
xdebug.remote_host  (setting renamed in Xdebug 3)   (setting renamed in Xdebug 3)
xdebug.remote_log   (setting renamed in Xdebug 3)   (setting renamed in Xdebug 3)
xdebug.remote_port  (setting renamed in Xdebug 3)   (setting renamed in Xdebug 3)   `

in php.ini [xdebug]:
`
[xdebug]
zend_extension = D:\xampp\php\ext\php_xdebug.dll
xdebug.remote_autostart = 1
;xdebug.profiler_append = 0
;xdebug.profiler_enable = 0
;xdebug.profiler_enable_trigger = 0
;xdebug.profiler_output_dir = "D:\xampp\tmp"

xdebug.remote_enable=1
xdebug.mode=debug
xdebug.remote_host=127.0.0.1
xdebug.remote_log="d:\xampp\tmp\xdebug.txt"
xdebug.remote_port="9000"
xdebug.start_with_request=yes
;xdebug.remote_mode=jit
;xdebug.remote_cookie_expire_time = 36000

`

A: I success to make it work, I pass the authorization of the xdebug chrome extension from "in case of a click" to "on all sites" in addition to add xdebug.start_with_request=yes in php.ini Thank you for your assistance


text:
Q: C# dynamically added GroupBox seems to be empty after adding controls to it I am having trouble with a little tool i am writing for myself.
I am trying to have a Windows Form that shows a web browser and multiple, dynamically added groups of textboxes and comboboxes.
The browser works fine and i can add textboxes etc. fine when not adding it to a groupbox, but rather to the main panel.
When trying to add the textboxes to groupboxes it works for the first groupbox, but every other one that followes stayes empty.
this is how my (simplified) code looks so far:
        //generate controls e.g.
        ComboBox dynamicComboBox = new ComboBox();
        dynamicComboBox.Name = "comboBox" + anzahlModule;
        dynamicComboBox.DataSource = new BindingSource(this.getInhaltComboBox(), null);
        dynamicComboBox.DisplayMember = "Value";
        dynamicComboBox.ValueMember = "Key";
        dynamicComboBox.Location = new System.Drawing.Point(153, Yloc + 25);
        dynamicComboBox.TabIndex = tabReihenfolge + 2;
        dynamicComboBox.SelectedIndexChanged += comboBox1_SelectedIndexChanged;

        ...do for all the others...

        //Get Interface and redraw
        GroupBox dynamicGroup = new GroupBox();
        dynamicGroup.Text = dynamicLabel.Text;
        dynamicGroup.Size = new System.Drawing.Size(600, 325);
        dynamicGroup.Location = button1.Location;
        dynamicGroup.Name = "dynamicGroupBox" + anzahlModule;
        dynamicGroup.Visible = true;

        dynamicGroup.Controls.Add(LabelComboBox);
        dynamicGroup.Controls.Add(LabelTextBox);
        dynamicGroup.Controls.Add(LabelTextBox2);
        dynamicGroup.Controls.Add(LabelInhalt);
        dynamicGroup.Controls.Add(LabelInhalt2);
        dynamicGroup.Controls.Add(LabelPictures);
        dynamicGroup.Controls.Add(LabelCheckBox);
        dynamicGroup.Controls.Add(LabelCheckBox2);
        dynamicGroup.Controls.Add(LabelLink);
        dynamicGroup.Controls.Add(LabelLink2);
        dynamicGroup.Controls.Add(dynamicTextBox);
        dynamicGroup.Controls.Add(dynamicTextBox2);
        dynamicGroup.Controls.Add(dynamicUeberschrift);
        dynamicGroup.Controls.Add(dynamicUeberschrift2);
        dynamicGroup.Controls.Add(dynamicComboBox);
        dynamicGroup.Controls.Add(dynamicPictureBox);
        dynamicGroup.Controls.Add(dynamicCheckBox);
        dynamicGroup.Controls.Add(dynamicCheckBox2);
        dynamicGroup.Controls.Add(dynamicLinkBox);
        dynamicGroup.Controls.Add(dynamicLinkBox2);
        panel1.Controls.Add(dynamicGroup);

this works if i add the stuff directly to panel1, but not when adding it to the groupboxes.
Can someone help my by giving me an idea on where the probleme might be or tell me what is actually wrong?
Thanks in advance.

A: Okay so I found my error and it is actually very simple, i was just too blind to see it :) I have positioned my textBoxes and so on in relation to a button that i afterwards moved. And that means that i tryed to display e.g. a label at point 750 / 300 in a group box that only has a size of 600x325, so it can not be visible. @Mikhail Neofitov thanks for the tip with multiple boxes at the same location, that lead to a solution.


text:
Q: How to read RGB values of picture with rawpy on Python I'm trying to get the information from a 16bit 'nef' image with Python.
I've been using rawpy to open the file and get a linear output with the image valuer. But now I want to look only at the green channel.
path = 'image.nef'
with rawpy.imread(path) as raw:
    rgb_linear = raw.postprocess(gamma=(1,1),no_auto_bright=True, output_bps=16)
    rgb= raw.postprocess(no_auto_bright=True, output_bps=16)

Now I don't know how to go  from this to getting the RGB values.

A: You can get the Red, Green and Blue channels separated and saved like this:
#!/usr/bin/env python3

import rawpy
import imageio

with rawpy.imread('raw.nef') as raw:
    rgb = raw.postprocess(gamma=(1,1), no_auto_bright=True, output_bps=16)

# Extract Red, Green and Blue channels and save as separate files
R = rgb[:,:,0]
G = rgb[:,:,1]
B = rgb[:,:,2]

imageio.imsave('R.tif', R)
imageio.imsave('G.tif', G)
imageio.imsave('B.tif', B)


text:
Q: How to reverse the process of linear filtering algorithms provided by OpenCV? I am currently working on a Python project designed to blur certain objects in pictures by using some filtering functions provided by OpenCV, such as linear filter cv2.blur() and cv2.GaussianBlur(). However, I was told that these kinds of processes are reversable, which means those blurred regions could be restored. For this reason, I've changed my blurring algorithm to cv2.filter2D() with randomly generated convolution kernel. My code is as follows:
from cv2 import cv2

kernel_size = 35
# Generate a 2D kernel filled with random float
kernel = np.random.randint(1, kernel_size ** 4 + 1, size=[kernel_size] * 2)
sum_kernel = np.sum(kernel)
normalized_kernel = kernel / sum_kernel

# Read, blur and save a picture
img = cv2.imread('./cat.jpeg')
blurred_img = cv2.filter2D(img, -1, cv2.flip(normalized_kernel, -1), borderType=cv2.BORDER_CONSTANT)
cv2.imwrite('random_blurred.jpeg', blurred_img)

I compared aforementioned algorithm with cv2.blur() result, code is as follows:
from cv2 import cv2

kernel_size = 35
img = cv2.imread('./cat.jpeg')
blurred_img = cv2.blur(img, (kernel_size, kernel_size))
cv2.imwrite('averaging_blurred.jpeg', blurred_img)

Here are the results of two algorithms, which are visually identical.
random_blurred.jpeg averaging_blurred.jpeg
I don't know if my algorithm for anti-restorage actually works? Is it possible to reverse the process if the kernel used for convolution is provided? I have tried many methods including Gonçalo Raposo's, what I finally got were images filled with snowflakes. I failed to come up with a practical solution to restore original pictures from blurred ones with known convolution kernels.

A: Linear filtering can be reversed as a huge linear system, where:

*

*each variable is an image pixel and

*each line is related to the application of the linear filter for one particular pixel.

*image border are constant initial values

This linear system will have a huge sparse matrix that is invertible for most of the kernels, and hence, lead to a closed solution.


text:
Q: Problems when creating Open Graph stories: "unable to generate story" and "failed to generate preview" I have an app on Facebook (we'll call it mygame), connected with an Android game I'm developing.
In this mobile app, I want to let users to share their scores after a match. For this, I've considered the use of Open Graph stories, actions and objects.
The first thing I've done is to create an action, "Play" and an object "Match", this one with an integer property named "score".
After that, I've created my first story in the form "Play a Match" using the relative button "Add custom story".
First problem: all the generated examples don't show a preview, instead a red message appears, Unable to Generate Story.
This problem was previously treated on Stackoverflow, and the cause was related to the fact that "facebook has no examples of the story to render".
That should not be true in my case, because if I open the Object Browser I can see two auto-generated Match objects. Does Facebook try to generate example stories from those records?
If not (or even true), what's the problem?
Second problem SOLVED, SEE ANSWERS: on Android, simply, I can't test this story due to an exception that says com.facebook.FacebookException: Failed to generate preview for user..
The method I've used to show a Facebook Dialog with the details of this "played match" is the one described here: https://developers.facebook.com/docs/android/open-graph#sharedialog-setup
In my app, the code is the following:
        OpenGraphObject setObj = OpenGraphObject.Factory.createForPost("mygame:match");
        setObj.setProperty("score", set.getThisUserScore());
        setObj.setProperty("title", set.getType().getDisplayString());
        setObj.setProperty("url", "http://www.mygame.com");
        setObj.setProperty("description", "Can you beat me?");

        OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
        action.setType("mygame:play");
        action.setProperty("match", setObj);

        FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(activity, action, "match").build();
        activity.getUiHelper().trackPendingDialogCall(shareDialog.present());

Once called, the Dialog appears on my device, but it closes itself after one second, throwing the exception.
I really can't focus on where the problem is (I'm trying to implement the simplest way of sharing stories). Are these two problems connected?

A: I use this code to publish on wall for multiple object properties.
 private void publishPhoto(String imageURL) {
Log.d("FACEBOOK", "Post to Facebook!");

try {

    JSONObject attachment = new JSONObject();
    attachment.put("message",text);
    attachment.put("name", "MyGreatAndroidAppTest");
    attachment.put("href", "http://stackoverflow.com/users/909317/sunny");
    attachment.put("description","Test Test TEst");

    JSONObject media = new JSONObject();
    media.put("type", "image");
    media.put("src",  imageURL);
    media.put("href",imageURL);
    attachment.put("media", new JSONArray().put(media));

    JSONObject properties = new JSONObject();

    JSONObject prop1 = new JSONObject();
    prop1.put("text", "Text or captionText to Post");
    prop1.put("href", imageURL);
    properties.put(text, prop1);

    // u can make any number of prop object and put on "properties" for    ex:    //prop2,prop3

    attachment.put("properties", properties);

    Log.d("FACEBOOK", attachment.toString());

    Bundle params = new Bundle();
    params.putString("attachment", attachment.toString());
    facebook.dialog(MyProjectActivity.this, "stream.publish", params, new DialogListener() {

        @Override
        public void onFacebookError(FacebookError e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onError(DialogError e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onComplete(Bundle values) {
            final String postId = values.getString("post_id");
            if (postId != null) {
                Log.d("FACEBOOK", "Dialog Success! post_id=" + postId);
                Toast.makeText(MyProjectActivity.this, "Successfully shared on Facebook!", Toast.LENGTH_LONG).show();

            } else {
                Log.d("FACEBOOK", "No wall post made");
            }

        }

        @Override
        public void onCancel() {
            // TODO Auto-generated method stub

        }
    });

} catch (JSONException e) {
    Log.e("FACEBOOK", e.getLocalizedMessage(), e);
}

}

A: I've solved the second problem about the FacebookException!
There's a wrong line:
setObj.setProperty("score", set.getThisUserScore());

Being "score" a custom property, the line must be replaced by:
setObj.getData().setProperty("score", set.getThisUserScore());

Note that I had to search deeply in the documentation to find this...


text:
Q: OpenCV, C++: Inserting into set I am developing a C++ application using NetBeans 6.9 on Ubuntu 11.04.  I am using OpenCV  2.3.1.  I was wondering if someone could tell me what is wrong with this code.

void AddTriangle(CvPoint buf[3], set< Triangle > &V)
{
    Triangle    triangle;
    int         inc;
for (inc=0; inc<3; ++inc)
{
    triangle.v[inc].x=buf[inc].x;
    triangle.v[inc].y=buf[inc].y;
}
V.insert((const Triangle) triangle);

}

I get the following error message when I try to compile.

                 from /usr/include/c++/4.5/bits/locale_classes.h:42,
                 from /usr/include/c++/4.5/bits/ios_base.h:43,
                 from /usr/include/c++/4.5/ios:43,
                 from /usr/include/c++/4.5/istream:40,
                 from /usr/include/c++/4.5/sstream:39,
                 from /usr/include/c++/4.5/complex:47,
                 from /usr/local/include/opencv2/core/core.hpp:59,
                 from ../../OpenCV-2.3.1/include/opencv/cv.h:64,
                 from ../../OpenCV-2.3.1/include/opencv/cv.hpp:50,
                 from ../../DraculaFiles/TwoDTriangulation.cpp:12:
/usr/include/c++/4.5/bits/stl_function.h: In member function 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = sTriangle]':
In file included from /usr/include/c++/4.5/string:50:0,
/usr/include/c++/4.5/bits/stl_tree.h:1184:4:   instantiated from 'std::pair, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = sTriangle, _Val = sTriangle, _KeyOfValue = std::_Identity, _Compare = std::less, _Alloc = std::allocator]'
/usr/include/c++/4.5/bits/stl_set.h:408:29:   instantiated from 'std::pair, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(const value_type&) [with _Key = sTriangle, _Compare = std::less, _Alloc = std::allocator, typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator = std::_Rb_tree_const_iterator, value_type = sTriangle]'

Triangle is defined as follows.

typedef struct sTriangle
{
        CvPoint v[3];
} Triangle;

Any help would be greatly appreciated,
Peter.

A: STL fails to distinguish instances of triangles in a set and it was looking for overloaded  "<" operator.

A: To put Triangle into a set, you have to implement comparison operator. Otherwise the set cannot tell which values are equal and which are different.
typedef struct sTriangle
{
CvPoint v[3];
bool operator<(const sTriangle& other) const;
} Triangle;

bool sTriangle::operator<(const sTriangle& other) const
{
   // compare 'this' with 'other'
}

For the implementation of less operator, you can inspire here.
Edit: you can implement the less operator even without modifying sTriangle structure:
typedef struct sCvPoint {
int x;
int y;
} CvPoint;

typedef struct sTriangle
{
CvPoint v[3];
} Triangle;

bool operator==(CvPoint const& left, CvPoint const& right)
{
    return left.x == right.x && left.y == right.y;
}

bool operator<(CvPoint const& left, CvPoint const& right)
{
    return left.x == right.x
        ? left.y < right.y
        : left.x < right.x;
}

bool operator<(Triangle const& left, Triangle const& right)
{
    return left.v[0] == right.v[0]
        ? left.v[1] == right.v[1]
            ? left.v[2] < right.v[2]
            : left.v[1] < right.v[1]
        : left.v[0] < right.v[0];
}


text:
Q: Definitions of K-L divergence based on likelihood ratio and on R-N derivative From Wikipedia

For distributions $P$ and $Q$ of a continuous random variable, KL-divergence is defined to be the integral:
  $$
    D_{\mathrm{KL}}(P\|Q) = \int_{-\infty}^\infty \ln\left(\frac{p(x)}{q(x)}\right) p(x) \, {\rm d}x, \!
$$
  where $p$ and $q$ denote the densities of $P$ and $Q$.
More generally, if $P$ and $Q$ are probability measures over a set $X$, and $P$ is absolutely continuous with respect to $Q$, then the Kullback–Leibler divergence from $P$ to $Q$ is defined as
  $$
    D_{\mathrm{KL}}(P\|Q) = \int_X \ln\left(\frac{{\rm d}P}{{\rm d}Q}\right) \,{\rm d}P, \!
$$
  where $\frac{{\rm d}P}{{\rm d}Q}$ is the Radon–Nikodym derivative of $P$ with respect to $Q$, and provided the expression on the right-hand side exists.

If I understand correctly, R-N derivative is same as likelihood ratio, but the latter can still exist when the former doesn't exist, i.e. when one measure isn't absolute continuous wrt the other measure.
The first definition of K-L divergence is based on likelihood ratio, and the second definition is based on R-N derivative. So how is the second "more general"?
Thanks and regards!

A: The first definition only applies to probability measures on $\mathbb{R}$ which have densities. Not all probability measures are defined on $\mathbb{R}$, and not all probability measures defined on $\mathbb{R}$ have densities.

A: My guess is that Wikipedia failed to mention some important conditions on their definition for the continuous random variable case. I believe the required condition for the first definition to be well-defined is
\begin{align}
P&\ll Q\ll \lambda,
\end{align}
where $\lambda$ is Lebesgue measure (and perhaps by abuse of notatation the random variables are substituted for the measures they induce). If this were not true, then $q(x)$ could be 0 on a set of nonzero Lebesgue measure for which $p(x)$ is not 0. Then the integrand would be $\infty$ on a set with larger than 0 measure. So the first definition fails to be well-defined (at least as a real valued function) without the added condition.
So, to answer the question, the second definition is more general because it only requires the condition $P\ll Q$, and not the condition $Q\ll\lambda$.


text:
Q: Adding an extra parameter [string] to my posts' permalink? I've been searching the internet for 6 hours now, so I decided to ask this in the forum and would appreciate every help.
I just want my permalink to say (e.g. portfolio, post, etc)
http://mysite.com/?portfolio=xxxx&param=whatever

I need the param, because the post itself defines the "whatever" parameter and there is a search form in the post, which initializes itself using this parameter (the searchform gets the parameter, if it's in URL). For single links, I could've placed the param into the link, but the WP defines the permalinks restrictively.
I tried adding add_query_arg() to functions.php without success (It's not even clear where to place the code (single.php or functions.php) and how to call the function from the post).
I then tried adding custom fields and Meta Boxes, but they seem to conatin the extra parameter but not add it to the URL. So all I get is:
http://mysite.com/?portfolio=xxxx

a.) BEST SOLUTION The best way would be, to add a custom field to the post (or post type), which inserts a value the param and shows the permalink-URL with that parameter.
b.) JUDO SOLUTION The simplest thing would be, to add this parameter (text) to the link.
There are a gazillion post about this online, but they all refer to parsing of parameters which external links pass ($_GET) and conditionally change the appearance of the site or adding one specific parameter/value to each post/page. I do not need this.
Is there any way to add this 1 single parameter to the permalink-URL directly from the post, without changing 18 php files and writing hundred lines of code?
Thank you for any help!
m
PS. I am using WP 3.6.1 DE with inovado
.
Things I have already tried

*

*WP Codex add_query_arg()

*Stackoverflow: question 4586835 how-to-pass-extra-variables-in-url-with-wordpress

*Cookie-monster: wordpress-url-parameter-utility

*Creativebloq: user-friendly-custom-fields-meta-boxes-wordpress-5113004

*Farinspace: how-to-create-custom-wordpress-meta-box

*stackexchange.com: questions 51444 - add-extra-parameters-after-permalink

and finally

*

*webopius: using-custom-url-parameters-in-wordpress

A: The Codex page for post_link has an example similar to what you need. For custom post types, there's also the post_type_link filter.
This would go in your theme's functions.php, and checks if a meta key query_arg exists, and appends it to the URL if so:
function wpa_post_link( $url, $post ){
    if ( $meta = get_post_meta( $post->ID, 'query_arg', true ) ) {
        $url = add_query_arg( 'param', $meta, $url );
    }
    return $url;
}
add_filter( 'post_link', 'wpa_post_link', 10, 2 );

A: I don't know if I understood your question correctly, but  ...
<a href="'. get_the_permalink($post->ID) . '?extraParam=xxx' .'">

Something like that is not enough?


text:
Q: Persistent data on serverside I'm creating a webserver using C# codebehind pages.
What I want is for one user to view and submit something on the page,
and that the data is stored serverside, in such a way that it's persistent,
AND that ANOTHER user can view this data.
Am I restriced to saving it to a flatfile or database, or is there some kind of feature I can use in C# or .NET for this purpose, like a peristent cross-session variable or something?
(normal static variables would be different for each different user, right?)

A: Any static variable will be common to all users, but you should use Application. It is like Session but common to all users. If you need persistence over application reset then use a database.

A: You can test these caching variable
Cache["Key"] = yourValue;

Application["Key"] = yourValue;

You have another cache associated to the session, but it's not global:
Session["Key"] = value;

You have another cache in your page
ViewState["Key"] = value;

A: If you don't have very much data, store it into memory, and write it to disk using either XmlSerializer or BinaryFormatter.
You will want to store your data in memory as an application singleton, accessible from everywhere in your set of pages.

A:
Am I restriced to saving it to a flatfile or database, or is there some kind of feature I can use
  in C# or .NET for this purpose?

There can not be another feature. See, a flat file (i.e. a file you write or another service writes) and a database (which can be a SQL database, a document database or any other form around) logically cover all possibilities that there are for persisting data. I do not think there CAN be any other way, theoretically, that would not already fall into a flat file (i.e. a file you manage) or a database (a file some driver or server process manages).
What you ask is like "I have a radio, it can be on or off. Is there any other state it can be in?" - bad news, no, either it is on or off.
Any feature in the .NET framework either runs down to being either of the two you name at the end.


text:
Q: Как ограничить доступ - показывать или не показывать блок? Здравствуйте.
Как можно ограничить доступ к пункту меню.
Есть таблица с доступами, ее структура:
id
id_staff
id_cabinet (id кабинета в который может заходить сотрудник)
vid_access (вид доступа, например: access_balance
access (если 0 то запрещен доступ, если 1 то разрешен)

Как, допустим, ограничить доступ к разделу меню с названием balance?
Что посоветуете?


text:
Q: Grammar rule extraction from parsed result I get following result when i execute stanford parser from nltk.
(S (VP (VB get) (NP (PRP me)) (ADVP (RB now))))

but i need it in the form
S -> VP
VP -> VB NP ADVP
VB -> get
PRP -> me
RB -> now

How can I get this result, perhaps using recursive function.
Is there in-built function already?

A: First to navigate a tree, see How to iterate through all nodes of a tree? and How to navigate a nltk.tree.Tree? :
>>> from nltk.tree import Tree
>>> bracket_parse = "(S (VP (VB get) (NP (PRP me)) (ADVP (RB now))))"
>>> ptree = Tree.fromstring(bracket_parse)
>>> ptree
Tree('S', [Tree('VP', [Tree('VB', ['get']), Tree('NP', [Tree('PRP', ['me'])]), Tree('ADVP', [Tree('RB', ['now'])])])])
>>> for subtree in ptree.subtrees():
...     print subtree
...
(S (VP (VB get) (NP (PRP me)) (ADVP (RB now))))
(VP (VB get) (NP (PRP me)) (ADVP (RB now)))
(VB get)
(NP (PRP me))
(PRP me)
(ADVP (RB now))
(RB now)

And what you're looking for is https://github.com/nltk/nltk/blob/develop/nltk/tree.py#L341:
>>> ptree.productions()
[S -> VP, VP -> VB NP ADVP, VB -> 'get', NP -> PRP, PRP -> 'me', ADVP -> RB, RB -> 'now']

Note that Tree.productions() returns a Production object, see https://github.com/nltk/nltk/blob/develop/nltk/tree.py#L22 and https://github.com/nltk/nltk/blob/develop/nltk/grammar.py#L236.
If you want a string form of the grammar rules, you can either do:
>>> for rule in ptree.productions():
...     print rule
...
S -> VP
VP -> VB NP ADVP
VB -> 'get'
NP -> PRP
PRP -> 'me'
ADVP -> RB
RB -> 'now'

Or
>>> rules = [str(p) for p in ptree.productions()]
>>> rules
['S -> VP', 'VP -> VB NP ADVP', "VB -> 'get'", 'NP -> PRP', "PRP -> 'me'", 'ADVP -> RB', "RB -> 'now'"]


text:
Q: How to perform an action if nothing is emitted from the observable after X seconds? I am subscribed to an observable, but I only want to listen to it for say 3 seconds. If nothing is emitted after 3 seconds, I want to perform a particular action. I have looked at lot of places, but can't seem to find an answer.
An example of it is listening for a web response for 3 seconds. If nothing is received after 3 seconds, I want to print out "Timed out" etc.
How can one achieve this in RxJava?

A: Have you tried the timeout operator?
public static void main(String[] args) throws InterruptedException {
    requestToApi()
            .timeout(3, TimeUnit.SECONDS)
            .subscribe(
                    System.out::println,
                    error -> System.out.println("Timed out")
            );

    Thread.sleep(5000);
}

private static Observable<String> requestToApi() {
    // simulate a request to an API that will take 5 seconds to return a response
    return Observable.just("response").delay(5, TimeUnit.SECONDS);
}


text:
Q: Function Type in Haskell I am new to Haskell. I want to have a function in which I get an Int value from the user using
putStr "Please Enter Your Number : "
submit_ans<- getLine

then after a series of calculations returns another Int which will be used by another function that has called it. What is the type of the described function? should I use return function at the end?
thanks in advance!
Update #1
ok I updated the function as below:
myFunction ::  Int -> IO Int
myFunction action = do

      putStr "\tPlease Enter Your Number : "
      submit_ans <- getLine

      if action == 1
        then do
       myFunctionII read submit_ans
        else do
       putStrLn("\n")

it gives me this error:
*** Term           : myFunction
*** Type           : Int -> IO Int
*** Does not match : IO a

A: Just write your function, say g, as a pure calculation, of type Int -> Int. Then you use it in IO monad as
...
putStr "Please Enter Your Number : "
submit_ans <- getLine
let i = g (read submit_ans)
...
print i

edit: Any Haskell value is pure. Functions are pure. IO x is a pure Haskell value. But it describes an impure computation, which will be run by the system (say, when your compiled application is run). As part of its execution, it will execute your pure function.

A: putStrLn has type String -> IO () and it seems myFunctionII has type Int -> IO (), so the type of myFunction should be Int -> IO () since both branches of your if return an IO ():
myFunction :: Int -> IO ()
myFunction action = do
  putStr "\tPlease Enter Your Number : "
  submit_ans <- getLine

  if action == 1
     then myFunctionII (read submit_ans)
     else putStrLn "\n"

A: Since you are performing an IO operation and you are returning an Int so my best guess would be IO Int but I can't tell for sure because you question is too vague to answer clearly.


text:
Q: Calculating average memory access time in a system implementing cache memory In order to find avg memory access time we have the formula :

Tavg = h*Tc +(1-h)*M

where  h     = hit rate
       (1-h) = miss rate
       Tc    = time to access information from cache
       M     = miss penalty  (time to access main memory)

I have been solving quite a few problems on this concept recently. At times I find that there is this disturbing inconsistency :
Case 1: M = Tm + Tc
Case 2: M = Tm

Meaning, the solutions indicate that value of 'M' is calculated for some question X as in 'Case 1' above, while in some other question Y, the same is calculated as in 'Case 2' above. I tried my best analyzing these questions to find what is that factor which makes the calculation different. No help. I've encountered situations where X & Y are exactly the same, just that the values are only different, yet calculation is done for X as in Case 1 and for Y as in Case 2.
Any other reason that I am not aware of which makes the calculation different? Thank you in advance.

A: The difference comes from when the latency of a miss is counted. If the problem states that the time is a miss penalty, it should mean that the time is in addition to the time for a cache hit; so the total miss latency is the latency of a cache hit plus the penalty. (Clearly your formula and variables do not take this approach, labeling M--which is really total access time on a miss--as the miss penalty.)
Sadly, if a problem says "memory access latency" or "L2 access latency", it is even less clear whether total access latency is meant (i.e., including the time for an L1 hit) or the extra time required by an L1 miss. The former has some conceptual advantages (e.g., it can hide details like L2 access beginning before data return would occur on a hit--say by using early miss detection or miss prediction or even parallel tag look-up for L1 and L2). The latter may make explaining latency effects of L2 size or associativity simpler (e.g., if doubling size increases L2-only access latency by 50%, it may be easier to understand L2-only latency increasing from 8 cycle to 12 cycles by doubling size and to 18 cycles by quadrupling size than to see total latency increase from 10 cycles [with Tc = 2] to 14 cycles and to 20 cycles.)
(Also, using a miss penalty number allows a slight simplification of the access time formula-- Tavg = Tc + (1-h)Tm --because Tc is always spent.)
A similar issue occurs for execution latency. With a scalar pipeline an instruction that takes one cycle to execute is often said to have zero latency because there is no delay in executing a subsequent dependent instruction. However, this use of latency can be confusing when considering a superscalar implementation.

A: Average memory access time = % instruction * (hit time + Instruction miss rate * miss penalty) + % data * (hit time + Data miss rate * miss penalty)

A: A related question was raised in comments:

Comment :     Why there is no hit rate in the formula? – enitihas May 13 at 18:09

The reason there is no hit rate in the formula is every access whether it hits or misses the first level cache has to access the first level and thus has the hit time i.e. Access latency of the first level cache.
So irrespective of whether the access is hit/miss, hit time (Access latency of the first level cache) needs to be included in the formula to calculate the Average access time.


text:
Q: Android not getting right photo from gallery I am implementing a pick photo from gallery and then show it in a ImageView. I had the some issues  and, thanks to this solution: Null Intent passed back on Samsung, is partially solved. I can take the photo and it's saved in a custom location:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Helpers.isExternalStorageWritable()) {
    Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File imagesFolder = new File(Environment.getExternalStorageDirectory(), Globals.Constants.APP_NAME);
    imagesFolder.mkdirs();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date());
    File image = new File(imagesFolder, "report" + timeStamp + ".jpg");
    Uri uriSavedImage = Uri.fromFile(image);
    imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
    getActivity().startActivityForResult(imageIntent, CAMERA_REQUEST);

However when in onActivityResult, when I show the taken picture in a ImageView, I got a random photo from my old photos. Here's my onActivityResult code:
try {
Log.i("TAG", "inside Samsung Phones");
String[] projection = {
        MediaStore.Images.Thumbnails._ID, // The columns we want
        MediaStore.Images.Thumbnails.IMAGE_ID,
        MediaStore.Images.Thumbnails.KIND,
        MediaStore.Images.Thumbnails.DATA };
String selection = MediaStore.Images.Thumbnails.KIND + "=" + MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
Cursor myCursor = getActivity().getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, selection, null, sort);
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";

try {
    myCursor.moveToFirst();
    imageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
    thumbnailImageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
    thumbnailPath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
} finally {
    // myCursor.close();
}
String[] largeFileProjection = {
        MediaStore.Images.ImageColumns._ID,
        MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
myCursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";

try {
    myCursor.moveToFirst();
    largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
    mImageCaptureUri_samsung = Uri.fromFile(new File(largeImagePath));
    mImageCaptureUri = null;
} finally {
    // myCursor.close();
}

Uri uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageId));
Uri uriThumbnailImage = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, String.valueOf(thumbnailImageId));

 image1.setImageURI(uriThumbnailImage);
}

Another issue is that the .thumbnail neither the actual photo are shown right away, it takes a couple minutes to be shown in the gallery or file manager. But now I would be happy if anyone can help me with the random picture shown. Thank you in advanced!


text:
Q: Python: changing string values in lists into ascii values I'm trying to convert characters in a string into individual ascii values. I can't seem to get each individual character to change into its relative ascii value.
For example, if variable words has the value ["hello", "world"], after running the completed code the list ascii would have the value :
[104, 101, 108, 108, 111, 119, 111, 114, 108, 100]
So far I've got:
words = ["hello", "world"]
ascii = []
for x in words:
    ascii.append(ord(x))

printing this returns an error as ord expect a character but gets a string. Does anyone know how i can fix this to return the ascii value of each letter? thankyou

A: Treat words as one long string instead (using a nested list-comp for instance):
ascii = [ord(ch) for word in words for ch in word]
# [104, 101, 108, 108, 111, 119, 111, 114, 108, 100]

Equivalent to:
ascii = []
for word in words:
    for ch in word:
        ascii.append(ord(ch))

If you wanted to do them as separate words, then you change your list-comp:
ascii = [[ord(ch) for ch in word] for word in words]
# [[104, 101, 108, 108, 111], [119, 111, 114, 108, 100]]

A: Your loop iterates over the words list which is a list of string. Now, ord is a function that will return the integer ordinal of a one-character string. So you need the iterate over the characters of the string also.
words = ["hello", "world"]
ascii = []
for word in words:
    ascii.extend(ord(ch) for ch in word)

print ascii will give you,
[104, 101, 108, 108, 111, 119, 111, 114, 108, 100]


text:
Q: awk NR==FNR for command syntax I am having trouble using awk NR==FNR to return lines of interest from an input .fastq file.
I have the following example input file called example.fastq
@SRR1111111.1 1/1
CTGGANAAGTGAAATAATATAAATTTTTCCACTATTGAATAAAAGCAACTTAAATTTTCTAAGTCG
+
AAAAA#EEEEEEEEEEEEEEEEEEEEEEEAEEEEEEEEEEEEEEEEEEEEEEEEEA<AAEEEEE<6
@SRR1111111.2 2/1
CTATANTATTCTATATTTATTCTAGATAAAAGCATTCTATATTTAGCATATGTCTAGCAAAAAAAA
+
AAAAA#EE6EEEEEEEEEEEEAAEEAEEEEEEEEEEEE/EAE/EAE/EA/EAEAAAE//EEAEAA6
@SRR1111111.3 3/1
CTATANTATTGAAATAATAATGTAGATAAAACTATTGAATAACAGCAACTTAAATTTTCAATAAGA
+
AAAAA#EE6EEEEEEEEEEEEAAEEAEEEEEEEEEEEE/EAE/EAE/EA/EAEAAAE//EEAEAA6

I am trying to extract groups of four lines that contain a string of interest, importantly approximate matches must be allowed hence the use of agrep instead of grep. The below example works.
agrep -1 -n "GAAATAATA" example.fastq | awk -F: 'NR==FNR{for(i=($1-1);i<=($1+2);i++)a[i];next}FNR in a' - example.fastq

The above command produces the following correct output.
@SRR1111111.1 1/1
CTGGANAAGTGAAATAATATAAATTTTTCCACTATTGAATAAAAGCAACTTAAATTTTCTAAGTCG
+
AAAAA#EEEEEEEEEEEEEEEEEEEEEEEAEEEEEEEEEEEEEEEEEEEEEEEEEA<AAEEEEE<6
@SRR1111111.3 3/1
CTATANTATTGAAATAATAATGTAGATAAAACTATTGAATAACAGCAACTTAAATTTTCAATAAGA
+
AAAAA#EE6EEEEEEEEEEEEAAEEAEEEEEEEEEEEE/EAE/EAE/EA/EAEAAAE//EEAEAA6

However if I use a sequence not contained in the second line this command still prints the top two lines as in the following example.
agrep -1 -n "TAGATAAAACT" example.fastq | awk -F: 'NR==FNR{for(i=($1-1);i<=($1+2);i++)a[i];next}FNR in a' - example.fastq

@SRR1111111.1 1/1
CTGGANAAGTGAAATAATATAAATTTTTCCACTATTGAATAAAAGCAACTTAAATTTTCTAAGTCG
@SRR1111111.3 3/1
CTATANTATTGAAATAATAATGTAGATAAAACTATTGAATAACAGCAACTTAAATTTTCAATAAGA
+
AAAAA#EE6EEEEEEEEEEEEAAEEAEEEEEEEEEEEE/EAE/EAE/EA/EAEAAAE//EEAEAA6

Thanks for helping me understand the behavior of this awk command.

A: There are no colons (:) in your input, so $1 refers to the whole line and ($1-1) & ($2+2) are going to be -1 and 2 respectively, meaning your for loop will always run exactly four times (for values of i equal to -1, 0, 1, then 2).
Inside the for loop, you're assuring that a[i] exists (that's a[-1], a[0], a[1], and a[2]).
The final part of your code prints the line being examined at that time (but not from the first file thanks to the next in the prior stanza) whenever the array a contains an entry for that file's line number. Therefore, it prints lines 1 and 2 from each input (since a[FNR] exists for FNR equal to 1 or 2).
Since you need an approximate answer and therefore must use agrep, the idea proposed by James Brown's answer to your other question makes sense but its implementation (as dissected above) does not.
The following solution uses agrep's hits as cues for surrounding lines to print alongside the hits (agrep does not support context lines like grep's -A NUM and -B num or else we'd be able to do agrep -A1 -B2 -1 -n PATTERN example.fastq for a simpler answer).
agrep -1 "GAAATAATA" example.fastq | awk '
  NR == FNR { agrep_hit[$0] = 1; next }
  agrep_hit[$0] { print last_line; i = 1 }
  0 < i && i < 4 { i++; print }
  { last_line = $0 }
' - example.fastq

This examines the input file twice. The first time uses agrep to find the approximate pattern matches while the second uses awk to get the requested lines of context.
When the overall line number in awk (NR) equals the local file's line number (FNR), it means we're examining the first input (-, standard input, which is the output of agrep). We store the approximate pattern hits in an associative array for later and then move on to the next line with next (therefore the rest of the awk commands only operate on later inputs).
Since you need the previous line, we have to print it explicitly. The final stanza of awk code saves the current line as last_line so we can retrieve it later. Upon a line that was outputted by agrep (and thus stored in our array), we print that saved last_line and set an iterator i to 1.
When i is 1, 2, or 3, we increment it and print the current line. This prints the matching line and then two more for context.

A: You may use this agrep + awk solution:
srch() {
   awk -F ': ' 'NR==FNR {
      a[$1] = 1
      next
   }
   a[FNR] {
      print p
      print
      for (i=0; i<2 && getline > 0; i++)
         print
   }
   {
      p=$0
   }' <(agrep -1 -n "$2" "$1") "$1"
}

Then run it as:
srch file 'GAAATAATA'

@SRR1111111.1 1/1
CTGGANAAGTGAAATAATATAAATTTTTCCACTATTGAATAAAAGCAACTTAAATTTTCTAAGTCG
+
AAAAA#EEEEEEEEEEEEEEEEEEEEEEEAEEEEEEEEEEEEEEEEEEEEEEEEEA<AAEEEEE<6
@SRR1111111.3 3/1
CTATANTATTGAAATAATAATGTAGATAAAACTATTGAATAACAGCAACTTAAATTTTCAATAAGA
+
AAAAA#EE6EEEEEEEEEEEEAAEEAEEEEEEEEEEEE/EAE/EAE/EA/EAEAAAE//EEAEAA6

and this:
srch file 'TAGATAAAACT

@SRR1111111.3 3/1
CTATANTATTGAAATAATAATGTAGATAAAACTATTGAATAACAGCAACTTAAATTTTCAATAAGA
+
AAAAA#EE6EEEEEEEEEEEEAAEEAEEEEEEEEEEEE/EAE/EAE/EA/EAEAAAE//EEAEAA6'

A: with record separator definition (GNU awk)
$ awk -v RS='(^|\n)@' '/GAAATAATA/{printf "%s", rt $0} {rt=RT}' file

@SRR1111111.1 1/1
CTGGANAAGTGAAATAATATAAATTTTTCCACTATTGAATAAAAGCAACTTAAATTTTCTAAGTCG
+
AAAAA#EEEEEEEEEEEEEEEEEEEEEEEAEEEEEEEEEEEEEEEEEEEEEEEEEA<AAEEEEE<6
@SRR1111111.3 3/1
CTATANTATTGAAATAATAATGTAGATAAAACTATTGAATAACAGCAACTTAAATTTTCAATAAGA
+
AAAAA#EE6EEEEEEEEEEEEAAEEAEEEEEEEEEEEE/EAE/EAE/EA/EAEAAAE//EEAEAA6


text:
Q: Parse JSON file using AFNetworking I have a link which contains the a json file. I mean if I launch that link in chrome a file is downloaded on my computer which is of .json extension.
say the link is www.foffa.com/sampleList.json
I am new to AFNetworking and not sure how to parse this json, with or without having to write this file down to the disk.
My code looks like below and I am pretty sure that I have to use streams and all for this but I am not sure how. As of now I get an error "Request failed: unacceptable content-type: text/plain"
I guess it expects the content type to be  "Content-Type" = "application/octet-stream";
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFHTTPResponseSerializer serializer];
    operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/octet-stream"];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSLog(@"Data retrived");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];

A: Change the second line in this:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];

to this:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];

Note you are using the AFJSONResponseSerializer response serialised.
Update
Updating my answer from info in the below comments, it appears you actually want to download a JSON file from a  server and then parse it as opposed to parsing JSON directly from the HTTP response:
In order to do that change the content type to text/plain and with the downloaded file/data parse either as a String or a JSON object like this:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:nil];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes =
    [NSSet setWithObjects:@"application/octet-stream", @"text/plain", nil];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
  NSError *error;
  id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];
  if (error) {
      NSLog(@"Error: %@", error);
  } else {
      NSLog(@"JSON: %@", json);
  }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                      message:[error localizedDescription]
                                                     delegate:nil
                                            cancelButtonTitle:@"Ok"
                                            otherButtonTitles:nil];
  [alertView show];
}];

A: AFNetwroking won't parse income data for you.
Use NSJSONSerialization's class method +JSONObjectWithData:options:error:. If your data is valid, result will be NSDictionary with same structure as original JSON file
You should place it inside success block


text:
Q: How do I squash two non-consecutive commits in git, using one line? I know I can do this using rebase -i, but I'm really looking for a way to do it in one line, e.g., with a script.
I took a look at How do I run git rebase --interactive in non-interactive manner? for example, but my bashfu is too weak to use it properly.
To be clear, this is what I have right now:

A1B2C3 Some commit
AAAAAA Some other commit
A3B2C1 More commit
BBBBBB Another commit

I want to squash AAAAAA and BBBBBB in one (or several) git lines, non-interactively.
Thanks

A: You could emulate rebase interactive with a series of cherry-picks and amended commits:
git checkout AAAAAA
git cherry-pick BBBBBB -n && git commit --amend -m "AAAAA squashed with BBBBB"
git cherry-pick A3B2C1

A: I ended up using a bash script with the help of the linked question.
I'm attaching it for completeness's sake.
Note: My bash is ugly.
One thing of importance though: Since the script cannot accept arguments, I've opted for a self-modifying code.
If there's a better solution (without using globals/environment variables), I'd love to know.
Also, I'm not entirely sure how to swap two lines in bash (and google wasn't a great help), so I ended up using a for loop.
#!/bin/bash
commit1=???
commit2=???
if [ "$#" -eq 2 ]; then #2 arguments, first phase of script
    #modify lines 2 and 3 with arguments
    currentFile=${BASH_SOURCE[0]}
    cat $currentFile | sed "2s/.*/commit1=$1/" | sed "3s/.*/commit2=$2/" >| $currentFile
    echo "$currentFile"
    exit
fi

# second phase of script
line1=$(grep -nr "pick $commit1" $1 | cut -f1 -d:)
if [ -z $line1 ]; then
    echo "Could not find a match for $commit1"
    exit
fi
line2=$(grep -nr "pick $commit2" $1 | cut -f1 -d:)
if [ -z $line2 ]; then
    echo "Could not find a match for $commit2"
    exit
fi
oldLine=$(($line1<$line2?$line1:$line2))
newLine=$(($line1>$line2?$line1:$line2))
cat $1
#move newLine to be below oldLine, by iterating over all lines in reverse and swapping one by one
for currentLineIndex in `seq $newLine -1 $(expr $oldLine + 2)`; do
    currentLine=$(sed -n "${currentLineIndex}p" "$1")
    nextLineIndex=$(expr $currentLineIndex - 1)
    nextLine=$(sed -n "${nextLineIndex}p" "$1")
    cat $1 | sed $currentLineIndex"s/.*/$nextLine/" | sed $nextLineIndex"s/.*/$currentLine/" >| $1
done

#change the pick to squash
cat $1 | sed $(expr $oldLine + 1)"s/pick/squash/" >| $1

example use: $ GIT_SEQUENCE_EDITOR=$(./rebase.sh d199 a548) git rebase -i 95e2a7c

A: A much simpler alternative, if you want to just fix an existing commit from the staging area: (Thanks to @Andrew C for pointing me towards --fixup)
function git_fix {
    git commit --fixup=$1
    GIT_SEQUENCE_EDITOR=: git rebase -i --autosquash "$1^" #empty script
}

As a git alias:
fix="!f() {\
    git commit --fixup=$1;\
    GIT_SEQUENCE_EDITOR=: git rebase -i --autosquash "$1^";\
}; f"