text:
Q: xml Class to substitute ini files I am learning Windows Forms in C#.NET 2008 and i want to build a class to work with SIMPLE xml files (config file like INI files), but i just need a simple class (open, getvalue, setvalue, creategroup, save and close functions), to substitute of ini files.
I already did something and it is working but I am having trouble when I need to create different groups, something like this:
<?xml version="1.0" encoding="utf-8"?>
<CONFIG>
  <General>
    <Field1>192.168.0.2</Field1>
  </General>
  <Data>
    <Field1>Joseph</Field1>
    <Field2>Locked</Field2>
  </Data>
</CONFIG>

how can i specify that i want to read the field1 of [data] group?  note that i have same field name in both groups (Field1)!
I am using System.Linq, something like this:
To open document:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FilePath);

To save document:
xmlDoc.Save(FilePath);

To get value:
public string getValue(string Field)
{
    string result = "";
    try
    {
        XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field);
        if (xmlComum.Item(0) == null)
            result = "";
        else
            result = xmlComum.Item(0).InnerText;
    }
    catch (Exception ex)
    {
        return "";
    }
    return result;
}

To set value:
public void setValue(string Group, string Field, string FieldValue)
{
    try
    {
        XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field);
        if (xmlComum.Item(0) == null)
        {
            xmlComum = xmlDoc.GetElementsByTagName(Group);
            if (xmlComum.Item(0) == null)
            {
                // create group
                createGroup(Group);
                xmlComum = xmlDoc.GetElementsByTagName(Group);
            }
            XmlElement xmlE = xmlDoc.CreateElement(Field);
            XmlText xmlT = xmlDoc.CreateTextNode(FieldValue);
            xmlE.AppendChild(xmlT);
            xmlComum.Item(0).AppendChild(xmlE);
        }
        else
        {
            // item already exists, just change its value
            xmlComum.Item(0).InnerText = Value;
        }
        xmlDoc.Save(FilePath);
    }
    catch (Exception ex)
    {
    }
}

The CreateGroup code:
public void createGroup(string Group)
{
    try
    {
        XmlElement xmlComum = xmlDoc.CreateElement(Group);
        xmlDoc.DocumentElement.AppendChild(xmlComum);
        xmlDoc.Save(FilePath);
    }
    catch (Exception ex)
    {
    }
}

A: Though you may be "using" System.Linq in your project, you are not using the so-called "Linq-to-XML" classes.  Which make things about 5 times easier, even you're not using LINQ on them!  Use the System.Linq.XML namesspace, to have access to these new xml classes (XDocument, XElement, etc.)
    XDocument XDoc = XDocument.Load("ThePath")
    String Field1 = (String)XDoc.Root.Element("Data").Element("Field1")

*

*Pretty good tutorial.

*Documentation.

*Good DNR TV vid-casts here/here and here.

*A great book on Linq in general, and Linq-to-XML in particular

A: If you're using the XML file as an actual repository of configuration data (just like we used to use .INI files for, back in the mists of time) then System.Configuration is your friend, as it handles reading and writing to App.Config, which is an XML file designed just for this.
Here's some detail and examples: System.Configuration
Of course, if you're writing a generic interface to XML files, System.Linq.XML is the right way to go.


text:
Q: PHP, JQuery - How to dynamically add more fields consist of dropdownlist(value from database, and a text box) I have 2 form component that i would like to add dynamically (allow user to add more than 1)
First i have a dropdownlist with values populated from MySQL. Followed by a text box which allows user to enter some enquires.
Basically, the dropdownlist will show a list of user and a textbox for the person to type a message to the person.
The user is allow to send to multiple different user, therefore there is a ADD button which will add another dropdownlist and a text box..
I tried using jQuery append. but append does not accepts PHP as its server side.
I also tried to jQuery clone to clone the whole DIV but fails.
I am using this code to add field dynamically
Add Remove field dynamically
This is my code for the dropdownlist and textbox

<button class="add_field_button">Add More Fields</button>

    <select name="msgrecever1" style="background:#252525" >
          <option value="">Select Faculty</option>
          <?php
            require_once("../dbconnection/dbcon.php");
            $sql="SELECT * FROM user WHERE role='Faculty'";
            $records=mysqli_query($con,$sql);
            while($row=mysqli_fetch_assoc($records)){
            $name=$row['username'];
            echo "<option value='$name'>".$name."</option>";
            }
            ?>

          </select><input type="text" name="mytext[]">

I want to duplicate as many of the above code as long as the user press "add new field"
jQuery:
$(document).ready(function() {

    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

     x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();

        if(x < max_fields){ //max input box allowed
            x++; //text box increment

            $(wrapper).append('
<input type=\"text\" name=\"mytext[]\"/>Remove');

        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

=================
EDITED:
i have used this solution and it works.
<?php require_once("../dbconnection/dbcon.php");

if(isset($_POST['submit']))
{
    $capture_field_vals ="";
    foreach($_POST["msgrecipient"] as $key => $text_field)
    {
        echo "Key: $key; Value: $text_field
\n";

        echo "
";

    }
        foreach($_POST["enquiry"] as $key => $text_field2)
        {
        echo "Key: $key; Value: $text_field2
\n";

        echo "
";
        }
}

    ?>
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Application</title>

<form action="#" method="post">

        <select name="msgrecipient[]" id="select">
            <option value="">Select Faculty</option>
              <?php
                require_once("../dbconnection/dbcon.php");
                $sql="SELECT * FROM user WHERE role='Faculty'";
                $records=mysqli_query($con,$sql);
                while($row=mysqli_fetch_assoc($records)){
                $name=$row['name'];
                echo "<option value='$name'>".$name."</option>";
                }

                ?>

              </select>

        <textarea id="textarea" name="enquiry[]" class="test-textarea"></textarea>

        <input type="button" id="btnAdd" value="[ + ] add to this form">
        <input type="button" id="btnDel" value="[ - ] remove the section above">

    <input type="submit" name="submit"class="button button-block" value="Submit"/>
</form>

A: Assuming you have a markup like this:
<form id="faculty_wrapper">

        <select id="faculty" name="faculty[]">
            <option value="faculty_one">faculty_one</option>
            <option value="faculty_one">faculty_two</option>
            <option value="faculty_one">faculty_three</option>
            <option value="faculty_one">faculty_four</option>
        </select>
        <input type="text" name="message[]">

</form>

Add More
Submit

Javascript:
jQuery(document).ready(function($){

   $("#add_more").on('click', function(e){
        e.preventDefault(); // Prevent Default the event
        var clone = $(".faculty_row").eq(0).clone(); // clone only first item
        $("#faculty_wrapper").append(clone); // append it to our form
   });

    $("#submit").on('click', function(e){
       e.preventDefault();
        alert($("#faculty_wrapper").serialize()); // get serialize data for further work
    })
})

You can check the working Jsfiddle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Chrome, Safari hangs while reading from localStorage while Firefox is good? I have the following code which fires off when Queue is clicked
$('#queue').click(function(){
        $("#feature").load("templates/queue.html", function(){
            var template = $('queue_item').clone();
            if (localStorage['queue'] == null) {
                $('.queue_list').append('
You have not added any video to the queue yet
');
            } else {
                var queue_list = JSON.parse(localStorage['queue']);
                for (var i = 0; i < queue_list.length; i++) {
                    console.log(queue_list[i]);
                    var item = fill_queue_item(queue_list[i]);
                    $('.queue_list').append(item).fadeIn('slow');
                }
            }
        });
    });

*

*Depending on number of items user added to queue this code creates a node and insert into queue_list

*When I test this on Firfox, things are pretty fine, but Safari and Chrome almost die to perform the same operation

Question
- How can I make Chrome and Safari happy like Firefox and let them do things fast?
UPDATE
function fill_queue_item(data) {
    var template = $('.queue_item').clone();
    template.removeClass('hide-item');
    template.find('img').attr('src', data.thumbnail);
    template.find('.title').html(data.title);
    template.attr('id', data.url);
    template.addClass('view-item');
    return template;
}

The queue can contain any number of items, but for Chrome/Safari it is not more than 20

A: I'd suggest changing:
var template = $('.queue_item').clone();

to this:
var template = $('.queue_item').first().clone();

The way you have it now, you are cloning every single .queue_item so as you add more and more, you are creating a lot of unnecessary clones when you really only mean to create one new clone each time to use as a template.  If you did this 20 times on the previous results each time, you could end up with 2^20 cloned elements which would be over a million objects.


text:
Q: Rails model create action shows id as nil I have a Rails 3 app where in a Model I'm creating a Comment record.
I then want to email the new Comment.
This is my model code:
  before_create :worequest_comment

  protected
  def worequest_comment
    if self.workorder.worequest_id != nil
      if self.internal_only == false
        newcomment = Comment.create({:worequest_id => self.workorder.worequest_id, :comments => self.log_desc, :status_date => DateTime.now, :user_id => self.employee.user_id})
        CommentMailer.comment_email(newcomment).deliver if self.workorder.worequest.employee_id != nil
      end
    end
  end
end

But, newcomment variable doesn't show the comment.id
See this:

Thank for your help!

A: This is because you are referring comment_id of object before saving object to db, since before_create execute in the context where record is not created/saved in the database.
Changing before_create :worequest_comment to after_create :worequest_comment should work

A: I moved the CommentMailer to the Comment model:
  after_create :comment_email

  protected
  def comment_email
    if !self.worequest.employee_id.nil?
      if Worequest.find(self.worequest_id).employee_id != nil
        Comment2Mailer.comment2_email(self.id).deliver
      end
      if Worequest.find(self.worequest_id).r_send == true
        CommentMailer.comment_email(self.id).deliver
      end
      if self.statuscode_id != nil
        Worequest.find(self.worequest_id).update_attributes(:statuscode_id => self.statuscode_id)
      end
    end
  end


text:
Q: Why should I (not) put my extension into app/code? a dumb question.
From: https://devdocs.magento.com/guides/v2.4/extension-dev-guide/build/module-file-structure.html

Magento installs third-party components in the <Magento install directory>/vendor directory. But we recommend adding your components to the <Magento install directory>/app/code directory. If you add your component to the <Magento install directory>/vendor directory, Git will ignore it because Magento adds the vendor directory to the <Magento install directory>/.gitignore file.

Why is it recommended to put code into app/code instead of creating a git repo and add it via composer.json?
All my code lives in repos. I do my changes there and just adjust composer.josn/composer.lock for my magento project.
I only see downsides using app/code directly. It's not update-safe as composer requirements are ignored. It makes my the repo bigger. I have an "unclean" commit log (even with squashed commits that only belong to extensions).

*

*What are the PROs and CONs of using app/code?

*What are the PROs and CONs of using composer?

A: IMHO, the way I see it is this:
app/code
wild-guess PROs:

*

*possibly a leaner/ easier learning curve for juniors. But wouldn't recommend this, even if the person learning Magento is a beginner, they should go from day 1 with learning what composer is, play with it, then go and write Magento code.

*possibly easier to find your code in the project - again for juniors who might be overwhelmed with seeing so many modules and vendors.

*possibly a more familiar approach for people coming from M1 development, where they were accustomed to writing code in app/code.

CONs:

*

*breaks the update strategy

*ignores version or libs dependencies

*hard to maintain if every custom module resides in a different repo and different versions are needed

*I saw projects where the whole Magento install was versioned :O :O just because the developers added the code to app/code.

*brings inconsistencies in the project.

*I saw also many times projects where 3rd party modules were added here manually - imagine what happens here if a change is needed. If that module is not versioned, it's  very difficult to tell whether the native code was altered manually.

vendor
definitely PROs:

*

*would go 100% with this approach in both development and production. Approach should be the same, regardless of the environment using the code - so no inconsistencies.

*dependencies are respected and this is a major plus - it's very easy to see that you have incompatibilities, missing stuff, BEFORE something breaks :)

*you can require as many custom modules as you need and still be able to update them from just running a single command.

*seamless code update on any environment, no need to write lists of commands for defining update procedures for different modules, etc

*code becomes easy to move around on any environment, just add the composer.json + composer.lock, run a composer install and VOILA, you have a brand new env 100% the same as the other one(s).

*if 'accidental' manual changes are added to the native code of a module, it's easy to remove the module and reinstall it from CLI, no need to unpack, jump through hoops and whatnot.

*ease in using different module versions on different envs/ projects

*everything is in one place :)

CONs:

*

*can't really come up with any TBH.


text:
Q: Uploading multiple files in parallel to Amazon S3 with Goroutines & Channels I'm trying to upload a directory into Amazon S3 bucket. However, the only way to upload a directory is to iterate through all the files inside the directory and upload them one by one.
I'm using Go to iterate over the files in directory. However, for each file I iterate through, I want to spin off a goroutine that uploads the file while the main thread iterates through the next element in the directory and spins off another goroutine to upload the same.
Any idea on how I can upload all the files in the directory parallelly using Goroutines and Channels?
Revised code snippet that implements a goroutine and a channel to upload files in parallel. But I'm not sure if this is the right implementation.
func uploadDirToS3(dir string, svc *s3.S3) {
    fileList := []string{}
    filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
        fmt.Println("PATH ==> " + path)
        fileList = append(fileList, path)
        return nil
    })
    for _, pathOfFile := range fileList[1:] {
        channel := make(chan bool)
        go uploadFiletoS3(pathOfFile, svc, channel)
        <-channel
    }
}

func uploadFiletoS3(path string, svc *s3.S3, channel chan bool) {
    file, err := os.Open(path)
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()
    fileInfo, _ := file.Stat()
    size := fileInfo.Size()

    buffer := make([]byte, size)
    file.Read(buffer)
    fileBytes := bytes.NewReader(buffer)
    fileType := http.DetectContentType(buffer)

    s3Path := file.Name()

    params := &s3.PutObjectInput{
        Bucket:        aws.String("name-of-bucket"),
        Key:           aws.String(s3Path),
        Body:          fileBytes,
        ContentLength: aws.Int64(size),
        ContentType:   aws.String(fileType),
    }

    resp, err := svc.PutObject(params)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("response %s", awsutil.StringValue(resp))
    close(channel)
}

Any ideas on how I could implement this better? I've looked into WaitGroups but for some reason, I found Channels much easier to understand and implement in this situation.

A: So, you are looking for concurrency, which is rooted in go instruction. For synchronization between started in loop goroutine, you can use chanels OR sync.WaitGroup. The second option is a little bit easier to do.
Also you have to refactor your function and move internal for logic into a separate function.
func uploadDirToS3(dir string, svc *s3.S3) {
    fileList := []string{}
    filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
        fileList = append(fileList, path)
        return nil
    })
    var wg sync.WaitGroup
    wg.Add(len(fileList))
    for _, pathOfFile := range fileList[1:] {
        //maybe spin off a goroutine here??
        go putInS3(pathOfFile, svc, &wg)
    }
    wg.Wait()
}

