text:
Q: Method does not return random number from another method It was hard to find right title for this problem. I had little problem earlier with this dice game and I solved it, thanks for the guys in here Stackoverflow.
My game is 99% ready now, but somehow main program cannot return the dice numbers. This game is meant to break when player have three wins and that makes him a winner. That why there is round.
Console should look like this:
Name of player 1:
Name of player 2:
Round 1
"Player 1 name": 5 + 4 = 9
"Player 2 name": 1 + 2 = 3
Round 2 et cetera
And when player get three wins it is winner. I have also two other class but problem is with Dice so I do not attach the others here.
Class game
using System;
using System.Collections.Generic;
using System.Text;
using static System.Console;

namespace Dicegame
{
    static class Game
    {
        static int winline = 3;

        static int round = 1;

        public static void Aja()
        {
            Player p1 = new Player
            (
                Helpers.Syote.Merkkijono("Name of player 1: ")
            );
            Player p2 = new Player
            (
                Helpers.Syote.Merkkijono("Name of player 2: ")
            );

            Dice dice1 = new Dice();
            Dice dice2 = new Dice();

            for (int i = 1; p1.Points < winline | p1.Points < winline; i++)
            {
                int p1throw1 = dice1.Throw(), p1throw2 = dice2.Throw(), p1total = p1throw1 + p1throw2,
                    p2throw1 = dice1.Throw(), p2throw2 = dice2.Throw(), p2total = p2throw1 + p2throw2;

                round++;
            }
        }
    }
}

Class Dice
using System;
using System.Collections.Generic;
using System.Text;
using static System.Random;

namespace Dicegame
{
    class Dice
    {
        static Random randomnumber = new Random();

        public int Count { get; set; }
        public int ThrowCount { get; set; }

        public Dice()
        {
            ThrowCount = 0;
        }

        public int Throw()
        {

            int Count = randomnumber.Next(1, 7);
            ThrowCount++;

            return Count;
        }

    }
}

A: You simply never actualise the points of P1 or P2.
Also you use a for loop where a simple while loop would work way better:
while(p1.Points < winline || p2.Points < winline)
{
    p1.AddPoints(dice1.Throw() + dice2.Throw());
    p2.AddPoints(dice1.Throw() + dice2.Throw());
    round++;
}

A: I post my solution of this I hope it helps someone in future. Commented all so it is easy to understand for beginners also.
do
    {
        if (p1.Points == WINLINE || p2.Points == WINLINE)
        {
            break; // Break this loop when either one reach WINLINE points (3)
        }
        else
        {
                // Get random numbers for each throw between 1-6 and sum them together
            int p1throw1 = dice1.Throw(), p1throw2 = dice2.Throw(), p1total = p1throw1 + p1throw2,

                // Get random numbers for each throw between 1-6 and sum them together
                p2throw1 = dice1.Throw(), p2throw2 = dice2.Throw(), p2total = p2throw1 + p2throw2;

            // Write round number which is how many times dice is thrown. Split with 2, because same dice is throwed two times in one round
            WriteLine($"Round {dice1.ThrowCount / 2}");

            // Write given player names and points of each throw and after all sum of those points
            WriteLine($"{p1.Name}: {p1throw1} + {p1throw2} = {p1total}");
            WriteLine($"{p2.Name}: {p2throw1} + {p2throw2} = {p2total}");

            // If player 1 get more points than player 2, add one point for player 1 and reset player 2 points
            if (p1total > p2total)
            {
                p1.Points++;
                p2.Points = 0;
            }

            // If player 2 get more points than player 1, add one point for player 2 and reset player 1 points
            else if (p1total < p2total)
            {
                p2.Points++;
                p1.Points = 0;
            }
                else // If something else (same points for both) do nothing
            {

        }
    }
}
while (true);

// When do loop broke print results of the game
if (p1.Points == WINLINE) // Print this if player 1 wins
{
    WriteLine($"Winner of the game is {p1.Name} and total rounds: {dice1.ThrowCount / 2}.");
}
else if (p2.Points == WINLINE) // Print this if player 2 wins
{
    WriteLine($"Winner of the game is {p2.Name} and total rounds: {dice1.ThrowCount / 2}");

}


text:
Q: Deploy Nodejs on Heroku fails serving static files located in subfolders I'm deploying a NodeJs application using Heroku. Everything works fine except a little issue serving static files.
I have the following configuration
app.use(express.static(__dirname + '/htdocs'));

It works fine except when I try to serve static files located in sub folders.

www.example.com/bar.js  // this serves the file /htdocs/bar.js
www.example.com/foo/bar.js  // this can't find the file
  /htdocs/foo/bar.js

I forgot to say that on my local environment everything works fine, might be something with heroku but I can't find the reason. Did someone had this problem before? Solutions?
Thanks!

A: If none of these solutions worked, check my solution.

Make sure that the sub directories of your directory are added to your Git repository.

A: Finally I found the solution.
I solved that just adding the npm version in my package.json.
{
    "name": "bla",
    "version": "0.0.1",
    "dependencies": {
        "express": "3.2.6"
    },
    "engines": {
        "node": "0.10.11",
        "npm": "1.2.25"
    }
}

A: Apparently, as explain in this question: Heroku(Cedar) + Node + Express + Jade Client-side javascript files in subdirectory work locally with foreman+curl but not when pushed to Heroku, you can't use __dirname with Heroku.
The alternative seems to be:

// At the top of your web.js
process.env.PWD = process.cwd()
// Then
app.use(express.static(process.env.PWD + '/htdocs'));

A: I solved the problem in my case by removing the public folder from the .gitignore file. I don't know what it was doing there.

A: I struggled with this for a while and had to revert to using /public (from /dist) as the static folder - works perfectly now

A: In my case, I had a step in my build that was actually wiping out the /public folder, and then adding back in a bundle.js and bundle.css.
So on my local I didn't see it, but when it was deployed to Heroku the assets were missing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I close javascript popup box after validation is successful with php ajax call In my html form, a popup window appears for registration. It validates data with an ajax/query call with regProcess.php page. This page is passing data to html form with json_encode. Well, when all validation is successful I want to close the html popup box after few second. How can I do this?

The popup window appears with following div call.

    <button type="button" name="" value="" class="css3button">Join the campaign</button>

A: You can put a jquery function in the success function with the setTimeout()
http://www.w3schools.com/jsref/met_win_settimeout.asp


text:
Q: UICollectionView in view controller I am looking for a possibility to drag and drop an image in a collection view cell to a UIImageView in the same view controller but outside of the collection view. The cv is below 5 collection views and i want to drag the image in the collection view and drop it into one of the 5 UIImage Views above the collection view. Is there a possibility to take the image from the collection view cell and reorder the collection view in new order so that the token dragged image (and cv-cell) will be deleted below? The images in the colectionview come from urls via json load. I am working with storyboard and with ARC ...
Thanks a lot for any help or tipps!

A: Maybe you could load the images of the collection view inside an NSMutableArray, which you can run through in order to get the data your collection view must show. When you drag it from the collection view into the UIImageView, remove the correspondent index of that image inside the NSMutableArray and reload the collection view data. At the same time you get that image data and load it to the image view. This could help if I understood your problem.


text:
Q: Assign List property on Select LINQ statement So i want to achieve something like:
 var query = from p in db.Project
                        select new A
                        {
                            Project = p,
                            Capacity = new List<Capacity>((from pp in db.ProjectActualCapacity
                                                           where pp.ProjectID == p.ID
                                                           select new Capacity
                                                           {
                                                               Actual = pp.Hours,
                                                               Date = pp.Date,
                                                               ProjectID = pp.ProjectID
                                                           }
                                                            ).ToList())
                        };

However, when the query is converted to list. It throws the following error

Only parameterless constructors and initializers are supported in LINQ to Entities.

Is there a workaround to this?
thanks
//Update
public class Capacity
{
    public DateTime Date { get; set; }
    public decimal? Actual { get; set; }
    public decimal? Projected { get; set; }
    public int ProjectID { get; set; }
    public decimal Rate { get; set; }
}

A: You are explicitly creating a list and using the constructor which accepts an enumerable. This is not necessary since you are already using .ToList() where you define that collection.
Also, your Capacity class needs a parameterless constructor.
So I think it will work like this.
var query = from p in db.Project
    select new A {
        Project = p,
        Capacity = (from pp in db.ProjectActualCapacity
                    where pp.ProjectID == p.ID
                    select new Capacity {
                        Actual = pp.Hours,
                        Date = pp.Date,
                        ProjectID = pp.ProjectID
                    }
                   ).ToList())
   };


text:
Q: Holomorphic functions on a region. Let $A$ be a region in complex plane $\Bbb C$, $f\colon A\to f(A)$  is continuous on $A$. $f^n$ is holomorphic on $A$. How to prove that $f$ is holomorphic on $A$?
Partial proof.
I have proved the theorem when $0$ doesn't belong to $A$. (by composition of functions)

A: If $f^n$ is holomorphic in $A$, it is either identically $0$ or its zeros are isolated.  As an isolated singularity of $f$, an isolated zero is removable.


