text:
Q: Telerik Loading Panel I have a problem with Telerik Loading Panel My Problem goes on like this: I have a user control which there is a placeholder and a Rad Menu item which I am loading on a aspx page, here on the menu item click I have to load another user control in the placeholder,but here my loading panel is not loading on the menu click can please someone help me on this.
Thanks in Advance


text:
Q: How do I connect with other xml file xml file I have two XML files using the XML data processing files How do I connect them to each other?
Example:
members.xml
<?xml version="1.0" encoding="UTF-8"?>
<Data>
<member id="1" username="selahattin" name="Selahattin" surname="Yüksel"/>
<member id="2" username="test" name="John" surname="Bravo"/>
</Data>

comments.xml
 <?xml version="1.0" encoding="UTF-8"?>
<Data>
<member id="1" username="selahattin" comment="Hi, stackoverflow"/>
<member id="2" username="test" comment="Hello world!"/>
</Data>

Using two XML files in the username field of the data How do you want to take this?
username==username

A: here is one method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME1 = @"c:\temp\test.xml";
        const string FILENAME2 = @"c:\temp\test2.xml";
        static void Main(string[] args)
        {
            DataSet ds1 = new DataSet();
            ds1.ReadXml(FILENAME1);
            DataSet ds2 = new DataSet();
            ds2.ReadXml(FILENAME2);

            var results = from dataRows1 in ds1.Tables["member"].AsEnumerable()
                                     join dataRows2 in ds2.Tables["member"].AsEnumerable()
                                     on dataRows1.Field<string>("id") equals dataRows2.Field<string>("id") into ps
                                     select dataRows1;
            DataTable combinedTable = results.CopyToDataTable();

        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why assign `this` to `self` and run `self.method()`? I'm reading the source from mongoose
Collection.prototype.onOpen = function () {
  var self = this;
  this.buffer = false;
  self.doQueue();
};

I don't understand why the author assigns this to self and runs self.doQueue(). Why not just run:
this.buffer = false;
this.doQueue();

I'm new to javascript, thanks for help.

A: Just to give more clarity to @richard said earlier,
Collection.prototype.onOpen = function () {
  var self = this;
  this.buffer = false;
  this.onclick = function(){
     //do some other operations here
     //if you refer `this` here then, `this` will refer to present function not the above. so to make sure it is referring to exact object people pass this to `me` or `self`
     self.doQueue();
  }
 };

A: The only reason you would usually do that is if the call to doQueue() is inside a block that will change the value of this such as another function.
In this case however it doesn't serve any purpose and was probably a remnant of older code that was not changed back.

A: Most likely the developer wanted consistency, but failed at doing so.
Otherwise you'd be using this in some functions, self in other functions and a mix of both in other functions, depending on where you use the object and if you use nested functions/callbacks.
By always assigning this to self and then using the latter you have one additional assignment at the very beginning of each function but you always use self to access the object.
However, what the developer did in the code you posted does not make much sense. He should either use self or this both times instead of a mix that is not even necessary.

A: You're right, in this instance they could have simply used this.
The use of me or self is a bit of a hack to ensure the correct context of this is used, as within JavaScript the scope of this is variant. If for example you have an event trigger a function within your class, this would be different, and wouldn't be your object that houses the function, but instead the object that called the function. To resolve this people often use me or self to ensure they're referring to the correct object... this, as in the actual object.

A: self is a copy of 'this',but it always refer to the right object,and 'this' may not.


text:
Q: T SQL Cursor is only updating row with same value I'm using MS SQL Server and I have the below table 'tmp_AVG_Weekly_Sales':
RowID   SKU   Shop  Week   Avg_Value   LAMBDA    PMF      Value
  1     ABC   200    2       1          2        0.13     NULL
  2     DEF   250    2       2          4        0.018    NULL
  3     XYZ   300    3       3          6        0.0024   NULL

I need to work out the Value field based on the below logic - I am using a Cursor and Loop:
DECLARE @CUMULATIVE AS FLOAT = 0;
DECLARE @COUNT AS INT = 0;
DECLARE @LAMBDA AS FLOAT;
DECLARE @RowID AS INT;
DECLARE @PoissonCursor AS CURSOR;
DECLARE @THRESHOLD AS FLOAT = 0.99;
DECLARE @PMF AS FLOAT --= EXP(-@LAMBDA)

SET @PoissonCursor = CURSOR FOR

SELECT RowID
FROM
[tmp_AVG_Weekly_Sales]

OPEN @PoissonCursor;

FETCH NEXT FROM @PoissonCursor INTO @RowID;

WHILE @@FETCH_STATUS = 0

BEGIN

    SELECT @LAMBDA = LAMBDA FROM [tmp_AVG_Weekly_Sales] WHERE RowID = @RowID

    SELECT @PMF = PMF FROM [tmp_AVG_Weekly_Sales] WHERE RowID = @RowID

    WHILE (@CUMULATIVE < @Threshold)

    BEGIN
        SET @CUMULATIVE += @PMF
        SET @COUNT += 1
        SET @PMF = @PMF * (@LAMBDA / @COUNT)

        END

        UPDATE [tmp_AVG_Weekly_Sales] SET [Value] = @COUNT - 1 WHERE RowID = @RowID

    FETCH NEXT FROM @PoissonCursor  INTO @RowID;

END

However, the above is just populating the Value field with the same value:
RowID   SKU   Shop  Week   Avg_Value   LAMBDA    PMF      Value
  1     ABC   200    2       1          2        0.13     6
  2     DEF   250    2       2          4        0.018    6
  3     XYZ   300    3       3          6        0.0024   6

When I am expecting the below:
RowID   SKU   Shop  Week   Avg_Value   LAMBDA    PMF      Value
  1     ABC   200    2       1          2        0.13     6
  2     DEF   250    2       2          4        0.018    9
  3     XYZ   300    3       3          6        0.0024   12

Where am I going wrong?

A: You never reset @CUMULATIVE or increase @Threshold, so the block of SET calls are only executed the first go through and each subsequent UPDATE just uses those original values.


text:
Q: Can you have a popup window without going to a new page in php? I am trying to get a popup window to come up after the user uploads a picture. I got the window to popup the only thing is it first takes them to a new page. I would like the window to popup without taking the user to a new page first.
Here is my code
<?php

$target_dir = "../images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if ($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 30000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if ( $imageFileType != "jpg" && $imageFileType != "png"
    && $imageFileType != "jpeg" && $imageFileType != "gif")
{
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
        copy($target_file, 'images/' . $target_file);
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

A: Yes, You can !

PHP is server-side, but you STILL can use CLIENT SIDE code.
Here is how we would make a popup using php :

        Hello World

This is my very very cool popup !

        <button onclick="closePopup();"></button>

Here is the html code with some Javascript , First of all i'd recommend trying the code and working with the css so it looks good.

Adding it to php

<?php
echo '

            Hello World

This is my very very cool popup !

            <button onclick="closePopup();"></button>

';

So You can always echo out some Html code.
Other way?

Yep ! We even have another way. We are going to use Javascript

            Hello World

This is my very very cool popup !

            <button onclick="closePopup();"></button>

<?php

if(1 === 1)
{
    echo "openPopup();";
}

 ##


text:
Q: Плавное изменение бэкграунда блока На странице есть слайдер, в котором крутится несколько картинок.
В слайдере определяется текущая картинка, из нее берется data-параметр и подставляется в качестве бэкграунда для блока.
slideItems.removeClass('current');
slideItems.eq(currentSlide).addClass('current');
var current_image_src = $('.carousel .slideItem.current img').data('bg-image-src');
$('.conteiner').css('background-image', 'url(http:' + current_image_src + ')');

Но при таком варианте картинка меняется резко.
Как можно сделать так, чтобы картинка менялась плавно с использованием animate()?
A: Можно попробовать вот так:

*

*http://jsfiddle.net/8su9hpcs/

*http://jsfiddle.net/8su9hpcs/4/

A: Background-image поддаётся анимации при помощи css3 transitions:
.conteiner {transition: background-image 0.3s;}

При помощи animate вы сможете выполнить похожую анимацию, только если меняться будет не background, а изображения img.
Могу посоветовать в качестве анимационного движка TweenMax. Он, по-моему, умеет анимировать в том числе и background-image.


text:
Q: Making a normal method asynchronous in c# I have a method in c#:
public DataSet OpenSqlQuery(string SqlQuery)
{
    con = new SqlConnection(connection_string);
    con.Open();
    var sqlc = new SqlCommand(SqlQuery, con);
    da = new SqlDataAdapter(sqlc);
    var ds = new DataSet();
    da.Fill(ds);
    con.Close();
    return ds;
}

Now I want to make it as an asynchronous method so I can call it by await. so I changed it to:
public async Task<DataSet> OpenSqlQuery(string SqlQuery)
{
    con = new SqlConnection(connection_string);
    con.Open();
    var sqlc = new SqlCommand(SqlQuery, con);
    da = new SqlDataAdapter(sqlc);
    var ds = new DataSet();
    await da.Fill(ds);
    con.Close();
    return ds;
}

I set await before da.Fill(ds) because at this line, the program waits for server. But the function shows this error:

'int' does not contain a definition for 'GetAwaiter' and no extension
  method 'GetAwaiter' accepting a first argument of type 'int' could be
  found (are you missing a using directive or an assembly reference?)

How can I make this method asynchronous?
P.S: The main goal is to call this method as follows:
Dataset ds = await objConnect.OpenSqlQuery(query);

P.S: Difference between this question and possible dupplicated one is that this post about making an existing synchronous method to asynchronous, while another is about making an asynchronous method.


text:
Q: Popover tableview with dynamic array data I am trying to reuse the popover tableview code such that when the user touches the Canada button, the provinces of Canada (Alberta, British Columbia, ...) are displayed; when the user touches the USA button the states of USA (Alabama, Alaska, ...) are displayed. The problem is when I hit the USA button after the Canada button, the first 12 states of the USA are not displayed by the 13 provinces/territories of Canada are still displayed.
I am following the code here
http://www.raywenderlich.com/1056/ipad-for-iphone-developers-101-uipopovercontroller-tutorial
but modifying the setColorButtonTapped code to take an array so I can reuse the code for different arrays
- (IBAction)setColorButtonTapped:(id)sender withData:(NSArray *) data {
    if (_colorPicker == nil) {
        self.colorPicker = [[[ColorPickerController alloc]
                             initWithStyle:UITableViewStylePlain] autorelease];
        _colorPicker.delegate = self;
        self.colorPickerPopover = [[[UIPopoverController alloc]
                                    initWithContentViewController:_colorPicker] autorelease];
    }
    [self.colorPickerPopover presentPopoverFromBarButtonItem:sender
                                    permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
_colorPicker.tableList = [data copy];
// I defined a property NSMutableArray *tableList
// I think the problem is with the way I copy the data  }

Sorry about the fomatting of the code.
Thanks for your help in advance.
Joe

A: Joe, I'm guessing many will tell you to be a bit more specific. Nonetheless, one thing that caught my eye is that you don't seem to empty your .tableList anywhere on this code snippet.
Basically, try checking whether it has data or not before you copy new one into it. If it does, remove the old data and copy the new one.


text:
Q: jEdit Mac OS keyboard behaviour Is there anyway to have jEdits keyboard controls behave the same way that a native Mac OS app does?
By behave I mean command+left moves the caret to the start of the line, alt+left moves to the beginning of the current word etc.

A: Unfortunately Brian's findings do not play well with QWERTZ keyboards: it disables the possibility to enter chars like pipe, curly brackets, or whatever uses the ALT-key as modifier.
According to the comments in startup.bsh:
/*{{{ Remapping modifier keys part II */

/* Note if you chose to make use of the M+ (option key) prefix on MacOS, you
 * will need to disable a little piece of code: */
//Debug.ALT_KEY_PRESSED_DISABLED = false;
/* Otherwise M+ will be ignored for the purposes of keyboard shortcuts. */

/* But if you enable this, you might find that Option+8 for example invokes your
 * macro but also inserts a bulletpoint, as per standard Macintosh keyboard
 * behavior. To disable the Option key for inserting special high ASCII
 * characters, uncomment this. Note that it has wider implications, notably
 * DROVAK keyboard shortcuts will be mapped as if the keyboard was QWERTY. */
//Debug.ALTERNATIVE_DISPATCHER = false;

/*}}}*/

only uncommenting Debug.ALT_KEY_PRESSED_DISABLED should do the trick, but here[1] it doesn't - I can either use ALT as modifier for shortcuts, or as a modifier for entering chars.. a prior section also deals with the mapping of modifiers:
/*{{{ Remapping modifier keys part I */

/* The below is the default, swap the items around to
 * change meaning of C+, A+, M+, S+.
 */
//KeyEventTranslator.setModifierMapping(InputEvent.CTRL_MASK,
//  InputEvent.ALT_MASK, InputEvent.META_MASK,
//  InputEvent.SHIFT_MASK);

/* ... and this the MacOS default: */
//KeyEventTranslator.setModifierMapping(InputEvent.META_MASK,  /* == C+ */
//  InputEvent.CTRL_MASK,  /* == A+ */
//  InputEvent.ALT_MASK,   /* == M+ */
//  InputEvent.SHIFT_MASK  /* == S+ */);

/*}}}*/

but whatever combination of settings I tried, I wasn't able to achieve a setup with both options (ALT as modifier for shortcuts and textinput) working.
So: any hint/fix would be highly appreciated. ;-)
[1] here means: jEdit 4.3.2 @ OSX 10.5.8 (Java 1.5.0_30) with QWERTZ (German) keyboard

A: First the ALT key needs to be enabled. Do this in the startup.bsh file located in:
JEDIT_HOME/Contents/Resources/Java/startup/startup.bsh

On Mac OX this would typically be:
/Applications/jEdit.app/Contents/Resources/Java/startup/startup.bsh

The following lines should be uncommented:
Debug.ALT_KEY_PRESSED_DISABLED = false;
Debug.ALTERNATIVE_DISPATCHER = false;

You can now include the ALT key in keymappings, where

C => CMD
M => ALT

Go to End of Line: C+Right
Go to Start of Line: C+Left
Go to Next Word: M+Right
Go to Previous Word: M+Left
Select Next Word: MS+Right
Select Previous Word: MS+Left
Select to End of Line: CS+Right
Select to Start of Line: CS+Left

A: A solution that works for me:
Create some macros that insert the special alt-characters you need into the textArea (one macro per character).
Then you can change the setup to enable the alt-key for jedit (I enabled only the first of the two properties).
After that you can assign alt-shortcuts for the macros you recorded in a way that the special characters will be insterted by the same shortcus as before.
After that you can change the shortcut-setup for text-navigation to match the mac-standard and you will still have the special characters available through the defined macro-shortcuts.


text:
Q: How to transfer jquery data from main file to an asp file? I have working autocomplete script, but it isn't work rapidly. Thus I decided to transfer my data another asp file. But i had a problem when i did this. My question is how to transfer my data to asp file? My working sample codes below (These are not my data. I retrieve data from MSSQL and at least 10000 record in it.).
<p>
<input id="autocomplete2" type="text" placeholder="U.S. state name">
<input id="autocomplete2-value" type="text" name="code">
</p>
<script>
    var data = [
        { value: "AL", label: "Alabama" },
        { value: "AK", label: "Alaska" },
        { value: "AZ", label: "Arizona" },
        { value: "AR", label: "Arkansas" },
        { value: "CA", label: "California" },
        { value: "CO", label: "Colorado" },
        { value: "CT", label: "Connecticut" },
        { value: "DE", label: "Delaware" },
        { value: "FL", label: "Florida" },
        { value: "GA", label: "Georgia" },
        { value: "HI", label: "Hawaii" },
        { value: "ID", label: "Idaho" },
        { value: "IL", label: "Illinois" },
        { value: "IN", label: "Indiana" },
        { value: "IA", label: "Iowa" },
        { value: "KS", label: "Kansas" },
        { value: "KY", label: "Kentucky" },
        { value: "LA", label: "Louisiana" },
        { value: "ME", label: "Maine" },
        { value: "MD", label: "Maryland" },
        { value: "MA", label: "Massachusetts" },
        { value: "MI", label: "Michigan" },
        { value: "MN", label: "Minnesota" },
        { value: "MS", label: "Mississippi" },
        { value: "MO", label: "Missouri" },
        { value: "MT", label: "Montana" },
        { value: "NE", label: "Nebraska" },
        { value: "NV", label: "Nevada" },
        { value: "NH", label: "New Hampshire" },
        { value: "NJ", label: "New Jersey" },
        { value: "NM", label: "New Mexico" },
        { value: "NY", label: "New York" },
        { value: "NC", label: "North Carolina" },
        { value: "ND", label: "North Dakota" },
        { value: "OH", label: "Ohio" },
        { value: "OK", label: "Oklahoma" },
        { value: "OR", label: "Oregon" },
        { value: "PA", label: "Pennsylvania" },
        { value: "RI", label: "Rhode Island" },
        { value: "SC", label: "South Carolina" },
        { value: "SD", label: "South Dakota" },
        { value: "TN", label: "Tennessee" },
        { value: "TX", label: "Texas" },
        { value: "UT", label: "Utah" },
        { value: "VT", label: "Vermont" },
        { value: "VA", label: "Virginia" },
        { value: "WA", label: "Washington" },
        { value: "WV", label: "West Virginia" },
        { value: "WI", label: "Wisconsin" },
        { value: "WY", label: "Wyoming" }
    ];
    $(function() {
        $("#autocomplete2").autocomplete({
            source: data,
            focus: function(event, ui) {
                // prevent autocomplete from updating the textbox
                event.preventDefault();
                // manually update the textbox
                $(this).val(ui.item.label);
            },
            select: function(event, ui) {
                // prevent autocomplete from updating the textbox
                event.preventDefault();
                // manually update the textbox and hidden field
                $(this).val(ui.item.label);
                $("#autocomplete2-value").val(ui.item.value);
            }
        });
    });
</script>

Thanks for your helps...

A: I found my solution for the problem by @charlietfl helps. My jquery codes below.
$(function() {
    $( "#Uni" ).autocomplete({
        source: "rm_universite2.asp",
        minLength: 2
});
});

And rm_universite2.asp codes:
If rsUrun.RecordCount > 0 Then
i = 1
Sinirla = 10

output = "["

Do While Not rsUrun.EOF And i < (Sinirla + 1)

output = output & "{""id"":""" & rsUrun("ID") & """,""value"":""" & rsUrun("Adi") & """},"

i = i + 1

rsUrun.MoveNext
Loop

output=Left(output,Len(output)-1)
output = output & "]"
End If

Response.Write output

That's all...


text:
Q: Data retrieved from parse and use it in a viewController this how i am retrieving user info using the objectId :
func loadData() {

    userId = toPass

    data.removeAllObjects()

    var profileQuery:PFQuery = PFUser.query()!
        profileQuery.whereKey("objectId", equalTo: userId)
        profileQuery.getObjectInBackgroundWithId(userId, block: { (objects, error) -> Void in
            if error == nil {
                self.data.addObject(objects!)
                println(self.data)  //...shouldn't be empty here
            } else {
                println("Error retrieving user: \(error) ")
            }
        })
   }

 override func viewDidLoad() {
    super.viewDidLoad()

    loadData()
   fullName.text = self.data["fullName"] as! String! // ***** error here.. cannot assign a value of type 'String' to a value of type 'String?'

}

error is in viewDidLoad.. Any idea where am i wrong? Thanks for your time.

A: data is an array of parseobjects and you want to read parseobject property from it ... iterate through array or get specific index number from it and then load "fullname" property from it or use getFirstObject... method


text:
Q: Post create instance code call in django models Sorry for some crazy subj.
I'd like to override django models save method and call some additional code if the model instance is newly created.
Sure I can use signals or check if the model have empty pk field and if yes, create temporary variable and later call a code:
Class EmailModel(models.Model):
    email = models.EmailField()

    def save(self, *args, **kwargs)
        is_new = self.pk is None
        super(EmailModel, self).save(*args, **kwargs)
        # Create necessary objects
        if is_new:
            self.post_create()

    def post_create(self):
          # do job, send mails
          pass

But I like to have some beautiful code and avoid using temporary variable in save method.
So the question is: is it possible to find if the instance of model is newly created object just after super save_base parent method call?
I've checked django sources can't find how to do that in right way.
Thanks
We have related post

A: For real - signals are best approch in this case.
You could use post_save() signal and in the listener just check if the credit_set exist for current model instance and if not - create one. That would be my choice - there is no need to overdo such a simple task.
Of course if you really need to know exactly when the model was initiated (I doubt it) use post_init() signal. You don't need to override save() method just to set some additional variables. Just catch post_init() signal, or pre_save(), and just change/add what you want. IMHO there is no sense to override save() method and check if this is new instance or not - that's why the signals are there.


text:
Q: Enterprise Library Logging: Custom trace listener which sends messages to arbitrary WCF endpoint I'm trying to write a custom trace listener for Enterprise Library Logging which sends all log messages to an arbitrary WCF endpoint. The idea behind this is that I can set up a simple console app, etc at the other end which prints out all log messages in real time.
My question is in two parts:

*

*Is there a mechanism to do this already? I already looked at the MSMQ listener and I'm not interested in using that because I may have a need to use a different protocol/binding at some point.

*The way I have it implemented below - is it efficient enough or is there a better way? My concern is that every time a message comes through from the Logger (which may be frequent) I'm opening a new channel and then slamming it shut. Will this cause performance issues?

In my sample RemoteClient derives from ClientBase<T>.
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class RemoteTraceListener : CustomTraceListener
{
    public override void Write(string message)
    {
        RemoteClient client = new RemoteClient();
        client.Open();
        client.Write(message);
        client.Close();
    }

    public override void WriteLine(string message)
    {
        RemoteClient client = new RemoteClient();
        client.Open();
        client.WriteLine(message);
        client.Close();
    }

    public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
    {
        if (data is LogEntry && this.Formatter != null)
        {
            WriteLine(this.Formatter.Format(data as LogEntry));
        }
        else
        {
            WriteLine(data.ToString());
        }
    }
}

A: How often is this writing? I suggest WCF streaming as a better alternative of you're going to be logging frequently.
Failing that, it's probably a good idea to keep the client instance around as long as possible. You could try pooling it.

A: I found an open-source project called 'CLog' which does exactly what I'm looking for: http://clog.codeplex.com/.
A brief glance at the source code shows that he's using a singleton object to keep track of all the open channels that will receive log messages, and he's going with ChannelFactory<TChannel> as opposed to ClientBase<T> to instantiate each channel proxy. There are some threading implications that need to be addressed but I still think this is the way to fly.
It shouldn't be too hard to use this as a starting point for the implementation of my own custom trace listener which logs to WCF endpoints.

A: I think you should use a SQL database on witch you should log to because if you logg in a console app you could not see for examle something before 2 days.While in SQL you can make a quote and get the right data you need.
Another solution is to use the log4net project.


text:
Q: save ASP.NET page as PDF and iTextsharp I want to save my ASP.NET page as a PDF, but I don't want to use response.write because I don't want to return it to the client. I want to save the PDF on the SERVER SIDE.
 protected void btnSubmit_Click(object sender, EventArgs e)
{
   //code below saves current ASP.NET page as PDF and returns save dialog to client on where to download PDF
    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    this.Page.RenderControl(hw);

    StringReader sr = new StringReader(sw.ToString());

    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);

    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();

    Response.Write(pdfDoc);
    Response.End();

}

How do I just save the PDF?

A:
How do I just save the PDF?

If you want to save the pdf to the file system, simply supply an appropriate FileStream to the PdfWriter.GetInstance call instead of your Response.OutputStream.

By the way, your line
Response.Write(pdfDoc);

results in trash in the response, the Document pdfDoc  doesn't wrap or otherwise contain the result PDF, it merely provides an API to add content to the pdf.


text:
Q: Append only if there are no duplicates I'm making a simple notification list with AJAX and I made it append html with data from a PHP script to a div with setInterval. It should only append if it hasn't appended that specific div already, and when I insert a new row in database it should add the new row only and not spam the div with old rows.

Notifications

I'm currently using an attribute called data-noti-attr for this. Basically if a div with the attribute data-noti-attr with the value of response[index].id already exist, do not add it again. But it doesn't work like I want it to, as it keep posting duplicates of everything.
How can I accomplish this? (I tried to explain it as good as I could, ask if it's confusing)

A: Attr will return value only for the first item. Read the full docs about it here.

Description: Get the value of an attribute for the first element in the set of matched elements.

So you need to filter the found items with your condition (specific data attribute in your case).
For example, using .is() method
if ($('.item').is('[data-id="' + myId+ '"]')) {
   // do stuff
}

A: just check the length. you can use this
if($('.notification-item[data-noti-attr="'+value.id+'"]').length ==0){
....
}


text:
Q: go module @latest found but does not contain package I'm trying to make use of go module for the first time. What exactly the following error message is telling me?
module github.com/mkideal/cli@latest found (v0.2.2), but does not contain package github.com/mkideal/cli
module github.com/mkideal/cli@latest found (v0.2.2), but does not contain package github.com/mkideal/cli/ext

It happens during go build, whereas go get is just fine:
$ go get -v github.com/mkideal/cli
go: github.com/mkideal/cli upgrade => v0.2.2

but not go get -v ./..., which gave me the same error as above. My proxy setting looks OK:
$ go env | grep GOPROXY
GOPROXY="https://proxy.golang.org,direct"

Is it a problem of the go module/package I'm trying to use, or my own code's problem? -- I took a look at
https://github.com/mkideal/cli/blob/master/go.mod and it seems fine to me.
See the following update for details.
How can I overcome the situation? (I'm getting the same error message for my own repo as well)
UPDATE:
Here is the full log how I'm getting the above error:

*

*prepare /tmp/015-file from https://github.com/mkideal/cli/blob/master/_examples/015-file

*do go mod init

*then go build
Now the details:
$ cd /tmp/015-file

$ GO111MODULE=on

$ go mod init github.com/mkideal/cli/015-file
go: creating new go.mod: module github.com/mkideal/cli/015-file

$ cat go.mod
module github.com/mkideal/cli/015-file

go 1.14

$ go build
go: finding module for package github.com/mkideal/cli
go: finding module for package github.com/mkideal/cli/ext
main.go:6:2: module github.com/mkideal/cli@latest found (v0.2.2), but does not contain package github.com/mkideal/cli
main.go:7:2: module github.com/mkideal/cli@latest found (v0.2.2), but does not contain package github.com/mkideal/cli/ext

$ go get -v github.com/mkideal/cli
go: github.com/mkideal/cli upgrade => v0.2.2

$ go get -v ./...
go: finding module for package github.com/mkideal/cli
go: finding module for package github.com/mkideal/cli/ext
go: finding module for package github.com/mkideal/cli
go: finding module for package github.com/mkideal/cli/ext
main.go:6:2: module github.com/mkideal/cli@latest found (v0.2.2), but does not contain package github.com/mkideal/cli
main.go:7:2: module github.com/mkideal/cli@latest found (v0.2.2), but does not contain package github.com/mkideal/cli/ext

$ go version
go version go1.14.1 linux/amd64

A: In my case cleaning cache didn't help.
Running go install in a project root printed no Go files in ... and that was the root cause, in the same time running go install gitlab.com/.... printed info about a missing package.
What had to be done was creating a go file in a project root directory with main function.

A: *

*Update to go version go1.14.3 linux/amd64

*Clear go module cache

don't know which one solved the problem (or both), now AOK.

A: Try clearing cache:
go clean -modcache
For more info on how this command works, use go help clean

A: I had the same error, but in my case I was attempting to import a module that made available only resource files, and no go pkgs. Adding an empty go file in the module with a package declaration solved it.

A: In my case, go.mod files were under src, after moving the go.mod file into one level up, then it works
Refer the Samples below,
directory structure when "package not found" error
dir1/src/
   main.go
   go.mod
   go.sum

directory structure after fix
dir1/
   go.mod
   go.sum
   src/
     main.go

A: I had a similar problem. In my case the package name was not matching the name of the folder it resided in.


text:
Q: odoo statusbar widget visible How to only show selected items from selection to statusbar.
I inherited a view which Selection  has only 'draft' and 'sent'.
Then I added 'cancel'.
state = fields.Selection([
    ('draft', 'Draft'),
    ('sent', 'Sent'),
    ('cancel', 'Cancelled'),
    ]

I wanted to only show draft and sent. How to make the cancel invisible?
or how can i make selected item statusbar invisible?

A: Find the statusbar in the view that you want and replace it with an xpath:
<record model="ir.ui.view" id="hide_cancel">
    <field name="name">Hides cancel button</field>
    <field name="model">your.model</field>
    <field name="inherit_id" ref="the_view_that_contains_the_statusbar" />
    <field name="arch" type="xml">
        <xpath expr="//field[@name='state']" position="replace">
           <field name="state" widget="statusbar" statusbar_visible="draft,sent"/>
        </xpath>

    </field>
</record>

A: try this
<field name="state" widget="statusbar" statusbar_visible="draft,sent"/>


text:
Q: How can I access the wordpress 5.7 API without being logged in? I was working on an older version of wordpress and now we had to update to 5.7.
After that, access to /wp-json/acf/v3/ was possible when I was logged in, but no longer with my react app,
which calls this URL for some data.
Every time I call the URL with my external script, I get an error:
Request failed with status code 403.
What am I missing right now?

A: There was a function in the theme (in function.php) of Wordpress which blocked the call.


text:
Q: How to get data from database in jQuery? The values do not pass for "id" and "rate_number" from database."ratingValue" is working, but "id" alert and "num" alert are not working.
Here is my PHP code.
$jsqla = mysql_query("select id,name,rate_score,rate_number,video_image from products where genre='$genre' limit 0,5");

if($jrowa['rate_number'] > 0){
  $ratea = $jrowa['rate_score'] / $jrowa['rate_number'];
}else{
  $ratea = 0;
}

Here is HTML code.
<div class="col-sm-2 portfolio-item" style="width: 20%;">

    <input class="rating form-control input-star-rate" name="rating" value="<?php echo $ratea; ?>" data-min="0" data-max="5" data-step="0.3" data-size="xs" style="display: none; text-align: center;"/>

</div>

Here is jQuery code.
$(function(){
    $(document).ready(function(e) {
        var $stars = $('.input-star-rate');

        $stars.bind('change', function() {
            var $this = $(this);

            var ratingValue = $this.val();
            alert(ratingValue);

            var id = $this.attr("id");
            alert(id);

            var num = parseInt("$this.attr("rate_number")")+1;
            alert(num);
        });
    });
});

A: You didn't set the id attribute in the <input>.
$rateid = 0;
if($jrowa['rate_number'] > 0){
  $ratea = $jrowa['rate_score'] / $jrowa['rate_number'];
  $rateid = $jrowa['id'];
}else{
  $ratea = 0;
}

and:
<input class="rating form-control input-star-rate" id="<?php echo $rateid; ?>" name="rating" value="<?php echo $ratea; ?>" data-min="0" data-max="5" data-step="0.3" data-size="xs" style="display: none; text-align: center;"/>

Same for num (also doesn't work because  you need to escape your quotes)


text:
Q: angular onpush component rerenders only with async pipe inside template I have my component with ChangeDetectionStrategy.OnPush strategy.
Im passing data from parent via async pipe, when that data change component refuse to rerender.
When im instead of using async pipe in parent pass obvservable and use async pipe inside of child template, rerenders are called correctly.
Anyone knows why that happens (angular v9)?
I guess it have something to do with zone.js triggering change detection but why where how? I have no clue :(

A: Thats why
https://github.com/angular/angular/blob/master/packages/common/src/pipes/async_pipe.ts#L146
using async pipe rerenders view.


text:
Q: Does iOS OpenAL support directional sound or only positional sound? For the 3D iPad app I am writing I want audio to increase/decrease in volume as a single virtual listener turns towards/away-from sound sources. The listener is always stationary. The listener can only rotate. The sounds are always stationary. The sounds fill a sphere of directions around the user. The sounds are all of equal distance from the listener.
I think of the sounds as analogous to light sources in 3D graphics. For each sound there is a vector pointing from the listener to that sound source. The listener has an outgoing directional vector. I want to weight the contribution of each audio source by the dotProduct of the listener vector and each of the audio source vectors. So as the listener's "head" rotates around sound contributions change directionally.
How much of what I describe can be handled by OpenAL and how much do I need to write myself?
Thanks,
Doug

A: Yes, you can do this in OpenAL. In fact you can do better! With the dot-product you would simply get full volume when they are parallel and zero when they are perpendicular, using OpenAL you can define a cone of sound coming from your source.
On the source you need to set the AL_CONE_INNER_ANGLE to be smaller than the AL_CONE_OUTER_ANGLE so you get full volume within the inner cone angle and it attenuates to zero outside the outer cone angle. You also need to set the AL_DIRECTION of course.
It's been a while, and I'm not sure if you can set the cone/direction of the listener, but that doesn't really matter since all your objects are static anyway, you can simply rotate the direction of the sources instead, to simulate it :D


text:
Q: cannot resolve nativescript ui component tns --version: 4.1.0
tns creat demo --ng
update package.json for nativescript-webpack
{
      "description": "NativeScript Application",
      "license": "SEE LICENSE IN <your-license-filename>",
      "readme": "NativeScript Application",
      "repository": "<fill-your-repository-here>",
      "nativescript": {
        "id": "org.nativescript.test",
        "tns-android": {
          "version": "4.1.3"
        }
      },
      "dependencies": {
        "@angular/animations": "~6.0.6",
        "@angular/common": "~6.0.6",
        "@angular/compiler": "~6.0.6",
        "@angular/core": "~6.0.6",
        "@angular/forms": "~6.0.6",
        "@angular/http": "~6.0.6",
        "@angular/platform-browser": "~6.0.6",
        "@angular/platform-browser-dynamic": "~6.0.6",
        "@angular/router": "~6.0.6",
        "nativescript-angular": "~6.0.0",
        "nativescript-theme-core": "~1.0.4",
        "reflect-metadata": "~0.1.8",
        "rxjs": "~6.0.0 || >=6.1.0",
        "tns-core-modules": "~4.1.0",
        "zone.js": "^0.8.26"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~0.7.0-rc.0",
        "@angular/compiler-cli": "~6.1.0-beta.1",
        "@ngtools/webpack": "^6.0.8",
        "babel-traverse": "6.4.5",
        "babel-types": "6.4.5",
        "babylon": "6.4.5",
        "clean-webpack-plugin": "~0.1.19",
        "copy-webpack-plugin": "~4.5.2",
        "lazy": "1.0.11",
        "nativescript-dev-typescript": "~0.7.0",
        "nativescript-dev-webpack": "^0.14.2",
        "tns-platform-declarations": "^4.1.0",
        "typescript": "~2.7.2",
        "webpack-bundle-analyzer": "^2.13.1"
      }
    }

./node_modules/.bin/update-ns-webpack --configs
tns build android --bundle
a lot of errors occur, as follows:
ERROR in ../node_modules/tns-core-modules/bundle-entry-points.js
Module not found: Error: Can't resolve 'ui/button'

A: "nativescript-dev-webpack" at 0.14.1 works fine.


text:
Q: How can I make Air remember the location of last opened file? All the walkthroughs I've seen specify either desktop, local files as the initial view when calling browseForOpen.
Is there a way to have the air application remember the last location a file was loaded from and default back there?
If necessary I suppose the path could be written to the local db, but even still, I do not know how to get the filepath of the loaded file.

A: You can use File.nativePath and File.resolvePath.

A: A few years later, perhaps, but thought this might help someone in the future.
var file:File = new File();
file.browseForOpen("Open");

This will open the last location.


text:
Q: Using variable in command path for ExecStart in systemd service Im trying to make a systemd service like below :
[Unit]
Description=Syslog

[Service]
Type=simple
Environment="TESTEXTSERVICESFILES=/opt/test/extservices"
Environment="TESTCONFDATA=/storage/test/conf"

ExecStartPre=/bin/echo ${TESTEXTSERVICESFILES}/syslog/bin/nxlog $TESTCONFDATA
ExecStart=/opt/test/extservices/syslog/bin/nxlog -c ${TESTCONFDATA}/syslog/nxlog.conf
#ExecStart=/${TESTEXTSERVICESFILES}/syslog/bin/nxlog -c ${TESTCONFDATA}/syslog/nxlog.conf

[Install]
WantedBy=multi-user.target

After running 'sudo systemctl daemon-reload ; sudo systemctl start test-syslog ; sudo systemctl status test-syslog', I get the following success output:
● test-syslog.service - TestSyslog
   Loaded: loaded (/usr/lib/systemd/system/test-syslog.service; enabled; vendor preset: disabled)
   Active: deactivating (stop-sigterm) since Fri 2018-02-23 10:15:09 UTC; 11ms ago
  Process: 9474 ExecStart=/./opt/test/extservices/test-syslog/bin/nxlog -c ${TESTCONFDATA}/test-syslog/nxlog.conf (code=exited, status=0/SUCCESS)
  Process: 9471 ExecStartPre=/bin/echo /.${TESTEXTSERVICESFILES}/test-syslog/bin/nxlog $TESTCONFDATA (code=exited, status=0/SUCCESS)
 Main PID: 9474 (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/test-syslog.service
           └─9478 /./opt/test/extservices/test-syslog/bin/nxlog -c /storage/test/conf/test-syslog/nxlog.conf

Feb 23 10:15:09 lt-x260-1606.test.local systemd[1]: test-syslog.service: control process exited, code=exited status=0
Feb 23 10:15:09 lt-x260-1606.test.local systemd[1]: test-syslog.service got final SIGCHLD for state start-pre
Feb 23 10:15:09 lt-x260-1606.test.local systemd[1]: About to execute: /./opt/test/extservices/test-syslog/bin/nxlog -c ${TESTCONFDATA}/test-syslog/nxlog.conf
Feb 23 10:15:09 lt-x260-1606.test.local systemd[1]: Forked /./opt/test/extservices/test-syslog/bin/nxlog as 9474
Feb 23 10:15:09 lt-x260-1606.test.local systemd[1]: test-syslog.service changed start-pre -> running
Feb 23 10:15:09 lt-x260-1606.test.local systemd[1]: Job test-syslog.service/start finished, result=done
Feb 23 10:15:09 lt-x260-1606.test.local systemd[1]: Started Test Syslog.
Feb 23 10:15:09 lt-x260-1606.test.local systemd[1]: Child 9474 belongs to test-syslog.service
Feb 23 10:15:09 lt-x260-1606.test.local systemd[1]: test-syslog.service: main process exited, code=exited, status=0/SUCCESS
Feb 23 10:15:09 lt-x260-1606.test.local systemd[1]: test-syslog.service changed running -> stop-sigterm

Here the service has started successfully. But when I comment the first ExecStart directive and uncomment the second one I get
as failure :
● test-syslog.service - Test Syslog
   Loaded: loaded (/usr/lib/systemd/system/test-syslog.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Fri 2018-02-23 10:11:44 UTC; 11ms ago
  Process: 9243 ExecStart=/$TESTEXTSERVICESFILES/test-syslog/bin/nxlog -c $TESTCONFDATA/test-syslog/nxlog.conf (code=exited, status=203/EXEC)
  Process: 9239 ExecStartPre=/bin/echo /.${TESTEXTSERVICESFILES}/test-syslog/bin/nxlog $TESTCONFDATA (code=exited, status=0/SUCCESS)
 Main PID: 9243 (code=exited, status=203/EXEC)

Feb 23 10:11:44 lt-x260-1606.test.local echo[9239]: /./opt/test/extservices/test-syslog/bin/nxlog /storage/test/conf

This time the service cannot start, like it doesnt want to start the process starting by ${TESTEXTSERVICESFILES} variable. Does someone have any idea why it is not working even if command lines are the same in both cases ?

A: Instead of Environment=, use EnvironmentFile=, to define multiple environment variables.
[Service]
Type=simple
EnvironmentFile=/etc/sysconfig/customsyslog
ExecStart=/bin/echo ${TESTEXTSERVICESFILES}/syslog/bin/nxlog $TESTCONFDATA

/etc/sysconfig/customsyslog would contain key=value pair, e.g.,
TESTEXTSERVICESFILES=/opt/test/extservices
TESTCONFDATA=/storage/test/conf

A: You can't use variables in the actual command. systemd.service:

The command to execute must be an absolute path name. It may contain
  spaces, but control characters are not allowed.

You might wan't to wrap it in a shell command (which does parameter expansion):
ExecStart=/bin/bash -c '/${TESTEXTSERVICESFILES}/syslog/bin/nxlog -c ${TESTCONFDATA}/syslog/nxlog.conf'

A: An old message that I've just stumbled on but looks like your ExecStart line that doesn't work may have 2 '/' at the beginning. One from the ExecStart line before the variable and one from the variable which is declared as /opt/test/extservices
Just a thought.


text:
Q: JQuery targeting all Textarea is not working with .keyup I have three text box on a page and each one has a different ID Class and located in different div. I am trying to target all the <textarea> on the page and running a function that will dosomething() if a user is still typing in the textarea. The problem is that it is only working on the #first textarea and the rest are just ignored. Below is the code I am using. Thanks!
$('#first, #second, .third').keyup(function(){
 if ($('#first, #second, .third').val()){
     alert("User is typing");
 }})

A: You can just target the elements by specifying the tag name in your selector:

$('textarea').on('keyup', function(e) {
  console.log('typing')
})

  <textarea></textarea>

  <textarea></textarea>

  <textarea></textarea>

A: $.val

Get the current value of the first element in the set of matched elements.

Your check is only seeing if the first element in your selection has a value.  You probably want to do:
$('#first, #second, .third').keyup(function(){
    if ($(this).val()) {
        alert("User is typing");
    }
})

A: Try this:
$('#first, #second, .third').forEach(function(txtarea){
 $(txtarea).keyup(function(){
    if ($(this).val()){
       alert("User is typing on THIS textarea");
    }
 })
})

I don't know why, but i had some issues with the textarea too. For me, some events are not fired on the textarea.
  In this code, i made a loop for each textarea and ser the keyup listener.
  Javascript have a lot many to do things. :)


text:
Q: fixing dynamic code injection issues flagged by fortify check I am trying to run fortify code checker for security vulnerabilities and it is flagging some instances where I have used setTimeout and also some instances from standard 3rd party code libraries. Not sure how to fix them.
my JS files
var hasHash = document.location.hash;

        if (hasHash) {
            if ($.browser.msie) {
                setTimeout(function () {
                    MOM.utils.scrollTo(MOM.$window.scrollTop() - 60);
                }, 1000);
            }
            else {
               MOM.utils.scrollTo(MOM.$window.scrollTop() - 60);
            }
        }

The file all.js interprets unvalidated user input as source code on
  line 7982. Interpreting user-controlled instructions at run-time can
  allow attackers to execute malicious code.

Flags on line 1 and line 4(setTimeout)
Time out function in bootstrap.editable.js which I am using to implement inline editing of some form fields.
if(this.options.highlight) {
                var $e = this.$element,
                    bgColor = $e.css('background-color');

                $e.css('background-color', this.options.highlight);
                setTimeout(function(){
                    if(bgColor === 'transparent') {
                        bgColor = '';
                    }
                    $e.css('background-color', bgColor);
                    $e.addClass('editable-bg-transition');
                    setTimeout(function(){
                       $e.removeClass('editable-bg-transition');
                    }, 1700);
                }, 10);
            }

setInterval function in selectivizr.js
if (enabledWatchers.length > 0) {
            setInterval( function() {
                for (var c = 0, cl = enabledWatchers.length; c < cl; c++) {
                    var e = enabledWatchers[c];
                    if (e.disabled !== e.$disabled) {
                        if (e.disabled) {
                            e.disabled = false;
                            e.$disabled = true;
                            e.disabled = true;
                        }
                        else {
                            e.$disabled = e.disabled;
                        }
                    }
                }
            },250)
        }

getting this same error on all 3 files. Not sure how to replace these JS commands or how to deal with 3rd party libraries as well. what is the good approach to deal with these security vulnerabilities.

A: Selectivizr is mainly use to make UI compatible with EI 9 or below. And mainly concern with CSS related stuff. And data is not coming from external source. So we can consider it as false positive But i am not sure frankly telling. But you can try  Conditional Comments OR htmlshiv.js as an alternative to Selectivizr.js


text:
Q: Different views on each different iphone, using sizing classes? I have a screen with a lot of buttons, however I want to show more buttons on bigger devices.
Looking at the sizing classes I can't achieve what I need, to uninstall them.
I need to have different about of buttons on iphone 4, 5, 6 and 6+.
iPhone 4 - 12 buttons
iPhone 5s - 12 buttons
iPhone 6 - 15 buttons
iPhone 6s - 18 buttons
iPhone 6 is part of the custom width but not regular height.
How can I achieve this with a storyboard?
EDIT:
MY layout is three buttons per row.
so:-
iPhone 4 - 4 rows
iPhone 5s - 4 rows
iPhone 6 - 5 rows
iPhone 6s - 6 rows

A: Im not sure if i understood your design but how about using a collectionView with "button" cells, or a tableview (how i said i don't really understand how it should look like), depending on the size of the screen you would have more cells thus buttons. And with a little bit of mathematics it will be done automatically you will not have to set the number of buttons, of-course again it depends on the design


text:
Q: PHP: Match a specific date to a recurring iCal rule I need to build a simple calendar to embed in my PHP application.
Basically I have a bunch of recurrent events whose iCal recurrent rule (rrule) is known (e.g.: "FREQ=MONTHLY;INTERVAL=2;BYDAY=SU" or "FREQ=WEEKLY;BYDAY=SU").
Basically I need a function that given
_ an event iCal rrule
_ a certain day (e.g. 04/10/2011)
returns a boolean telling me whether the event is on at that date.
Obviously I can build it myself but it would take ages: is there any reliable library already available for that?
Thanks,
Dan

A: Although I am at the end of my own calendar project and I am not using iCal, perhaps this will help.
My own experience is that I could not find any sort of library and I coded my own backend from scratch.
For the front-end, I would urge you to use FullCalendar, it is an amazing calendar with what you can do with it.  All you need to then, is concentrate on the backend.
For the db, I would go the route of having only 1 database row per event and when that event is modified, if it is recurring then you amend the existing event and create a new event with the change.
For the back-end logic, in conjunction with fullcalendar it gives you a window to work with.  Within this window, I would then work out when the event occurs and then show, if the event is recurring to then work out when it should be shown on the calendar.  It can get a bit complex but you can do it.
I'm attaching pics of what I have done, sadly this project isn't open source.
Add New Recurring Event
Calendar with Recurring Events
Amend Recurring Event
Agenda List View
Cheers


text:
Q: how to compare value in array php i have data in array
[list] => Array
    (
        [0] => Array
            (
                [id] => 216
                [name] => item A
                [nilai] => 0.456
            )

        [1] => Array
            (
                [id] => 217
                [name] => item B
                [nilai] => 0.999
            )
    )

here I want to make a condition if the value is the largest then the text is green
how to make the condition in foreach ?
this my code
<?php foreach($res['method']['list'] as $key=>$row) { ?>

        <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1">
        <?php echo $row['nilai'] ?>

<?php } ?>

A:   <?php
  $val_array = array_column($res['method']['list'], 'nilai');
  $hightestValueIndex = array_keys($val_array, max($val_array));
  foreach($res['method']['list'] as $key=>$row) { ?>

          <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1">
  <?php if ($key == $hightestValueIndex[0]){ ?>
          <?php echo $row['nilai'] ?>
  <?php} else { ?>
  <?php echo $row['nilai'] ?>

  <?php } } ?>

In the above code we at first extract the 'nilai' in separate and find max value and store it's index using that index in foreach loop we can achieve the desired result

A: This will first calculate the maximum 'nilai' value in your list, and then in array_map a copy of your list will be created with an additional key 'max' for each item in your list. This value will be set to 'true' or 'false' depending on nihai being equal to $maxNilai or not. You then can use that 'max' boolean value to color in green or not.
$list = [
    [ 'id' => 216, 'name' => 'item A', 'nilai' => 0.456 ],
    [ 'id' => 217, 'name' => 'item B', 'nilai' => 0.999 ]
];

$maxNilai = max(array_column($list, 'nilai'));

$result = array_map(
    fn($item) => array_merge($item, [ 'max' => $item['nilai'] === $maxNilai ]),
    $list
);

print_r($result);

Output:
Array
(
    [0] => Array
        (
            [id] => 216
            [name] => item A
            [nilai] => 0.456
            [max] =>
        )

    [1] => Array
        (
            [id] => 217
            [name] => item B
            [nilai] => 0.999
            [max] => 1
        )

)


text:
Q: ASP.NET Sitemap Provider sitemap tabs not showing I am using VS2005 and I'm having some trouble with the sitemap tabs.
I have assigned 2 roles in my ASP.NET Configuration tool, and assigned each user with a role.
My login is working normally, and the access control is working. If I am not logged in and I try to access a role restricted page, it will redirect me to login page.
However, when I logged in, some of the site nodes which are suppose to display when I am logged in with the correct privileged user, it still does not show.

Before login:

After login:
From the screenshots above, my nodes only showed Home in both logged in and not logged in. I should see a Database Management tab which is unrestricted to admin01.

Below is my Web.config code snippet:
    <system.web>
  <authentication mode="Forms" />
  <roleManager enabled="true" />
  <pages styleSheetTheme="DataWebControls" />

        <siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
            <providers>
                <add name="XmlSiteMapProvider"
                  description="Default SiteMap provider."
                  type="System.Web.XmlSiteMapProvider"
                  siteMapFile="Web.sitemap"
                  securityTrimmingEnabled="true" />
            </providers>
        </siteMap>
        <compilation debug="true"/>
    </system.web>

If I remove the whole code from <siteMap></siteMap>, my nodes will appear as normal:

I am not expecting a perfect solution as I do not know if the information I provided is sufficient, but I will appreciate any help given.
If more info is needed from me, please tell me and I will provide additional information.
Thank you

EDITED: Added Web.sitemap code snippet:
<siteMapNode url="/Project/Default.aspx"
          title="Home" description="Home">

    <siteMapNode title="Database Management"
     description="Database tab">

        <siteMapNode url="/Project/Database/Employee.aspx"
         title="Employee"
         description="" />

        <siteMapNode url="/Project/Databaase/Customer.aspx"
          title="Customer"
          description="" />

        <siteMapNode url="/Project/Database/Goods.aspx"
          title="Goods"
          description="" />

        <siteMapNode url="/Project/Database/Transactions.aspx"
          title="Past Transactions"
          description="" />

    </siteMapNode>

</siteMapNode>

EDITED: Added Access role screenshot on folder /Project/Database:

Additional info:
Even if access rules are not created, and users are not assigned with any roles, the Database nodes are still not displayed

A: Have you tried adding roles attribute to the relevant sitemapnodes?
<?xml version="1.0" encoding="utf-8" ?>
<siteMap>
<siteMapNode url="/Project/Default.aspx"
          title="Home" description="Home">

    <siteMapNode title="Database Management"
     description="Database tab" roles="Admin">

        <siteMapNode url="/Project/Database/Employee.aspx"
         title="Employee" roles="Employee,Admin"
         description="" />

        <siteMapNode url="/Project/Databaase/Customer.aspx"
          title="Customer" roles="Customer,Employee,Admin"
          description="" />

        <siteMapNode url="/Project/Database/Goods.aspx"
          title="Goods"
          description="" />

        <siteMapNode url="/Project/Database/Transactions.aspx"
          title="Past Transactions"
          description="" />

    </siteMapNode>
</siteMapNode>
</siteMap>

Have you checked the web.config files that the web site management tools added in to the folders that you restricted access to? Since sometimes the problem lies there..
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <authorization>
      <allow roles="Admin,Employee" />
      <deny users="?" />
    </authorization>
  </system.web>
</configuration>

A: I think I have found a solution for you.
The web configs that are restricting access...
First allow access and then deny it :
<configuration>
    <system.web>
        <authorization>
            <allow roles="Admin1" />
            <deny users="*" />
        </authorization>
    </system.web>
</configuration

When ı do it vice versa the link disaappears and in the above way it appears..
Hope it solves your problem.... Since I created a solution for this and tested. (Since I am using sqlsitemapprovider)


text:
Q: Why objects are not recognized if declared after the function that uses them Here is a simple example: I have two functions: someFunction and someFunction2.
someFunction recognizes someFunction2 event thoug it is defined after someFunction. It is different with the object someVar thoug. If it is defined after the function that uses it, it is not recognized by the function hence undefined. But if the object is defined before the funcution that uses it the function itself recognizes the objec. Here is an example that showcase:
function someFunction() {
    console.log(someVar)
    someFunction2()
}

someFunction()

function someFunction2() {
    console.log("Some Function 2 has been called")
}

var someVar = 'Some Var Displayed Here'

In the case above someFunction recognizes someFunction2 but doesn't recognize the object someVar WHY? what is the difference between the someFunction2 and someVar?


text:
Q: Remove whitespace in  but only outside of  elements I want to remove whitespaces inside a  element.
Inside this element I have several  elements and between them are unnecessary whitespaces. Is there a way to remove them without removing the whitespaces inside the  element?
I've no possibility to remove them in the code and I've to deal with them by using css or to change the PHP output.
I had the following idea but it removes (of course) all whitespaces:
echo str_replace(' ', '', $total['value']);

I also tried a CSS approach:
white-space: pre-line

But this adds a line bevore every space...
Are there any other ideas?
EDIT:
This is what I have:

                                € 636,17

                                Enthält€ 101,57 MwSt. (19%)

I now want to remove all whitespaces between the tags (but not in the text inside the tags):
€ 636,17
Enthält€ 101,57</span MwSt. (19%)

EDIT 2:
I've tried to replace all  tags with a whitespace before them. I tried to do this with preg_replace but I'm not sure how to set a wildcard for the different classes inside the span

A: $new = preg_replace('/>\s*</','><',$orig);

Works for me!  From your sample input and output, I noticed that you only remove whitespace between tags.
Complete code from my test:
    $orig="
                            € 636,17

                            Enthält€ 101,57 MwSt. (19%)
                      	";

    $new = preg_replace('/>\s*</','><',$orig);
    print($new);

I get this (view source):
 € 636,17
Enthält€ 101,57 MwSt. (19%)


text:
Q: Arrow Function returns undefined when called from an object but returns a string when called from a class instance 1. I am calling a function myDes() which is an Arrow Function inside
an Object Cameras. It is returning undefined.
2. But when I call the function myDes() from a Class instance obj1
it returns a string - "abc".

In my understanding arrow function binds by default the properties of
the parent function or the global scope, then why does it not return
the price in the first example as it does name in the
second?

Example 1 — Calling from an Object

const cameras = {
  price: 600,
  weight: 2000,
  myDes: () => {
    return `This canon camera is of ${this.price}`
  }
}

console.log(cameras.myDes()) // price undefined

Example 2 — Calling from an Instance of a Class

class Student {
  name = 'abc'
  myDes = () => {
    console.log(this.name)
  }
}

let obj = new Student
obj.myDes() // return abc

*

To the Comments Below suggesting some link reference for answers. What
I meant since there is no parent function around the arrow function in
the Class then how the arrow function is inheriting the properties of
the class. To which a satisfied answer has been provided

*

*

A: In your first example, there is no parent function around the arrow function definition, so it does indeed bind to the global this. An arrow function is not a method of the object.
In your second example, you are using class field syntax. This is actually syntactic sugar for
class Student {
  constructor() {
    this.name = 'abc'
    this.myDes = () => {
      console.log(this.name)
    }
  }
}

where the parent function is the constructor of the class, whose this value refers to the instance. This is also the value that the this inside the arrow function will refer to.

A: As the comments to your question state, this inside arrow functions do not behave like you think. You may do this instead:

const cameras = {
  price:600,
  weight: 2000,
  myDes: function(){
    return `This canon camera is of ${this.price}`
  }
}

console.log(cameras.myDes())


text:
Q: FormatMessage() pauses the program when dwMessageId = 35, 37, 40... etc I was playing with C++ again when I found this problem. I want to list all errors when I met GetLastError();. I found that it only gives the error code and so it is when I've met FormatMessage();. Everything goes smoothly and until DWORD en reaches 35.
#include <iostream>
#include <sstream>
#include <windows.h>
#include <conio.h>

void psdem(DWORD en) {
    LPVOID error;
    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        en,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)&error,
        0,
        NULL);
    cout << (LPCTSTR)error;
}

int main() {
    for (int i = 0 ; ((i <= 2147483647) & (i >= 0)) ; i++) {
        psdem(i);
        cout << endl;
    }
    getch();
}

It is confusing and I am stuck with it. I believe there IS a solution to fix it but I've searched for the solution via the Internet but I just can't find the solution.
So, I then coded to skip 35 and then here comes 37 who causes the program to stuck. Again, I coded to skip it and 40 comes to place. Then, I realized that it is not an individual error.

Why is this happening and how can I fix that?


text:
Q: Setting dynamic folder and report name in pytest I have a problem with setting report name and folder with it dynamically in Python's pytest.
For example: I've run all pytest's tests @ 2020-03-06 21:50 so I'd like to have my report stored in folder 20200306 with name report_2150.html. I want it to be automated and triggered right after the tests are finished.
I'm working in VS Code and I'm aiming to share my work with colleagues with no automation experience so I'm aiming to use it as "click test to start".
My project structure:
webtools/
|── .vscode/
|──── settings.json
|── drivers/
|── pages/
|── reports/
|── tests/
|──── __init__.py
|──── config.json
|──── conftest.py
|──── test_1.py
|──── test_2.py
|── setup.py

Code samples:
settings.json
{
    "python.linting.pylintEnabled": false,
    "python.linting.flake8Enabled": true,
    "python.linting.enabled": true,
    "python.pythonPath": "C:\\Users\\user\\envs\\webtools\\Scripts\\python.exe",
    "python.testing.pytestArgs": [
        "tests",
        "--self-contained-html",
        "--html=./reports/tmp_report.html"
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.testing.unittestArgs": [
        "-v",
        "-s",
        "./tests",
        "-p",
        "test_*.py"
    ]
}

config.json
{
    "browser": "chrome",
    "wait_time": 10
}

conftest.py
import json
import pytest
from datetime import datetime
import time
import shutil
import os

from selenium import webdriver
from selenium.webdriver import Chrome

CONFIG_PATH = 'tests/config.json'
DEFAULT_WAIT_TIME = 10
SUPPORTED_BROWSERS = ['chrome', 'explorer']

@pytest.fixture(scope='session')
def config():
    # Read the JSON config file and returns it as a parsed dict
    with open(CONFIG_PATH) as config_file:
        data = json.load(config_file)
    return data

@pytest.fixture(scope='session')
def config_browser(config):
    # Validate and return the browser choice from the config data
    if 'browser' not in config:
        raise Exception('The config file does not contain "browser"')
    elif config['browser'] not in SUPPORTED_BROWSERS:
        raise Exception(f'"{config["browser"]}" is not a supported browser')
    return config['browser']

@pytest.fixture(scope='session')
def config_wait_time(config):
    # Validate and return the wait time from the config data
    return config['wait_time'] if 'wait_time' in config else DEFAULT_WAIT_TIME

@pytest.fixture
def browser(config_browser, config_wait_time):
    # Initialize WebDriver
    if config_browser == 'chrome':
        driver = webdriver.Chrome(r"./drivers/chromedriver.exe")
    elif config_browser == 'explorer':
        driver = webdriver.Ie(r"./drivers/IEDriverServer.exe")
    else:
        raise Exception(f'"{config_browser}" is not a supported browser')

    # Wait implicitly for elements to be ready before attempting interactions
    driver.implicitly_wait(config_wait_time)

    # Maximize window for test
    driver.maximize_window()

    # Return the driver object at the end of setup
    yield driver

    # For cleanup, quit the driver
    driver.quit()

@pytest.fixture(scope='session')
def cleanup_report():
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    os.chdir("./reports")
    os.mkdir(timestamp)

    yield

    shutil.move("./tmp_report.html", "./%s/test_report.html" % timestamp)

In current situation the report is created as tmp_report.html in the reports folder, but I don't know how I can force running cleanup_report() after all tests are completed and tmp_report.html is present and complete in folder. For checking if complete I assume I'd have to verify if all html tags have their closing (or at least <html> one).
Can somebody help me with that? If you need some further code portions I'll provide them as soon as possible.
Thank you in advance!

A: You can customize the plugin options in a custom impl of the pytest_configure hook. Put this example code in a conftest.py file in your project root dir:
from datetime import datetime
from pathlib import Path
import pytest

@pytest.hookimpl(tryfirst=True)
def pytest_configure(config):
    # set custom options only if none are provided from command line
    if not config.option.htmlpath:
        now = datetime.now()
        # create report target dir
        reports_dir = Path('reports', now.strftime('%Y%m%d'))
        reports_dir.mkdir(parents=True, exist_ok=True)
        # custom report file
        report = reports_dir / f"report_{now.strftime('%H%M')}.html"
        # adjust plugin options
        config.option.htmlpath = report
        config.option.self_contained_html = True

If you want to completely ignore what's passed from command line, remove the if not config.option.htmlpath: condition.
If you want to stick with your current impl, notice that on fixtures teardown, pytest-html hasn't written the report yet. Move the code from cleanup_report to a custom impl of the pytest_sessionfinish hook to ensure pytest-html has already written the default report file:
@pytest.hookimpl(trylast=True)
def pytest_sessionfinish(session, exitstatus):
    shutil.move(...)


text:
Q: Facing issue while using set_value() function in form_validation library in Codeigniter I am using form_validation library in Codeigniter, I am facing an issue while using set_value() function.
It not sets the value when an error occure in form validation.
Here is my form ==>

    First Name*
    <input type="text" name="first_name" id="first_name" required placeholder="Enter First Name" class="form-control" <?php set_value('first_name'); ?>>

    <?php echo form_error('first_name', '
', '
'); ?>

Here is my Controller code ==>
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('
', '
');
$this->form_validation->set_rules('first_name', 'First Name', 'trim|required|regex_match[/^[a-zA-Z]+$/]',array('required' => 'Please enter %s.', 'regex_match' => 'Only Characters allowed, no space'));
if ($this->form_validation->run() == FALSE)
{
  $this->load->view('admin/user/add_user');
}

Here I am attaching an image of the output.
It does not show the previous entered value.

A: Use set_value() as the value of value attribute
<input type="text" name="first_name" id="first_name" required placeholder="Enter First Name" class="form-control" value="<?php echo set_value('first_name'); ?>">


text:
Q: Spark DataFrame to DataSet with custom columns We are struggling to convert a Spark DataFrame to a DataSet of case class with dynamic columns. Starting points for each use case are DataFrames like the one below:
root
|-- id: string (nullable = true)
|-- time: long (nullable = true)
|-- c: struct (nullable = true)
|    |-- d: long (nullable = true)
|    |-- e: string (nullable = true)
|    |-- f: array (nullable = true)
|    |    |-- element: struct (containsNull = true)
|    |    |    |-- g: long (nullable = true)
|-- x: string (nullable = true)
|-- y: string (nullable = true)

All these DataFrames have id and time column in common. The other columns (c, x, y) are configurable and can be vary for each use case in count (in some DataFrames we have up to 10 columns beside id and time) and type.
To simplify the complex processing of the these events we would like to cast each row to a scala case class like this:
case class Event(id: String, time: Long, payload: Seq[Any])

or:
case class Event(id: String, time: Long, payload: Map[String, Any]) // payload: <column-name>/<value>

Sadly, df.as[Event] doesn't work out of the box. Any ideas, how to do the trick?
Writing a case class for every use case is not an option, because we just want to configure the job via a YAML file and don't want to adjust the code for every new use case. We need something more generic! (I thought about generating a case class at runtime, but this is quite complicated...)
Thanks for your help!
Update - Solution
We now came up with the following solution:
case class Event(id: String, time: Long, payload: Seq[Array[Byte]])
and convert the DataFrame with the help of kryo:
val idIndex = df.columns.indexOf("id")
val timeIndex = df.columns.indexOf("time")
val otherColumns = List.range(0, df.columns.length).filterNot(i => i == idIndex && i == timeIndex)

val kryo = new Kryo()

val ds = df.map(row => {
  Event(
    row.getAs[String](idIndex),
    row.getAs[Long](timeIndex),
    otherColumns.map(index => {
      val output = new Output(192, 8192)
      kryo.writeObject(output, row.get(index))
      output.getBuffer
    })
  )
})

ds.printSchema()

Thx, for your help.


text:
Q: xbacklight works, system settings don't affect I am running Ubuntu 15.10 x64 on my Dell M4800 with the lvds connected to the Nvidia K2100M via nvidia-355, as the intel card does not support the 3K screen.
So when I change the screen brightness using hotkeys or within energy settings, it doesn't change anything.
When I change it via xbacklight, it works perfect.
So, what's the difference, and is there a way I can help devs to make it work ootb?
Thanks for your help.

A: Buggy driver. You can try adding the options acpi_osi=Linux acpi_backlight=vendor to grub
sudo gedit /etc/default/grub

Add the following parameters to grub configuration:
GRUB_CMDLINE_LINUX="acpi_osi=Linux acpi_backlight=vendor"

Update Grub:
sudo update-grub

reboot

A: Actually, it's now fixed with the newest nvidia-352  version 352.63.
https://bugs.launchpad.net/ubuntu/+source/xbacklight/+bug/1511127


text:
Q: how can i print data of array? Here are my codes:
app.get('/index/:name',function(req, res){
    data = connection.query('SELECT * FROM deneme', function(err, rows, fields){
        if(err) throw err;
        veri = rows;
        return veri;
    });

    console.log(data);

    res.render('index', {
        title: req.params.name,
        para: data
    });
});

When i call localhost:8080/index/example it returns [object Object]
I want to print data of array, how can i do this?
I can do it when I'm using php with print_r() function..
Meantime, array's data:
Id Name
1  yab
2  sad

A: I think OP just want to print the data for debugging purposes, for that you can use the following cross-browser way that uses JSON to print a nice representation of the data:
console.log( JSON.stringify(data, null, 4) );

A: Something like this should work:
for (var colName in data) {
    console.log("column " + colName);
    var rows = data[colName];
    for (var i = 0; i < rows.length; i++) {
        console.log(rows[i]);
    }
}

You will have to tweak it for your needs, that's the general way to iterate such objects.

A: You need to iterate the result collection and print the attributes
      $.each(resultArray, function() {
             this.id;//use this to write id
             this.name;//use this to write name
       });

A: To output to the console you could do something like:
for(var index in data) {
    var item = data[index];
    var output = [];
    for(var field in item) {
        output.push(item[field]);
    }
    console.log(output.join("\t"));
}

For outputting in html, you'd do something like similar, but creating actual HTML nodes. Maybe, something like:
var output = ["
"];
for(var index in data) {
    output.push("
");
    var item = data[index];
    for(var field in item) {
        output.push("");
        output.push(item[field]);
        output.push("	");
    }
    output.push("
");
    console.log(output.join("\t"));
}
output.push("
");
element.innerHTML = output.join("");

I've not tried that in a browser, so there might be a couple of mistakes, but that should do it.
Let me know if you'd like any more help.


text:
Q: Why does a $elemMatch MongoDB query behave differently on client and server with an extended RexExp EJSON type? This is a very specialized case, but quite relevant to anyone wanting to leverage MongoDB's RegExp powered lookups from client (Mini-Mongo) to server (MongoDB) using publications and subscriptions in Meteor. I would like to understand why the disparity between server and client MongoDB query functionality, and develop a pull-request to Meteor if it is A) needed and B) beneficial to other developers.
I. General Case:

*

*Run a Meteor installation with aldeed:meteor-simple-schema, aldeed:collection2, accounts-password, and ejson at a minimum.

*Extend EJSON by adding the RegExp type using EJSON.addType with these instructions: How to extend EJSON to serialize RegEx for Meteor Client-Server interactions?

*Add a Meteor.user with the email address "admin@foo.com"

*Run this on the Meteor server code (UNEXPECTED RESULT):
# anywhere on the server
if Meteor.isServer
  user_selector = { 'emails': { '$elemMatch': { 'address': /^adm/ } } }
  user_count = Meteor.users.find(user_selector).count()
  console.log user_count
  # prints 0 WHY!?

*Run this on the MongoDB shell (bypassing Meteor.users):
# mongo shell
> db.users.find({ 'emails': { '$elemMatch': { 'address': /^adm/ } } }).count()
# prints 1

*Attempt an independent Mongo.Collection lookup with identical data.
# server
MyUsers = new Mongo.Collection 'myusers'

*Copy the user document from Meteor.users() into the MyUsers collection.

*Run this on the Meteor server (ALSO UNEXPECTED):
# anywhere on the server
if Meteor.isServer
  user_selector = { 'emails': { '$elemMatch': { 'address': /^adm/ } } }
  user_count = MyUsers.find(user_selector).count()
  console.log user_count
  # prints 0 WHY!?

Furthermore, if I publish ALL the users, but run the exact same query against the client side code (e.g. within a template helper param), the query returns the expected count.
II. Pub/Sub Template Helper Case:

*

*Publish and subscribe to users.
# Server
Meteor.publish 'all_users', ->
  return Meteor.users.find({})

# Client
Template.people.onCreated ->
  self = @
  self.peopleReady = new ReactiveVar()
  self.autorun ->
    users = Meteor.subscribe 'all_users'
    self.peopleReady.set users.ready()

Template.people.helpers
  user_count: ->
    user_selector = { 'emails': { '$elemMatch': { 'address': /^adm/ } } }
    user_count = Meteor.users.find(user_selector).count()
    console.log user_count
    # prints 1
    return user_count

Why the difference in the server code demonstrated in I.4 above? I wonder because...

*

*EJSON is properly extended.

*MiniMongo properly selects and counts records on the client.

*Using a MyUser Collection (instantiated with Mongo.Collection) also fails to report the correct count on the server but runs successfully on the client using the extended RegExp EJSON type in this query selector { 'emails': { '$elemMatch': { 'address': /^adm/ } } } with identical documents outside the scope of Meteor.user
Where can I see (and experiment with) the server side definition of Collection.find() inside the Meteor source code?

A: This does look like a bug. Please file an issue at http://github.com/meteor/meteor/issues . Be sure to follow our reproduction guidelines.


text:
Q: Backpressure with Spring Webflux and several slow HTTP-backend requests In my webflux-application I am consuming messages from AWS-SQS and use them to invoke several HTTP-requests on a slow backend (response times up to 5 seconds).
I realized that the more messages I consume, the slower the backend gets, until it dies, due to too much traffic.
How can I use the reactor / webflux mechanism, to control the number of requests I send to a backend? I tried some stuff with limit / limitRate, but it didn't work as expected.
Do you have any samples/ideas?

A: Take a look at resilience4j library. Among several resiliency features like circuit breaker, retry, bulkhead there is rate limiting as well.
They support Project Reactor.


text:
Q: Cusom UIStoryboardSegue back animation not work as expected For some reason I want to have a custom push animation for my segue transition in storyboard which instead of pushing from right to left it pushes from left to right, I developed a custom segue which does this with this code:
UIViewController *sourceViewController = (UIViewController*)[self sourceViewController];
UIViewController *destinationController = (UIViewController*)[self destinationViewController];

CATransition* transition = [CATransition animation];
transition.duration = .25;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush; //kCATransitionMoveIn; //, kCATransitionPush, kCATransitionReveal, kCATransitionFade
transition.subtype = kCATransitionFromLeft; //kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom

[sourceViewController.navigationController.view.layer addAnimation:transition
                                                            forKey:kCATransition];

[sourceViewController.navigationController pushViewController:destinationController animated:NO];

The problem is when back button in next view is clicked the segue animation is default one and it has not been changed (it should be right to left but instead it shows left to right which is default one)
How should I change back animation too?

A: actually it's my fault,UIStoryboardSegue has no control on back animation because it belongs to uiviewcontroller pop animation ! and for purpose of mine i should have write custom pop animation for my scene.


text:
Q: how can I stay on the same page without return on my login again? how can I stay on the same page when I write localhost/store
1.- when I enter to my system i have this url localhost/store/view/home.php, but I write localhost/store then it'll returned to my login page again. how can I return my page to home.php or whatever page when I write localhost/store.
controller
<?php

require_once('../model/user_model.php');

$boton = $_POST['boton'];

switch ($boton) {
    case 'logout':
        session_start();

        if (isset($_SESSION['session_user_id'])){
            $user = new user();
            $user->updateCheckPoint($_SESSION['session_user_id']);
        }
        session_destroy();
        break;
    case 'login':
        if(isset($_POST['username']) && $_POST['username'] != '' && isset($_POST['password']) && $_POST['password'] != ''){
            $username = $_POST['username'];
            $password = $_POST['password'];
            $username = stripslashes($username);
            $username = mysql_real_escape_string($username);
            $password = stripslashes($password);
            $password = mysql_real_escape_string($password);
            $ins = new user();
            $array = $ins->identification($username, $password);
            if($array[0] == 0){
                echo 0;
            }else{
                session_start();
                $_SESSION['login'] = 'YES';
                $_SESSION['full_name'] = $array[1] . ' ' . $array[2];
                $_SESSION['session_type_user'] = $array[5];
                $_SESSION['job_position'] = $array[6];
            }
        }else{
            echo 'something went wrong';
        }
     break;
   }
?>

model
<?php
    if (session_id() === ''){
        session_start();
    }

    class user{
    private $conexion;

    public function __construct(){
        require_once('conexion.php');
        $this->conexion = new conexion();
        $this->conexion->conectar();
    }

    function identification($username,$password){
        $pass = md5(sha1($password));
        $sql="SELECT iduser,name,last_name,username,password,typeuser_idtypeuser,type from user INNER JOIN typeuser ON user.typeuser_idtypeuser = typeuser.idtypeuser WHERE username = '$username' AND password = '$pass'";
        $record = $this->conexion->conexion->query($sql);
        if ($record->num_rows > 0){
            $row = $record->fetch_array();
            session_regenerate_id();
            $_SESSION['session_user_id'] = $row['iduser'];
            $_SESSION['session_username'] = $row['username'];
            $_SESSION['session_type_user'] = $row['typeuser_idtypeuser'];
            echo $_SESSION['session_type_user'];
            session_write_close();
        }else{
            $row[0] = 0;
        }
        return $row;
        $this->conexion->cerrar();
    }

    public function updateCheckPoint($id_user){
        $id_user = intval($id_user);
        $t = time();
        $sql = "UPDATE user SET checkpoint = {$t} WHERE iduser = {$id_user};";
        $this->conexion->conexion->query($sql);
        $this->conexion->cerrar();
    }
  }
?>

index.php
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>punto</title>

    <link rel="stylesheet" href="../assests/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assests/css/main.css">

            Store

Sign In

                        <form data-toggle="validator" role="form" method="POST" onsubmit="return login();">

                                Username

                                    <input type="text" class="form-control" name="username" id="username" placeholder="Username" required>

                                Password

                                    <input type="password" class="form-control" id="password" placeholder="Password" required>

Invalid username or password !!

                            <button type="submit" class="btn btn-lg btn-success btn-block" onsubmit="login();">Login</button>
                        </form>

home.php
    <?php
session_start();
if (isset($_SESSION['login']) && $_SESSION['login']=='YES'){?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Store</title>
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <link rel="stylesheet" href="../assests/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assests/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../assests/ionicons-2.0.1/css/ionicons.min.css">
    <link rel="stylesheet" href="../assests/dist/css/AdminLTE.min.css">
    <link rel="stylesheet" href="../assests/dist/css/skins/_all-skins.min.css">

          ALT

          StoreLTE

            Toggle navigation

                        0

                                See All Notifications

                  <?php echo $_SESSION['full_name']; ?>

                      <?php echo $_SESSION['full_name']; ?>
                      <?php echo $_SESSION['job_position'];?>

                      Sign out

MENÚ

                Home
                4

                 Inventory

 Product

                 Purchase

 Provider

                Sale

                 Charts

 Best selling product

                 User

 Invoice

 Profile

 Login

 Register

 Lockscreen

 404 Error

 500 Error

 Blank Page

            Sale

                  Likes
                  41,410

                  Sales
                  760

                  New Members
                  2,000

                  CPU Traffic
                  90%

<?php
  }
  else
    header("location: ./");
 ?>

A: Put this code at the top of index.php
<?php
    session_start();

    if(isset($_SESSION['login']) && $_SESSION['login'] == 'YES'){
        die(header("Location: home.php"));
    }
?>


text:
Q: Laravel update or create Good evening from Malaysia!
I am trying to create an invoice website, I am done with the project but I have an issue with updating the invoice item, first I use to update or create using the barcode, and description as checking tools, but I found out it's difficult to make changes to the barcode, as this will create new item.  So I used product_id as a parameter, to check before updating or creating, but if new item is added this doesn't save to the database.
Please can anyone help me out?
Below is my code.
    //After successfully deleted proceed to update or create a new request
        if(count ($request->input('product_id')) > 0) {
            foreach($request->input('product_id') as $item => $i) {
                $inv_item = invoice_item::UpdateOrCreate(
                    [
                        'invoice_id' => $id,
                        'id' => $request->product_id[$item]
                    ],
                    [
                        'barcode' => $request->barcode[$item],
                        'description' => $request->description[$item],
                        'serialnumber' => $request->serialnumber[$item],
                        'quantity' => $request->quantity[$item],
                        'selling_price' => $request->s_price[$item],
                        'total' => $request->total[$item]
                    ]);
                }
            }
        }

This code will update the item as per request, but if new item is added it will not save to database.
If I use the code below
    //After successfully deleted proceed to update or create a new request
        if(count ($request->input('barcode')) > 0) {
            foreach($request->input('barcode') as $item => $i) {
                $inv_item = invoice_item::UpdateOrCreate(
                    [
                        'invoice_id' => $id,
                        'id' => $request->product_id[$item]
                    ],
                    [
                        'barcode' => $request->barcode[$item],
                        'description' => $request->description[$item],
                        'serialnumber' => $request->serialnumber[$item],
                        'quantity' => $request->quantity[$item],
                        'selling_price' => $request->s_price[$item],
                        'total' => $request->total[$item]
                    ]);
                }
            }
        }

I always get undefined array key for the product_id.
Any suggestion please? Thanks!
what i want now is how to update or create array in laravel.

A: I have to create a new jquery to append updated form table and i added this to the javascript
<td hidden="">
        <input type="hidden" class="form-control" id="prodct_id" name="product_id[]"
        value="">
    </td>

And this solved the problem


text:
Q: How to calculate $9^{47^{51}} \mod 67$? I've looked at some other related things on here, but this seems a little more complicated with the double exponentiation. Is there a general algorithm to calculate $a^{c_1^{c_2^{...^{c_n}}}} \mod p$ or something?

A: $67$ is a prime number, thus, Fermat's Theorem holds.
This implies
$$9^{66}=1 \pmod  {67} $$ you should resolve now $$ 47^{51} = ? \pmod {66}  $$
Consider that $66 = 2\cdot3\cdot11$, you can use the Chinese Remainder Theorem.

A: First focus on $47^{51}$ in your example.  You must figure that out mod $66$, the latter number being the Euler totient of $67$.  Let $r$ be that residue and then attack $9^r$ modulo $67$.

A: $$\phi(67)=66=2\cdot 3\cdot 11$$ and
By Fermat's Theorem,
$$47^{51}\equiv47^{1}\equiv 47\pmod2$$
$$47^{51}\equiv47^{1}\equiv 47\pmod3$$
$$47^{51}\equiv47^{1}\equiv 47\pmod {11}$$
Thus, using Chinese Remainder
$$47^{51}\equiv 47\pmod {66}$$
Thus, by Fermat' Little theorem:
$$9^{47^{51}}\equiv 9^{47}\equiv 3^{94}\equiv 3^{28}\equiv (-64)^{28}\equiv ((-4)^3)^{28}\equiv (-4)^{84}\equiv (-4)^{18}\equiv 4^{18}\equiv 2^{36}\equiv -2^3\equiv -8\pmod{67}$$
, where $2^{33}\equiv -1$ comes from the fact that $2^{33}=\left(\frac 2{67}\right)=(-1)^{\frac{p^2-1}8}$

A: First of all,
$$9^{47^{51}}=3^{2\cdot47^{51}}$$
As $\phi(67)=\lambda(67)=66,$
$$3^{2\cdot47^{51}}\equiv3^{2\cdot47^{51}\pmod{66}}\pmod{67}$$
As $(2\cdot47^{51},66)=2,$ let us find $47^{51}\pmod{33}$
As $\lambda(33)=\cdots=10,51\equiv1\pmod{10},$
$$47^{51}\equiv47^1\pmod{33}\equiv14$$
$$\implies2\cdot47^{51}\equiv14\cdot2\pmod{66}$$
$$\implies3^{2\cdot47^{51}}\equiv3^{28}\pmod{67}$$
Now $3^4\equiv14,3^8=(3^4)^2\equiv14^2\equiv-5$
$\implies3^{28}=3^4\cdot(3^8)^3\equiv14\cdot(-5)^3\equiv14\cdot9\equiv-8\equiv-8+67$


text:
Q: Eclipse update problem? Please take a look here:
alt text http://img16.imageshack.us/img16/2810/errrp.jpg
Why i got that error when i'm trying to update my Eclipse Galileo to the newest Eclipse M6 Helios?
I'm using the update URL from here:
http://eclipsesource.com/blogs/2010/03/14/eclipse-3-6-m6-helios-available-for-download/
Is this a bug? If not, what can i do?
Please help. Thanks!

A: Can you try the upgrade process after re-launching eclipse with the -clean option?
Do you confirm you are using the http://download.eclipse.org/eclipse/updates/3.6milestones/ update site address?
What version of eclipse are you using (3.5, 3.5.1, 3.5.2?) and what extra plugin did you installed?
For instance, if you have installed Scala for Eclipse, you could not upgrade AspectJ which could block the upgrade process. (see this thread for illustration)

To summarize the 3-days span and 15 comments below:
An easiest path to solve this would be:

*

*have a fresh installation of Eclipse, especially the Java EE Helios package (see Helios packages)

*with an eclipse.ini including a -data /path/to/existing workspace
( That way, you have 2 Eclipse referencing the same Eclipse projects. You can launch one or the other, and if the new one does not work, you can still revert to the old one. This is safer than trying modifying extensively -- through the update process -- your current Eclipse)

*add the  GlassFish plugin for Eclipse
(download both the plugin and feature jar files, quit Eclipse, then copy the unzipped contents of the first into the plugins directory and the second into the features directory of your Eclipse installation)

*Check you Java EE JDK if needed

And here you go: you should be able to see a GlassFish Server and integrate it as a target runtime there.


text:
Q: Sort array into an object with key and value pairs with same values being pushed into the same key/value I would like to sort an array into and object with key value pairs.
So if I had an array like this [1,2,3,2,4,1,5,1,6] it should spit out something like this. I was trying to use lodash for it!
{
  1: [1, 1, 1],
  2: [2, 2],
  3: [3],
  4: [4],
  5: [5],
  6: [6]
}

A: You can use reduce() and return object.

var ar = [1, 2, 3, 2, 4, 1, 5, 1, 6];
var result = ar.reduce(function(o, e) {
  o[e] = (o[e] || []).concat(e);
  return o;
}, {});

console.log(result)

A: Some basic iteration would do that, where you either set an array, or push to an existing array

var arr = [1,2,3,2,4,1,5,1,6];
var obj = {};

arr.forEach( (x) => x in obj ? obj[x].push(x) : obj[x] = [x]);

document.body.innerHTML = '<pre>'+ JSON.stringify(obj, 0, 4) +'</pre>'

A: Here is a very simple pure JavaScript version to achieve this (https://jsfiddle.net/azkuodyc/)
var array = [1,2,3,2,4,1,5,1,6];
var newArrayObject = {};

for (key in array) {
    var value = array[key];
    if (typeof newArrayObject[key] == 'undefined') {
        newArrayObject[key] = [];
    }
    newArrayObject[key].push(value);
}

A:

const arr = [1,2,3,2,4,1,5,1,6];
const r = {};

arr.forEach(e=>r[e]?r[e].push(e):r[e]=[e]);

console.log(r);

A: One other way of doing this is;

var arr = [1,2,3,2,4,1,5,1,6],
    obj = arr.reduce((p,c) => (p[c] = p[c] ? p[c].concat(c) : [c],p),{});
console.log(obj);

A: var arr =  [1,2,3,2,4,1,5,1,6];

var res = _(arr).countBy().mapValues((value, key) => {
  return _.times(value, _.constant(parseInt(key)));
}).value();

console.log(res);

https://jsfiddle.net/7bppaxx5/


text:
Q: Populate a map with a default value I want to create a map of 48 default key value pairs.
This code works fine:
var m = new Map();

for(var i=1; i <= 48 ; i++) {
  m.set(i,'0')
}

But, I want to know if this can be done without using for loop.

A: You can pass an array to the Map constructor:
const map = new Map([...Array(48)].map((_, i) => [i + 1, '0']));

If your first key can be 0 instead of 1, this would be a cleaner solution:
const map = new Map(Array(48).fill('0').entries());


text:
Q: Having count condition with greater than and less than for Sybase DB I am using below query in sybase db, i need data to show where count(Field1 >=2 and Field1 <=5)
Select * FROM Table1 WHERE Field1 IN( SELECT Field1 FROM Table1 GROUP BY Field1 HAVING COUNT(Field1) >= 2 ORDER BY Field1How can i achieve this

A: You are basically there:
Select *
FROM Table1
WHERE Field1 IN (SELECT Field1
                 FROM Table1
                 GROUP BY Field1
                 HAVING COUNT(Field1) BETWEEN 2 AND 5
                )
ORDER BY Field1;

However, I would suggest window functions:
select t1.*
from (select t1.*, count(*) over (partition by field1) as cnt
      from table1 t1
     ) t1
where t1.cnt between 2 and 5;