func putInS3(pathOfFile string, svc *s3.S3, wg *sync.WaitGroup) {
    defer func() {
        wg.Done()
    }()
    file, _ := os.Open(pathOfFile)
    defer file.Close()
    fileInfo, _ := file.Stat()
    size := fileInfo.Size()
    buffer := make([]byte, size)
    file.Read(buffer)
    fileBytes := bytes.NewReader(buffer)
    fileType := http.DetectContentType(buffer)
    path := file.Name()
    params := &s3.PutObjectInput{
        Bucket:        aws.String("bucket-name"),
        Key:           aws.String(path),
        Body:          fileBytes,
        ContentLength: aws.Int64(size),
        ContentType:   aws.String(fileType),
    }

    resp, _ := svc.PutObject(params)
    fmt.Printf("response %s", awsutil.StringValue(resp))
}

A:
Following does not strictly speaking answer the OP, however its an attempt to introduce parallel processing using the go language.
hope this helps.
package main

import (
    "log"
    "sync"
    "time"
)

func main() {

    // processInSync()
    // The processing takes up to 3seconds,
    // it displays all the output and handles errors.

    // processInParallel1()
    // The processing takes up to few microseconds,
    // it displays some of the output and does not handle errors.
    // It is super fast, but incorrect.

    // processInParallel2()
    // The processing takes up to 1s,
    // It correctly displays all the output,
    // But it does not yet handle return values.

    processInParallel3()
    // The processing takes up to 1s,
    // It correctly displays all the output,
    // and it is able to return the first error encountered.

    // This merely just an introduction to what you are able to do.
    // More examples are required to explains the subtletlies of channels
    // to implement unbound work processing.
    // I leave that as an exercise to the reader.
    // For more information and explanations about channels,
    // Read The Friendly Manual and the tons of examples
    // we left on the internet.
    // https://golang.org/doc/effective_go.html#concurrency
    // https://gobyexample.com/channels
    // https://gobyexample.com/closing-channels
}

func aSlowProcess(name string) error {
    log.Println("aSlowProcess ", name)
    <-time.After(time.Second)
    return nil
}

//processInSync a dummy function calling a slow function one after the other.
func processInSync() error {
    now := time.Now()
    // it calls the slow process three time,
    // one after the other;
    // If an error is returned, returns asap.
    if err := aSlowProcess("#1"); err != nil {
        return err
    }
    if err := aSlowProcess("#2"); err != nil {
        return err
    }
    if err := aSlowProcess("#3"); err != nil {
        return err
    }
    // This is a sync process because it does not involve
    // extra synchronisation mechanism.
    log.Printf("processInSync spent %v\n", time.Now().Sub(now))
    return nil
}

// processInParallel1 implements parallel processing example.
// it is not yet a fully working example, to keep it simple,
// it only implements the sending part of the processing.
func processInParallel1() error {
    now := time.Now()

    // We want to execute those function calls in parallel
    // for that we use the go keyword which allows to run the function
    // into a separate routine/process/thread.
    // It is called async because the main thread and the
    // the new routines requires to be synchronized.
    // To synchronize two independant routine we must use
    // atomic (race free) operators.

    // A channel is an atomic operator because it is safe to
    // read and write from it from multiple parallel
    // and independant routines.

    // before we implement such processing, we must ask ourselve
    // what is the input i need to distribute among routines,
    // and what are the values i want to get from those routines.

    // lets create a channel of string to distribute the input to multiple
    // independant workers.
    distributor := make(chan string)

    // The input channel MUST be read from the new routines.
    // We create three workers of slow process, reading and processing.
    go func() {
        value := <-distributor
        aSlowProcess(value)
    }()
    go func() {
        value := <-distributor
        aSlowProcess(value)
    }()
    go func() {
        value := <-distributor
        aSlowProcess(value)
    }()

    // we must now write the values into the distributor
    // so that each worker can read and process data.
    distributor <- "#1"
    distributor <- "#2"
    distributor <- "#3"

    log.Printf("processInParallel1 spent %v\n", time.Now().Sub(now))

    return nil
}

// processInParallel2 implements parallel processing example.
// it is not yet a fully working example, to keep it simple,
// it implements the sending part of the processing,
// and the synchronization mechanism to wait for all workers
// to finish before returning.
func processInParallel2() error {
    now := time.Now()

    // We saw in the previous example how to send values and process
    // them in parallel, however, that function was not able to wait for
    // those async process to finish before returning.

    // To implement such synchronization mechanism
    // where the main thread waits for all workers to finish
    // before returning we need to use the sync package.
    // It provides the best pattern to handle that requirements.

    // In addition to the previous example we now instantiate a
    // WaitGroup https://golang.org/pkg/sync/#WaitGroup
    // The purpose of the wait group is to record a number
    // of async jobs to process and wait for them to finish.

    var wg sync.WaitGroup

    distributor := make(chan string)

    // Because we have three workers, we add three to the group.
    wg.Add(1)
    go func() {
        // Then we make sure that we signal to the waitgroup
    // that the process is done.
        defer wg.Done()
        value := <-distributor
        aSlowProcess(value)
    }()
    //-
    wg.Add(1)
    go func() {
        defer wg.Done() // as an exercise, comment this line
    // and inspect the output of your program.
        value := <-distributor
        aSlowProcess(value)
    }()
    //-
    wg.Add(1)
    go func() {
        defer wg.Done()
        value := <-distributor
        aSlowProcess(value)
    }()

    // we can now write the data for processing....
    distributor <- "#1"
    distributor <- "#2"
    distributor <- "#3"

    //....and wait for their completion
    wg.Wait()

    log.Printf("processInParallel2 spent %v\n", time.Now().Sub(now))

    return nil
}