text:
Q: CUPS: `stopped "Filter failed"' when trying to print after ubuntu update D [15/Apr/2021:02:45:21 -0500] [Job 21] PID 20964 (/usr/lib/cups/backend/socket) exited with no errors.
D [15/Apr/2021:02:45:21 -0500] [Job 21] Start rendering...
D [15/Apr/2021:02:45:21 -0500] [Job 21] Processing page 1...
D [15/Apr/2021:02:45:21 -0500] [Job 21] Error: /ioerror in --showpage--
D [15/Apr/2021:02:45:21 -0500] [Job 21] Operand stack:
D [15/Apr/2021:02:45:21 -0500] [Job 21] true   (/tmp/gs_wO3nvv)   --nostringval--   1   true
D [15/Apr/2021:02:45:21 -0500] [Job 21] Execution stack:
D [15/Apr/2021:02:45:21 -0500] [Job 21] %interp_exit   .runexec2   --nostringval--   showpage   --nostringval--   2   %stopped_push   --nostringval--   showpage   showpage   false   1   %stopped_push   1990   2   3   %oparray_pop   1989   2   3   %oparray_pop   1977   2   3   %oparray_pop   showpage   1978   4   3   %oparray_pop   showpage   showpage   2   1   1   showpage   %for_pos_int_continue   1981   4   7   %oparray_pop   showpage   showpage   1840   3   9   %oparray_pop   showpage   showpage
D [15/Apr/2021:02:45:21 -0500] [Job 21] Dictionary stack:
D [15/Apr/2021:02:45:21 -0500] [Job 21] --dict:752/1123(ro)(G)--   --dict:1/20(G)--   --dict:80/200(L)--   --dict:80/200(L)--   --dict:135/256(ro)(G)--   --dict:318/325(ro)(G)--   --dict:33/64(L)--   --dict:6/9(L)--   --dict:7/20(L)--
D [15/Apr/2021:02:45:21 -0500] [Job 21] Current allocation mode is local
D [15/Apr/2021:02:45:21 -0500] [Job 21] Last OS error: Broken pipe
D [15/Apr/2021:02:45:21 -0500] [Job 21] GPL Ghostscript 9.52: Unrecoverable error, exit code 1
D [15/Apr/2021:02:45:21 -0500] [Job 21] Rendering completed
D [15/Apr/2021:02:45:21 -0500] [Job 21] PID 20961 (/usr/lib/cups/filter/gstoraster) stopped with status 1.
D [15/Apr/2021:02:45:21 -0500] [Job 21] Hint: Try setting the LogLevel to "debug" to find out more.
D [15/Apr/2021:02:45:21 -0500] [Job 21] End of messages
D [15/Apr/2021:02:45:21 -0500] [Job 21] printer-state=3(idle)
D [15/Apr/2021:02:45:21 -0500] [Job 21] printer-state-message="Rendering completed"
D [15/Apr/2021:02:45:21 -0500] [Job 21] printer-state-reasons=none

I updated my ubuntu to 20.10 Groovy Gorilla and now the above happens.
I got the logs above with this command: sudo tail -n 100 -f /var/log/cups/error_log
I have tried going to http://localhost:631 in browser and have deleted and reinstalled printer with every driver for my printer model. The error in cups is always the same stopped "Filter failed" after I try printing a test page. The ink level shows up in my printer settings correctly. I can print from this printer from windows on the same pc when I boot from my windows partition.
I have also run the following commands successfully:
sudo apt-get update
sudo apt-get upgrade

sudo service cups restart

sudo apt-get install hpijs-ppds printer-driver-hpijs

sudo service cups restart

sudo rm /usr/share/ghostscript/9.52/iccprofiles
sudo apt-get install --reinstall libgs9-common

sudo service cups restart

The printer I bought is: HP LaserJet Pro M15w Wireless Laser Printer
The driver I install in CUPS is: HP LaserJet m14-m17, hpcups 3.21.2 (grayscale)
thanks for any help :)

A: Try this:
1) sudo apt purge hplip hplip-gui printer-driver-hpcups
2) sudo apt autoremove
3) sudo apt update
4) sudo apt upgrade
5) sudo apt install hplip hplip-gui printer-driver-hpcups <+ anything that's removed in the last steps>
6) sudo service cups restart
7) sudo apt-get install hpijs-ppds printer-driver-hpijs
8) sudo service cups restart
9) hp-plugin

:) I'm not sure if 7 and 8 is essential... I make all by tips... and nothing, then 9 save me! I have HP cp1025


text:
Q: How do I limit fetch calls made to an endpoint service so that no more than 10 calls per second are made? In order to avoid the "Error 429 Too Many Requests" error in browser, how can I modify the below code so that no more than 10 calls per second are made?
This 10 calls per second rate limit is imposed by a 3rd-party API, over which we have no control.
Thanks in advance!
// Array of hundreds of URLS
const urls = allNames.map(
        (name) =>
`https://example.com/api/v3/results/${name}?limit=120&apikey=123`
    );

// TODO add throttle so as to not exceed 10 calls per second
const getStaticProps = async () => {
            Promise.allSettled(
            urls.map((url) =>
                fetch(url).then((resp) => resp.json())
            )
        ).then(console.log);
};

A: You can fetch ten and wait for one second.

// Array of hundreds of URLS
const urlsList = allNames.map(
        (name) =>
`https://example.com/api/v3/results/${name}?limit=120&apikey=123`
    );

// TODO add throttle so as to not exceed 10 calls per second
// Fuction that returns a Promise that resolves after given Milliseconds
const timer = ms => new Promise(res => setTimeout(res, ms))

for (let i = 0; i < urlsList.length; i+=10) {
  getStaticProps(urlsList.slice(i-10, i));
  await timer(1000); //It will make 10 calls and wait 1 seconds
}

const getStaticProps = async (urls) => {
            Promise.allSettled(
            urls.map((url) =>
                fetch(url).then((resp) => resp.json())
            )
        ).then(console.log);
};

A: Hopefully this helps :)
const urls = allNames.map(
  (name) => `https://example.com/api/v3/results/${name}?limit=120&apikey=123`
);

// 1s === 1000ms
const delay = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const isEven = (num) => num % 2 === 0;

const getStaticProps = async () => {
  const response = await Promise.allSettled(
    urls.map(async (url, index) => {
      if (index && isEven(index / 5)) await delay(1000);
      return await fetch(url).then((res) => res.json());
    })
  );
};


text:
Q: INI files or Registry or personal files? I want to save the configuration of my project which includes

*

*Screen size

*Screen position

*Folder paths

*Users settings and so on.

The standard places where you can save these are configuration values are:

*

*Registry

*INI files

*Personal files (like *.cfg)

How do you choose between these places? Also, are there any pros and cons of using any of them?

A: My preference is XML files.  They are hierarchical, you can bend them to your will in almost any way imaginable, they are well understood, platform independent, and there is a wide array of software available to read and write them.

A: To expand Jeff D's suggestion of YAML, here's a brief intro.
YAML is similar to JSON (in fact, JSON is a subset of YAML since version 1.2 of the YAML standard, and can thus valid JSON can be parsed by YAML parsers).  At first glance, the main difference being that YAML (by default) uses indentation rather than bracketing to show hierarchy.  There is also a noticable lack of quotes for strings.  A quick example from above:
configuration:
  window:
    width:       600
    height:      350
    position:
      x:         400
      y:         200
  paths:
    path1:       some/random/path
    path2:       some/other/random/path
  user:
    name:        Joe Soap
    preference:  YAML

See Wikipedia's YAML page for better examples.  Support for YAML exists for most major languages (see yaml.org for details).

A: You forgot an option: the Database.
This is mostly used in scenarios where you have users logging into your application when your application can't rely on the logged in windows user.
This is for instance when your app is running in a kiosk mode windows.

A:
Also are there any pros and cons of using any of them?

Registry:

*

*+ Relatively standard in the Windows environment.

*+ Generally good support from installers, etc.

*- Platform specific API, if you ever want to port your application.

*- Not particularly human readable.

INI Files:

*

*+ Simple format.

*+ Portable.

*+ Human readable.

*- May be difficult to store more complex information (for example, anything nested more than two levels deep).

*? May have to write your own parser (although not difficult) or use an external library like SimpleIni (thanks to Jonathan Merlet for the comment).

XML Files (I'm guessing this is the .cfg option):

*

*+ A standard format.

*+ Portable.

*+ Supports deeply nested structures.

*- Not particularly human readable.

Personally, for Windows applications I tend to use C#, and go with a personal file for the user, stored as XML. I do this typically because human readability is not usually a priority in the types of applications I write (and the application should have a configuration editor, in any case), and in the .NET environment, it's very easy to work with XML. I very often end up with a UserConfiguration object which simply gets serialised to and from a configuration file - almost no development involved (parsing, casting stuff around), and you have your configuration ready to use in a strongly typed environment.

A: I'd go with INI files, they are the more human friendly option:
[window]
width       = 600
height      = 350
position.x  = 400
position.y  = 200

[paths]
path1       = "/some/random/path/"
path2       = "/some/other/random/path/"

[user]
name        = "Yannis"
preference  = "INI"

XML might be a good option, but it can't beat INIs' simplicity and elegance:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <window>
        <width>600</width>
        <height>350</height>
        <position>
            <x>400</x>
            <y>200</y>
        </position>
    </window>
    <paths>
        <path1>/some/random/path/</path1>
        <path2>/some/other/random/path/</path1>
    </paths>
    <user>
        <name>Robert</name>
        <preference>XML</preference>
    </user>
</configuration>

INIs are also very well understood and platform independent. There aren't probably as many tools available for them as for XML files, because, well, who needs a specialized tool to read and edit an INI file?

A: My personal preference is XML files:
In most cases I don't expect the user to have to edit their configuration settings so the human readability issue is not an argument in this case.
If they do need to edit them you can provide a editing tool - this prevents the user doing something daft with the data. If they want to restore the default settings you can just tell them to delete file x which most users will be comfortable doing.
Note that you still need to be careful that you have permission to store your file as some locations do not have write access by default in Windows 7 etc.

INI Files are a good standard way of storing configuration and are tried and tested but they just feel a bit 'Windows 3.1' to me!
Probably the best option if you want the user to be able to tinker with their data

I would personally steer away from the registry. For one thing you cannot guarantee that the user has the necessary permissions to read/write to wherever you want to store your data.
In more recent OSs where registry virtualisation comes into play this can cause major confusion because you can't 'see' the virtualised settings - this has bitten us more than once where have spent hours trying to figure out why something was not working.


text:
Q: Access a class in a different folder In my main package I have two classes and a folder with more classes in it. One of the outer classes is a singleton class that I need access to from a bunch of the other classes (which are inside of the subfolder). I can access the singleton from classes on the same level as it no problem but when in one of the subclasses it will not let me access it as the others can. How do I resolve this issue? Just incase here is a layout:
com.blah
    [Connect]
        Ftp.java    //I want to be able to say AppConfig.getInstance().blah() in this class
    App.java        //I can say AppConfig.getInstance().blah() in here just fine
    AppConfig.java

EDIT This is the top of the AppConfig Singleton class:
class AppConfig {

    private static AppConfig config = new AppConfig();

    private AppConfig(){}

    public static AppConfig getInstance(){
        return config;
    }

    static Properties prop = new Properties();
...

EDIT Realized that i needed public infront of AppConfig class declaration. Thanks for the tips guys.

A: Import it into your Ftp class.
import com.blah.AppConfig;

(Make sure that Ftp is a public class when you do this as well.)
You don't have to import classes that are in the same folder, because they're considered to be in the same package.  Anything that is outside of the package you're currently in has to be imported.

A: Ftp.java must be a public class if its singleton so that it will be accessible everywhere
And if its public then there should be no problem accessing it outside just import it in those classes where you want that
import com.blah.AppConfig;


text:
Q: mvn liquibase:diff command does not generate contexts and What is createSequence changeSet, why it is generated? I'm using maven liquibase and on running the mvn liquibase:diff -Plocal, the generated diff changelog is not having a context tag in changeSets.
<?xml version="1.1" encoding="UTF-8" standalone="no"?><databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" xmlns:pro="http://www.liquibase.org/xml/ns/pro" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/pro http://www.liquibase.org/xml/ns/pro/liquibase-pro-4.1.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.1.xsd">
<changeSet author="testUser (generated)" id="1603187434414-1">
    <createSequence cycle="false" incrementBy="1" maxValue="9223372036854775807" minValue="-9223372036854775808" sequenceName="orderconsumer_shipment_id" startValue="1"/>
</changeSet>
<changeSet author="testUser (generated)" id="1603187434414-2">
    <createSequence cycle="false" incrementBy="1" maxValue="9223372036854775807" minValue="-9223372036854775808" sequenceName="orderlineroutingjobs_jobnumber_seq" startValue="1"/>
</changeSet>
<changeSet author="testUser (generated)" id="1603187434414-3">
    <createSequence cycle="false" incrementBy="1" maxValue="9223372036854775807" minValue="-9223372036854775808" sequenceName="revision_sequence" startValue="1"/>
</changeSet>
<changeSet author="testUser (generated)" id="1603187434414-4">
    <addColumn tableName="fulfillment_container_details_audit_3">
        <column name="container_number_3" type="varchar(255 BYTE)"/>
    </addColumn>
</changeSet>

What is createSequence changeSet, why it is generated?
Note: application-local.properties is my property file, I have added property spring.liquibase.contexts=local and I'm using it against SQL SERVER/MSSQL


text:
Q: How can I add a character into a specified position into string in SQL? I have a column which can contain up to 500 characters (Message Varchar (500)).
I need to insert a Caret (^) at position 250, or if there are less then 250 characters i.e. 120, then at the last characters position.
Example 497 characters;
strong textFar far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean. A small river named Duden flows b^y their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth. Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographi.

The Caret is inserted at characters 250 which splits the word "by" into "b^y".
Example 140 characters;
Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in.^

As this example has less than 250 characters, then the Caret is inserted at the end of the message.
The max characters that will ever be inputted will be 499, therefore leaving 1 character for the inserting of the Caret.
Any help would be grateful.

A: Quite simple with CASE and STUFF:
-- @t is assumed to contain the text to be changed

CASE WHEN LEN(@t) > 250
    THEN STUFF(@t,250,0,'^')
    ELSE @t + '^' END


text:
Q: JSF null value in parameter for managed bean viewscoped I'm trying to send the value of an attribute of a managedbean called Categoria_foro from another managedbean called ControllerManagedForo, in which it is redirected to a view foro.xhtml, so that when it calls EL, Categoria_foro already has the values set. The problem is that the value is not being set
I am using JSF 2.2.9 and primefaces 6.2, this is the code
@ManagedBean(name = "controllerManagedForo")
@ViewScoped
public class ControllerManagedForo {

    private String categoria_nombre;

    public void buscar_foro_porCategoria() {
        categoria_nombre = "something"
        ExternalContext ec =
        FacesContext.getCurrentInstance().getExternalContext();
                ec.getRequestMap().put("categoria_nombre",
        categoria_nombre);
        ec.redirect("foro.xhtml");
    }
}

@ManagedBean(name = "categoria_foro")
@ViewScoped
public class Categoria_foro {

    private String nombre;

    @PostConstruct
    public void init() {
        ExternalContext ec =
        FacesContext.getCurrentInstance().getExternalContext();
        nombre =  (String) ec.getRequestMap().get("categoria_nombre");

    }
}

Obviously getters and setters are defined.
The attribute nombre of Categoria_foro that receives the value of the key is null, any idea of what the problem might be?


text:
Q: Mysql group by clause with multiple selects I have 2 columns in my product table -name and brand, Given is the data,
NAME               BRAND
'Ruby Axe Guitar', 'Guitar''s & Co'
'TV'             , 'LG'

When I tried this query its working fine,
select name,brand, sum(1000) as sum,'Test' as name1
from products
group by name,brand

but I got surprised even when I dont include brand in the group by clause the query is working fine..
select name,brand, sum(1000) as sum,'Test' as name1
from products
group by name

Can someone explain?

A: You cannot select ungrouped row without aggregate function - MySQL will give you random value. I guess you are lucky with this second query

A: Because NAME is already unique with your data, so GROUP BY NAME is same as GROUP BY NAME, OTHER_FIELD.
NAME is unique, then the combination with any other column is unique too.

A: MySQL is a lot less strict than it should be IMHO. According to the actual SQL specification, any non-grouped column needs an aggregate function in a query containing a GROUP BY clause.
MySQL will allow retrieving non-grouped columns without such aggregate functions, returning an arbitrary value. They have an explanation of this choice in their documentation:

MySQL extends the use of GROUP BY so that the select list can refer to
  nonaggregated columns not named in the GROUP BY clause. This means
  that the preceding query is legal in MySQL. You can use this feature
  to get better performance by avoiding unnecessary column sorting and
  grouping. However, this is useful primarily when all values in each
  nonaggregated column not named in the GROUP BY are the same for each
  group. The server is free to choose any value from each group, so
  unless they are the same, the values chosen are indeterminate.

A: I believe its intended as an ignored oversight.  TYPICALLY, you would be required to include any column that is a non-aggregate into the "GROUP BY" clause.  However, MySQL basically grabs the first entry for the column not part of the aggregate it encounters.
This could be ok, such as doing a query against a table/columns that you know wont change no matter how many records in the corresponding group by.  For example.  You want a list of customers and their total orders.  The orders table has a customer ID that joins to the customer table.  So, you can do a SUM( Orders.Amount ), yet still get customer ID, Name, Address, Phone.  Since the join is on a customer ID, the corresponding name, address, etc will never change and thus not be important within the group by.  Just group by a customer ID.
So, MySQL won't choke on you if you inadvertently leave out a column...


text:
Q: C: Store parameter passed when calling main I would like to know how to store parameters in C when I compile:
For example: I'd like to store 2 user-input string variables.
The main is called like this:
./main "Hello World!" World

We should store "Hello World!" in string1 and "World" in string2
(supposing we can only use the main function and no head function), without using pointers.
edit: here is my code that still doesn't work:
#include <stdio.h>
#include <err.h>

int
main (int argc, char *argv[])
{
    if (argc != 2)
    {
    errx(1, "Error");
    }
    printf("Number of arguments = %i\n", argc);
    for (int k = 0; k < argc; k += 1)
        {
        printf("argv[%i] = %s\n", i, argv[i]);
        }
return 0;
}

A: Actually the main declaration is int main(int argc, char **argv); or int main(int argc, char *argv[]);, where:

*

*argc is the number of arguments passed

***argv or *argv[] contains the arguments to pass

So you have to use pointers to pass the arguments (as main is declared), there is no other way. In your example (./main "Hello World!" World), the program will receive:

*

*argc is 3

*argv[0] is ./main

*argv[1] is Hello World!

*argv[2] is World


text:
Q: How to hide parts of the view given a user role on Rails 4 I'm trying to hide parts of my views depending on the User role.
So let's say I want only admins to be able to destroy Products. Besides the code in the controller for preventing regular users from destroying records, I would do the following in the view:
<% if current_user.admin? %>
  <%= link_to 'Delete', product, method: :delete %>
<% end %>

The previous code works, but it's prone to errors of omission, which may cause regular users to see links to actions they are not allowed to execute.
Also, if I decide later on that a new role (e.g. "moderator") can delete Products, I would have to find the views that display a delete link and add the logic allowing moderators to see it.
And if there are many models that can be deleted only by admin users (e.g. Promotion, User) maitenance of all the ifs would be pretty challenging.
Is there a better way of doing it? Maybe using helpers, or something similar? I'm looking for something maybe like this:
<%= destroy_link 'Delete', product %> # Only admins can see it
<%= edit_link 'Edit', promotion %> # Again, only admins see this link
<%= show_link 'Show', comment %> # Everyone sees this one

I found these two questions that are similar to mine, but none of them answered my question:
Show and hide based on user role in rails
Ruby on Rails (3) hiding parts of the view

A: I strongly recommend pundit.
It allows you to create "policies" for each model. For your Product model you might have a ProductPolicy that looks something like this
class ProductPolicy < ApplicationPolicy
  def delete?
    user.admin?
  end
end

In your view you can do something like this
<% if policy(@post).delete? %>
  <%= link_to 'Delete', product, method: :delete %>
<% end %>

If later on you want to add a moderator role, just modify the policy method
class ProductPolicy < ApplicationPolicy
  def delete?
    user.admin? || user.moderator?
  end
end

A: So I kind of figured a way to move the IFs out of the view. First, I override the link_to helper in my application_helper.rb:
def link_to(text, path, options={})
  super(text, path, options) unless options[:admin] and !current_user.admin?
end

Then on my views I use it as:
<%= link_to 'Edit Product', product, admin: true, ... %>

This prevents regular users from seeing admin links, but for other html tags with content inside, such as divs, tables etc., an if would still be needed.

A: CanCan is another gem that lets you define "Abilities" per user role.
In views you can use something like if can? :delete, @post to check if the
user may delete that specific post.

A: Using the CanCan and Role gems, what is still needed is a way to Check The Route and see if "current_user" has permissions to access that Route based on their role(s) - then show/hide based on that.
This saves the user clicking on things and getting told they cannot see it - or us having to write per-item "if" logic specifying what roles can see what list-items (which the customer will change periodically, as roles are changed/refined) around every single link in one's menu (consider a bootstrap menu with 50+ items nested in groups with html formatting, etc), which is insane.
If we must put if-logic around each menu-item, let's use the exact same logic for every item by checking the role/permissions we already defined in the Ability file.
But in our menu-list, we have route-helpers - not "controller/method" info, so how to test the user's ability to hit the controller-action specified for the "path" in each link?
To get the controller and method (action) of a path (my examples use the 'users_path' route-helper) ...
Rails.application.routes.recognize_path(app.users_path)
        => {:controller=>"users", :action=>"index"}

Get just the controller-name
    Rails.application.routes.recognize_path(app.users_path)[:controller]
        => "users"

Ability uses the Model for its breakdown, so convert from controller name to it's model (assuming default naming used) ...
    Rails.application.routes.recognize_path(app.users_path)[:controller].classify
        => "User"

Get just the action-name
    Rails.application.routes.recognize_path(app.users_path)[:action]
        => "index"

And since the "can?" method needs a Symbol for the action, and Constant for the model, for each menu-item we get this:
    path_hash = Rails.application.routes.recognize_path(app.users_path)
    model = path_hash[:controller].classify.constantize
    action = path_hash[:action].to_sym

Then use our existing Abilty system to check if the current_user can access it, we have to pass the action as a symbol and the Model as a constant, so ...
    <% if can? action model %>
        <%= link_to "Users List", users_path %>
    <% end %>

Now we can change who can see this resource and link from the Ability file, without ever messing with the menu, again.  But to make this a bit cleaner, I extracted out the lookup for each menu-item with this in the app-controller:
def get_path_parts(path)
  path_hash = Rails.application.routes.recognize_path(path)
  model_name = path_hash[:controller].classify.constantize
  action_name = path_hash[:action].to_sym
  return [model_name, action_name]
end
helper_method :get_path_parts

... so I could do this in the view (I took out all the html-formatting from the links for simplicity, here):
<% path_parts = get_path_parts(users_path); if can?(path_parts[1], path_parts[0]) %>
    <%= link_to "Users Listing", users_path %>
<% end %>

... and to make this not take all day typing these per-menu-item if-wraps, I used regex find/replace with capture and wildcards to wrap this around every list-item in the menu-item listing in one pass.
It's far from ideal, and I could do a lot more to make it much better, but I don't have spare-time to write the rest of this missing-piece of the Role/CanCan system.  I hope this part helps someone out.


text:
Q: How to do "in-place editing" of a JFace Table? In WPF (.net), when a DataGrid is made editable and set to an observable collection, there is a placeholder row. When one clicks on it, a new element is added to the backing collection and the table is put into edit mode.
Is something like this possible with JFace Table Viewers as well?
The only solution I can think of is to create a custom observable list that delegates to the "real" list I want to observe, but always adds an additional placeholder object to the end, which gets inserted into the "real" list as soon as it is edited. But that seems a bit hackish to me...


text:
Q: Understanding socket.io broadcasting of messages to specific users connected to a socket Using socket.io within a Node.js/Express setup, I'm trying to understand the functionality of when it comes to broadcasting messages to specific sockets/user-ids.
For example:
io.on('connection', (socket) => {
  socket.join('user-1');
});

then further down the code, I have the following code:
io.to('user-1').emit('user-1 has joined the room');

What I am trying to understand is the broadcasting of messages to specific users.
Say I I had 5 different users accessing the website that has the above code and assuming that each of these users had their own unique user-ids,
i.e. user-1, user-2, user-3 etc, which was passed in as part of the socket.join('user-2') for user-2, socket.join('user-3') for user-3 and so on.
Now if I wanted to broadcast a message from a specific endpoint to a specific user, say user-3 ONLY, could I achieve this with just the following code:
io.to('user-3').emit('user-3 has joined the room');

or would I also need to associate each user connected with the socket#id?
I'm hoping the io.to(....).emit(....) syntax can use the user-id alone but if not, what would be the best approach to accomplish the above as there may well be a lot of users connected.


text:
Q: GStreamer pipeline in C++ I have a working GStreamer-1.0 pipeline in terminal and I'm trying to replicate it in code using GStreamer 1.0 on Mac/Xcode.
My sending pipeline:
gst-launch-1.0 videotestsrc ! videoconvert ! x264enc ! rtph264pay config-interval=1 ! udpsink host=127.0.0.1 port=5000

My receiving pipeline:
gst-launch-1.0 -vvv udpsrc port=5000 caps="application/x-rtp" ! rtph264depay ! avdec_h264 ! videoconvert ! xvimagesink

This can also by played back in VLC with the following SDP file:
v=0
m=video 5000 RTP/AVP 96
c=IN IP4 127.0.0.1
a=rtpmap:96 H264/90000

I've created the following code to replicate the aforementioned but the problem is that the receiving pipeline doesn't display anything while running this code. The code does send packets to the network according to the Xcode debug console.
gint
main (gint   argc,
      gchar *argv[])
{
    GstElement *pipeline, *videosrc, *conv,*enc, *pay, *udp;

    // init GStreamer
    gst_init (&argc, &argv);
    loop = g_main_loop_new (NULL, FALSE);

    // setup pipeline
    pipeline = gst_pipeline_new ("pipeline");

    videosrc = gst_element_factory_make ("videotestsrc", "source");

    conv = gst_element_factory_make ("videoconvert", "conv");

    enc = gst_element_factory_make("x264enc", "enc");

    pay = gst_element_factory_make("rtph264pay", "pay");
    g_object_set(G_OBJECT(pay), "config-interval", 1, NULL);

    udp = gst_element_factory_make("udpsink", "udp");
    g_object_set(G_OBJECT(udp), "host", "127.0.0.1", NULL);
    g_object_set(G_OBJECT(udp), "port", "5000", NULL);

    gst_bin_add_many (GST_BIN (pipeline), videosrc, conv, enc, pay, udp, NULL);

    if (gst_element_link_many (videosrc, conv, enc, pay, udp, NULL) != TRUE)
    {
        return -1;
    }

    // play
    gst_element_set_state (pipeline, GST_STATE_PLAYING);

    g_main_loop_run (loop);

    // clean up
    gst_element_set_state (pipeline, GST_STATE_NULL);
    gst_object_unref (GST_OBJECT (pipeline));
    g_main_loop_unref (loop);

    return 0;
}

A: The problem was that the port parameter is supposed to be an int, so I had to change
g_object_set(G_OBJECT(udp), "port", "5000", NULL);

to
g_object_set(G_OBJECT(udp), "port", 5000, NULL);

Sometimes it's easy to miss one's own simple mistakes.


text:
Q: Error in AWS DMS Endpoint using Oracle database as a source I have tried to configure an AWS DMS Endpoint, but when I try to do the connection test it shows me the following error:

Test Endpoint failed: Application-Status: 1020912, Application-Message: Log Miner is not supported in Oracle PDB environment Endpoint initialization failed.

I have given all the grants that are required in Oracle DB following the documentation:
https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.Oracle.html
But the error still persists. What could be the solution?

A: Add this line to extra connection attributes (under endpoint settings)
useLogMinerReader=N;useBfile=Y;

make sure to grant necessary permission to your container user on this link https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.Oracle.html#CHAP_Source.Oracle.Self-Managed.BinaryReaderPrivileges


text:
Q: jQuery undefined in 1.2 stable jquery.mobile.js I have updated jquery.mobile-1.0b2.js to jquery.mobile-1.2.0.js. I am getting jQuery undefined error.
In the previous beta version, I have modified the js as
(function(jQuery) {
// beta version code here..
})(custom.jquery);

where custom.jquery is defined as
custom.jquery = jQuery.noConflict(true);

in the jquery.js
I have done similar wrapping in the stable 1.2 js and got the undefined error.
Without wrapping also got the same error.
Please advice me.


text:
Q: The method getColumnName in ResultSetMeta can't return right name of column (jdbc) I want to get table label of column .like string display in mysql. Like this

However, when I use getColumnName, It turn out there is some difference  between returned string and  below string.  Like this:

But It is right in Variables explorer in eclipse when I debug, Like this:

I can't find other way to get column. It seem returned string is originalColumnName, but how to get ColumnName? Anyone know how to fix it?
There is my code, I know there is other problem in code. Please just assume the type of all column is String.
      public ResultSet DisplayShowTables() throws SQLException
  {
      ResultSet Res = Sta.executeQuery("DESC Code2Name");
      ResultSetMetaData ResMeta = Res.getMetaData();
      String [] ColumnName = new String [ResMeta.getColumnCount()];
      int MetaCount = ResMeta.getColumnCount();
      for (int i = 0; i < MetaCount; i++) {
          ColumnName [i] =  ResMeta.getColumnName(i+1);
    }
      String LeftAlignFormat = "|";
      String Separator = "+";
      for (int i = 0; i < MetaCount; i++) {
          LeftAlignFormat = LeftAlignFormat.concat(" %-20s |");
          Separator =Separator.concat("----------------------+");
    }
      LeftAlignFormat = LeftAlignFormat.concat("%n");
      Separator = Separator.concat("%n");
      if(Res.isBeforeFirst()){
            System.out.format(Separator);
            System.out.format(LeftAlignFormat, ColumnName);
            System.out.format(Separator);
        }
      while (Res.next()) {
        Vector<String> RowData = new Vector<String>();
        for (int i = 0; i < MetaCount; i++) {
            RowData.add(Res.getString(i+1).toString());
        }
        System.out.format(LeftAlignFormat, RowData);
    }
        if(Res.isAfterLast())
            System.out.format(Separator);
      return Res;
  }

A: It looks like DESC is just a shortcut for a query of the information schema with aliases for the columns.
Column aliases can be retrieved with ResultSetMetadata.getColumnLabel(int).
JDBC defines column label as:

Gets the designated column's suggested title for use in printouts and displays. The suggested title is usually specified by the SQL AS clause. If a SQL AS is not specified, the value returned from getColumnLabel will be the same as the value returned by the getColumnName method.

This also means that in almost all situation you should be using getColumnLabel instead of getColumnName.


text:
Q: Browser installation on CentOS after install the latest stable version of Google Chrome on a fresh CentOS 7 I get this error when trying to run it as "root".
[root@ip-172-31-49-161 /]# google-chrome &
[4] 11889
[root@ip-172-31-49-161 /]# [1:1:0912/031926:ERROR:image_metadata_extractor.cc(111)] Couldn't load libexif.
[1:1:0912/031926:ERROR:nacl_fork_delegate_linux.cc(314)] Bad NaCl helper startup ack (0 bytes)

Do you have any idea how to solve this problem?


text:
Q: How can I get javascript value and store to html? I want to add a rating to my system,  please help me to get the value from javascript and store in html.
Here is my js
$( document ).ready(function() {
  $('#stars').on('starrr:change', function(e, value){
  $('#count').html(value); });

The js is working fine, it return the number of rating.

You gave a rating of 0 star(s)

I want to get the result of id = count and store in html input named rate.
<input type="hidden" name="rate" value="">

Thank you so much!

A: Here's an example, hope this helps.

document.getElementById('rate').addEventListener('input', function() {
  document.getElementById('count').innerHTML = this.value;
});

You gave a rating of 0 star(s)

<input id="rate" type="number" name="rate" value="">

A: I'm pretty sure that instead of .html you can use .val().text() for this case. You're wanting the value right?

A: Select the input box using Jquery Selector $('input[name=rate]') and assign value to it.
$('input[name=rate]').val($('#count').html());

A: $('input[name=rate]').val(starcount);

Where starcount is the variable that holds the number of stars


text:
Q: django rest framework search filter all fields I have a base model view set which i can handle order, pagination and search functionalities.
When i have proper filter backends, i can set ordering_fields, search_fields but my question is that:
 like i can set ordering_fields = '__all__'  isn't it possible to set search_fields for all?
I've looked for deep inside filtering mechanism and came here:
def filter_queryset(self, request, queryset, view):
    search_fields = getattr(view, 'search_fields', None)

    if not search_fields:
        return queryset

    orm_lookups = [self.construct_search(six.text_type(search_field))
                   for search_field in search_fields]

    for search_term in self.get_search_terms(request):
        or_queries = [models.Q(**{orm_lookup: search_term})
                      for orm_lookup in orm_lookups]
        queryset = queryset.filter(reduce(operator.or_, or_queries))

    return queryset

drf fails on generate search_fields if it is set search_fields='__all__'
Is there any other way to provide search by all functionality?

A: Not possible and it's not a good idea anyway..
One reason is because there can be different types of searching query (__istartswith, __iexact, etc.), which you can set up for each field name.
You can also have different field types which won't necessary support text-base search.
More important - it will result in much slower queries, while you keep adding new fields into the model. It's always better to be explicit, so you know which fields are actually searched upon.
If your searching feature relies on multiple fields, maybe you should consider haystack or look for any other dedicated searching engine.


text:
Q: what is the security risk when enabling directory listing in linux web servers I have a few folders in which i did not have any index.htm or index.php and i dont want to have one so that i can see all the html files in that. I dont have other extensions other than .htm in those folders.
What will be the security risk in having directory listing enabled?

A: The security risk is such that users can see whats in that directory and if that directory has other directories below it.
Some PCI security scanners will detect directory indexing as a security issue because malicious users could potentially work out what file structure you are using, which system and even sometimes which web script if you use one and use that info to launch an attack - this risk is generally classified as low though


text:
Q: zf2 code completion in PHPStorm for $this->form I'm using zend framework 2 with PHPStorm 7.1.2
Inside my view I want to have code completion for $this->form().
Here is the code:
Controller:
public function indexAction() {
    $viewModel = new ViewModel();
    $form = new SearchForm('search');
    $viewModel->setVariable('form', $form);
    return $viewModel;
}

View:
<?php
/**
 * @var \Zend\View\Renderer\PhpRenderer $this
 * @var \Application\Form\SearchForm $form
 */
?>

<?php $form->setAttribute(...); ?>
<?php $form->prepare(); ?>
<?php $this->form()->openTag($form); ?>

...

<?php $this->form()->closeTag(); ?>

In my view I got code completion on e.g. $this->url(...); and on $form->setAttribute(...);.
How must I annotate my file to get code completion on $this->form()?
PHPStorm tells something about

Method 'form' not found in class Zend\View\Renderer\PhpRenderer

...
Thanks,
Jens

A: $this->form() as well as $this->formXY() are ViewHelpers and you won't get any kind of type-hinting for those.


text:
Q: Custom Android build script in eclipse that behaves differently for release and debug without ant I have created a custom build script in python that changes some strings in my strings.xml. But now I need it to change some other strings depending on whether it is a release or debug build. I can't seem to find a variable that I can send as parameter to the script that differentiates between the two.
I want to avoid going over to ant if at all possible, since we have build servers and all kinds of stuff that need changing then too.
Does anyone have experience with this?

A: One way to do this is to test the app's signature at runtime. You could load different strings based on that result:
How to make Android app automatically configure w/ debug vs. release values?


text:
Q: How to enforce low FPS in v4l2 for /dev/video0? I am running 2 Philips SPC900NC Webcams under Debian Jessie (3.4 and 4.7 kernels). The cam is doing great in low light situations, if FPS can be reduced to 10 FPS or even 5 FPS. This works fine e.g. by recording a video with ffmpeg via:
ffmpeg -f v4l2 -framerate 5 -video_size 640x480 -i /dev/video0 test.mp4

But with surveillance tools like Motion and ZoneMinder, the cam always defaults to 15FPS - independently of any FPS rates I set in these programs. Also running "v4l2-ctl --set-parm 5" gets overwritten when Motion or ZoneMinder are started (I checked with: v4l2-ctl --get-parm).
I played with v4l2loopback and the following config is actually enforcing 5fps: /dev/video0 -> ffmpeg -> /dev/video1 -> Zoneminder. But the problem is additional CPU consumption of ffmpeg.
Is there any possibility to archive 5 FPS by enforcing the FPS in v4l2 natively (avoiding adding v4l2loopback/ffmpeg to the mix) ?

A: if it is this what you looking for:
v4l2loopback-ctl set-fps 25 /dev/video0
Source.


text:
Q: Migrating a Win32 app that uses the AppData folder to share files to Desktop Bridge I am migrating some Win32 apps to the Windows Store using Desktop Bridge. I have several apps that have been sharing files in %APPDATA%\Roaming\XYZCompany. I understand from the Microsoft docs that this will no longer work since each app will have its own isolated version of the AppData folder.
So what is the "right" way to share files between my own UWP / Desktop Bridge apps?
The best solution I've come up with so far is moving the shared files to the user's documents folder, but that seems ugly. In iOS and Android there are slick ways for apps from one developer to share files. Is there something like that for UWP apps that I just haven't found?

A: You can create a PublisherCacheFolder (see documentation) which can be used to share data among your UWP apps.
To be able to use this API, you need to declare the names of your folder in the package.appxmanifest file:
<Extensions>
    <Extension Category="windows.publisherCacheFolders">
     <PublisherCacheFolders>
       <Folder Name="MyFolder" />
     </PublisherCacheFolders>
    </Extension>
</Extensions>

Now you can access this folder:
var folder = ApplicationData.Current.GetPublisherCacheFolder( "MyFolder" );

For more info look into this article on MSDN.


text:
Q: OpenCV : Python equivalent of `setTo` in C++ What is the python equivalent of Mat::setTo in C++ ?
What I'm trying to do is to set value by mask:
Mat img;
...
img.setTo(0, mask);

Update:
Here is possible solution:
#set by mask area to zero
img= np.random.rand(200, 200, 3) * 255
img= img.astype(np.uint8)
mask = np.zeros((200, 200), np.uint8)
mask[10:100, 60:140] = 255
inv_mask= cv2.bitwise_not(mask)
n_channels= img.shape[2]
for i in range(0,n_channels):
    img[..., i]= img[..., i] * (inv_mask/255)

#to set arbitary value
img= np.random.rand(200, 200, 3) * 255
img= img.astype(np.uint8)
mask= np.zeros((200,200), np.uint8)
mask[10:100, 60:140]= 255
mask_bool= np.where(mask > 0)
value= 120
img[mask_bool]= value

A: You can simply use img[mask > 0] = 0 which is the python equivalent of img.setTo(0, mask);

A: opencv in python uses numpy as backend (more specifically numpy.ndarray) for images. This means you can do the following:
import numpy
img = numpy.zeros((256, 256, 3))  # This initializes a color image as an array full of zeros

Then if i wish to set the third channel as 1 all I have to do is:
img[:, :, 2:3] = 1

Therefore if Mask has the same dimensions as my third channel i can use it to set the third channel:
img[:, :, 2:3] = mask

edited after comment: in case you simply wish to set pixels of image to zeros using a mask a simple image * mask should suffice. make sure mask has same number of dimensions as image.
edit #2: Yeah that might work, but if the shape of your mask is the only issue, i would use mask[:, :, numpy.newaxis] to add a dimension and then multiply with image.
btw numpy.newaxis is same as using mask[:,:,None].


text:
Q: How to cut text placed beetween two words using regular expression? I'm beginner in regular expressions and I want to cut some text placed beeween two other words. I'm using QT to do it. Some exapmle:

Feels like 55°

I want to get

Feels like 55°

From code above, sespecially a number 55 , my idea was to cut whole line from text first and then search it for nubers, but I cannot recover it from whole text.
I typed somthing like that:

QRegExp rx("(Feels like )[0-9]{1,3}(°)");
QStringList list;
list = all.split(rx);

Where     all  is a whole text, but a list contains only those substrings I didn't wanted, is there a posibity split QString into three pieces?
First - text at the beginning (which I don't want)
Second - wanted text
Third - rest of text?

A: Description
This regex will collect the inner string within the li tags where the li tag has a class of wx-feels, it'll also capture the numeric value inside the span tag.

]*\bclass=(["'])wx-feels\1[^>]*?>(.*?\bitemprop=(['"])feels-like-temperature-fahrenheit\3[^>]*>(\d+).*?)<\/li>

Groups
Group 0 gets the entire string including the open and close LI tags

*

*gets the open quote for the LI class attribute. This allows us to find the correct close quote after the value

*get the string directly inside the LI tag

*gets the open quote for the itemprop attribute

*gets the digits from the span inner text

Example
This PHP example is simply to show how the regex works.
<?php
$sourcestring="

Feels like 55°

";
preg_match('/
]*\bclass=(["\'])wx-feels\1[^>]*?>(.*?\bitemprop=([\'"])feels-like-temperature-fahrenheit\3[^>]*>(\d+).*?)<\/li>/ims',$sourcestring,$matches);
echo "
".print_r($matches,true);
?>

$matches Array:
(
    [0] =>

Feels like 55°

    [1] => "
    [2] =>
Feels like 55°

    [3] => "
    [4] => 55
)

Disclaimer
Parsing html with a regex can be problematic because of the high number of edge cases. If you are in control of the input text or if it's always as basic as your sample, then you should have no problem.
If QT has one, I recommend using an HTML parsing tool to capture this data.


text:
Q: Find directories and create new sub directory inside each directory found I need to insert a file in a new subdirectory that I will create when the find command is executed.
# find /home/user*/.dir/anotherdir -maxdepth 1 -type d -iname "*.default"
anotherdir/dwwcop9o.default
anotherdir/dge77smm.default

In each of the above "find" results I need to create subdir so that the directory structure would look like below:
anotherdir/dwwcop9o.default/subdir
anotherdir/dge77smm.default/subdir

Finally, after creating subdir above, I need to insert a file inside of the subdir.
How do I do this using xargs, -exec or -execdir?

A: Finally able to solve this, see below.
# find /home/user*/.dir/anotherdir -maxdepth 1 -type d -iname "*.default" -exec mkdir {}/anotherdir \; -exec cp newfile {}/anotherdir \;

N.B.
newfile must be in your current working directory, if not, define its absolute path.


text:
Q: MS Access db.Execute " INSERT INTO can anyone write "db.Execute " INSERT INTO" command for below details.
Table name - Data_Load
Form name - Form1
take data from - Form1 - Cmb1 , txt1 , txt2
save to - Data_load = Style, Size1, Size 2

A: Just bind your form (set its RecordSource) to Data_Load, and Cmb1, txt1, and txt2 to Style, Size1, Size2 respectively.
That's the way to do it in Access using a form.


text:
Q: Comparing dates in Selenium IDE The following is meant to compare a Date of Birth and confirm the individual is 10 years old or greater. It appears to work, however I want some advice to improve or ensure my logic is correct for my date comparison within Selenium IDE. Do I need to use Date.parse() to turn these to milliseconds as per this advice or will these proper date formats be sufficient to compare them accurately?

storeEval
new Date("${DateOfBirthYear}","${DateOfBirthMonth}"-1,"${DateOfBirthDay}");
DateOfBirthAsDate

storeEval
new Date();
today

storeEval
(Date.prototype.addMonth = function(month) { var dat = new Date(this.valueOf()); dat.setMonth(dat.getMonth() + month); return dat; }); var dat = storedVars['today'];dat.addMonth(-120)
DateOfBirthEleven

storeEval
(storedVars['DateOfBirthEleven'] < storedVars['DateOfBirthAsDate'] ) ? true : false
AgeOK

Advice and suggestions welcome.

A: The code looks fine. I wouldn't change it if it works - comparing milliseconds won't make any difference when you are comparing days.

A: I would do something like this:
var a = new Date('03/21/1980');
var b = new Date('03/21/1989');
console.log(a);
console.log(b);
var yearDiff = b.getYear() - a.getYear();
if( yearDiff >= 10) {
  console.log("over 10!");
}
else if (yearDiff >= 9) {
 //compare milliseconds for 1 year
 console.log("over 9!");
}

Just because a "year" is different with leaps, etc... but if their over 10 clearly you can skip semantics...
Sorry, didn't have time to put into seleniumese


text:
Q: Removing rows based on a stretch of repeated values in R, but not the whole data frame I have a data frame of ~20,000 rows that is two columns: Time and Steps. There are stretches duplicate/repeated readings of steps that are a few seconds to a few minutes apart, so unique() does not catch them. !duplicates removes duplicates for the whole data frame, so that there is only one row with X steps, even if a legit record days later has X steps. I want to remove these stretches of repeats, leaving one unique record, it doesn't matter which one is kept. Also, the number of repeats is not consistent. It may be 8, it may be 2.
>View(df)
          Time                Steps
    13737 2017-08-07 09:53:14 16
    13738 2017-08-07 09:53:14 16
    13739 2017-08-07 09:57:51 61
    13740 2017-08-07 09:59:05 61
    13741 2017-08-07 09:59:07 61
    13742 2017-08-07 09:59:11 61
    13743 2017-08-07 09:59:14 61
    13744 2017-08-07 09:59:14 61
    13745 2017-08-07 10:03:51 29
    13746 2017-08-07 10:05:05 29
    13747 2017-08-07 10:05:07 29
    13748 2017-08-07 10:05:11 29
    13749 2017-08-07 10:05:14 29
    13750 2017-08-07 10:05:14 29
    13751 2017-08-07 10:09:51 54
    13752 2017-08-07 10:11:05 54
    13753 2017-08-07 10:11:07 54

Desired output:
13737 2017-08-07 09:53:14 16
13739 2017-08-07 09:57:51 61
13745 2017-08-07 10:03:51 29
13751 2017-08-07 10:09:51 54

Another solution I've pondered is just paring down the dataset to just take rows every 10 minutes or so, and if that is ideal, I could use some guidance there too

A: We can use dplyr. Arrange the data frame by Steps and Time first and then group by Steps. Finally, slice the data frame for the first row per group.
library(dplyr)
library(lubridate)

df2 <- df %>%
  mutate(Time = ymd_hms(Time)) %>%
  arrange(Steps, Time) %>%
  group_by(Steps) %>%
  slice(1)

Or this
df2 <- df %>%
  mutate(Time = ymd_hms(Time)) %>%
  arrange(Steps, Time) %>%
  group_by(Steps) %>%
  filter(row_number() == 1)

Or we can use the data.table.
library(data.table)
dt <- as.data.table(df)
dt2 <- dt[, .SD[1], by = Steps][, c("Time", "Steps")]

Data Preparation
df <- read.table(text = "          Time                Steps
    13737 '2017-08-07 09:53:14' 16
    13738 '2017-08-07 09:53:14' 16
    13739 '2017-08-07 09:57:51' 61
    13740 '2017-08-07 09:59:05' 61
    13741 '2017-08-07 09:59:07' 61
    13742 '2017-08-07 09:59:11' 61
    13743 '2017-08-07 09:59:14' 61
    13744 '2017-08-07 09:59:14' 61
    13745 '2017-08-07 10:03:51' 29
    13746 '2017-08-07 10:05:05' 29
    13747 '2017-08-07 10:05:07' 29
    13748 '2017-08-07 10:05:11' 29
    13749 '2017-08-07 10:05:14' 29
    13750 '2017-08-07 10:05:14' 29
    13751 '2017-08-07 10:09:51' 54
    13752 '2017-08-07 10:11:05' 54
    13753 '2017-08-07 10:11:07' 54",
                 header = TRUE, stringsAsFactors = FALSE)


text:
Q: Postgres/Redshift: Extract Quarter and Year from date column for a group by in one call? I was wondering if there was a way to extract a year and Quarter from a date column in one call from Redshift/Postgres DB in order for me to group by on them?
Since query speed is very important to me, I currently have the year and column as two columns along with the date which I am not happy about, as I have this information in the date column however they make queries almost twice as fast if I join on them versus using two extract() calls on the date to get the year and quarter.
e.g
Select SUM(some_column),
EXTRACT(YEAR FROM the_date) as year_date,
EXTRACT(YEAR FROM the_date) as q_date
FROM table
Group by year_date, q_date;

vs
Select SUM(some_column),
year_date,
q_date
FROM table
Group by year_date, q_date;

I would be looking for something like this:
Select SUM(some_column),
extract(Year | Quarter from the _date) AS year_q
FROM table
Group by year_q;

I tried the to_char method but it's slower than both options above.
Thanks

A: I assume this is for analytics purpose.
It's much better to materialize separate columns for the year, quarter and year-quarter from the_date column, as is suggested in one of the comments. That way you can use these to group by year, quarter number across years or by quarters. But what columns you materialize really depends on the analytics requirements.
To answer your specific question, lets say you have a table as below.
create table source_table (
    some_column         int,
    the_date            timestamp
);

You can use a CTAS query of the following form to create a table suitable for analytics from this.
create table analytics_table as (
    select
        some_column,
        extract(year from the_date) as year,
        extract(quarter from the_date) as quarter,
        extract(year from the_date) || '-' || extract(quarter from the_date) as year_quarter
    from
        source_table
);

On this table you could then run queries of the following form, which should go through much faster.
select
    year,
    sum(some_column)
from
    analytics_table
group by
    year
;

select
    year_quarter,
    sum(some_column)
from
    analytics_table
group by
    year_quarter
;


text:
Q: Two Separate .xaml files into one window I have ColorStream.xaml and SkeletonStream.xaml files, and I would like to put the SkeletonStream view in the bottom-right corner of the ColorStream window. Is that possible?
And if so, how would I connect the two, especially with the xaml file? Sorry, I'm pretty new with C#. I feel like it should just be an extra line, and I tried looking at the KinectExplorer example. Thanks!

A: Maybe I'm missing something, but is there a reason for having two xaml files? I would think you could just combine the xaml code into a single xaml file and use something like a grid to separate the sections. Like so:
<Grid x:Name="myGrid">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
</Grid>

// Bottom Right
<Stackpanel Grid.Row="1" Grid.Column="1"/>


text:
Q: Using Shapeless to implement an (HList of Function, Input) => Tuple typeclass I've got some existing code along the lines of
trait Field[T]
object Fields {
  case object Id extends Field[Int]
  case object Name extends Field[String]
  // ... and so on
}

// basically just a Map[Field[_], Any]
class QueryResultData {
  def apply[T](field: Field[T]): T
}

def query(fields: Set[Field]): QueryMonad[QueryResultData]

So for example if I want to query the Id and Name data, I need to do something like:
val idsAndNames = for {
  results <- query(Set(Fields.Id, Fields.Name))
} yield {
  val id = results(Fields.Id)
  val name = results(Fields.Name)
  (id, name)
}

Having to manually extract each field's result is tedious, especially when the query includes more fields. What I'd like to be able to do is:
val idsAndNames: QueryMonad[(Int, String)] = query(Fields.Id -> Fields.Name)

And have some kind of typeclass handle the val id = ... part and reconstruct the tuple for me, e.g.
def query[Fields <: HList, Tuple](fields: Fields)
  (implicit extractor: Extractor[Fields, T])
  : QueryMonad[T]

How can I implement the Extractor typeclass so that I don't have to manually extract results?

What I've Tried
I figured this was a job for Shapeless, as the query method is meant to work on any number of fields, and is expected to give me back an appropriate tuple.
I defined a FieldExtractor type:
class FieldExtractor[T](field: Field[T]) {
  def apply(results: QueryResultData): T = results(field)
}

and a polymorphic function for Field to FieldExtractor:
object makeFieldExtractor extends (Field ~> FieldExtractor) {
  def apply[T](field: Field[T]) = new FieldExtractor[T]
}

and for simplicity's sake I'll start by dealing with HLists instead of Tuples:
val someFields = Fields.Id :: Fields.Name :: Fields.OtherStuff :: HNil

I tried using my makeFieldExtractor to convert someFields into someFieldExtractors. This is where I started running into trouble.
val someFieldExtractors = someFields.map(makeFieldExtractor)

error: could not find implicit value for parameter mapper: shapeless.ops.hlist.Mapper[MakeFieldExtractor.type,shapeless.::[Fields.Id.type,shapeless.::[Fields.Name.type,shapeless.::[Fields.OtherStuff.type,shapeless.HNil]]]]

It seems like the problem is that it's seeing types like Fields.Id.type when it probably should be seeing Field[Int]. If I explicitly specify the field types for someFields, the map works, but I don't want client code to have to do that. The compiler should do that for me. And let's assume I can't just change the Id/Name definitions to a val instead of a case object.
I found https://github.com/milessabin/shapeless/blob/master/examples/src/main/scala/shapeless/examples/klist.scala but didn't manage to make any successful use of it.

A: Here is how I would done it.
import shapeless.{::, HList, HNil}
import Field._

trait Field[A]
object Field {
  case object IntField extends Field[Int]
  case object StringField extends Field[String]
  // Here is a little trick to proof that for any T that
  // happened to be a subclass of Field[A] the Out is A
  implicit def fieldExtractor[T, A]
  (implicit ev: T <:< Field[A]): Extractor.Aux[T, A] =
    new Extractor[T] {
      override type Out = A
    }
}

// The extractor for A
trait Extractor[A] {
  type Out // Produces result of type Out
}

object Extractor {
  // The Aux pattern http://gigiigig.github.io/posts/2015/09/13/aux-pattern.html
  type Aux[A, Out0] = Extractor[A] {
    type Out = Out0
  }

  // Proof that Out for HNil is HNil
  implicit val hnilExtractor: Aux[HNil, HNil] =
    new Extractor[HNil] {
      override type Out = HNil
    }

  // Proof that Out for T :: H is hlist of extractor result for H and T
  implicit def hconsExtractor[H, HO, T <: HList, TO <: HList]
  (implicit H: Aux[H, HO], T: Aux[T, TO]): Aux[H :: T, HO :: TO] =
    new Extractor[H :: T] {
      override type Out = HO :: TO
    }
}

type QueryMonad[A] = A

// Use dependent type Out as a result
def query[Fields](fields: Fields)(implicit extractor: Extractor[Fields]): QueryMonad[extractor.Out] = ???

val result = query(IntField :: StringField :: HNil)


text:
Q: Преобразование сырой строки списка в список Допустим есть строка "[{1 : 1, 2 : 2},2,[3,4]]" каким образом лучше всего преобразовать в питоновский список? Без использования eval.

A: Нашел ответ на англоязычном stackoverflow, если кратко, то так:
import ast
A = "[{1 : 1, 2 : 2},2,[3,4]]"
ast.literal_eval(A) [{1: 1, 2: 2}, 2, [3, 4]]

A: Попробуй вот так:
А = "[{1 : 1, 2 : 2}, 2, [3,4]]"
for i in A:
    if i == "[" or "]" or "{" or "}" :
        A.remove(i)
    else:
        pass

Если remove не сработает попробуй pop


text:
Q: Determining which variables to use in regression model So I'm trying to fit some binary outcome data to a logistic regression model. Besides the binary outcome I have several different metrics (numeric, integers, as well as factors) associated with each case (and outcome). Now, the idea is as usual to get the best model describing the data without overfitting of course.
I'm using R for this, so just to try it out, and getting the data well organized I use the glm function. I can use this to create a model using all variables (not a good one), or I can choose which ones I would like to use. But how does one determine which ones should be used ? I know I can use AIC values to see if one is better than another, but I have many metrics I can use, so that would result in a lot of different models to try out. And I don't think that is the way to use AIC.
So yeah, what is the basic approach in situations like this ? Do I run the glm function on a single variable at a time, and see if that has any significance, and then choose from there, or are there other more effective approaches ?


text:
Q: Applying jquery to WordPress admin edit.php We use the latest versions of WordPress with the Woocommerce plugin. I'm searching for the best way to apply jquery to custom post types such as WC. I have a lot of hooks already for Woocommerce, so for now I have added some jquery into a meta box that I have previously added to the edit.php page. For instance, I'm using jquery to click on the address buttons to display all the address fields and to hide the Refund button from non-admin users upon loading the page. I'm sure there must be a better apply jquery as I'm doing now below?
add_action( 'add_meta_boxes', 'my_add_meta_boxes' );
function my_add_meta_boxes(){
add_meta_box(
    'woocommerce-order-my-custom',
    __( 'My Meta Box' ),
    'order_my_custom',
    'shop_order',
    'side',
    'default'
);
}
// Add fields to the metabox
function order_my_custom( $post ){
//<code omitted that places fields in meta box>
?>
<script type="text/javascript">
    jQuery(document).ready(function ($) {
        $(".edit_address").click();
        $(".add-line-item").click();
    });
</script>
<?php
}

I have used admin_enqueue_scripts to add my own common jquery functions, but what is the best way to add your own jquery to a specific post type?

A: The previous answer works good with my example above using this hook:
add_action( 'admin_head', 'woocommerce_admin_init' );
function woocommerce_admin_init() {
    $screen = get_current_screen();
    if ( $screen->post_type == "shop_order" ) {
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            $(".edit_address").click();
            $(".add-line-item").click();
        });
    </script>
    <?php
    }
}