// processInParallel3 implements parallel processing example.
// It is a fully working example that distribute jobs,
// wait for completion and catch for return values.
func processInParallel3() error {
    now := time.Now()

    var wg sync.WaitGroup
    distributor := make(chan string)

    // To catch for return values we must implement a
    // way for output values to safely reach the main thread.
    // We create a channel of errors for that purpose.
    receiver := make(chan error)

    // As previsouly we start the workers, and attach them to a waitgroup.
    wg.Add(1)
    go func() {
        defer wg.Done()
        value := <-distributor
        err := aSlowProcess(value)
        // to return the value we write on the output channel.
        receiver <- err
    }()
    //-
    wg.Add(1)
    go func() {
        defer wg.Done()
        value := <-distributor
        receiver <- aSlowProcess(value)
    }()
    //-
    wg.Add(1)
    go func() {
        defer wg.Done()
        value := <-distributor
        receiver <- aSlowProcess(value)
    }()

    // we can now write the data for processing....
    distributor <- "#1"
    distributor <- "#2"
    distributor <- "#3"

    /// ... read the output values
    err1 := <-receiver
    err2 := <-receiver
    err3 := <-receiver

    //....and wait for routines completion....
    wg.Wait()

    log.Printf("processInParallel3 spent %v\n", time.Now().Sub(now))

    // finally check for errors
    if err1 != nil {
        return err1
    }
    if err2 != nil {
        return err2
    }
    if err3 != nil {
        return err3
    }

    return nil
}


text:
Q: How to validate duplicates in nestjs dto? In the Nest js create dto I receive two properties name and age. I need to validate if user with name and age already exists should trough 400 error "duplicate values".
Like in table we have name: "John", age: 20
and we create user with the same value/combination "John" and 20, it should show error.
I tried to use validation check NameExists but do not know how to take values for both, I only take for one.
https://dev.to/avantar/custom-validation-with-database-in-nestjs-gao
@IsNotEmpty({
    message: 'Name is missing',
  })
  @MinLength(5, {
    message: 'Name is too short. Select name longer than 5 characters.',
  })
  @UserExists()
  name: string;

@IsNotEmpty({
    message: 'Age is missing.',
  })
  @IsInt()
  @Transform(({ value }) => Number(value))
  age: number;

A: In this example, you could see how to access other properties of the object in your custom decorator.
https://github.com/typestack/class-validator#custom-validation-decorators
However, my choice, in this case, would be to create proper unique indexes in the database and handle the DB error as you could encounter race conditions if 2 requests will come with the same user name and age at the same time.


text:
Q: Difficulty passing struct to a function Though there are many threads on this matter, i cannot find one that addresses my question, apologies if im being thick.  An important distinction is that my solution cannot use pointers.  I've started the chapter on structures and the problem i am working on calls for a function that takes two arguments t1 and t2, which are two different times in the framework of a structure.  ive reduced that code as much as possible, and am finding that the values of my struct items arent getting through to the function.
#include<stdio.h>

struct time
{
    int hour;
    int minute;
    int second;
};

struct time t1 = {3, 45, 15};
struct time t2 = {9, 44, 03};

int main (void)
{
    struct time elapsedTime(struct time t1,struct time t2);

    return 0;
}

struct time elapsedTime(struct time t1,struct time t2)
{
    printf ("%i:%i:%i\n", t1.hour, t1.minute, t1.second);
    printf ("%i:%i:%i\n", t2.hour, t2.minute, t2.second);

    return;
}

A: You never called your function
elapsedTime( t1, t2 );

A: You are declaring the function in main, but not calling it.
Instead of:
int main (void)
{
    struct time elapsedTime(struct time t1,struct time t2);

    return 0;
}

You need:
struct time elapsedTime(struct time t1,struct time t2);

int main (void)
{
    struct time mt = elapsedTime(t1, t2);

    // Do something with mt...

    return 0;
}

A more common way to return a "bulky" data item would be as a pointer:
typedef struct my_time {
    int hour;
    int minute;
    int second;
} my_time_t;

void elapsedTime(my_time_t t1, my_time_t t2, my_time_t *t3)
{
    t3->hour = ...;
    t3->minute = ...;
    t3->second = ...;

    ...
}

NOTE: I would strongly recommend avoiding a generic, common name such as time for your struct since it has the potential of conflicting with some system defined value (now or later). Avoid naming your own variables names like like time, file, string, etc...

A: I have found a solution:
#include<stdio.h>

struct time
{
  int hour;
  int minute;
  int second;
};

void elapsedTime(struct time t1, struct time t2)
{
  printf("%i:%i:%i\n", t1.hour, t1.minute, t1.second);
  printf("%i:%i:%i\n", t2.hour, t2.minute, t2.second);
}

int main()
{
  struct time t1 = { 3, 45, 15 };
  struct time t2 = { 9, 44, 03 };
  elapsedTime(t1, t2);
  return 0;
}

Compiles to the expected result for me.
As other have said, you need to call the function with just elapsedTime(t1, t2);.
EDIT:
To get what you said in your comment below with pointers, you can use the following concept:
struct time
{
  int hour;
  int minute;
  int second;
};

void elapsedTime(struct time t1, struct time t2, struct time *t3)
{
  printf("%i:%i:%i\n", t1.hour, t1.minute, t1.second);
  printf("%i:%i:%i\n", t2.hour, t2.minute, t2.second);
  t3->hour = 100;
  t3->minute = 50;
  t3->second = 25;
}

int main()
{
  struct time t1 = { 3, 45, 15 };
  struct time t2 = { 9, 44, 03 };
  struct time t3 = { 0, 0, 0 };

  elapsedTime(t1, t2, &t3);
  printf("%i:%i:%i\n", t3.hour, t3.minute, t3.second);
  return 0;
}

As you can see I passed a third struct to the function and change the struct values by reference in the function. (The values get changed outside of the function)
Then I print the struct outside of the function to check whether it worked.
Hope this will help when you can use pointers.

A: Most likely the behavior described is caused by hiding the global variables t1 and t2 with the parameters of identical name. (There are other problems with the code as written that others have covered).
I would change the argument names ,for example:
struct time t1 = {3, 45, 15};
struct time t2 = {9, 44, 03};

struct time elapsedTime(struct time time1,struct time time2)


text:
Q: When TestComplete is opened I Could not create Java Virtual Machine Problem Description:
My Java application is launched using a .cmd file from a network path. It gets launched without any issues. But if I open TestComplete tool and then try to open the application, I get an error as "Could not create the Java Virtual Machine" as a popup with ok button. Upon clicking ok, the application process gets closed. Infact there is only option to click Ok:).
Environment Info:
I use TestComplete to automate a Windows based java application. The Java application is developed using Java 1.6 and TestComplete version is 10.5. The system is of Windows 7 64 bit. JRE in the local machine is of version 1.7
Understandings by googling:
My application is needs a JVM (Java Virtual Machine) with a heap memory of 1GB. TestComplete is somehow not letting it happen.
Trials Attempted:
1.Tried editing the heap size in Java control panel located in control panel with -Xmx1024m.
Does something rings for someone?


text:
Q: find ASP.NET dynamically created radio button selected value using javascript I use VS2010,C# to develop my ASP.NET web app, I'm creating a vote page for my users, I get some questions from my DB, each question is displayed in a dynamically created row, also there are 5 options (very good, good, bad....), user must select one. I use following code to create a radio button for each choice, of course all five radio buttons of a row have a unique group name:
                tr = new TableRow();
            tr.HorizontalAlign = HorizontalAlign.Right;

            tc = new TableCell();
            tc.HorizontalAlign = HorizontalAlign.Center;
            RadioButton r = new RadioButton();
            r.Text = "";
            r.GroupName = i.ToString();
            tc.Controls.Add(r);
            tr.Cells.Add(tc);

            tc = new TableCell();
            tc.HorizontalAlign = HorizontalAlign.Center;
            r = new RadioButton();
            r.Text = "";
            r.GroupName = i.ToString();
            tc.Controls.Add(r);
            tr.Cells.Add(tc);

// five radio buttons are created in each row

now I'm going to find user choices, I think the best approach is using a JavaScript function to find selected value for each question, then perform the calculations, how can I do so? I don't want to use AutoPostback for radio buttons as it can be really slow,
thanks

A: Just add a submit button. In the submit event handler, use c# to browse through the controls and get the selected values. You don't need JavaScript for this.
Update
Basically, you will need to assign some similar names to your dynamically generated controls. I.E. Question1Radio1, Question1Radio2, etc..
After that you can use the Request.Form method to retrieve the values from the radio buttons by calling Request.Form("Question1Radio1"), Request.Form("Question1Radio2"), etc.. in your submit handler.


text:
Q: InkWell not working with a background image I am building my first Flutter app and I would like to create a simple layout: a background image and a translucent Material Button on top of it.
My Widget tree is pretty simple, but the InkWell / Ripple is not visible. Why do I have this behaviour ?
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Material(
      child: new Stack(
        children: <Widget>[
          new Container(
              decoration: new BoxDecoration(
                  image: new DecorationImage(
            image: new AssetImage("res/imgs/splashscreen_bg.png"),
            fit: BoxFit.cover,
          ))),
          new Center(
              child: new FlatButton(
                  onPressed: () {}, child: new Text("Hello world")))
        ],
      ),
    );
  }
}

Without the background image, the InkWell is working.
What should I do?
Thanks

A: After a few researches, I have found this issue: https://github.com/flutter/flutter/issues/3782
And if I change the Widget content with this new tree, it now works:
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
      return new Stack(
        children: <Widget>[
          new Container(
              decoration: new BoxDecoration(
                  image: new DecorationImage(
            image: new AssetImage("res/imgs/splashscreen_bg.png"),
            fit: BoxFit.cover,
          ))),
          new Material(
            type: MaterialType.transparency,
          child: new FlatButton(...),
          )
        ],
    );
  }
}

A: There was a recent update to support this: https://github.com/flutter/flutter/pull/13900. I'm not sure if it has made its way to alpha yet, but it should solve your issue.


text:
Q: unable to get data from postgres using pg-promise and vue.js I want to use pg_promise with feathersjs and vuejs to display results of query run on postgres db, my sql.js looks as follows
sql.js
const express = require('express');
const jsonexport = require('jsonexport');
const dbgeo = require('dbgeo');
const router = express.Router();
function dbGeoParse(data) {
  return new Promise((resolve, reject) => {
    dbgeo.parse(
      data,
      {
        outputFormat: 'geojson',
      },
      (err, result) => {
        if (err) {
          reject(err);
        } else {
          resolve(result);
        }
      },
    );
  });
}

// expose sql endpoint, grab query as URL parameter and send it to the database
router.get('/sql', (req, res) => {
  const { app } = req;
  const sql = req.query.q;
  const format = req.query.format || 'topojson';
  console.log(`Executing SQL: ${sql}`, format); // eslint-disable-line

  // query using pg-promise
  app.db
    .any(sql)
    .then((data) => {
      console.log('data',data)
      // use dbgeo to convert WKB from PostGIS into topojson
          return dbGeoParse(data).then((geojson) => {
            res.setHeader('Content-disposition', 'attachment; filename=query.geojson');
            res.setHeader('Content-Type', 'application/json');
            return geojson;
          });
    })
    .then((data) => {
      res.send(data);
    })
    .catch((err) => {
      // send the error message if the query didn't work
      const msg = err.message || err;
      console.log('ERROR:', msg); // eslint-disable-line
      res.send({
        error: msg,
      });
    });
});