A: You can use the get_current_screen() function...it returns an object that contains lots of useful information about the screen that you are viewing inside of wp-admin.
For your purposes you'll want the post_type property of that object which will return the post type that the current admin screen is working with.
<?
$screen = get_current_screen();
if ( $screen->post_type == "ENTERYOURPOSTTYPE" ) {
?>
    <script>
        JAVASCRIPT HERE
    </script>

<?
}
?>

In your specific example you'll want to add the javascript where I've indicated and then attach that function to the admin_head hook.
add_action( 'admin_head', 'woocommerce_admin_init' );

function woocommerce_admin_init() {

    $screen = get_current_screen();

    if ( $screen->post_type == "shop_order" ) {
    ?>

        <script type="text/javascript">
            jQuery(document).ready(function ($) {
                $(".edit_address").click();
                $(".add-line-item").click();
            });
        </script>

    <?php
    }

}

Reference: http://codex.wordpress.org/Function_Reference/get_current_screen


text:
Q: SharePoint page under Pages library not loading When clicking on a link to a SharePoint page(newpage.aspx) from another page, it is taking to the actual page library rather than the page itself. When I switch to classic experience it loads the page.
Can someone please tell why it is happening?

A: Per my test in my SharePoint online environment, I can access one page from another page by the link, it can load the page.
Did you switch to classic experience in the Pages library?
To troubleshoot the issue, check things below:

*

*Check if the URL of the page(newpage.aspx) is right.

*Create a new page library and check if the same issue will occur.
If the issue only occurs in the Pages library, you could create a new page library and move the content to the new page library.


text:
Q: Dynamic Links domain not available According to the docs, there should be a Dynamic Links domain for my project, which is displayed at the top of the Dynamic Links page. The docs have a screen capture like so:
Location of domain according to the Firebase documentation
However, on the Dynamic Links page for my project there is no such domain, at least not one I can see. Here is a screen shot (I've blacked out identifying info, there was no domain under the black square or circle!):
Screen shot of Dynamic Links page with no domain displayed
I've tried looking through settings and options in case there was some kind of toggle, but haven't found anything relevant.

A: Create a test link with whatever informations you want and you will have a complete link with your app domain like: app_code.app.goo.gl


text:
Q: Is there a way to call ActionScript on Android? I have a SWF file in my assets folder that I need to use in my Android application.
So I write html file with SWF embedded and Javascript to call its ActionScript. I can play Flash file in WebView but the ActionScript doesn't seem to get called, but the JavaScript work.
I tried it on my laptop web browser and it doesnt work until I trusted the project folder in Flash setting.
Is there a similar setting on Android?
Here is the code I used for WebView.
WebView mWebView=(WebView)findViewById(R.id.webViewDisplay);

    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setSaveFormData(true);
    mWebView.getSettings().setPluginsEnabled(true);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.setInitialScale(100);
    mWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
    mWebView.setWebViewClient(new MyWebViewClient());
    mWebView.setOnTouchListener(new View.OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
          return (event.getAction() == MotionEvent.ACTION_MOVE);
        }
      });
    mWebView.loadUrl("file:///android_asset/flash.html");