module.exports = router;

I have configured my app.js to use sql.js as a route by adding following lines to it
const pgp = require('pg-promise')({
  query(e) {
    console.log(e.query); // eslint-disable-line
  },
});
const connectionString = 'postgres://abc:abc123@localhost:5678/gisdb';
// initialize database connection
const app = express(feathers());
app.db = pgp(connectionString);
app.use('/sql', require('sql'));

but when I call handleSubmit fuction shown below from my vue component
handleSubmit() {
    const SQL = "select * from spatial_search(searchmethod := 'id',sale_price :=10000,tax_ogcid :=
84678,distance := 0.5)";
    const queryType = 'sql';

    fetch(`/${queryType}?q=${encodeURIComponent(SQL)}`)
      .then(res => {console.log('res',res.json())})}

I get the following error
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I think I might be doing something wrong here. Can someone help me?


text:
Q: Do I need a comma for this quotation? Do I need a comma before the quotation, or can I write without it? This is the sentence:

Someone, not so long ago said, "Simply put: If you're doing business with the biggest companies in the world, you're not just spending time in New York, London, and Hong Kong"

A: According to the Oxford Dictionary:

If direct speech comes after the information about who is speaking, you should use a comma to introduce the piece of speech, placed before the first inverted comma:
Steve replied, 'No problem.'

So yes, you need a comma there.


text:
Q: Alias setup -bash: vm: command not found In the Build Larabook from scratch Laracast tutorial, it is required to synchronize the local folder of the app with the virtual machine (Homestead) and vice versa.
To simplify development, the tutorial recommends to create the following alias:
ssh vagrant@127.0.0.1 -p 2222

by placing alias vm="ssh vagrant@127.0.0.1 -p 2222" in an ~/.aliases file, which I did.
This lets the narrator simply type the vm command from the local app folder to launch the virtual machine.
When I try to do so, I get -bash: vm: command not found
Did I miss something?


text:
Q: Ruby on Rails generating controller with existing folder I'm really new at this and I don't want to mess up my current application. I'm currently working on HTML/CSS stuff but I have a little understanding as to how to get things working.
I created a new controller by just doing
rails generate controller sign_up

I've created a index file (index.html.erb) inside sign_up folder from rails that automatically generated. Now I wanted to add more files, can I just add more files by typing in
rails generate controller sign_up send_page more_page other_pages

Will send_page, more_page, other_pages be automatically combined into the existing sign_up folder? Is this the correct way of adding pages if I want rails to add other files automatically? I just want it to ruin what I have so far so I don't want to try it for myself because I'm still really new to this,
Thanks!

A: To answer your question :
New files will be added to the existing folder but existing files will not be merged, you'll have to resolve the conflict by choosing between old and new files.
It seems to me you're trying to use generators for every action you need in your app :
Scaffolding is great to have a sample structure, but as soon as you start building your controller for real you need to move away from it : extend the controllers, models and views by hand. It's the only way you'll start to really understand how things are working.