A: Check this out http://code.google.com/p/java-actionscript-api-for-android/
With this framework, it is expected that any ActionScript coder could easily write Android app without the need of the Adobe Flash for Android.

A: For android, try using Adobe Flash Builder in CS5.5.
Import and play the swf and you can publish it for android there.


text:
Q: How to upgrade Administrate gem I have a Rails 4 app with Thoughtbot Administrate for the admin part.
Recently I tried to upgrade from version 0.1.2 to 0.1.4, but I got this error: cannot load such file -- administrate/fields/base.
It was triggered from a custom field file, so I tried to run rails g administrate:install, which asked me to overwrite all my administrate controllers and dashboards.
Now, I have made customizations to those files, so I opted not to overwrite them, but then I ended up with the same error as before.
Next, I made another branch to test and let administrate to overwrite my controllers and dashboards, and this time it worked!
So, I think the question is, what is the process to upgrade the gem without losing my customizations?
Is there any task I can run in order to "register" the updated gem, like rake administrate:upgrade or so?
Thanks!

A: Found out the error.
Seems that administrate/fields/base is now administrate/field/base, so this subtle update in the Administrate gem code is breaking my custom field.
Anyway, I think a potentially breaking update to the gem's code should be advertised and maybe even change the mayor version number, so I'll rise an issue in github for this one.


text:
Q: I want to add a new value in my list in response body product_sp.add(newItemPrice);

http.Response response = await client.patch(url,

    body: jsonEncode(<String, dynamic>{
       "records": [
{
      "id": orderId,
  "fields": {
  "product_sp": product_sp,
  }
    }
       ]
    },
    ));

 if (response.statusCode == 200) {
  var data = jsonDecode(response.body);
  print(data);
} else {
  throw Exception();
}

I am trying to add a new item in the product_sp and patching it but it results into an exception.

This is the response body of product_sp right now-
product_sp: [L, test]
response.body generatig error:
I/flutter ( 6545): {error: Invalid payload, details: Error: body.records[0] is not a Record; body.records[0].fields.product_sp is not a CellValue; body.records[0].fields.product_sp is none of number, string, boolean, null, 1 more; body.records[0].fields.product_sp[0] is not a GristObjCode; body.records[0].fields.product_sp[0] is not a valid enum value}

A: you can use List.generate like
"fields": {
    "list_one": List<int>.generate(array.length, (index)=>index),
  }

For generating random int array with random length which generates int between 1-100 with the length of upto 100 (change max length) . here is the code
"fields": {
    "list_one": List<int>.generate(Random().nextInt(100), (index) => Random().nextInt(100)),
  }


text:
Q: Entity framework - VB .net, insert entries into child table before saving changes to parent table I am using Entity Framework 4.0 using VB Express 2010 and SQL Server 2008 express. I have setup EDM. I have two tables 1. Trans_Details which is parent and 2. Trans_Details_Split which is child table .These are linked with PK and FK relationship in database with trans_id column.
I have a form having datagridview which is bound to parent table (trans_details). User is allowed to save only 1 row in this datagridview at a time. This datagridview has a button called "Split". When user wants to enter various child entries for the parent transaction row, they click on Split button (even before saving this parent transaction row). It opens up another form which has a datagridview bound to child table trans_details_split.
Business case says that once the user enters details of child recods and closes child form, the focus will come back to parent row. User will then click on Save button on this parent form. At this time, the application should insert the records for parent and child forms/tables together.
I searched through internet but could not figure out the way to do it. I am sure this must be very common requirement, but I am feeling lost.
Could anyone help me in this regard?
ps: Since these are different forms I am having difficulty in passing the information from child to parent (or vice versa). If both were in the same form, I think I know how to go about.
Thanks in advance
--Prasad


text:
Q: How to set dynamic id for each td in Html table using javascript How can I set id for each td in the html table? For more information what I need is that each created new field will have in a unique Id for example: first tr will have three  with id-s :edit_mailing_dates_delivery_input_2; edit_mailing_dates_deadline_input_2; edit_mailing_dates_release_input_2;
the second new  will have : edit_mailing_dates_delivery_input_2_1; edit_mailing_dates_deadline_input_2_1; edit_mailing_dates_release_input_2_1; and so on.

`enter code here`const seasonChart = document.getElementsByClassName('MailingSeason')[0];
`enter code here`const createSeason = document.getElementById('createNewSeason');

createSeason.addEventListener('click', editMailingDates());

function editMailingDates() {
  let editMailingDatesFrame = document.createElement('div');
  let editMailingDatesOuter = document.createElement('div');
  let editMailingDatesHeader = document.createElement('div');
  let editMailingDatesHeaderText = document.createElement('h6');
  let editMailingDatesBody = document.createElement('div');
  let editmailingdatesTable = document.createElement('table');
  let editMailingDatesTableBody = document.createElement('TBODY');
  let editMailingDatesRow = document.createElement('tr');
  let editMailingDatesDeadlineFrame = document.createElement('th');
  let editMailingDatesReleaseFrame = document.createElement('th');
  let editMailingDatesdeliveryFrame = document.createElement('th');
  let editMailingDatesEditFrame = document.createElement('th');
  let editMailingDatesDeleteFrame = document.createElement('th');
  let editMailingDatesDeadlineHeader = document.createElement('h5');
  let editMailingDatesReleaseHeader = document.createElement('h5');
  let editMailingDatesDeliveryHeader = document.createElement('h5');
  let editMailingDatesEditFrameHeader = document.createElement('h5');
  let editMailingDatesDeleteFrameHeader = document.createElement('h5');
  let editMailingDatesFooter = document.createElement('div');
  let editMailingDatesSaveButton = document.createElement('button');
  let editMailingDatesPrevButton = document.createElement('button');
  let editMailingDatesAddNewButton = document.createElement('button');
  let editMailingDatesAddNewButtonSave = document.createElement('button');

  let editMailingDatesAddNewButtonFrame = document.createElement('div');
  let editMailingDatesBodyOuter = document.createElement('div');

  editMailingDatesFrame.setAttribute('id', 'edit_mailing_dates_frame');
  editMailingDatesOuter.setAttribute('class', 'new_season_options_outer');
  editMailingDatesHeader.setAttribute('class', 'new_season_header');
  editMailingDatesBody.setAttribute('id', 'edit_mailing_dates_body');
  editMailingDatesBodyOuter.setAttribute('id', 'edit_mailing_dates_body_inner');
  editMailingDatesDeadlineFrame.setAttribute('id', 'edit_mailing_dates_deadline_frame');
  editMailingDatesReleaseFrame.setAttribute('id', 'edit_mailing_dates_release_frame');
  editMailingDatesdeliveryFrame.setAttribute('id', 'edit_mailing_dates_delivery_frame');
  editMailingDatesFooter.setAttribute('class', 'manage_products_footer');
  editMailingDatesPrevButton.setAttribute('id', 'edit_mailing_dates_prev_button');
  editMailingDatesAddNewButton.setAttribute('id', 'edit_mailing_dates_add_new_button');
  editMailingDatesAddNewButtonSave.setAttribute('id', 'edit_mailing_dates_add_new_button_save');
  editMailingDatesTableBody.setAttribute('id', 'edit_mailing_dates_table_body');
  editMailingDatesAddNewButtonFrame.setAttribute('class', 'buttons_frame');

  editMailingDatesHeaderText.textContent = "Termine andern / change dates";
  editMailingDatesDeadlineHeader.textContent = "Bestellfrist";
  editMailingDatesReleaseHeader.textContent = "Druckfreigabe bis";
  editMailingDatesDeliveryHeader.textContent = "Anlieferung";
  editMailingDatesEditFrameHeader.textContent = "Edit";
  editMailingDatesDeleteFrameHeader.textContent = "Delete";
  editMailingDatesSaveButton.textContent = "Save";
  editMailingDatesPrevButton.textContent = "Go Back";
  editMailingDatesAddNewButton.textContent = "+";
  editMailingDatesAddNewButtonSave.textContent = "Update";

  seasonChart.appendChild(editMailingDatesFrame);
  editMailingDatesFrame.appendChild(editMailingDatesOuter);
  editMailingDatesOuter.appendChild(editMailingDatesHeader);
  editMailingDatesHeader.appendChild(editMailingDatesHeaderText);
  editMailingDatesOuter.appendChild(editMailingDatesBodyOuter);
  editMailingDatesBodyOuter.appendChild(editMailingDatesBody);
  editmailingdatesTable.appendChild(editMailingDatesRow);
  editMailingDatesBody.appendChild(editmailingdatesTable);
  editMailingDatesRow.appendChild(editMailingDatesDeadlineFrame);
  editMailingDatesRow.appendChild(editMailingDatesReleaseFrame);
  editMailingDatesRow.appendChild(editMailingDatesdeliveryFrame);
  editMailingDatesRow.appendChild(editMailingDatesEditFrame);
  editMailingDatesRow.appendChild(editMailingDatesDeleteFrame);
  editMailingDatesEditFrame.appendChild(editMailingDatesEditFrameHeader);
  editMailingDatesDeleteFrame.appendChild(editMailingDatesDeleteFrameHeader);

  editMailingDatesBodyOuter.appendChild(editMailingDatesAddNewButtonFrame);
  editMailingDatesAddNewButtonFrame.appendChild(editMailingDatesAddNewButton);
  editMailingDatesAddNewButtonFrame.appendChild(editMailingDatesAddNewButtonSave);
  editMailingDatesDeadlineFrame.appendChild(editMailingDatesDeadlineHeader);
  editMailingDatesReleaseFrame.appendChild(editMailingDatesReleaseHeader);
  editMailingDatesdeliveryFrame.appendChild(editMailingDatesDeliveryHeader);
  editmailingdatesTable.appendChild(editMailingDatesTableBody);
  editMailingDatesOuter.appendChild(editMailingDatesFooter);
  editMailingDatesFooter.appendChild(editMailingDatesPrevButton);
  editMailingDatesFooter.appendChild(editMailingDatesSaveButton);

}