A: If you run the generator again, it's going to complain about conflicts with existing files.  Then you'll have to choose to overwrite (losing your existing changes to e.g. the controller), or not (in which case you won't get the new auto-generated methods, etc.).
You can just create a new controller action and a new view for each additional page you want to add (and a unit test, of course!).  If you're using non-standard/non-restful action names, you'll also have to edit config/routes.rb to route them.
Looking at the names in your example, and your reference to "pages", I suspect what you really may want to do is create separate controllers for send_page and more_page.  If that's the case, you'd run the generator separately for each new controller.


text:
Q: Mongo filter results by distinct field I use this ruby driver for mongo : https://github.com/mongodb/mongo-ruby-driver
I have many documents in a collection like this :
{
  "_productId" => 10
  ....
}
{
  "_productId" => 10
  ....
}
{
  "_productId" => 12
  ....
}

What is the request to get all documents with a distinct "_productId", I mean I want to take the first and the last collection item in this exemple.

A: @db['collection'].distinct('_productId')
http://docs.mongodb.org/manual/reference/method/db.collection.distinct/
http://wiki.summercode.com/mongodb_aggregation_functions_and_ruby_counting_and_grouping

A: With the basis of selecting a document from a group being unknown, and assuming the first document for each productid to be selected is based on their insertion order, you can use the aggregation $group,$project operators together.
Group all the records based on their productId, choose the first document from each group.
db.collection.aggregate([
{$group:{"_id":"$_productId","distinct_doc":{$first:"$$ROOT"}}},
{$project:{"distinct_doc":1,"_id":0}}
])

If you have an _id field for each document, the first document would be the one which was inserted first for that particular group. If you choose to do it based on some other field, then you would need to perform an additional $sort operation before you group the records.
for example,
db.collection.aggregate([
{$sort:{"someField":1}},
{$group:{"_id":"$_productId","distinct_doc":{$first:"$$ROOT"}}},
{$project:{"distinct_doc":1,"_id":0}}
])

In this case the first document per group, would be the one which comes top when sorted.


text:
Q: GroupBy with MVC Scaffolding Background
I am currently working on an MVC project, in which I am looking to display a list of films and times in which they will be programmed to play. In order to achieve this, I have a basic table for this (summarised):
+-------------+----------------+
| FilmID (int)| Time (datetime)|
+-------------+----------------+
|  1          | 01:00          |
|  1          | 03:00          |
|  2          | 02:30          |
+-------------+----------------+

This is linked to a 'FilmStore' in which basically gives information relating to synopsis/genre/etc.
Controller
I have set up a controller with the automatically-generated code:
public ActionResult Index()
{
    var filmShowings = db.FilmShowings.Include(f => f.FilmStore);

    return View(filmShowings.ToList());
}

View
I have altered the preset view to
@foreach (var item in Model)
{
    @Html.DisplayFor(modelItem => item.FilmID)

       @Html.DisplayFor(modelitem => item.Time).ToString().Substring(0, 5)

}

What I want
I am looking to groupBy the filmID within the view. So The filmID will display in a span, and for every record with that filmID will be displayed within a div. Something like:
1
   01:00
   03:00
2
   02:30

What I've Tried
I have tried to add a groupby clause into the controller:
.GroupBy(f => f.FilmID);

and altered my view to:
  @foreach (var item in Model)
    {
            @Html.DisplayFor(modelItem => item.FilmID)
            @foreach(var group in groupItem.FilmID){

                   @Html.DisplayFor(myitem => group.Time).ToString().Substring(0, 5)

            }
    }

I presumed a nested for loop would have allowed me to add this grouping. However, this inevitably failed. Would anyone be able to even point me in the right direction?

A: You can do this in 2 ways:

*

*Have your strongly typed model grouped by Film ID, ex: you will have a class that has 2 properties, FilmID and List, in your controller, you will retrieve the data and group it by FilmID and fill your model then pass it to the view and draw it the same way you did but instead of groupBy, You will simply iterate over the model using foreach and inside the foreach you will iterate over the list of times.

*Keep it as is without group by, and add a collapse/expand icon and on clicking the icon, fire an Ajax request passing the film ID and retrive the content as Partial view and draw this content in a span below the film ID, this option is better from performance perspective

A: The return of GroupBy is IEnumerable<IGrouping<TKey, TSource>>. Which means you end up essentially with a list of lists. The implementation of IGrouping will itself be an IEnumerable with the addition of a Key property, which will hold the value of the property you grouped by.
So, for your example, you would need to iterate over all the groups, and then for each group, iterate over the items in that group.
@foreach (var group in Model)
{
    @Html.DisplayFor(modelItem => group.Key)
    @foreach(var item in group){

           @Html.DisplayFor(myitem => item.Time).ToString().Substring(0, 5)

    }
}


text:
Q: Compile a simple program on ubuntu arm I have a simple program
#include <glib.h>
int main(){
  g_print("hallo\n");
}

and try to compile it on the embedded system (Odroid X2) with Ubuntu like that
root@odroid:~/# gcc $(pkg-config --libs --cflags glib-2.0) -o main main.c
/tmp/cci48ASK.o: In function `main':
main.c:(.text+0xc): undefined reference to `g_print'
collect2: error: ld returned 1 exit status

Installed compiler:
root@odroid:~/x# gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/arm-linux-gnueabihf/4.7/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.7.3-1ubuntu1' --with-bugurl=file:///usr/share/doc/gcc-4.7/README.Bugs --enable-languages=c,c++,go,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.7 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.7 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --disable-libitm --enable-plugin --with-system-zlib --enable-objc-gc --with-cloog --enable-cloog-backend=ppl --disable-cloog-version-check --disable-ppl-version-check --enable-multiarch --enable-multilib --disable-sjlj-exceptions --with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard --with-mode=thumb --disable-werror --enable-checking=release --build=arm-linux-gnueabihf --host=arm-linux-gnueabihf --target=arm-linux-gnueabihf
Thread model: posix

Any ideas why the linker does not find the reference?

A: The order of options to gcc (and other compilers) matters.
gcc -Wall main.c $(pkg-config --libs --cflags glib-2.0) -o main

And I don't really like the above. You should learn how to use GNU make. At the very least, put the compile flags, then the sources, then the object files, then the libraries (from high level to low level).
gcc -Wall $(pkg-config  --cflags glib-2.0) main.c \
    $(pkg-config --libs glib-2.0) -o main

Better yet, have a Makefile starting with
CC=gcc
CFLAGS= -Wall  $(pkg-config  --cflags glib-2.0)
LIBES= $(pkg-config --libs glib-2.0)

And compiling as root should be avoided. Only installation should require root privilege...
You probably want to add -g (compiler flag for debugging information). Once the program is ready and nearly bugfree, replace it with -O2 (optimizations) and do some serious testing again!

A: Ok found a solution
gcc -o main main.c  `pkg-config --libs --cflags glib-2.0`

works, but I don't know why on my X64 linux system it worked also the other way.

A: You need to add the $(pgk-config --libs glib-2.0) after the main.c in your compile line - because library functions are only dragged into the binary if there is anything using them - so main.c is what is using the g_print, and if the -lglib (or whatever the result of the pkg-config bit is) is before main.c, it doesn't get included in the resulting binary.


text:
Q: How to optimize a for loop to fill a data frame R I have a data frame where I compute a distance matrix.
bb=data.frame(Name=paste0('row',1:10),col1=rnorm(10),col2=2*rnorm(10),col3=5*rnorm(10))
dis <- dist(bb[1:nrow(bb),3:ncol(bb)], method = "euclidean")

From the computed distance matrix, I create a list showing the distance between every point.
library(reshape2)
df=melt(as.matrix(dis), varnames = c("row", "col"))

From this, I make a loop to extract the comparison of each point, and normalize based on the values. I then fill a data frame so I get all of them in a single source.
s=NULL
for(i in 1:10){
  w=df[df$row==i&df$col!=i,]
  w=w[order(w$value),]
  w[,3]=(w[,3]-min(w[,3]))/(max(w[,3])-min(w[,3])) # there are a few other computations as well, but not included here for simplicity
  s=rbind(s,w)
}

At the end, I want to be able to have a single table which can be used in another program which has this format.
> head(s,10)
   row col      value
71   1   8 0.00000000
61   1   7 0.08982679
41   1   5 0.25082060
31   1   4 0.42078163
11   1   2 0.53509305
21   1   3 0.61867437
51   1   6 0.67420271
81   1   9 0.69711889
91   1  10 1.00000000
22   2   3 0.00000000

My real data has 3K rows and 1.2k columns, and processing time is very slow. Is there a more efficient way of performing a calculation on certain subsets of the dataframe, df, such that I end up with the same at the end.
I have heard that for loops should not be used to grow a data frame, so am curious if there is a more efficient way of doing this.

A: You would probably be better start thinking in vectorized mode.
What you are doing is performing an operation on every row that involves other values on the same row, or simple aggregates like max and min.
The packages dplyr or data.table help you doing so.

With dplyr:
# Take only the rows where col is different from row
df <- filter(.data = df, row != col)

# Group by the col variable, usedto isolate each group
df <- group_by(.data = df, col)

# Create a new var 'value2' with the result of the operation
# Note that min and max refers only to the specific group
df <- mutate(.data = df, value2 = (value-min(value))/(max(value) - min(value)))

What is nice with dplyr is that you can concatenate these steps using %>%, where the first argument(.data) of the next function is the result of the last operation:
df %>%
    filter(row != col) %>%
    group_by(col) %>%
    mutate(value2 = (value-min(value))/(max(value) - min(value)))

With data.table:
df <- data.table(df)
df[row!=col, .(value2 = (value-min(value))/(max(value) - min(value))), by=col]

[Pls note I'm not that good with data.table, there may be better ways to do it]


text:
Q: get file location in android? I use the following code to check file availability
    File f1=new File("/data/data/com.myfiledemo/files/settings.dat");
    if(f1.exists())
    textview.setText("File Exist");

If i use the following code it's not responding
   File f1=new File("settings.dat");
   if(f1.exists())
   tv.setText("File Exist");

Here com.myfiledemo is my application package . I simply create the file like this
   fileInputstream = openFileInput("settings.dat");

why It's not responding for the second if condition.??Is it Wrong??

A: The second code snippet is not the correct way to use, If you insist on using a java.io.File object, it should be:
File f1=new File(context.getFilesDir(), "settings.dat");
if(f1.exists()) {
  tv.setText("File Exist");
}

A: If you create the file by using openFileInput, then this is the way to check whether the file exists or not:
FileInputStream input = null;
try{
    input = openFileInput("settings.dat");
}
catch(FileNotFoundException e){
    // the file does not exists
}

if( input != null ){
    tv.setText("File Exist");
}


text:
Q: WMIC mystery - why is this query invalid? Why is this an invalid query?
wmic service where 'caption like "%documentum%"' get name, caption

Node - PE95AOECM
ERROR:
Description = Invalid query

This is the expected output:
Caption                                 Name
EMC Documentum Thumbnail Server         DctmThumbnailServer
Documentum Docbroker Service Docbroker  DmDocbroker
Documentum Java Method Server           DmMethodServer
Documentum Docbase Service KxKDOC_DEV   DmServerKxKDOC_DEV
Documentum Docbase Service KxKTAX_DEV   DmServerKxKTAX_DEV
Documentum Docbase Service KxK_Dev      DmServerKxK_Dev
Documentum Docbase Service KxK_Dev_HRP  DmServerKxK_Dev_HRP
Documentum Docbase Service KxK_Dev_TAX  DmServerKxK_Dev_TAX

If I modify the query slightly I do in fact get a valid response similar to the above:
removed the first %
wmic service where 'caption like "documentum%"' get name, caption

added a space after documentum
wmic service where 'caption like "%documentum %"' get name, caption

removed the last m of documentum
wmic service where 'caption like "%documentu%"' get name, caption

and as an example of a similar case where I query for the first word of a multi-word caption is successful
wmic service where 'caption like "%group%"' get name, caption

Caption              Name
Group Policy Client  gpsvc

A: Try an echo wmic service where 'caption like "%documentum%"' get name, caption and you can see what's going on. You can also do echo %documentum%.
(It should echo the exact command back, including the %documentum%)
Maybe you have an environment variable named documentum.
(environment variables have precedence over the command parameters. So if they are present, they get substituted.)
You can do set documentum= and then execute the line to empty the variable (if set).


text:
Q: Catalog Price Rules: Why my rule has not effect? I'm on Mage 1.8 with custom data.

*

*I have created a catalog rule that give 10% discount when sku = 'n2610' ( relative product id is 16 )

*saved the rule

*apply all the rule

Now I m testing the rule with the following code:
<?php
require_once './app/Mage.php';
umask(0);
Mage::app();
//Mage::setIsDeveloperMode(true);

$rule = Mage::getModel('catalogRule/rule')->load(5);

var_dump($rule->getData());
var_dump($rule->getMatchingProductIds());

getMatchingProductIds() gives me back an array() with all prod. here the part for the interested product.
RESULT:
16 =>
array (size=3)
  0 => int 0
  1 => int 0
  2 => int 0

I expect that the array contains some 1.
If I debug the following method, I can see that the $validatedValue is always empty so the rule never match.
Mage_Rule_Model_Condition_Abstract::validateAttribute($validatedValue)
Anyone can point me to the error ? is it a bug on 1.8 ( I'm quite sure I haven't touched any core file.)

A: According to this answer:
https://stackoverflow.com/questions/19857309/magento-1-8-0-0-promotion-catalog-price-rules-does-not-work-when-condition-i

It's a bug/feature in 1.8, Catalog Rules work with conditions for
  attributes with scope other than Global.

A: As far as I am aware the function getMatchingProductIds will return a multi-dimensional array with the following structure:
array(
    'product_id_1' => array(
        'website_id_1' => 0,
        'website_id_2' => 0,
    ),
    'product_id_2' => array(
        'website_id_1' => 0,
        'website_id_2' => 1,
    )
)

This means it will give you an array of all product ids and all website ids, then the value attached to the website will be the result of the validation of the rule's conditions for that product/website combination using (int)$this->getConditions()->validate($product)
For more information about the structure you can look at https://magento.stackexchange.com/a/13224/158


text:
Q: Spin decomposition in general I can turn-the-crank and show that  $\frac{1}{2}\otimes \frac{1}{2} = 1\oplus 0$ etc, but what would be a strategy to proving the general statement for spin representations that $j\otimes s =\bigoplus_{l=|s-j|}^{|s+j|} l$.

A: It's easy to prove the formula if you just look at the individual basis vectors of the tensor product. Let's use $(2j+1)$ and $(2s+1)$ eigenvectors of $j^2, j_z$ and $s^2, s_z$ called $|j,j_z\rangle$ and so on.
Now let's ask about the multiplicity of basis vectors of the tensor product with a given eigenvalue of $J_z = j_z+s_z$. The maximum eigenvalue of $J_z$ in the tensor product is $j+s$: it can be obtained if we choose
$$ |J,J_z=j+s\rangle = |j,j\rangle \otimes |s,s\rangle $$
There are no higher eigenvalues of $J_z$; this proves that no representation with $J>j+s$ is included in the tensor product. However, the $J=j+s$ representation must be included exactly once to obtain one basis vector with $J_z=j+s$; representations with lower values of $J<j+s$ wouldn't contribute any vectors with $J_z=j+s$.
So the tensor product
$$ Rep(j) \otimes Rep(s) = Rep(j+s)\oplus Rep(rest) $$
I have used the fact that reducible representations of simple compact groups may be written as direct sums. Now, what about the remaining representation(s) $Rep(rest)$? It is the linear envelope of a set of basis vectors in which we have already removed all the $(2J+1)$ basis vectors with $J=j+s$.
Well, in the rest, the maximum allowed $J$ is $j+s-1$. From the original bases, we see that the original space was 2-dimensional: the old basis included
$$|j,j-1\rangle \otimes |s,s\rangle, \qquad |j,j\rangle \otimes |s,s-1\rangle $$
But we have already included one combination to $Rep(j+s)$; so the $Rep(rest)$ representation only contains the other one. By the same argument as above, we may see that the multiplicity of $Rep(j+s-1)$ in the tensor product is also one.
By induction, this algorithm may continue: at the beginning, the number of eigenvectors with a given $J_z$ is increasing by one every time we decrease $J_z$ by one. However, this behavior stops once we get to too low values of $J_z$ that would require too negative values of $j_z$, either $j_z<-j$ or $s_z<-s$. When that happens, the number of basis vectors no longer jumps by one; it stays constant. It happens when
$$J_z^{max} \equiv J = |j-s|$$
so $J=|j-s$ is the lowest-$J$ representation included in the decomposition of the tensor product. Another way to see that at this moment, we have already written down all components, is either to notice that $J$ can't be smaller than $|j-s|$ because the minimum is obtained by adding "oppositely directed vectors" and can't be further shortened; or, alternatively, we may check that the dimensions of your formula work:
$$ (2j+1)(2s+1) = \sum_{J=|j-s|}^{(j+s)} (2J+1) $$

A: I think the best way is not the textbook way, but the one described in the warm-up problem in this answer: Mathematically, what is color charge?
I will repeat the main point: the irreducible represenations of SU(2) are given by all complex completely symmetric tensors with all indices down, where each index takes two values 0,1. This is because you have invariant $\epsilon_{ij}$ tensor, which you can use as a metric to raise and lower indices, and you can remove the antisymmetric parts using the $\epsilon$ tensor. The fully symmetric k-index tensor is the spin k/2 representation.
When you tensor two of these together of size k and m, you just put the two tensors end to end, which gives a reducible k+m tensor. You need to remove the antisymmetric parts using the $\epsilon$ tensor, and this steps down by 2 each time, producing exactly one representation of every size between k+m (where you start) and k-m (when you run out of indices to contract).

A: You can solve this by examining characters.  Any finite dimensional representation of $SU(2)$ breaks up into a sum of 1-dimensional representations of $U(1)$, which are classified by an integer called weight (you may divide by 2 to get a half-integer if you need to conform to physics conventions).  You can then write the decomposition of a representation as a generating function, by adding the monomial $q^n$ for each representation of $U(1)$ of weight $n$ that you see.  For example, the representation $\frac12$ corresponds to $q + q^{-1}$, and the representation $1$ corresponds to $q^2 + 1 + q^{-2}$.
The two facts you need are then:

*

*For any non-negative integer $k$, the irreducible representation $k/2$ has character of the form $$\frac{q^{k+1} - q^{-k-1}}{q - q^{-1}} = q^{k} + q^{k-2} + \cdots + q^{-k}$$

*The character of a tensor product is the product of characters.
In other words, the tensor product decomposition can be reconstructed by forgetting the $SU(2)$ action, taking the tensor product of the underlying  $U(1)$ representations, then remembering that the characters of irreducible $SU(2)$ representations have a special form.
In your example, squaring $q + q^{-1}$ yields $q^2 + 2 + q^{-2}$.  You then subtract $q^2 + 1 + q^{-2}$ to get $1$.  For your more general question, you want to show that:
$$\frac{q^{j+1} - q^{-j-1}}{q - q^{-1}}\frac{q^{s+1} - q^{-s-1}}{q - q^{-1}} = \sum_{\ell = |s-j|}^{s+j} \frac{q^{l+1} - q^{-l-1}}{q - q^{-1}}$$
You can prove this by induction on $s$: Your base cases are $s=0$ and $s=1$, which are relatively easy to check.  For larger $s$, you can do a reduction by splitting the sum $\frac{q^{s+1} - q^{-s-1}}{q - q^{-1}}$ as $(q^s + q^{-s}) + \frac{q^{s-1} - q^{-s+1}}{q - q^{-1}}$.  Note that
$(q^s + q^{-s})(q^j + q^{j-2} + \cdots + q^{-j})$ is expanded as $$(q^{s+j} + q^{s+j-2} + \cdots + q^{-s-j}) + (q^{|s-j|} + q^{|s-j|-2} + \cdots + q^{-|s-j|}).$$
These are the extreme summands in $\sum_{\ell = |s-j|}^{s+j} \frac{q^{l+1} - q^{-l-1}}{q - q^{-1}}$.  The remaining summands are what you get by replacing $s$ by $s-2$.
There is also a combinatorial method (which would be easier to communicate if I could draw): view the Laurent polynomial $q^j + \cdots + q^{-j}$ as a set of evenly spaced dots on the number line, and view each of the monomials in $q^{s} + \cdots + q^{-s}$ as a  shifting operator.  You get a bunch of shifted sets of dots, and you can reorganize them into a sort of symmetric pile.  Each layer of the pile is one of the new irreducible representations.


text:
Q: can not use underscore.js in reduce function when do mapreduce on mongodb using mongoose I have a movie collection, each movie has several stars, for example:
{
    movie: "Pride & Prejudice",
    starList: ["Keira Knightley", "Matthew Macfadyen"]
}

{
    movie: "Begin Again",
    starList: ["Keira Knightley", "Mark Ruffalo"]
}

And I want to get an Inverted Index, each star has several movies

{
    star: "Keira Knightley",
    movieList: ["Pride & Prejudice", "Begin Again"]
}

This can be accomplished by using mapreduce on mongodb. I use nodejs with mongoose driver. Following is the code:
var _ = require("underscore");

var o = {};

o.scope = { _: _ };

o.map = function()
{
    var movie = this.movie;
    this.starList.forEach(function(star)
    {
        emit(star, { movieList: [movie]});
    });
};

o.reduce = function(k, vals)
{
    var movieList = _.flatten(_.pluck(vals, "movieList"));
    return { movieList: movieList};
};

Movie.mapReduce(o).then(function(results)
{
    console.log(JSON.stringify(results, null, 4));
});

I got an error which shows I cannot use underscore.js in reduce function.
MongoError: TypeError: _.pluck is not a function :
_funcs2@:8:34

    at Function.MongoError.create (/app/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:31:11)
    at commandCallback (/app/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:1187:66)
    at Callbacks.emit (/app/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
    at null.messageHandler (/app/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:358:23)
    at Socket.<anonymous> (/app/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:292:22)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:153:18)
    at Socket.Readable.push (_stream_readable.js:111:10)
    at TCP.onread (net.js:536:20)

A: A very simple approach which uses the aggregation framework follows:
Movie.aggregate([
    { "$unwind": "$starsList" },
    {
        "$group": {
            "_id": "$starsList",
            "movieList": {"$push": "$movie"}
        }
    },
    {
        "$project": {
            "_id": 0,
            "star": "$_id",
            "movieList": 1
        }
    }
]).exec(callback);

or using the fluent aggregate() builder API:
Movie.aggregate()
     .unwind("starsList")
     .group({
        "_id": "$starsList",
        "movieList": {"$push": "$movie"}
     })
     .project({
        "_id": 0,
        "star": "$_id",
        "movieList": 1
     })
     .exec(callback);

A: I may be wrong here. But i think when you try to acess underscore methods in reduce method your _  variable doesn't have all methods or for access you must use different approach. I would suggest to try like this
_['pluck'](....)

And also check _ variable to see if you got all methods in scope correctly.
Hope this helps.


text:
Q: After I upgrade to Solr4.10, the SolrJ return SolrDocument as NULL I upgrade to the Solr 4.10 this week.
I can query data from Solr with the Solr admin page.
I can query data from Solr with the URL [127.0.0.1/solr/core/dismax?] in the browser.
But when I use Solrj(4.10) to query the data, in the results, the SolrDocument is NULL.
By the way, the numFound in the results of QueryResponse is set correctlly.
And the same code runs well when I query to a Solr4.5 server
Please help me.Thanks.


text:
Q: Best way to find a folder in the test directory for pytest I have a folder structure as below for my pytest files
tests/my_test1.py
tests/input/data.txt
tests/bench/bench.csv

The test my_test1.py would have to read the file tests/input/data.txt. The challenge is to find the location of the file.
The tests can be invoked in Mutiple ways as mentioned here https://docs.pytest.org/en/6.2.x/usage.html. The current working directory may be different based on the invocation. so the way to open a file the input folder  data_f = open ("./input/data.txt") would be incorrect.
What would be the correct path to access the file? I tried to infer the path from os.getenv('PYTEST_CURRENT_TEST'). However this always give the value of the path as 'tests/' no matter from where the test is invoked.

A: You could create a fixture in the root of the tests folder (tests/conftest.py) to help you read any file relative to the tests folder:
from pathlib import Path
import pytest

@pytest.fixture()
def get_file():
    def _(file_path: str):
        return (Path(__file__).parent / file_path).read_text()

    return _

In any test you could then use the fixture to read the file for you:
def test_a(get_file):
    content = get_file('input/data.txt')
    ...

In this example the fixture returns a function that would read the content of any file within tests/ directory, but there are multiple other options:

*

*The fixture can return a Path object instead of the content.

*If you would always use the same file, it can return file object/content directly so within your test function you wouldn't need to call it.


text:
Q: TortoiseHg: Why do I always need to check "Discard local changes, no backup" to update working directory? I have just pulled all incoming changes, committed everything, even pushed all my commits and even then the Update button is grayed out in Update Working directory window if I don't check the "Discard local changes, no backup" checkbox. Last time I did that, I lost all my work compared to the latest remote working directory.
Is it normal that that checkbox should always be checked or not? If not, then why is it like that in my TortoiseHg?

A: The behavior you are describing is what I get when I right-click on the changeset that is the parent of my Working Directory and try to update. Since the difference between my Working Directory and that parent is only my local changes, Update would do nothing unless I was going to discard the local changes.
If you are seeing that behavior when trying to update to other changesets farther back in the repo's history, you may have an issue. What version(s) are you using?
(Full disclosure: I have THg 2.4.1, hg 2.2.2, python 2.6.6, which are not the current versions, but I typically use hg from the console window.)


text:
Q: Android jsoup get text I need to get text from

 معاني الأسماء التي تبدأ بحرف الف في قاموس المعاني صفحة 1

I have tried this:-
     Elements dec = doc.select("h1");
     str = dec.text().toString();

A: select("h1") returns an "array" of elements. You probably should get the first element of dec and then get it's text.
I've just tested it and this solution worked with jsoup version 1.8.3.
    Document doc = Jsoup.connect("https://www.almaany.com/ar/name/").get();
    Elements dec = doc.select("h1");
    Element neededH1 = dec.first();
    String text = neededH1.text();
    System.out.println("Your text here [" + text + "]"); //معاني الأسماء


text:
Q: How to convert below method to Java 8 inline function? I need to convert below method java 8 inline function. need some expert help and explanation to do this.
@Override
public boolean a(final Collection<DoseDetailMutableDTO> detailModels) {
    for (DoseDetailMutableDTO dd : detailModels) {
         final boolean doseDetailTextScheduled = isDoseDetailTextScheduled(dd, 1);
         if (doseDetailTextScheduled) {
             return true;
         }
    }
    return false;
}

and Are there any short cut to do this intelj IDE ?

A: You can make use of Stream.anyMatch as:
public boolean a(final Collection<DoseDetailMutableDTO> detailModels) {
    return detailModels.stream()
                       .anyMatch(dd -> isDoseDetailTextScheduled(dd, 1));
}

returns true if any elements of the stream match the provided predicate, otherwise false

Edit: (from comments)

The control to learn for such suggested shortcuts on IntelliJ IDEA is
  Ctrl+Space or on MacOS can use Alt+Enter as well.

A: We can try using a stream here:
@Override
public boolean a (final Collection<DoseDetailMutableDTO> detailModels) {
    return detailModels.stream()
               .filter(x -> isDoseDetailTextScheduled(x, 1))
               .findFirst()
               .orElse(false);
}

Actually, to make your method null safe, in the event that the input list might be null, we can try this:
@Override
public boolean a (final Collection<DoseDetailMutableDTO> detailModels) {
    return Optional.ofNullable(detailModels)
                   .map(Collection::stream)
                   .orElseGet(Stream::empty)
                   .filter(x -> isDoseDetailTextScheduled(x, 1))
                   .findFirst()
                   .orElse(false);
}

A: You can use anyMatch for this.
Since the second parameter to the function is constant you can write a method that calls isDoseDetailTextScheduled.
I think it becomes even more concise:
public boolean a(final Collection<DoseDetailMutableDTO> detailModels) {
   return detailModels.stream().anyMatch(this::isDoseDetailTextScheduledOne);
}

public boolean isDoseDetailTextScheduledOne(DoseDetailMutableDTO dto) {
    return isDoseDetailTextScheduled(dto, 1);
}


text:
Q: cv2.imshow() giving black screen I'm converting a image (numpy array) into a string. Then I'm converting this string back to a numpy array of the original dimensions. Hence both the numpy arrays are equal- infact numpy.array_equals() also returns True for the arrays being equal.
When I call cv2.imshow() on the original numpy array, it prints the image. But when I call cv2.imshow() on the new numpy array, I get only a black screen.
Why is this happening? Both the numpy arrays are equal, so I should get the same output right?
import numpy as np
import cv2

frame = cv2.imread( '/home/nirvan/img_two.png' , cv2.IMREAD_GRAYSCALE)
string = ' '.join(map(str,frame.flatten().tolist()))

frameCopy = frame.copy()

x = frame.shape[0]
y = frame.shape[1]

frame = string.strip()
temp = [ int(t) for t in frame.split(' ')]
temp = np.array(temp)
temp = temp.reshape( (x,y) )

print( np.array_equal(frameCopy , temp) )

#gives black screen
cv2.imshow('l' , np.array(temp) )

#gives proper image
#cv2.imshow('l' , np.array(frameCopy) )

cv2.waitKey()

A: Your arrays i.e. your frames are equal, but the data types are not. Your temp array is of type int64 while imshow expects uint8. The following will fix your script:
cv2.imshow('l' , np.array(temp, dtype = np.uint8 ) )


text:
Q: JQUERY swap div value for select box value I am trying to contemplate the concepts of swapping content for a div from a chosen select box value.  So for instance here is my code and let's say I select All Sizes.  I would like for that string to replace the Employer Size string from the class out:

  <select class="selectboxdiv" id="ddlEmployerSize">
    <option value=""></option>
    <option value="All_Sizes">All Sizes</option>
    <option value="0_99">0 – 99</option>
    <option value="100_499">100 – 499</option>
    <option value="500">500+</option>
    <option value="1000">1,000+</option>
  </select>

Employer Size

Thanks for any help in advance.

A: Try
jQuery(function($){
    $('#ddlEmployerSize').change(function(){
        $('.out').text($(this).find('option:selected').text())
    })
})

Demo: Fiddle


text:
Q: 3-Way Merge in git - how comparing works I have three versions of the file:
version 1       common ancestor      version  2
-------------   ---------------      -------------
before          original line        original line
original line                        after

What happens while comparing these versions to produce final merge version ?
I have read some information about this topic, but I am still confused how exactly it works.
As for latter example:
Is comparing individual lines between versions linear ?
If so, then final merge should look like this:
1 line: before
2 line: conflict (both left and right contributors are changed compared to ancestor)

Is this correct understanding or does it work differently ?

A: A three-way merge usually means that instead of just comparing the final result to perform the merge, the common base version is already being looked at. What Git then does is create a representation of changes for each version.
So what it actually gets, relative to the base version, is the following:
version 1           version  2
-------------       -------------
+before              original line
 original line      +after

It will then use common lines as context to align the changes:
version 1           version  2
-------------       -------------
+before
 original line       original line
                    +after

At which point, the merge is easy to resolve without a conflict to the following:
before
original line
after

Note that such a merge may still result in a conflict because Git might not have enough common content to align the changes properly. Especially for very small files this might happen.

A: I don't think merge is done by "comparing" individual lines straight between version 1 and version 2. It's more involved than that. It's about trying to see where the diffs between common-ancestor..version1 and common-ancestror..version2 can be "merged". In your particular case, there's a single line on the original version, right? I think that if the line had an EOL at the end before the EOF, then merging them won't break (because that line would be present on both final versions) and so it would be merged perfectly fine. However, if the line did not have an EOL at the end, then version 2 would have removed that line (because the original line is not there anymore.... now it's a different line because of the EOL) and then you would end up with a conflict.


text:
Q: Need to find matrix formulation I have a $B$ matrix: $B = B_{ij}$
I need to find closed matrix formulation of:
$$\sum_i \sum_j \sum_m \sum_n  B_{ij} B_{jm} B_{mn} B_{ni}$$
But I am so confused!
Edit by Henrik:
Originally, it was asked to express
$$\sum_i \sum_j \sum_m \sum_n  B_{mi} B_{mj} B_{ni} B_{nj}$$
in terms of matrices.
actually, there is also a condition: i is not equal to j.

A: If this is indeed a Mathematica question, then first note that:
$$\sum _j B_{i,j} B_{j,k}\equiv (B.B)_{i,j}$$
and
$$\sum _i B_{i,i}\equiv \operatorname{Tr}[B]$$
So, the Mathematica equivalent of:
$$\sum _i \sum _j \sum _m \sum _n B_{i,j} B_{j,m} B_{m,n} B_{n,i} $$
is:
Tr[B . B . B . B]

or:
Tr[MatrixPower[B, 4]]

For the original form of the question, note that:
$$ B_{i,j}\equiv B^T{}_{j,i} $$
So, the Mathematica equivalent of:
$$\sum _i \sum _j \sum _m \sum _n B_{m,i} B_{m,j} B_{n,i} B_{n,j}$$
is:
Tr[B.Transpose[B].B.Transpose[B]]

Addendum
The OP added the requirement that terms where $i=j$ should not be included.  Without explaining why, you can use the following to compute this version:
$$\sum _i \sum _j \sum _m \sum _n B_{m,i} B_{n,i} B_{m,j} B_{n,j} \
\left(1-\delta _{i,j}\right)\equiv \operatorname{Tr}\left[B^T.B.B^T.B\right]-\
\operatorname{Tr}\left[\left(B^T.B\right)^2\right]$$
For your example, $B=\left(
\begin{array}{cc}
 1 & 2 \\
 3 & 4 \\
\end{array}
\right)$, we have:
B = {{1, 2}, {3, 4}};
Tr[Transpose[B] . B . Transpose[B] . B] - Tr[ (Transpose[B] . B)^2 ]

392

A: Carl's answer is perfect as it is. His use of MatrixPower inspired me to think a little about computational complexity: Matrix-matrix multiplication has complexity $O(n^3)$ (in the straight-forward implementations, not these theoretically fancy but practically irrelevant algorithms). If we can get rid of one or two of them, we can even afford a transposition to speed up the computation:
n = 5000;
B = RandomReal[{-1, 1}, {n, n}];
a = Tr[B.B.B.B]; // RepeatedTiming // First
b = Tr[MatrixPower[B, 4]]; // RepeatedTiming // First
c = With[{A = B.B}, Total[A Transpose[A], 2]]; // RepeatedTiming // First
a == b == c

5.7
4.207
2.5
True

For the original question, LouisB's answer (c below) seems to be both correct and efficient:
n = 5000;
B = RandomReal[{-1, 1}, {n, n}];
a = Tr[B.Transpose[B].B.Transpose[B]]; // RepeatedTiming // First
b = With[{u = Flatten[B.Transpose[B]]}, u.u]; // RepeatedTiming // First
c = Total[(Transpose[B].B)^2, 2]; // RepeatedTiming // First
a == b == c

5.8
2.4
2.40
True

A: This is a closed matrix formulation of $B^4$.


text:
Q: Как это работает? Добавление массива в список В процессе изучения Java столкнулся с ситуацией которая меня поставила в ступор.
Мне нужно был список из массивов [0, 0] [0, 1] [0, 2] [0, 3] [1, 0] [1, 1] и так далее до [3, 3]
Не долго думая написал такой код
import java.util.ArrayList;
import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        ArrayList<int[]> field = new ArrayList<>();
        int[] cell = new int[2];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4 ; j++) {
                cell[0] = i;
                cell[1] = j;
                field.add(cell);
            }
        }
        for(int[] array: field){
            System.out.print(Arrays.toString(array) + " ");
        }
    }
}