const createNewDateInputFields = document.getElementById('edit_mailing_dates_add_new_button');
const createNewCostsInputFields = document.getElementById('edit_printing_costs_add_inputs_button');

createNewDateInputFields.addEventListener('click', function() {
  const deadlineFrame = document.getElementById('edit_mailing_dates_table_body');
  const datesInputFieldsFrame = document.createElement('tr');
  const additonalInput1Td = document.createElement('td');
  const additonalInput2Td = document.createElement('td');
  const additonalInput3Td = document.createElement('td');
  const additonalInput1 = document.createElement('input');
  const additonalInput2 = document.createElement('input');
  const additonalInput3 = document.createElement('input');

  datesInputFieldsFrame.setAttribute('id', 'dates_input_fields_frame');
  additonalInput1.setAttribute('id', 'edit_mailing_dates_delivery_input_2')

  additonalInput2.setAttribute('id', 'edit_mailing_dates_deadline_input_2')

  additonalInput3.setAttribute('id', 'edit_mailing_dates_release_input_2')

  deadlineFrame.appendChild(datesInputFieldsFrame);
  datesInputFieldsFrame.appendChild(additonalInput1Td);
  datesInputFieldsFrame.appendChild(additonalInput2Td);
  datesInputFieldsFrame.appendChild(additonalInput3Td);

  additonalInput1Td.appendChild(additonalInput1);
  additonalInput2Td.appendChild(additonalInput2);
  additonalInput3Td.appendChild(additonalInput3);
});
#edit_mailing_dates_frame {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

#edit_mailing_dates_body {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
}

#edit_mailing_dates_body div {
  margin: 0.5rem;
  display: flex;
  flex-direction: column;
}

#edit_mailing_dates_body_inner {
  display: flex !important;
  justify-content: space-between;
  flex-direction: row !important;
  margin: 0 !important;
}

#edit_mailing_dates_body_inner tr {
  border: none;
}

#edit_mailing_dates_deadline_input_2 {
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
}

#edit_mailing_dates_release_input_2 {
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
}

#edit_mailing_dates_delivery_input_2 {
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
}

th {
  border: 1px solid black;
  padding: 0.5rem;
}

tr {
  border: 1px solid black;
  padding: 0.5rem;
  text-align: center;
}

td {
  border: 1px solid black;
}

Mailing Order

A: Got it done, if someone wishes to have a reference in the future.

let currentRow = 1;

createNewDateInputFields.addEventListener('click', function() {
  const deadlineFrame =
    document.getElementById('edit_mailing_dates_table_body');
  const datesInputFieldsFrame = document.createElement('tr');
  const additonalInput1Td = document.createElement('td');
  const additonalInput2Td = document.createElement('td');
  const additonalInput3Td = document.createElement('td');
  const additonalInput1 = document.createElement('input');
  const additonalInput2 = document.createElement('input');
  const additonalInput3 = document.createElement('input');

  datesInputFieldsFrame.setAttribute('id', 'dates_input_fields_frame');
  additonalInput1.setAttribute('id',
    'edit_mailing_dates_delivery_input_' + currentRow)

  additonalInput2.setAttribute('id',
    'edit_mailing_dates_deadline_input_' + currentRow)

  additonalInput3.setAttribute('id',
    'edit_mailing_dates_release_input_' + currentRow)

  deadlineFrame.appendChild(datesInputFieldsFrame);
  datesInputFieldsFrame.appendChild(additonalInput1Td);
  datesInputFieldsFrame.appendChild(additonalInput2Td);
  datesInputFieldsFrame.appendChild(additonalInput3Td);

  additonalInput1Td.appendChild(additonalInput1);
  additonalInput2Td.appendChild(additonalInput2);
  additonalInput3Td.appendChild(additonalInput3);

  currentRow++
});


text:
Q: At which point can I securely access the frame in a UIImageView subclass? I've subclassed an UIImageView. After
self = [super initWithImage:image]

I try to access the self.frame.origin.y value. But it is always 0.0. One moment later, in a method that gets called from the outside, the property is fully there with a nice 100.0.
I also tried to override -(id)initWithFrame:(CGRect)aRect, but the result is the same. Is that property first set correctly as soon as the view is added to some superview? I belief that I am trying to get the frame rect directly after the object has been allocated and initialized, but before it gets added to the superview. That happens one line later.

A: The frame of an object may be set at any time. If you wish to monitor for changes to the frame, override setFrame: and setBounds:
- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    // Your code here
}
- (void)setBounds:(CGRect)bounds
{
    [super setBounds:bounds];
    // Your code here
}

A: I can't reproduce this issue, but I'm having to interpolate a bit to guess where you are expecting the 100 to come from. Where are you setting it? This seems to work fine:
- (id)initWithImage:(UIImage*)image {
    self = [super initWithImage:image];
    if (self != nil)
    {
        CGRect frame = self.frame;
        frame.origin = CGPointMake(100.0, 100.0);
        self.frame = frame;
        NSLog(@"y=%d", self.frame.origin.y);
        NSLog(@"frame=%@", NSStringFromCGRect(self.frame));
    }
    return self;
}

Perhaps you could provide a bit larger piece of code?


text:
Q: JSF2 commandButton action not invoked in an updated fragment I have command buttons in the form. Those that are rendered on page load are invoking actions,
but those two in the <p:fragment> tag are rendered on postback and are not working.
<h:form>
    <p:commandButton action="#{bean.actionA()}"/>
    <p:commandButton actionListener="#{bean.actionB()}"/>

    <p:fragment rendered="#{not empty bean.field}">
        <p:commandButton action="#{bean.actionA()}"/>
        <p:commandButton actionListener="#{bean.actionB()}"/>
    </p:fragment>

    <ui:include ..>
        ...
        <p:commandLink update="@form">
            <i class="fa fa-folder"></i>
            <f:setPropertyActionListener value="#{data.document}" target="#{bean.field}" />
        </p:commandLink>
    </ui:include>
</h:form>

I am noob in JSF. I know that issue is related to the JSF life cycle but I can not find a working solution.
My bean is view scoped and I use primefaces 5.1.
Is this suppose to work or I am ussing wrong approach to show/hide buttons?
Thanks.
EDIT:
After some testing it seams that even when action is invoked is invoked on bean with null==bean.field.
This doesn't make sense to me, because I get rendered value #{bean.field.name} after update is done and hidden butons are displayed.
What am I missing?
Same effect when changing update=@form to update=@all.
Any help is appreciated.
My bean with session scope loks likek this. In this case of SessionScoped buttons are working. Why view scope is not enough?
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.faces.view.ViewScoped;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

//TODO: change to @ViewScoped
@ManagedBean(name="bean")
@SessionScoped
public class Bean extends BeanBase {

private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = LogManager.getLogger(Bean.class.getName());

    @PostConstruct
    protected void init() {
        super.init();
    }

    public void actionA() {
        LOGGER.debug("Action A triggerd!");
    }
    public void actionB( ActionEvent event) {
        LOGGER.debug("Action B event triggerd!");
        super.edit(event);
    }
}

A: First of all, the p:fragment tag is supposed to use to partially submit and process fragments of your form during an AJAX call without the need to explicitly defining this behaviour on the corresponding components directly. Better just use e.g a p:outputPanel, if you just want a caontional rendering of a group of components.
But what is causing the problem here, is that the rendered attribut is not only evaluated when the form has to be rendered, but also when the form is processed. If, for some reason, the expression in the rendered attribut is now evaluated to false then processing the form will be stopped and the action will not be invoked. Just for security reasons.
In your case field is evaluated to null when the form is preocessed, thus the rendered attribute of the parent of your commandButton is evaluated to false and thats why the action method is not invoked.
The reason for this is, that the Scope of your ManagedBean is to small for some reason and/or it is destroyed after the render-response phase, so that, when you are clicking the command button, your are using a completly new instance of your managed bean where the value for field has never been set.
Most likely, your ManagedBean is in request scope instead of view scope, as you expected. Check if you are using the correct annotation the put the Bean in the correct scope and that you are not mixing up JSF and CDI annotations.


text:
Q: How add html elements to head element of page using javascript? (Cross Browser -> such as IE) How add html elements to head element of page using javascript? (show us both jQuery and javascrip, but js is so important)
There are some threads in stack about this, but none of show a way for html elements.
"<b>Test</b>"

For example one of them is :
Append some HTML into the HEAD tag?
As you see it's about adding css to head not html codes.
How can I do that?

A: it is invalid to put <b> elements inside the head element..
Allowed elements are found at http://www.w3.org/TR/html-markup/head.html (read the Permitted contents section and links)

A: Using this code you can append multiple script with rendomnumber in head section
 var MultiJsLink = ['js/enjoyhint.min.js', 'js/tab-help-common-on-off.js'];
    var jshtml ='';
    $(MultiJsLink).each(function(i){
    jshtml += '<script src='+MultiJsLink[i]+'?vrsn='+Math.floor(Math.random() * 1000)+'><\/script>';
});

$('head').append(jshtml);

Your script append like this:
<script src=js/enjoyhint.min.js?vrsn=332></script><script src=js/tab-help-common-on-off.js?vrsn=57></script>


text: Q: shared object 'stringi.so' not found Just a few days ago I had no issues loading packages, now I get  "shared object 'stringi.so' not found" whenever I try to load a few packages. I tried installing stringi but I still kept getting the same error. Thoughts?