В итоге я получил список:
[3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3] [3, 3]

Т.е. после каждой итерации цикла не просто добавлялся какой то конкретный элемент в конец списка, а менялся весь список!
Каким образом? Как это происходит?

A:
Как это работает?

Вы создаете объект:
int[] cell = new int[2];
Далее, в цикле, Вы меняете его состояние и добавляете его в список. На последующих итерациях цикла Вы изменяете тот же самый объект и добавляете его в список. В итоге у Вас в списке на разных позициях находится один и тот же объект.
Для решения данной проблемы создавайте новый объект на каждой итерации цикла:
public class Test {
    public static void main(String[] args) {
        ArrayList<int[]> field = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4 ; j++) {
                int[] cell = new int[2];
                cell[0] = i;
                cell[1] = j;
                field.add(cell);
            }
        }
        for(int[] array: field){
            System.out.print(Arrays.toString(array) + " ");
        }
    }
}


text:
Q: Problems with adding a shadow to Navigation Bar When I add the code:
image.layer.shadowColor = [[UIColor blackColor] CGColor];
image.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
image.layer.shadowRadius = 3.0f;
image.layer.shadowOpacity = 1.0f;

and also import
<QuartzCore/CALayer.h>

and
<QuartzCore/QuartzCore.h>

I get an error for each of the mentioned lines starting with image.layer, satiating that: "Property 'layer' not found on object of type 'UIImage *'
How can I fix this?

A: Set this properties for UIImageView * not Image *

A: UIImage instance represents image data. UIImageView instances represent actual images in UI. UI objects have layer, not data objects, so you need to do what you are doing on an instance of UIImageView instead of UIImage.


text:
Q: Code running in Codepen does not work on vscode Javascript codes work on the codepen, but when I test it with vscode, the shapes do not appear and the download button does not work, so javascript codes do not work.
https://codepen.io/rebelchris/pen/rNevrXg
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const download = document.getElementById('download');

// Cirlce
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.stroke();

// Triangle
ctx.beginPath();
ctx.moveTo(200, 75);
ctx.lineTo(100, 75);
ctx.lineTo(100, 25);
ctx.fill();

// Hearth
ctx.beginPath();
ctx.moveTo(75, 40);
ctx.bezierCurveTo(75, 37, 70, 25, 50, 25);
ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
ctx.bezierCurveTo(20, 80, 40, 102, 75, 120);
ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
ctx.bezierCurveTo(85, 25, 75, 37, 75, 40);
ctx.stroke();

download.addEventListener('click', function(e) {
  console.log(canvas.toDataURL());
  var link = document.createElement('a');
  link.download = 'download.png';
  link.href = canvas.toDataURL();
  link.click();
  link.delete;
});

A: Not sure why you're unable to do it. Below is the code for your reference
<html>
<head>
    <style>
        // Code in CSS part goes here...
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>
<body>

    <!-- Code under HTML goes here -->
    <canvas id="canvas" height="200"></canvas>
    <br />
    <button id="download">Download</button>

    <script>
        // Code under Javascript goes here
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        const download = document.getElementById('download');

        // Cirlce
        ctx.beginPath();
        ctx.arc(100, 100, 50, 0, 2 * Math.PI);
        ctx.stroke();

        // Triangle
        ctx.beginPath();
        ctx.moveTo(200, 75);
        ctx.lineTo(100, 75);
        ctx.lineTo(100, 25);
        ctx.fill();

        // Hearth
        ctx.beginPath();
        ctx.moveTo(75, 40);
        ctx.bezierCurveTo(75, 37, 70, 25, 50, 25);
        ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
        ctx.bezierCurveTo(20, 80, 40, 102, 75, 120);
        ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
        ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
        ctx.bezierCurveTo(85, 25, 75, 37, 75, 40);
        ctx.stroke();

        download.addEventListener('click', function(e) {
            console.log(canvas.toDataURL());
            var link = document.createElement('a');
            link.download = 'download.png';
            link.href = canvas.toDataURL();
            link.click();
            link.delete;
        });
    </script>
</body>
</html>


text:
Q: Add a Trending Proposals tab to the sidebar like Hottest Questions I think that currently there is very little exposure for new site proposals (considering how much traffic sites like Stack Overflow generate). I'm not sure that a large amount of the user base even knows that there is an Area 51 site (even though the hottest questions sidebar does help users discover some of the lesser-known sites).
I think that something highlighting Area 51 better (such as the trending proposals sidebar) would help a lot more proposals gain the followers and interest they need to succeed. What do people think about that?


text:
Q: objProcess.Terminate not Found specific to iexplore.exe When terminating internet explorer within VBA I'm using the following code sourced (more or less) from stackoverflow:
Sub IE_Sledgehammer()
    Dim objWMI As Object, objProcess As Object, objProcesses As Object
    Set objWMI = GetObject("winmgmts://.")
    Set objProcesses = objWMI.ExecQuery( _
        "SELECT * FROM Win32_Process WHERE Name = 'iexplore.exe'")
    MsgBox "iexplore.exe processes = " & objProcesses.Count
    For Each objProcess In objProcesses
        Call objProcess.Terminate
    Next
    Set objProcesses = Nothing: Set objWMI = Nothing
End sub

The number of processes returned is "2" (which is correct) but in the first iteration of the For loop, when the first iexplore.exe is terminated that also terminates the second process and so in the second loop iteration a 'not found' error occurs. I understand that this is because closing one iexplorer.exe process closes all iexplore.exe tasks.
My question is, how can I reference and terminate only the first 'objprocess' in the objprocesses list OR force the For loop to exit after one iteration?

A:
Do you mean you want to close the first tab or IE window?
I suggest you create an object of Shell and loop through IE windows.
You can close the first IE window and exit the loop or you can match the title of the IE window and close that specific IE window.
You need to add the reference to Microsoft Shell Controls and Automation and Microsoft Internet Controls.

Code:
Sub demo()

Dim oShellWin As Shell
Dim oWin As Object
Dim objIE As InternetExplorer

    Set oShellWin = New Shell

      For Each objIE In oShellWin.Windows

        If TypeName(objIE.Document) = "HTMLDocument" Then

            'Debug.Print objIE.Document.Title
            If objIE.Document.Title = "Bing" Then 'User can modify the title here...
                objIE.Quit
                Exit For
            End If
        End If

    Next objIE

End Sub

Output:

Further, you can try to modify the code as per your requirement.


text:
Q: Session not storing some values I'm not a C# programmer anymore (last project in 2005), but I fell on a ASP.NET 4.0 project and to made some "small" changes.
I'm not really sure HOW can I look/search about this problem, but, here we go:
When I'm on a controller, and I set a session with System.Web.HttpContext.Current.Session["Test"] = "mydata"; and I'm trying to retrieve in the view with this:
@{
    String test = "";
    if (System.Web.HttpContext.Current.Session["Test"] != null) {
        test = (string)System.Web.HttpContext.Current.Session["Test"];
    }
}

--<span>@test</span>--

But the session is always null.
The problem is if I test with another session key ("MEX.User" for instance) already used in the system, it works.
I don't know where is the big deal, and neither how to find it.

Update
I ran the project in another Windows 7 machine and the sessions worked fine. Now I have to figure out why it's not working on stating and development environments. Staging is exactly like production, so I think it will not work either.


text:
Q: How to re-post data to the server after a JWT token has been refreshed in Vuejs/Laravel I'm building a PWA wherein users log in to enter production data to a form and submit to the server for subsequent processing. I'm using a JWT token to manage the user's status. I'm using Axios interceptors to check that the token is fresh/expired. If the latter, I'm refreshing the token.
My current problem is that I don't know how to automatically resubmit a user's data input if, upon form submission, their token was found to be expired and a new one created.
So, in my bootstrap.js file I have:
window.axios.interceptors.response.use((response) => {
  return response;
}, error => {
  let pathUrl = error.config.url;

  if (error.response.status !== 401) {
    return new Promise((resolve, reject) => {
      reject(error);
    });
  }

  if (pathUrl == '/api/question' || error.response.message == 'Your session has expired; please log in again.') {
    getRefreshToken();
    return Promise.reject(error)
  }

});

function getRefreshToken() {
  window.axios.post('/api/auth/refresh')
    .then(response => {
        const token = response.data.access_token
        localStorage.setItem('token', token)
        const JWTtoken = 'Bearer ' + token
        window.axios.defaults.headers.common['Authorization'] = JWTtoken;
    })
}

The method for submitting the form in the component within which the data are inputted is:
  submitData () {
    let vm = this;
    if (vm.$v.formvar.$pending || vm.$v.formvar.$error) return;
      axios.post('/api/question',vm.formvar)
      .then(res => {
        this.$router.push('/' + this.$i18n.locale + res.data.path)
      })
  },

Any help here would be gratefully received.
Thanks/Tom

A: You can try using window.axios.request(error.config) to resend the request
if (pathUrl == '/api/question' || error.response.message == 'Your session has expired; please log in again.') {
  return getRefreshToken()
    .then(JWTtoken => {
      error.config.headers['Authorization'] = JWTtoken
      return window.axios.request(error.config)
    })
}

getRefreshToken should return a Promise
function getRefreshToken() {
  return window.axios.post('/api/auth/refresh')
    .then(response => {
      const token = response.data.access_token
      localStorage.setItem('token', token)
      const JWTtoken = 'Bearer ' + token
      window.axios.defaults.headers.common['Authorization'] = JWTtoken;
      return JWTtoken
    })
}


text:
Q: Javascript Hyperlink formula field Is it possible to embed javascript in Hyperlink formula field to open a vf page in a pop up?Can you share the formula,if possible?

A: Here is an example.

Use of formula field to open a visualforce page in Console and standard view page in Standard or Custom App. [applicable to Classic]

HYPERLINK("javascript:if(typeof(srcUp)=='function') {srcSelf('/apex/VisualforcePage?id=" & Id & "');} "+
" else {window.location.href='/" & Id & "'}"
,Name
, "_Parent"
)

You can refer my blog post: Different ways of navigation


text:
Q: Multi-threading with different Buttons view: Android So I am writing an android code where there are 3 buttons:record, pause, take frame. Record button records a video, pause button pauses the video displaying in VideoView and Take frame button shows the paused frame in imageView. Now I need 3 threads - one main thread is for user interaction (pause button), one sub thread records the video(record button) and second sub thread saves the frame(take frame button).
protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            mvideoview = (VideoView) findViewById(R.id.videoView);
            imgview = (ImageView) findViewById(R.id.imageView);
            mrecord = (Button) findViewById(R.id.button);
            mpause = (Button) findViewById(R.id.button2);
            mtakeframe = (Button) findViewById(R.id.button4);

            mrecord.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                            dispatchTakeVideoIntent();
                            mvideoview.start();
                        }
            });

            mpause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mvideoview.pause();
                }
            });

            mtakeframe.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                            Bitmap bmp = takeFrame();
                            imgview.setImageBitmap(bmp);
                        }
                    });
        }

        private void dispatchTakeVideoIntent() {
            //code directs towards the video recorder screen
        }

        protected void onActivityResult(int requestcode, int resultcode, Intent intent) {
            //recorded video sent back and its path stored
        }

        public Bitmap takeFrame() {
            //paused frame shown in imageView
        }

I tried putting different threads at onClick(View view) of different buttons but at the end the application crashes saying the error "Only the original thread that created a view hierarchy can touch its views." And also if I want to add one more button that is PLAY(plays the paused video) then how should I write it, I can't understand. Can someone help me here in how to thread such a program in Android?

A: View object can modify or do any action only by UI thread If another thread tries to process on the View object, it should call like this,
runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // do the view operation here
            }
        });

For more information you can refer this, this


text:
Q: How do I toggle multiple list elements with same class? I have a list with 5 elements of the same class: "navbar_item". With this code I toggle the 'active' status when clicking the item with the class mentioned, but it only toggles the first element of the list. What do I do to toggle all of them?
const menu = document.querySelector('#mobile-menu');
const menuMenu = document.querySelector('.navbar_menu');
const menuItem = document.querySelector('.navbar_item');

const mobileMenu = () => {
    menu.classList.toggle('is-active');
    menuMenu.classList.toggle('active');
    menuItem.classList.toggle('active');
};

menu.addEventListener('click', mobileMenu);
menuItem.addEventListener('click', mobileMenu);

A: You need to use querySelectorAll to get all elements. This provides a list which you can iterate or loop through to both apply eventListeners and toggle classes.
Something like this

const menuItem = document.querySelectorAll('.navbar_item');

const mobileMenu = () => {
    menuItem.forEach( (item) => {
        item.classList.toggle('active');
  })
};

menuItem.forEach( (item)=> {
    item.addEventListener('click', mobileMenu)
})
.active{
  background-color: lightblue;
}

.navbar_item{
  margin-bottom: 10px;
}

Item 1

Item 2

Item 3

Item 4

Item 5

A: because "querySelector" will only get the first element, if you want to get All; please use "querySelectorAll"; you can also to learn Event delegation to get a better way to solove this problem
const menu = document.querySelector('#mobile-menu');
const menuMenu = document.querySelector('.navbar_menu');
const menuItems = document.querySelectorAll('.navbar_item');

const mobileMenu = () => {
    menu.classList.toggle('is-active');
    menuMenu.classList.toggle('active');
};

menu.addEventListener('click', mobileMenu);
for(let i = 0; i < menuItems.length; i ++) {
  menuItems[i].addEventListener('click', () => {
    menuItem[i].classList.toggle('active');
  });
}