text:
Q: Redireccionar a diferentes Activity con Views Buenas,
Estoy haciendo una App en la cual se se posesionan diferentes imágenes en forma de circulo, y en cada una de esas imágenes tiene que direccionar a una vista diferente.
Así es como se vería el App con las imágenes cargadas.

El problema viene cuando doy clic a alguno de las imágenes, ya que no importa cual seleccione siempre me direcciona a la ultima vista que cargué.
Para poner menos codigo lo que hice fue solamente poner dos imagenes que deberian direccionar a diferentes vistas.
Algo así:

El código cuando hago el OnClickListener seria este:
public void actionViews(){
   c0.setOnClickListener(this);
   c2.setOnClickListener(this);

   LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
   addContentView(c0, params);
   addContentView(c2, params);
}

@Override
public void onClick(View v) {
    if (v ==  c0){
        try{
            Intent intent = new Intent(inicio.this, ciclo.class);
            startActivity(intent);
        }catch (Exception e){}
    }else if(v == c2()){
        try{
            Intent intent = new Intent(inicio.this, chat.class);
            startActivity(intent);
         }catch (Exception e){}
    }
}

En este caso lo que pasa siempre es que cuando le doy click a cualquiera de las dos imágenes, siempre direcciona al chat class.
El crear y cargar las imágenes lo hago en la misma clase de la siguiente forma:
static public class CircleView extends View implements View.OnClickListener {
Paint paint;
Object[] circulos;
Bitmap imagen;

//variables
float CX;
float CY;
float CR;

//tag
String btnTag = "";

public CircleView(Context context, float x, float y, float r, Bitmap img, String tag) {
    super(context);
    CX = x;
    CY = y;
    CR = r;
    imagen = img;
    paint = new Paint();
    btnTag = tag;
}

@Override
public void onDraw(Canvas canvas) {
    paint.setColor(Color.GREEN);
    canvas.drawBitmap(imagen, CX-(CR/2), CY-(CR/2), paint);
    this.setTag(btnTag);
}

Esto lo que hace simplemente es poner la imagen en los puntos (x,y) que le envío.
Si me pudieran ayudar les agradecería mucho.

A: Si tu método anterior funciona con el de chat, y copiaste el código tal como lo tienes, puedo ver que te faltan unos paréntesis en el primer if, en el c0. Prueba con agregarlos, si no funciona, puedo ayudarte a modificar ese código para que manejes los clicks de forma diferente. Podrías usar un switch.
 @Override
    public void onClick(View v) {
        if (v ==  c0()){
            try{
                Intent intent = new Intent(inicio.this, ciclo.class);
                startActivity(intent);
            }catch (Exception e){}
        }else if(v == c2()){
            try{
                Intent intent = new Intent(inicio.this, chat.class);
                startActivity(intent);
             }catch (Exception e){}
        }

Debeías agregar un id a tus botones y mediante el click accedas al View y compares el View con el id mediante un switch.


text:
Q: Using combinations to combinations for probability with dependent events I am reading a problem about probabilities with dependent events.

There are $3$ people selected from $5$ freshmen, $2$ sophomores and
$4$ juniors. What is the probability that the first $2$ people
selected are freshmen and the third a junior?

I thought that this is solvable by using combinations.
I.e.
There are $\binom{11}{3}$ ways to select $3$ out of $11$ students (I hope that the notation is for combinations and not permutations as I get these 2 notations mixed).
This is $$\frac{11!}{3!\cdot 8!} = 165$$ ways
To choose $2$ freshman from $5$ is: $$\frac{5!}{2!\cdot 3!}$$
To choose $1$ junior from $4$ is: $$\frac{4!}{1!\cdot 3!}$$
So the probability we are looking for is:
$$\frac{\frac{5!}{2!\cdot 3!} \cdot \frac{4!}{1!\cdot 3!}}{165} = \frac{40}{165}=\frac{8}{33}$$
but the answer is wrong.
Is it not possible to use the combinations formula for calculating such a probability with $3$ dependent events?

A: Your answer would be correct if the question were:

What is the probability that two of the people selected are freshman and one is a junior?

That would be a question about combinations - how many ways to choose 2 freshman out of 5 and one junior out of 4, over the number of ways to choose a group of 3 students from 11.
That is subtly different from the question which was asked. The question in your post says the first two people are freshman, and the third is a junior - i.e., the order of selection matters. So you should instead use permutations.

A: When a particular order is specified, it is simplest to directly multiply probabilities,
so $\dfrac5{11}\cdot\dfrac4{10}\cdot\dfrac4{9}$
If you want to use combinations, you will have to take an extra step which unnecessarily lengthens the process, viz divide by $\dbinom32$,
thus $\dfrac{\dbinom52\dbinom41}{\dbinom{11}3}\div\dbinom32$

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the role of program interpreters in executable files? I was going through disassembly of elf executables and understanding the elf format. In there, I saw lib64/ld-linux-x86-64.so.2 used as program interpreter in the generated executable.
My guess is: I had used printf in the source code, which had to be dynamically linked. When I checked through dynamic section, I was able to find a reference to libc.so.6 shared library (tag:DT_NEEDED). In my system, I found multiple files with that name in different directories:
sourav@ubuntu-VirtualBox:/$ sudo find / -name libc.so.6
/usr/lib/x86_64-linux-gnu/libc.so.6
find: '/run/user/1000/doc': Permission denied
find: '/run/user/1000/gvfs': Permission denied
/snap/snapd/13170/lib/x86_64-linux-gnu/libc.so.6
/snap/snapd/11107/lib/x86_64-linux-gnu/libc.so.6
/snap/core18/1988/lib/i386-linux-gnu/libc.so.6
/snap/core18/1988/lib/x86_64-linux-gnu/libc.so.6
/snap/core18/2128/lib/i386-linux-gnu/libc.so.6
/snap/core18/2128/lib/x86_64-linux-gnu/libc.so.6

So, I guess purpose of program interpreter is to resolve these names to the proper libraries and load them during execution. Is this correct?
It seems, we can also have executables with no program interpreter (which is the case for program interpreter itself). In that case, does system/os itself loads the shared library? If so, how does it resolves the path of library?
Is it possible to generate executable with no program interpreter using gcc? My gcc version is 'gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)'.

A:
So, I guess purpose of program interpreter is to resolve these names to the proper libraries and load them during execution. Is this correct?

Yes, but that that's a bit minimalistic.  Loading dynamic libraries involves locating them, loading or mapping them into memory if necessary, and resolving dynamic symbols within, possibly lazily, for multiple kinds of relocations.  It involves recursively loading the libraries' own needed libraries.  Also, in a dynamically linked executable, the program interpreter provides the program entry point (from the kernel's perspective), so it is also responsible for setting up and entering the program-specific entry point (for example, main() in a C or C++ program).

It seems, we can also have executables with no program interpreter (which is the case for program interpreter itself). In that case, does system/os itself loads the shared library? If so, how does it resolves the path of library?

You can have ELF executables without a program interpreter, but they are not dynamically linked, at least not in the ELF sense.  There are no shared libraries to load, and certainly the system does not load any.

Is it possible to generate executable with no program interpreter using gcc? My gcc version is 'gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)'.

If you have static versions of all needed libraries available then you should be able to achieve that by including the -static option on the command line when you link the program.  It is entirely possible, however, that you do not have the needed static libraries, even if libc is the only library you need.


text:
Q: How to get the names of files present in  tags from a string and create an array of all those file names in PHP? I've one sample string as follows :
$feed_status = Nice to see you all back again ;

(Forgive me for syntactical errors like placing of single quotes and double quotes)
For your reference I've just added three  tags to the string but in real situation ths string could contain a single  tag or no  tag or more than one  tags.
I want to get names of files present in each of the  tag's src attribute and make array of those file names.
In this case the resultant array should be as follows :
$new_arr = {smile.png, smile.png, smile.png};

How should I do this in an optimum way using PHP?
Thanks in advance.


text:
Q: Python 3 CSV file giving UnicodeDecodeError: 'utf-8' codec can't decode byte error when I print I have the following code in Python 3, which is meant to print out each line in a csv file.
import csv
with open('my_file.csv', 'r', newline='') as csvfile:
    lines = csv.reader(csvfile, delimiter = ',', quotechar = '|')
    for line in lines:
        print(' '.join(line))

But when I run it, it gives me this error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 7386: invalid start byte

I looked through the csv file, and it turns out that if I take out a single ñ (little n with a tilde on top), every line prints out fine.
My problem is that I've looked through a bunch of different solutions to similar problems, but I still have no idea how to fix this, what to decode/encode, etc. Simply taking out the ñ character in the data is NOT an option.

A: For others who hit the same error shown in the subject, watch out for the file encoding of your csv file. Its possible it is not utf-8. I just noticed that LibreOffice created a utf-16 encoded file for me today without prompting me although I could not reproduce this.
If you try to open a utf-16 encoded document using open(... encoding='utf-8'), you will get the error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position
  0: invalid start byte

To fix either specify 'utf-16' encoding or change the encoding of the csv.

A: We know the file contains the byte b'\x96' since it is mentioned in the error message:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 7386: invalid start byte

Now we can write a little script to find out if there are any encodings where b'\x96' decodes to  ñ:
import pkgutil
import encodings
import os

def all_encodings():
    modnames = set([modname for importer, modname, ispkg in pkgutil.walk_packages(
        path=[os.path.dirname(encodings.__file__)], prefix='')])
    aliases = set(encodings.aliases.aliases.values())
    return modnames.union(aliases)

text = b'\x96'
for enc in all_encodings():
    try:
        msg = text.decode(enc)
    except Exception:
        continue
    if msg == 'ñ':
        print('Decoding {t} with {enc} is {m}'.format(t=text, enc=enc, m=msg))

which yields
Decoding b'\x96' with mac_roman is ñ
Decoding b'\x96' with mac_farsi is ñ
Decoding b'\x96' with mac_croatian is ñ
Decoding b'\x96' with mac_arabic is ñ
Decoding b'\x96' with mac_romanian is ñ
Decoding b'\x96' with mac_iceland is ñ
Decoding b'\x96' with mac_turkish is ñ

Therefore, try changing
with open('my_file.csv', 'r', newline='') as csvfile:

to one of those encodings, such as:
with open('my_file.csv', 'r', encoding='mac_roman', newline='') as csvfile:

A: I also faced the issue with python 3 and my issue got resolved using the encoding type as utf-16
with open('data.csv', newline='',encoding='utf-16') as csvfile:

A: with open('my_file.csv', 'r', newline='', encoding='ISO-8859-1') as csvfile:
ñ character is not listed on UTC-8 encoding. To fix the issue, you may use ISO-8859-1 encoding instead. For more details about this encoding, you may refer to the link below:
https://www.ic.unicamp.br/~stolfi/EXPORT/www/ISO-8859-1-Encoding.html

A: easy... just open it in Excel or OpenOffice calc, use text as columns, select ,, and then just save the file as .csv... it takes me one day and several hour of search in google... but at the end i figure it out.

A: Just try UTF 16 for the file that may include characters rather than English ones and that's why UTF-16 is implemented for it. 8 and 16 implementations are the same unicode, yet the only difference is the bits number so it 16 will handle character like ~ while 8 will not, just a-zA-Z0-9 characters
with open('my_file.csv', 'r', newline='', encoding='UTF-16') as csvfile:

A: with open('my_file.csv', 'r', newline='', encoding='utf-8') as csvfile:

Try opening the file like above

A: A much simpler solution is to open the csv file in notepad and select "Save As" in "File" dropdown list. Choose "Save as type" to "All files(.)". Select "UTF-8 Encoding" in Encoding dropdown list and put ".csv" extension to the file name


text:
Q: write script without CDATA and Merge two scripts with same functions I have these scripts which are almost the same but I'm unable to merge them into one..
also I want remove "CDATA" and keep the script functioning in blogger XML template
    <script type='text/javascript'>// <![CDATA[
!function(){const e=document.querySelectorAll(".vplayer");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi_webp/"+e[t].dataset.v+"/hqdefault.webp";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1"),this.innerHTML="",this.appendChild(e)})}}();// ]]></script>

and that the second
    <script type='text/javascript'>// <![CDATA[
!function(){const e=document.querySelectorAll(".vplayerold");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi/"+e[t].dataset.v+"/hqdefault.jpg";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1"),this.innerHTML="",this.appendChild(e)})}}();// ]]></script>

the scripts are the same and I dont want write the whole of it twice
I want this
const e = document.querySelectorAll(".vplayer");

to work with that
const a = "//i.ytimg.com/vi_webp/" + e[t].dataset.v + "/hqdefault.webp";

and this
const e = document.querySelectorAll(".vplayerold");

to work with that
const a="//i.ytimg.com/vi/"+e[t].dataset.v+"/hqdefault.jpg";

the rest of scripte work with both as well

A: Merged example
You mean like this?
<script type='text/javascript'>// <![CDATA[
!function(){const e=document.querySelectorAll(".vplayer");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi_webp/"+e[t].dataset.v+"/hqdefault.webp";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1"),this.innerHTML="",this.appendChild(e)})}}();

!function(){const e=document.querySelectorAll(".vplayerold");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi/"+e[t].dataset.v+"/hqdefault.jpg";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1"),this.innerHTML="",this.appendChild(e)})}}();
// ]]>
</script>

Adding them in separate script tags should also work, depending what your backend allows you to do.

A:
I want remove "CDATA" and keep the script functioning in blogger XML template

That's not possible. It's pretty much required for valid XML unless you want to use escape sequences for <>'".

the scripts are the same and I dont want write the whole of it twice

Make that IEFE a named function declaration, give it parameters, call it twice with different arguments.
<script type="text/javascript">//<![CDATA[
function createPlayer(selector, makeUrl) {
    const e = document.querySelectorAll(selector);
    for (var t = 0; t < e.length; t++) {
        console.log(e[t].dataset.v);
        const a = makeUrl(e[t].dataset.v);
        var n = new Image;
        n.src = a;
        n.addEventListener("load", void e[t].appendChild(n));
        e[t].addEventListener("click", function() {
            const e = document.createElement("iframe");
            e.setAttribute("allowfullscreen", "");
            e.setAttribute("frameborder", "0");
            e.setAttribute("src", "//www.youtube.com/embed/" + this.dataset.v + "?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1");
            this.innerHTML = "";
            this.appendChild(e);
        })
    }
}
createPlayer(".vplayer", v => "//i.ytimg.com/vi_webp/" + v + "/hqdefault.webp");
createPlayer(".vplayerold", v => "//i.ytimg.com/vi/" + v + "/hqdefault.jpg");
//]]></script>


text:
Q: SQL Server - select closest row to 30 minute interval We are using SQL Server 2016:
This is my current table:
countx  RunDateTime
104 7/15/20 0:05
104 7/15/20 0:10
102 7/15/20 0:15
102 7/15/20 0:20
100 7/15/20 0:25
100 7/15/20 0:30
102 7/15/20 0:35
99  7/15/20 0:40
97  7/15/20 0:46
99  7/15/20 0:56
93  7/15/20 1:01
93  7/15/20 1:10
93  7/15/20 1:16
91  7/15/20 1:31
89  7/15/20 1:39
87  7/15/20 1:57
88  7/15/20 2:05
80  7/15/20 2:11
81  7/15/20 2:20

I would like only the following results

countx    RunDateTime
104   7/15/20 0:05
100   7/15/20 0:30
93    7/15/20 1:01
91    7/15/20 1:31
88    7/15/20 2:05

How could I only select rows that are most close to the nearest 30 minute interval?
I only want rows most close to the hour and most close to half hour
For example I only want rows most close to
00:00 and 00:30
01:00 and 01:30
02:00 and 02:30
etc.
I was able to select rows closest to the hour, but I can't figure out how to get data closest to the half hour.  Here is what I tried.
SELECT
       RunDateTime,
       COUNT(DISTINCT id) countxbyhour
FROM (SELECT
            t.*,
            MIN(RunDateTime) OVER(PARTITION BY CAST(RunDateTime AS DATE),
            DATEPART(HOUR,RunDateTime)) mintmstmp
      FROM table t) x
WHERE RunDateTime = mintmstmp
GROUP BY RunDateTime
ORDER BY RunDateTime

A: based on Jason's:
declare @t table(countx int, RunDateTime datetime);
insert into @t values
(104, '7/15/20 0:05'),
(104, '7/15/20 0:10'),
(102, '7/15/20 0:15'),
(102, '7/15/20 0:20'),
(100, '7/15/20 0:25'),
(100, '7/15/20 0:30'),
(102, '7/15/20 0:35'),
(99,  '7/15/20 0:40'),
(97,  '7/15/20 0:46'),
(99,  '7/15/20 0:56'),
(93,  '7/15/20 1:01'),
(93,  '7/15/20 1:10'),
(93,  '7/15/20 1:16'),
(91,  '7/15/20 1:31'),
(89,  '7/15/20 1:39'),
(87,  '7/15/20 1:57'),
(88,  '7/15/20 2:05'),
(80,  '7/15/20 2:11'),
(81,  '7/15/20 2:20');

WITH CTE AS
(--get data and dif
select *, ROW_NUMBER() OVER (PARTITION BY (countx) ORDER BY (CASE WHEN DATEPART(MINUTE, RunDateTime) >= 30
            THEN (DATEPART(MINUTE, RunDateTime) - 30) / 30.0
            ELSE DATEPART(MINUTE, RunDateTime) / 30.0
        END)) as rowno
from @t
)
select *
from
    CTE
where
    CTE.rowno = 1;

A: Try this ...
IF OBJECT_ID('tempdb..#Table') IS NOT NULL DROP TABLE #Table

SELECT * INTO #Table FROM (VALUES
    (104, CAST('7/15/20 0:05' as datetime)),
    (104, '7/15/20 0:10'),
    (102, '7/15/20 0:15'),
    (102, '7/15/20 0:20'),
    (100, '7/15/20 0:25'),
    (100, '7/15/20 0:30'),
    (102, '7/15/20 0:35'),
    (99, '7/15/20 0:40'),
    (97, '7/15/20 0:46'),
    (99, '7/15/20 0:56'),
    (93, '7/15/20 1:01'),
    (93, '7/15/20 1:10'),
    (93, '7/15/20 1:16'),
    (91, '7/15/20 1:31'),
    (89, '7/15/20 1:39'),
    (87, '7/15/20 1:57'),
    (88, '7/15/20 2:05'),
    (80, '7/15/20 2:11'),
    (81, '7/15/20 2:20')
) S(countx, RunDateTime);

SELECT * FROM #Table;

WITH DataSource AS (
    SELECT
        *,
        CASE WHEN DATEPART(MINUTE, RunDateTime) >= 30
            THEN (DATEPART(MINUTE, RunDateTime) - 30) / 30.0
            ELSE DATEPART(MINUTE, RunDateTime) / 30.0
        END FracHalfour
    FROM
        #Table
)
SELECT
    D.countx, D.RunDateTime
FROM
    DataSource D
    JOIN (
        SELECT
            countx,
            MIN(FracHalfour) FracHalfour
        FROM
            DataSource S
        GROUP BY
            countx
    ) S ON
        S.countx = D.countx AND
        S.FracHalfour = D.FracHalfour
ORDER BY
    countx DESC

A: Jason beat me to the punch, but here is my version:
SELECT
    t.countx,
    t.RunDateTime
FROM
    test t
WHERE
    DATEPART(minute,t.RunDateTime) BETWEEN 0 AND 5
 OR (DATEPART(minute,t.RunDateTime) > 25 AND DATEPART(minute,t.RunDateTime) < 35)
 OR DATEPART(minute,t.RunDateTime) > 55

A: If by closest you mean first time value after the half-hour mark:
with data as (
    select *, row_number() over (
        partition by dateadd(minute, -datepart(minute, RunDateTime) % 30, RunDateTime)
        order by RunDateTime
    ) as rn
    from t
)
select * from data where rn = 1;

This is basically truncating the extra minutes by a simple deduction. I'm assuming that there are no (milli)seconds involved.
You could also have it "round" to the nearest half hour by adding fifteen minutes prior to the "truncate" operation and taking the absolute value of the distance:
with data as (
select *, row_number() over (
        partition by dateadd(minute, -datepart(minute, shiftedDt) % 30, shiftedDt)
        order by abs(datediff(minute, RunDateTime, dateadd(minute, -datepart(minute, RunDateTime) % 30, RunDateTime))), RunDateTime
    ) as rn
    from t cross apply ( values (dateadd(minute, 15, RunDateTime)) ) as s(shiftedDt)
)
select * from data where rn = 1;

Where ties come into play it would take the earlier one. Also, if you were to use this method on your sample data it would return a different set of rows.

A: I used some of Jasons code for ideas to partition the datepart:
select
RunDateTime,
count(distinct id) Countx
from (
        select t.*,
        min(RunDateTime) over(
        partition by cast(RunDateTime as date),( datepart(hour,RunDateTime)*100+CASE WHEN DATEPART(MINUTE, RunDateTime) >= 30
    THEN 30
    ELSE 00 end )) mintmstmp
        from table t
     ) x
where RunDateTime=mintmstmp
group by RunDateTime
order by RunDateTime


text:
Q: Make popup on button click without new window class? I have a button that when you click it a popup is supposed to be displayed just showing a simple text message until the user clicks on the canvas. Do I have to do something like this in my button click method?:
    Window win2 = new Window();
    win2.Show();
    this.Close();

I just don't want to have another .xaml file for that window when all it's going to be doing is displaying a message for a short amount of time. Right now I'm using a Popup TextBlock but it's not quite what I want, since I can't make it movable.

A: WPF has a built in message box which you can use to display information then can easily be closed. This is used in many Windows applications as error popups.
MessageBoxResult result = MessageBox.Show("Text here ","Error", MessageBoxButton.OK, MessageBoxImage.Question);

Just place this inside your button click method and change the "Text Here" to whatever you want.
https://msdn.microsoft.com/en-us/library/system.windows.messagebox(v=vs.110).aspx


text:
Q: Change permission for IBM liberty server logs I have liberty server running on redhat linux for my java batch application. When I liberty start server, logs gets generated with the permission of 640(messages.log). My splunk configuration not able to access this logs and expects 755 permission. what is the configuration change required to change log file permission to 755.
I have tried changing server.env with the below parameter. But didn't work as expected.
     WLP_SKIP_UMASK=true
 LogFilePermissions=755


text:
Q: MockBean doesn't work in Spring boot integration test I have Spring Integration test where I'm trying to Mock some of my Beans. For some reason although I Mocked them they are NULL. Here is code snippet:
The Bean which I want to Mock
@Component
public class MockWS {

    public String callSoapClient() throws JAXBException{
        return "CallSoapCl";
    }
}

The class where the Bean is used
public class SmDpES2PortImpl implements ES2SmDp {
    @Autowired
    private MockWS mock;

    @Override
    public void es2DownloadProfile(ES2DownloadProfileRequest parameters) {
         try {
            LOG.info("\n\n\n TEST BEAN: " + mock.callSoapClient() + "\n\n");
          }
     }
}

Spring boot integration test where the Bean has been mocked
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ES2SmDpApplicationTests {

    @MockBean(name="mockWS")
    MockWS mockService;

    @Test
    public void test1Es2DownloadProfile_Sucess() throws MalformedURLException, JAXBException, SOAPException {
        when(mockService.callSoapClient()).thenReturn("CallMockCLient");
    }
}

Output from the build execution:  TEST BEAN: null

A: In my case the following combination of annotations worked:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ControllerThatIAmTesting.class })
@AutoConfigureMockMvc(addFilters = false) // if using MockMvc object

But I had to declare explicitly both Autowired objects that I use in the ControllerThatIAmTesting in the test class with @MockBean annotation - otherwise Spring would complain that it cannot find suitable implementation - incidentally both my interfaces and their implementations are in the same corresponding packages
Also, using @WebMvcTest instead of @SpringBootTest (other suggest it as more specific scenario) resulted in Spring failing to find and initialize some other @Autowired dependencies from my @Configuration classes.
Related posts post1 post2 post3

A: You should mock an interface, not a class. Also, SmDpES2PortImpl must be a Spring bean. Try the following:
Interface:
public interface IMockWS {

    public String callSoapClient() throws JAXBException;
}

Component class:
@Component
public class MockWS implements IMockWS {

    @Override
    public String callSoapClient() throws JAXBException{
        return "CallSoapCl";
    }
}

Service class:
@Service //Also @Component is a good alternative
public class SmDpES2PortImpl implements ES2SmDp {
    @Autowired
    private IMockWS mock; //Notice that you are wiring an interface

    @Override
    public void es2DownloadProfile(ES2DownloadProfileRequest parameters) {
         try {
            LOG.info("\n\n\n TEST BEAN: " + mock.callSoapClient() + "\n\n");
          }
     }
}

Test class:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ES2SmDpApplicationTests {

    @MockBean
    IMockWS mockService; //Again, you are mocking the interface, not the implementing class

    @Test
    public void test1Es2DownloadProfile_Sucess() throws MalformedURLException, JAXBException, SOAPException {
        when(mockService.callSoapClient()).thenReturn("CallMockCLient");
    }
}


text:
Q: Feed data between 2 persons on Facebook Is it possible to get the data posted by a person on the timeline of one other person on Facebook?
If it is, how could I do it? Do I need to use FQL queries?

A: This will get you things that someone else has posted on the active user's timeline with FQL:
SELECT actor_id, created_time, message, attachment FROM stream
   WHERE source_id=me() AND actor_id != me()


text:
Q: Submit after a jquery-ajax function I check two values with ajax. And if both are correct then i want to make a submit (post-back).
But the post-back doesn't work.
Here is the code:
 $('form').submit(function () {

            var correctCaptcha = false;
            var correctWebcode = false;

        $.ajax({
            url: '/Competition/CheckForm',
            type: "POST",
            data: $(this).serialize(),
            success: function (data) {
                if (data == true) {
                    $('#recaptcha_response_field').removeClass("captchaError");
                    correctCaptcha = true;
                }
                else {
                    Recaptcha.reload();
                    $('#recaptcha_response_field').addClass("captchaError");
                }
            }
        });

        $.ajax({
             // like the code above (for webcode)
        });

        if (correctCaptcha == true && correctWebcode == true) {
            document.forms['form'].submit();
        }
        else { return false; }
    });

A: Use Async:false
    $.ajax({
        url: '/Competition/CheckForm',
        type: "POST",
        async:false,
        data: $(this).serialize(),
        success: function (data) {
            if (data == true) {
                $('#recaptcha_response_field').removeClass("captchaError");
                correctCaptcha = true;
            }
            else {
                Recaptcha.reload();
                $('#recaptcha_response_field').addClass("captchaError");
            }
        }
    });

This will cause the infinite loop:
if (correctCaptcha == true && correctWebcode == true) {
    document.forms['form'].submit();
}

So use use like this here
if (correctCaptcha == true && correctWebcode == true) {
    return true;
}
else {return false;}

A: Since ajax is async in nature you cannot expect those variables to be set right away when ajax call. You can either set async to false or submit the form inside success handler. Try this.
$('form').submit(function () {

            $.ajax({
                url: '/Competition/CheckForm',
                type: "POST",
                data: $(this).serialize(),
                success: function (data) {
                    if (data == true) {
                        $('#recaptcha_response_field').removeClass("captchaError");
                        $('form')
                        .unbind('submit')//we dont need any handler to execute now
                        .submit();
                    }
                    else {
                        Recaptcha.reload();
                        $('#recaptcha_response_field').addClass("captchaError");
                    }
                }
            });

            $.ajax({
                 // like the code above
            });

            return false;//To prevent the form from being submitted.
        });

A: By default, $.ajax works asynchronously, your way won't submit the form, you should submit the form in the callback function.


text:
Q: What is the difference between amd64.msi and win64.msi? I'm creating an installer for a Python program using cx_Freeze. Sometimes, running py setup.py bdist_msi generates an amd64.msi installer; other times it generates a win64.msi installer.
What's the difference, if any, between these two installer types?


text:
Q: How to handle fetch requests in CoreData when you know there are no Entities saved I have an app that I know the first time it runs there will be nothing saved in CoreData. I am trying to check for that scenario like this:
let fetchRequest = NSFetchRequest(entityName: "Person")
    let error = NSErrorPointer()

    do{
        let fetchResults = (try! coreDataStack.context.countForFetchRequest(fetchRequest, error: error))
        print("Count \(fetchResults)")
    } catch let error as NSError{
        print("Fetch failed: \(error.localizedDescription)")
    }

I get a warning saying "Cast from "Int" to unrelated type '[Person]' always fails.
I'm just not sure what I'm missing. I'm sure checking for any Entities in CoreData is a common practice.

A: You don't need to convert that into [Entity] because the countForFetchRequest returns the number of counts. So, you need need to call without casting.
let fetchResults = coreDataStack.context.countForFetchRequest(fetchRequest, error: error)
print("Count \(fetchResults)")

A: I was able to use this code to get the countForFetchRequest working:` let fetchRequest = NSFetchRequest(entityName: "Person")
    var error: NSError?

    let count = coreDataStack.context.countForFetchRequest(fetchRequest, error: &error)

    if count != NSNotFound {
        print("Count \(count)")
    } else {
        print("Could not fetch \(error), \(error?.userInfo)")
    }`


text:
Q: How to set permission to all users in IBM queue manager/queue channel and queues How can I set permission to queue manager/queue channel/queues in IBM mq without specifying the user? i need to give the permission to all the users

A: On UNIX and Linux systems you can grant permission to all users by granting permission on the special group nobody.
From the Knowledge Center page "Principals and groups"

You can change the authorization in the nobody group to grant access to WebSphere® MQ resources to users without specific authorizations.


text:
Q: Mongoose.js Doc Refs - how to safely delete "The documents returned from calling populate become fully functional, removeable, saveable documents. Do not confuse them with embedded docs. Take caution when calling its remove method because you'll be removing it from the database, not just the array."
I find that a bit terrifying - how do you safely unlink a reference to a document in a mongoose document without deleting said document?

A: Not quite sure what you're trying to do.  You can call toObject() on a Mongoose document to generate a plain JavaScript object representation of the document that's safe to pass around and modify without fear of accidentally altering the database.


text:
Q: In a read-heavy MySQL database, is it ever worth creating a two-column table that holds an item_id and an item_summary (of data from 5 other tables)? In this case, I'm working on a project that involves a database of library book data.  I have several tables in this database:

Books (book_id, title, description, genre_id, language_id, purchase_date, chapters, words, book_review_count)
BookSearchData (book_id, Fulltext-searchable titles and descriptions)
Genres (genre_id to genre_name)
Language (language_id to language_name)
CheckoutData (book_id, last_checkout_date, checkout_user_id)

A bit of table-construction rationale: I made separate Books and CheckoutData tables because in my setup, I will be making frequent requests for the CheckoutData information and won't need anything other than the data included in the CheckoutData fields.  Hopefully this was the right way to go.
The most frequent data request, however, will be a book data summary, which currently involves JOINs between all of the tables.  A book result includes the following information:

*

*Title

*Description

*Genre Name

*Language Name

*Purchase Date

*Chapters

*Words

*Review Count

*Checked Out?  (Which is determined by whether or not the value of checkout_user_id equals 0 in the CheckoutData table row associated with the book)

My question: Do you think it would be helpful (performance-wise) if I created another table in this database that included a simple two-colum setup consisting of a book_id and a book_data_summary?
The book_id would be, as you'd imagine, some kind of integer.  The book_data_summary would be a field of type TEXT.
The problem as I see it...this introduces a lot of data redundancy.  It also means that every time that a book is checked out (Table: CheckoutData) or if a book review is added by a user (Table: Books), I'll also need to update the book_data_summary field.
Is this worth doing?
Thanks!
Edit:  I need to clarify something.  In this case, I'm doing somewhat of a high-speed library scenario (yes, that seems kind of silly, but it's somewhat of an experimental project).  The CheckoutData table is going to be receiving a lot of inserts - very frequently (we're talking...a few hundred per minute).  And Book results will be requested at around the same rate, with perhaps 10 or 20 book entries being requested each time.
So TONS of checkouts, as well as TONS of requests for book summaries.

A:
(we're talking...a few hundred per
  minute)

60 seconds per minute, about 10 inserts per second. That is not very much, a database can handle thousands of inserts per second.
If you have a query with a performance problem, start using EXPLAIN to see what is going on and why things are slow.

A: I don't like a two column setup, but a denormalized version of the main query (e.g. create a view with all 5 tables joined appropriately, and then insert from there into another table) would have real benefits.


text:
Q: Any workaround to set PATH for debugger (VS 2017, 2019, toolset v141)? In Visual Studio 2017/2019, in a c++ project, project property pages / configuration properties / debugging / environment, we set environment to a certain value, but it is ignored (it does not work) when we use toolset v141, and it works with v142 (VS2019 only).
Is there any way to set a certain $env:path for the debugger, in a specific configuration (debug/release) ?
I thought about running a command before the Command = $(TargetPath), but it's not straightforward.

Reference: https://developercommunity.visualstudio.com/content/problem/549114/project-propertiesenvironmentpath-being-ignored-by.html


text:
Q: A question regarding the cone where the solution to an ODE lies inside I am currently reading the Chapter 4 of the book Ordinary Differential Equations by Arnold. Here the book wants to prove the Existence and uniqueness of the solution to an ODE from the approach of the contraction mapping. In the following image, it wants to study the convergence of the Picard approximations within a small neighborhood of a single point.

I understand the construction of the cylinder and even the further explanations how the solution can be sought inside the cone. However, I didn't understand the definition of the cone $K_0$ and how it lies inside the cylinder with only if $a'$ is sufficiently small. Namely, can anyone explain to me how the definition
$$
K_0 = \{ t, x:|t-t_0| \leq a',\ |x-x_0| \leq C|t-t_0|\}
$$
comes naturally?

A: You want that the double cone $K_0$ lies completely inside the cylinder $C$, meaning that it only intersects the "time" sides of the cylinder, never the "space" mantle of it. This requires that $C|t-t_0|\le b$ and thus $Ca'\le b$, which is satisfied if $a'$ is sufficiently small. You could of course also directly take $a'=b/C$.
If you want to additionally also prove claims on the dependence of the solution on the initial point, you also need to allow for small variations $|x_0'-x_0|\le b'$ of this initial point in the fixed-point computations. Then you want
$$
|x(t)-x_0|\le |x(t)-x_0'|+|x_0'-x_0|\le C|t-t_0|+b'\le Ca'+b'
\overset{\Large !}\le b
$$
giving a correspondingly smaller value of $a'$.


text:
Q: Draw square and bullet arrow with core graphics Is it possible to draw the following in objective-c? I tried using the image, but It pixelates. So I figured it is best to draw it programatically. Can someone provide me some sample code to achieve this.
Thank you.

A: Use a CAShapeLayerand assign it a path describing your shape:
- (UIBezierPath *)createBubblePathInFrame:(CGRect) frame{
    CGFloat arrowInset = 10;
    CGFloat arrowHeight = 10;
    CGFloat arrowWidth = 20;

    UIBezierPath *path  = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, arrowHeight)];
    [path addLineToPoint:CGPointMake(arrowInset, arrowHeight)];
    [path addLineToPoint:CGPointMake(arrowInset+arrowWidth/2, 0)];
    [path addLineToPoint:CGPointMake(arrowInset+arrowWidth, arrowHeight)];
    [path addLineToPoint:CGPointMake(frame.size.width, arrowHeight)];
    [path addLineToPoint:CGPointMake(frame.size.width, frame.size.height)];
    [path addLineToPoint:CGPointMake(0, frame.size.height)];
    [path addLineToPoint:CGPointMake(0, arrowHeight)];
    return path;
}

Use it like this:
    CAShapeLayer *shapelayer  = [CAShapeLayer layer];
    shapelayer.frame = CGRectMake(50, 50, 200, 100);
    shapelayer.path = [self createBubblePathInFrame:shapelayer.bounds].CGPath;
    shapelayer.fillColor = [UIColor grayColor].CGColor;
    shapelayer.strokeColor = [UIColor redColor].CGColor;
    shapelayer.lineWidth = 1;
    [self.view.layer addSublayer:shapelayer];

Or you can draw it yourself in drawRect:
[[UIColor grayColor] setFill];
[bezierPath fill];
[[UIColor redColor] setStroke];
[bezierPath stroke];

A: You can use this as a triangle view:
 @implementation Triangle

 - (id)initWithFrame:(CGRect)frame
 {
     self = [super initWithFrame:frame];
     if (self)
     {
         self.backgroundColor = [UIColor clearColor];
         self.alpha = 0.75;
     }
    return self;
 }

 - (void)drawRect:(CGRect)rect
 {
     CGContextRef ctx = UIGraphicsGetCurrentContext();

     CGContextBeginPath(ctx);
     CGContextMoveToPoint(ctx, CGRectGetMinX(rect), CGRectGetMinY(rect));  // top left
     CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMinY(rect));  // top right
     CGContextAddLineToPoint(ctx, CGRectGetMidX(rect), CGRectGetMaxY(rect));  // bottom mid
     CGContextClosePath(ctx);

     CGContextSetRGBFillColor(ctx, 25.0/255.0, 25.0/255.0, 25.0/255.0, 1.0);
     CGContextFillPath(ctx);
 }

 @end

Then just subclass a UIView and add an instance of Triangle where appropriate (in your case on the top left corner).
For your purpose you also should rotate this triangle 180 degrees as the code above drwas a triangle that points downwards.


text:
Q: set a field in pivot table whenever a record insert or update happens in laravel OK, recently I am implementing an RBAC based system in laravel.
I have these two classes as my models:
class User extends Authenticatable
{
    public function roles(){
        return $this->belongsToMany(\App\Role::class, 'user_role', 'user_id', 'role_id')->withPivot('is_expired', 'assigned_at', 'expire_at');
    }
}

class Role extends Model
{
    public function users(){
        return $this->belongsToMany(\App\User::class, 'user_role', 'role_id', 'user_id')->withPivot('is_expired', 'assigned_at', 'expire_at');
    }
}

it works fine BUT, I want to set a default value for the expire_at attribute of the pivot table based on an attribute of the Role model. for example I have a period attribute on Roles table, and its a number representing number of months.
So i want when a role assigned to a user (inserted in pivot table) the value of expire_at set to currentDatetime + thePeriodNum months and save in the pivot table.
how can I achieve this?
I have tried laravel custom pivot class and mutators but it seems not working or I did something wrong.
somebody mentioned that the mutators dont get triggered when using attach()/detach() methods so I think even if it was working i could not see the difference.
Someone mentioned its possible with observers but I have no Idea what is an observer im noob.
So thats all, it would be really good for me if anybody could help me through this mess I'm in right now.
Thanks in advance.

A: It is possible to attach the new role and set the expires_at column at the same time. This would avoid needing to use observers (listeners of model events) within your code.
The code would look like the following:
$role = Role::find($roleId);

$expireAt = now()->addMonths($role->period)->toDateTimeString();

// or Carbon::now()->addMonths($role->period)->toDateTimeString();

User::find($userId)->roles()->attach($role->id, ['expire_at' => $expireAt]);

Here, the role is found. A timestamp is created by taking the current time, adding the addition months based on the role's period (this should be an integer value).
Finally, this is added to the attachment of the role to the user.
Add as a model method
This can all be added as a function/method on the User model which would clean up the code into one action, ->addRole($roleId):
// Within App\User.php

public function addRole($roleId)
{
    $role = \App\Role::find($roleId);

    $expiresAt = now()->addMonths($role->period)->toDateTimeString();

    $this->roles()->attach($role->id, [ 'expire_at' => $expiresAt ]);
}

This can then be called with the following:
$user = User::find($id);

$user->addRole($roleId);

I hope this help.


text:
Q: Django - Valores iniciales en un modelform maestro-detalle utilizando inlineformset_factory Tengo las siguientes tablas:
models.py
class RegistroPago(models.Model):
fechaPago = models.DateField(default=timezone.now)
contrato = models.ForeignKey(Contrato, on_delete=models.CASCADE)
formapago = models.ForeignKey(FormaPago, on_delete=models.CASCADE)
nota = models.CharField(max_length=255, blank=True)
archivo = models.FileField(upload_to='images/', blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
    return str(self.pk)

class RegistroPagoDato(models.Model):
    registropago = models.ForeignKey(RegistroPago, related_name='items', on_delete=models.CASCADE)
    # aqui el secreto fue este related_name = 'items'
    categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE)
    concepto = models.CharField(max_length=150, verbose_name="Concepto")
    importe = models.DecimalField(max_digits=12, decimal_places=2, default=0)

    def __str__(self):
        # return self.cliente
        return str(self.pk)

en views.py:
class CrearRegistroPago(CreateView):
model = RegistroPago
template_name = 'registropago.html'
form_class = RegistroPagoForm
success_url = reverse_lazy('listado_pagos')

def get(self, request, *args, **kwargs):
    self.object = None
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    detalle_orden_registro_pago_formset = DetalleRegistroPagoFormSet()
    return self.render_to_response(self.get_context_data(form=form, detalle_registro_pago_form_set=detalle_orden_registro_pago_formset))

def post(self, request, *args, **kwargs):
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    detalle_registro_pago_form_set = DetalleRegistroPagoFormSet(
        request.POST)

    if form.is_valid() and detalle_registro_pago_form_set.is_valid():
        return self.form_valid(form, detalle_registro_pago_form_set)
    else:
        return self.form_invalid(form, detalle_registro_pago_form_set)

def form_valid(self, form, detalle_registro_pago_form_set):
    form.instance.user = self.request.user
    self.object = form.save()
    detalle_registro_pago_form_set.instance = self.object
    detalle_registro_pago_form_set.save()

    return HttpResponseRedirect(self.success_url)

def form_invalid(self, form, detalle_registro_pago_form_set):
    return self.render_to_response(self.get_context_data(form=form, detalle_registro_pago_form_set=detalle_registro_pago_form_set))

def get_form_kwargs(self):
    kwargs = super(CrearRegistroPago, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})

    return kwargs

en forms.py:
class RegistroPagoForm(forms.ModelForm):

class Meta:
    model = RegistroPago
    labels = {
        "contrato": "Contrato / Nombre del Inquilino:",
        "fechaPago": "Fecha de Pago:",
        "formapago": "Forma de Pago:",
        "nota": "Agregar Nota:",
    }
    fields = ['fechaPago', 'contrato', 'formapago', 'nota', 'archivo',]

def __init__(self, user, *args, **kwargs):
    super(RegistroPagoForm, self).__init__(*args, **kwargs)
    # self.fields['inquilino'].queryset = Inquilino.objects.all().filter(user=user, status=1)
    self.fields['contrato'].queryset = Contrato.objects.all().filter(user=user, status=1)

    for field in iter(self.fields):
        self.fields[field].widget.attrs.update({
            'class': 'form-control'
        })

class RegistroPagoDatoForm(forms.ModelForm):
class Meta:
    model = RegistroPagoDato
    fields = ['categoria', 'concepto', 'importe',]

def __init__(self, *args, **kwargs):
    super(RegistroPagoDatoForm, self).__init__(*args, **kwargs)

    for field in iter(self.fields):
        self.fields[field].widget.attrs.update({
            'class': 'form-control'
        })

DetalleRegistroPagoFormSet = inlineformset_factory(RegistroPago, RegistroPagoDato, form=RegistroPagoDatoForm, extra=4)

formset = DetalleRegistroPagoFormSet(initial=[{'categoria': 6, 'concepto': 'probando, 123 probando', 'importe': 999.99}, {'concepto': 'probando, 123 probando'}, {'importe': 999.99},])

for form in formset:
    print(form.as_table())

No logro hacer funcionar que cuando quiero capturar un nuevo pago los campos del formulario RegistroPagoDatoForm creado con inlineformset_factory me aparezcan prellenados o con los valores iniciales definidos en:
formset = DetalleRegistroPagoFormSet(initial=[{'categoria': 6, 'concepto': 'probando, 123 probando', 'importe': 999.99}, {'concepto': 'probando, 123 probando'}, {'importe': 999.99},])

Los curioso es que al ver el html que genera el DetalleRegistroPagoFormSet, ahí si aparecen los valores iniciales:

Categoria:	<select name="items-0-categoria" class="form-control" id="id_items-0-categoria">
  <option value="">---------</option>
  <option value="1">Renta</option>
  <option value="2">Agua</option>
  <option value="3">Electricidad</option>
  <option value="4">Gas</option>
  <option value="5">Intereses</option>
  <option value="6" selected>Depósito</option>
  <option value="7">Mantenimiento</option>
</select>

Concepto:	<input type="text" name="items-0-concepto" value="probando, 123 probando" maxlength="150" class="form-control" id="id_items-0-concepto">

Importe:	<input type="number" name="items-0-importe" value="999.99" step="0.01" class="form-control" id="id_items-0-importe">

Eliminar:	<input type="checkbox" name="items-0-DELETE" id="id_items-0-DELETE"><input type="hidden" name="items-0-id" id="id_items-0-id"><input type="hidden" name="items-0-registropago" id="id_items-0-registropago">

Categoria:	<select name="items-1-categoria" class="form-control" id="id_items-1-categoria">
  <option value="" selected>---------</option>
  <option value="1">Renta</option>
  <option value="2">Agua</option>
  <option value="3">Electricidad</option>
  <option value="4">Gas</option>
  <option value="5">Intereses</option>
  <option value="6">Depósito</option>
  <option value="7">Mantenimiento</option>
</select>

Concepto:	<input type="text" name="items-1-concepto" value="probando, 123 probando" maxlength="150" class="form-control" id="id_items-1-concepto">

Importe:	<input type="number" name="items-1-importe" value="0" step="0.01" class="form-control" id="id_items-1-importe">

Eliminar:	<input type="checkbox" name="items-1-DELETE" id="id_items-1-DELETE"><input type="hidden" name="items-1-id" id="id_items-1-id"><input type="hidden" name="items-1-registropago" id="id_items-1-registropago">

Categoria:	<select name="items-2-categoria" class="form-control" id="id_items-2-categoria">
  <option value="" selected>---------</option>
  <option value="1">Renta</option>
  <option value="2">Agua</option>
  <option value="3">Electricidad</option>
  <option value="4">Gas</option>
  <option value="5">Intereses</option>
  <option value="6">Depósito</option>
  <option value="7">Mantenimiento</option>
</select>

Concepto:	<input type="text" name="items-2-concepto" maxlength="150" class="form-control" id="id_items-2-concepto">

Importe:	<input type="number" name="items-2-importe" value="999.99" step="0.01" class="form-control" id="id_items-2-importe">

Eliminar:	<input type="checkbox" name="items-2-DELETE" id="id_items-2-DELETE"><input type="hidden" name="items-2-id" id="id_items-2-id"><input type="hidden" name="items-2-registropago" id="id_items-2-registropago">

pero en el navegador no aparecen:

Lo que quiero lograr es que al generar un pago, el formulario inicie así:

Muchas gracias por la ayuda!


text:
Q: Need Help on SQL I actually found something that I could work on regarding my problem "Need help with sql query". But I would appreciate it if I can get an answer to my specific question.
I have 2 tables one is TRANSACTIONS and one is EXPENSES.
TRANSACTION:
transaction_id
emp_id
sales_date
total_sales

And
EXPENSES:
expenses_id
emp_id
expense_date
expenses1
expenses2
total_expenses

I would like to sum all the TRANSACTION.transaction_amount AS sales_sum WHERE TRANSACTION.sales_date = @sales_date and TRANSACTION.emp_id = @emp_id ..... and then, subtract the EXPENSES.total_expenses as expenses_deducted_sales WHERE EXPENSES.emp_id = TRANSACTION.emp_id AND TRANSACTION.sales_date = EXPENSES.expense_date
PLEASE HELP.. Thank you
Ex
transaction_id    emp_id   sales_date     total_sales
1                  101     11/11/2012      300
2                  101     11/11/2012      400
3                  101     11/11/2012      300

expenses_id emp_id expenses_date  expenses1  expenses2  total_expenses
1            101    11/11/2012      100        100        200
2            102    12/12/2012      50         50         100
3            103    10/12/2012      200        200        400

expenses_deducted_sales = (300 + 400 + 300) - 200
I've tried the code given by AHiggins and came up with these:
SELECT
CashTransactionsTbl.emp_id,
CashTransactionsTbl.trans_date,
CashTransactionsTbl.total_amt - ISNULL(ExpensesTbl.total_expenses,0) AS expenses_deducted_sales
FROM
 (
    SELECT
          emp_id,
           trans_date,
           SUM(total_amt)  AS sales_sum
     FROM CashTransactionsTbl
     GROUP BY emp_id, trans_date
 ) tr
   LEFT JOIN
   ExpensesTbl ON
           tr.emp_id = ExpensesTbl.emp_id AND
           tr.trans_date = ExpensesTbl.trans_date
WHERE
          tr.trans_date = 2014-07-10
but no I have this error that says:
"Operand type clash: date is incompatible with int"
Please help!

A: You need two derived tables: One with the transaction sum per employee, one with the expenses sum per employee. Full outer join These to get all records.
select
  coalesce(t.emp_id, e.emp_id) as emp_id,
  coalesce(t.sum_sales, 0) as sum_sales,
  coalesce(e.sum_expenses, 0) as sum_expenses,
  coalesce(t.sum_sales, 0) - coalesce(e.sum_expenses, 0) as expenses_deducted_sales
from
(
  select emp_id, sum(total_sales) as sum_sales
  from transaction
  group by emp_id
) t
full outer join
(
  select emp_id, sum(total_expenses) as sum_expenses
  from expense
  group by emp_id
) e on e.emp_id = t.emp_id;

A: You need to get the aggregate data from Transactions before you match that with the data from Expenses, like so:
SELECT
    tr.Emp_ID,
    tr.Sales_Date,
    tr.Sales_Sum - ISNULL(Expenses.Total_Expenses,0) AS Expenses_Deducted_Sales
FROM
  (
    SELECT
        Emp_ID,
        Sales_Date,
        SUM(Total_Sales) Sales_Sum
    FROM Transactions
  ) tr
     LEFT JOIN
    Expenses ON
        tr.Emp_ID = Expenses.Emp_ID AND
        tr.Sales_Date = Expenses.Expenses_Date
WHERE
    tr.Sales_Date = @sales_date -- this could also go under the 'FROM Transactions' statement

A: This is pretty rough but something like this would work:
Select T_Sales.*,T_Sales.totalsales-totalexpesnses 'Expenses_deducted_sales'
from (
    select t.emp_id,sales_date,SUM(totalsales) 'totalsales'
    from #transaction t
    group by t.emp_id,sales_date
    ) T_Sales
left join #expenses e
on T_Sales.emp_id = e.emp_id
and T_Sales.sales_date = e.expenses_date
where sales_date = @sales_date

ps. Apologies for spelling - quick work.


text:
Q: Extracting  triplet from unstructured text I need to extract simple triplets from unstructured text. Usually it is of the form noun- verb- noun, so I have tried POS tagging and then extracting nouns and verbs from neighbourhood.
However it leads to lot of cases and gives low accuracy.
Will Syntactic/semantic parsing help in this scenario?
Will ontology based information extraction be more useful?

A: I expect that syntactic parsing would be the best fit for your scenario. Some trivial template-matching method with POS tags might work, where you find verbs preceded and followed by a single noun, and take the former to be the subject and the latter the object. However, it sounds like you've already tried something like that -- unless your neighborhood extraction ignores word order (which would be a bit silly - you'd be guessing which noun was the word and which was the object, and that's assuming exactly two nouns in each sentence).
Since you're looking for {s, v, o} triplets, chances are you won't need semantic or ontological information. That would be useful if you wanted more information, e.g. agent-patient relations or deeper knowledge extraction.
{s,v,o} is shallow syntactic information, and given that syntactic parsing is considerably more robust and accessible than semantic parsing, that might be your best bet. Syntactic parsing will be sensitive to simple word re-orderings, e.g. "The hamburger was eaten by John." =>  {John, eat, hamburger}; you'd also be able to specifically handle intransitive and ditransitive verbs, which might be issues for a more naive approach.


text:
Q: Why do we invert word order when asking a question? What's the difference between an inverted question and a normal-order question?
Why invert? Is there a reason or a benefit?

*

*I love you?

*Do I love you?

A: "Do I love you?" is the proper form. In spoken English, though, you can, and in suitable situations you would, use the form "I love you?"
To put this into an example (spoken):
Situation A:

Person A: "This guy came in and asked whether he can borrow my cell phone. Do I know him?"
  Person B: "Yes, he's one of our former employees, we've worked together long time ago."

Situation B:

Person A: "Have you heard? Some guy went to the bank today and started shooting people.
  Person B: "Yes, it is kind of sad, because he's one of our former employees. You two have worked together long time ago."
  Person A: "I know him??"

In situation A, you are really asking the question, because you want to know the answer. In situation B, you kind of already know the answer, but for the matter of the situation, you want to assure yourself, as if to not wanting to believe the result.

A: The non-inverted question is used in one specific case: when the first speaker has expressed as fact something the second speaker doubts.  @RiMMER's example demonstrates that.  Or, to use your sentence:

Person A: Since you love me and I love you, we should get married.
  Person B: I love you?

If B had said "Do I love you?", it would be an expression of genuine curiosity; as it is, he's just expressing his uncertainty or disagreement.

A: I suppose a benefit of having a different word order for questions is that you can usually tell a question from a statement as soon as the speaker starts asking it.

Can you—  (starts a question)
You can—  (starts a statement)

I'm not sure this is really helpful, though, as you can generally tell anyway, from body language or tone of voice. Even if this is useful, questions could of course be distinguished in any of a dozen other ways (and I imagine they are, in various other languages).
Generally there are not good well-known reasons for all the quirks in English.


text:
Q: How to change AWT Label Font I am trying to define the Font for an AWT Label.
While I can manage to use fonts for a Java2D graphics environment, same font seems not to work with AWT Labels. I would like to understand if there is any limitation on font usage I am not aware about it for AWT Labels, or if I am simply not using the right syntax/procedure.
this is my code, it basically adds a Label and text to the graphics context:
package com.company.test;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Label;

public class TestTest extends Frame {

    Label myLabel = new Label();
    Font myFont = new Font("Roboto Condensed Light", Font.PLAIN, 12);
    Graphics2D g2d;

    public TestTest() {

        setSize(500,200);
        setLocation(10,10);
        setUndecorated(false);

        myLabel.setBackground(Color.red);
        myLabel.setFont(myFont);
        myLabel.setText("ROBOTO CONDENSED, THIS DOES NOT WORK!");
        add(myLabel, BorderLayout.SOUTH);

        setVisible(true);

    }

    public void paint(Graphics g) {

        g2d = (Graphics2D) g;
        g2d.setStroke(new BasicStroke(0.0f));

        g2d.setFont(myFont);
        g2d.setColor(Color.BLACK);
        g2d.drawString("ROBOTO CONDENSED THIS WORKS!",50, 50);

    }

    public static void main( String[] args ) {

        TestTest window = new TestTest();

    }

}

This is the result:

While font is properly defined (as it is used in the Text element in the Graphics component), it is not being applied to the AWT Label component.
Any tip is welcomed.
Note: please do not suggest to use SWING or JavaFX, I am well aware that they are the recommended way of using widgets. Question is specifically related to AWT Label widget.

A: Ok you have to create your own label; the idea is to get to the graphics of things. I have added my inline class but you can create a proper class; then you have to pass the string or other parameters to that class:
class TestTest extends Frame {

Font myFont = new Font("Rockwell Nova", Font.PLAIN, 12);
Graphics2D g2d;

public TestTest() {

  Label myLabel = new Label() {
    public void paint(Graphics g) {
      g.setFont(myFont);
      g.drawString("ROBOTO CONDENSED, THIS DOES NOT WORK!", 0, 20);
    }
  };
    setSize(500,200);
    setLocation(10,10);
    setUndecorated(false);

    myLabel.setBackground(Color.red);

    add(myLabel, BorderLayout.SOUTH);
    setVisible(true);

}

public void paint(Graphics g) {

    g2d = (Graphics2D) g;
    g2d.setStroke(new BasicStroke(0.0f));

    g2d.setFont(myFont);
    g2d.setColor(Color.BLACK);
    g2d.drawString("ROBOTO CONDENSED THIS WORKS!",50, 50);

}

}


text:
Q: Write update sql script in migration I have an entity for the Landlord.
Here is the model:
[Required]
    [MaxLength(PM101Consts.MaxNameLength)]
    public virtual string FirstName { get; set; }
    [Required]
    [MaxLength(PM101Consts.MaxNameLength)]
    public virtual string LastName { get; set; }

    [MaxLength(PM101Consts.MaxCompanyNumberLength)]
    public virtual string CompanyNumber { get; set; }

    [MaxLength(PM101Consts.MaxVatNumberLength)]
    public virtual string VatNumber { get; set; }

    [Required]
    public virtual int LandlordTypeId { get; set; }

    public string Email { get; set; }

    [Required]
    public virtual Status Status { get; set; }

    [Required]
    [MaxLength(PM101Consts.MaxCompanyNameLength)]
    public virtual string OrganizationName { get; set; }

    [MaxLength(PM101Consts.MaxWebsiteLength)]
    public virtual string Website { get; set; }

    public long? UserId { get; set; }

    [ForeignKey("UserId")]
    public User User { get; set; }

I create a User table with those properties:
public virtual string Name { get; set; }

public virtual string Surname { get; set; }

public virtual string Email { get; set; }

public virtual string Password { get; set; }

And I need to create Users for all Landlords, that already created in the database. I need to do this in-migration. So User.Name = Landlord.FirstName , User.Surname = Landlord.LastName,
User.Email = Landlord.Email. How I need to write a script.

A: you can seed data like following example
protected override void Seed(DbContext context)
{
   var landlords = context.Landlord.ToList();

   foreach(var landlord in loandlords){
     var user = new Users(){
         Name = landlord.FirstName,
         Surname = landlord.LastName,
         Email = landlord.Email
   }
   context.Users.Add(user);
}

    base.Seed(context);
}


text:
Q: Encapsulate a postgresql Transaction in a structure I'm trying to encapsulate a Postgresql transaction and I'm running into some lifetime issue.
Here is the code :
Code
I understand the error message : "returns a value referencing data owned by the current function"
But I have no idea how I could keep my "Transaction" in my the SQLConnection structure.
use postgres::{Client, NoTls, Transaction};

pub struct SQLConnection<'a> {
    client: Client,
    transaction: Transaction<'a>,
}

impl<'a> SQLConnection<'a> {
    pub fn new(connect_string: &str) -> Self {
        let mut client = Client::connect(connect_string, NoTls).unwrap();
        let transaction = client.transaction().unwrap();
        Self {
            client,
            transaction,
        }
    }

    pub fn commit(&self) {
        let _ = self.transaction.commit();
    }

    pub fn rollback(&self) {
        let _ = self.transaction.rollback();
    }
}

A: You' re returning a reference to a value you don't keep. You can't have a reference if there's no owned value.
In your case, there's also no reason to keep both the client and the transaction. Your connection should wrap the client but not the transaction which is a short lived object and shouldn't be kept for more than just the operation.
Your connection should thus just be
pub struct SQLConnection {
    client : Client,
}

Then you should, for an operation, get a transaction, use it, then drop it while keeping the connection.

A: I found a solution that suits my needs. I have now SQLConnection and SQLTransaction and I get the SQLTransation from the my connection.
Now I can use my transaction to group my elementary sql operations.
Here is the code:
use postgres::{Client, NoTls, Transaction};

pub struct SQLConnection {
    client: Client,
}

impl SQLConnection {
    pub fn new(connect_string: &str) -> Self {
        let client = Client::connect(connect_string, NoTls).unwrap();
        Self { client }
    }

    pub fn transaction(&mut self) -> SQLTransaction {
        let t = self.client.transaction().unwrap();
        SQLTransaction { transaction: t }
    }
}

pub struct SQLTransaction<'a> {
    transaction: Transaction<'a>,
}

impl<'a> SQLTransaction<'a> {
    pub fn new(transaction: Transaction<'a>) -> Self {
        Self { transaction }
    }

    pub fn commit(self) {
        let _ = self.transaction.commit();
    }

    pub fn rollback(self) {
        let _ = self.transaction.rollback();
    }
}


text:
Q: Negation, Converse, or contrapositive? S: Every employee who is honest and persistent is successful or bored.
Would this statement be the negations, converse, or contrapositive of S?
-> All employees who are dishonest or not persistent must be unsuccessful and not bored.

A: The altered statement is the converse of the contrapositive of $S$.
Contraposive of $S$: "All employees who are unsuccessful and not bored are dishonest or not persistent."
Converse of the contrapositive of $S$: "All employees who are dishonest or not persistent are unsuccessful and not bored."

A: Sorry if my notation is unfamiliar.
Write
\begin{align*}
Hx &= \text{$x$ is honest}\\
Px &= \text{$x$ is persistent}\\
Sx &= \text{$x$ is successful}\\
Bx &= \text{$x$ is bored}
\end{align*}
Then $S$ can be written $\forall x (Hx \land Px) \to (Sx \lor Bx)$.
The next statement can be written $\forall x (\neg Hx \lor \neg Px) \to (\neg Sx \land \neg Bx)$.
Can you apply De Morgan's laws to make sense of that?


text:
Q: Any idea why my variables won't print? I know why these types of errors generally occur, but in my situation, I can't figure out why.
Here's what I'm trying to do: First of all, the type of file I'm working with is a spreadsheet that contains integers and strings, or combinations of both in a given cell.
Now, I have previously written a program that will allow me to append and make a list of all values from a given column on this spreadsheet, and all the values look something like this "c.2232_2234A>G" or "c.23C>T" (these are the types of values that the variables 'mutation' and 'mutation_list' contain. So, for each value in my list, I want to cross-reference it with all other values in my list and find possible matches, and then if they match, then I want to append certain info from a different column of the spreadsheet and print it, and so on.
Edit: I just changed it so that I am comparing the same list against itself. So in this given list, for a particular mutation, I want it to cross-reference it with all other mutations in the list and append the family number and other variables (listed below) for those matches. Although now I don't get the index error, I don't get an output in terms of the variables that I listed. Any ideas?
Here's what I have so far:
for y in range(1, len(mutation)):
      for z in range(1,len(mutation):
            if mutation[y] == mutation[z]:
                  print "Family Number", family_num[z], "\t", "Result", result[z], "\t", "Mutation", mutation[y], "\t", "Site", site[z]

Thanks!

A: In the print statement, concatenate the list, variables, whatever, to string. Try that?
for y in range(1, len(mutation)):
      for z in range(1,len(mutation):
            if mutation[y] == mutation[z]:
                  print("Family Number", str(family_num[z]), "\t", "Result", str(result[z]), "\t", "Mutation", str(mutation[y]), "\t", "Site", str(site[z]))


text:
Q: Как при перезагрузке страницы сохранять прогресс игры Пишу тетрис, ситуация такая, игрок зарегался в игре и во время его сессии произошла перезагрузка страницы, нужно чтобы весь прогресс остался и игра продолжалась, помогите!
Тетрис на канвасе.
И еще, как хранить информацию, а именно имя и количество очков?


text:
Q: Why does the following expression return true? I am having a tough time in understanding the precedence of the short circuit operators in Java. As per the short circuit behavior, the right part of the expression "true || true" shouldn't matter here because once the first part of the "&&" condition is evaluated as "false", the rest of the expression should have not been evaluated.
But, when executing the following piece of code, I see the result declared as "true". Could someone explain this to me?
    public class ExpressionTest{
        public static void main(String[] args) {
        boolean result1 = false && true || true;
        System.out.println(result1);
        }
    }

A: Check this tutorial on operators. The table clearly shows that && has higher precedence than ||.
So,
false && true || true;

is evaluated as:
(false && true) || true;

Rest I think you can evaluate on your own.

A: From The JAVA turorial

Operators on the same line have equal precedence. When operators of
  equal precedence appear in the same expression, a rule must govern
  which is evaluated first. All binary operators except for the
  assignment operators are evaluated from left to right; assignment
  operators are evaluated right to left

Therefor, the compiler parse it as
boolean result1 = (false && true) || true;

Therefor, A || true return true regardless of A value.
To get the desirable expression do as follow:
boolean result1 = false && (true || true);


text:
Q: mySql regular expression in WHERE statement I have a database where I store a code which is an implode("|", $array) of various codes.  So the results will be something like:

*

*100|5100|510

*100|5200|510

*410|5200|520

*100|790|5100|320

I want to write a regular expression to search mySQL for matches from PHP ...  I might have something like 100|*|510 to show me both 100|5100|510 and 100|5200|510.   This RegEx works in PHP:
/100\|(?:.*)\|510/
But it does not work in mySQL.  I found answers that ?: does not work, so if I remove that and use
/100\|.*\|510/
i.e. Query is:
SELECT * FROM tra_amounts WHERE coa_codes REGEXP "/100\|.*\|510/"
It shows all results from the table.
How do I write a RegEx to match some parts of the code, while leaving other parts of the code as a wildcard?
Thanks!

A: Have you heard of MySQL's LIKE operator?  Something like this might be what you have in mind:
SELECT *
FROM yourTable
WHERE someCol LIKE '100|%|510;

Assuming that someCol had 100|5100|510 and 100|5200|510 as data, this query would return both of these records.

A: Use RLIKE instead of LIKE or =.


text:
Q: What is the right way to create ViewModels with Repository pattern I am learning to use ASP.NET MVC with the Repository pattern.
I have a list of Users and a list of Roles. Users contain a RoleId, and Roles contain a RoleName and Id. I want to return a list of UsersWithRoles and put it in a ViewModel that has a UserName and a RoleName. What is the right way to proceed.
I am thinking of:
   1) Get the list of Names and Roles and fill the ViewModel from the controller(foreach)
   2) Join the Roles and Names in the Repository and return them as an Entity to the Controller, where I fill the ViewModel
   3) Join the Roles and Names in the Repository and return as a ViewModel directly

A: u can done this by get user records using LINQ and using that user info u can again get record of role using LINQ. at the end u can add in custom model and that model u can send to respected view.
In Controller
Find Specific record and store common field (Primary Data) to the local variable
var Users = _Entity.UserInfoTable.Where(p => p.UserCode.Equals(UserID)).FirstOrDefault();
string strUserID = Users.UserID

strUserID hold the UserID
now using local variable get the role data specific to that user
var UserRole = _Entity.UserRoleTable.Where(p => p.UserCode.Equals(strUserID)).FirstOrDefault()

Final step : add UserRole data to the Custom/View model/Repo
CustomeModel cm = new CustomeModel();
cm.UserID  = UserRole.UserID;
cm.RoleID = UserRole.RoleID;
cm.RoleName = UserRole.RoleName;

A:    var usersWithRoles = (from u in Users
                         join r in Roles on r.Id equals u.RoleId
                         select new UserWithRoles{
                                UserName = u.UserName,
                                RoleName = r.RoleName

                        }).ToList();


text:
Q: How can I use sed in /etc/apache2/sites-available? I'm attempting to write a script that uses sed to copy the default file for apache and writes a new file, replacing /var/www ($DOC_ROOT below) with my own directory, $NEW_SITES_DIR. However, sed isn't operating correctly running under sudo: I get a "permission denied" error for the following:
sudo sed -ie 's:$DOC_ROOT:$NEW_SITES_DIR:g' < default > $NEW_SITE

I've tried to spawn a sub-shell
sudo sh -c "sed -ie 's:$DOC_ROOT:$NEW_SITES_DIR:g' < default > $NEW_SITE"

and use tee
sudo sed -ie 's:$DOC_ROOT:$NEW_SITES_DIR:g' < default | sudo tee $NEW_SITE

but I get a "no input files" error instead.
I'm sure the last two attempts I have written are a bit off. Any suggestions would be greatly appreciated.

ANSWERED
Thank you to everyone for your help. Here is the exact command:
sudo sed -e "s:$DEF_SITES_DIR:$NEW_SITES_DIR:g" < $DEF_SITE | sudo tee $NEW_SITE

And here is a key phrase from this reference:

Don't lose sleep over this, but
  someday it will come handy, and when
  you can figure out why the "sudo" does
  not apply after the ">" in your
  command, remember tee and come back here.

A: Your problem is the -i. That's telling sed to edit the file in place, but you're providing the file on stdin by redirecting it. Try dropping the -i.
There's really no need to redirect the input file since sed accepts a filename as an argument. If the read permissions on the file are restricted then sudo sed (and not using redirection) will take care of that. By not using -i the original file will be left intact.
The sudo tee should take care of the write permissions for output if that's necessary.


text:
Q: PHP - Create multiple XML files from Mysql data I'm pulling data from my mysql database and using it to create an XML file. the idea is for each row of data pulled, it be appended to its own XML file
Here's my sample code:
//sql statement here
$results = $fetch_data->fetchAll(PDO::FETCH_ASSOC);

foreach($results as $data)
{
    $invoice_no = $data["invoice_no"];

    $doc = new DOMDocument();
    $doc->formatOutput = true;
    $Order = $doc->appendChild($doc->createElement('Order'));
    $OrderHead = $Order->appendChild($doc->createElement('OrderHead'));

    $Schema = $doc->createElement('Schema');
    $Schema->appendChild($doc->createElement('Version', '3.05'));
    $OrderHead->appendChild($Schema);

    $CrossReference = $doc->createElement('CrossReference', $invoice_no);
    $OrderHead->appendChild($CrossReference);

    //more xml code...

    $doc->save($invoice_no.".xml", LIBXML_NOEMPTYTAG);
}

As shown above, i'm looping through the data from the database to create the XML file then want to save each file(s)  prefixed by the $invoice_no. But only one XML file is created and to be more specific, only the last record pulled from the database is used to create the XML file. this is happening though i'm creating the file inside my loop
where could i be going wrong?


text:
Q: Running a method on self inside a tokio task I have created a very simplified example of the code I am having an issue with:
use core::time;
use std::thread;
use tokio::sync::{mpsc::Receiver, RwLock};

struct MyStruct {
    counter: Arc<RwLock<i32>>,
    rx: RwLock<Receiver<i32>>,
}

impl MyStruct {
    async fn start_here(&self) { // <--------- Lifetime error here on self
        while let Some(message) = self.rx.write().await.recv().await {
            tokio::spawn(self.do_some_work_then_update_counter());
        }
    }

    async fn do_some_work_then_update_counter(&self) {
        let dur = time::Duration::from_millis(10000);
        thread::sleep(dur);
        let mut counter = self.counter.write().await;
        *counter += 1;
    }
}

There is a receiver that is receiving messages from another part of the program, and I want to be able to process each message in its own task to prevent blocking the next message from being processed.
As you can imagine it's a lifetime error since the task could outlast self in this case.
One solution I have done is this:
impl MyStruct {
    async fn start_here(&self) {
        while let Some(message) = self.rx.write().await.recv().await {
            let counter = self.counter.clone();
            tokio::spawn(do_some_work_then_update_counter(counter));
        }
    }
}

async fn do_some_work_then_update_counter(counter: Arc<RwLock<i32>>) {
    let dur = time::Duration::from_millis(10000);
    thread::sleep(dur);
    let mut counter = counter.write().await;
    *counter += 1;
}

This just doesn't seem like a good option, I want to keep do_some_work_then_update_counter as an impl of MyStruct instead of a free function since it is modifying data on MyStruct.
I am wondering if there is a better solution to this?

A: You can if you'll return impl Future directly instead of being async fn:
fn do_some_work_then_update_counter(&self) -> impl Future<Output = ()> {
    let counter = Arc::clone(&self.counter);
    async move {
        let dur = time::Duration::from_millis(10000);
        thread::sleep(dur);
        let mut counter = counter.write().await;
        *counter += 1;
    }
}


text:
Q: C++ - Vector iterator + offset out of range I have looked at 10 or so answers about the same message but have yet to find my problem.
in level.h in the Level class:
std::vector<Bomb> m_bombs;

in level.cpp:
adding a bomb:
Bomb bomb;
bomb.owner = player;
bomb.power = power;
bomb.x = pos.x;
bomb.y = pos.y;
bomb.timer = 3.0f;
m_bombs.push_back(bomb);

checking bombs (every frame):
void Level::updateBombs(float dt)
{
    for(int i = 0; i < m_bombs.size(); i++)
    {
        m_bombs[i].timer -= dt;
        if(m_bombs[i].timer <= 0)
            m_bombs.erase(m_bombs.begin() + i);
    }
}

I am 100% sure the program crashes on the line where the erase function is called. I am able to output information from the vector which makes this way more confusing. The bombs are correctly in the vector. If I do m_bombs.remove_last() it removes the last element in the vector. Seem to just have problems with erase and begin().

A: Perhaps you can try erasing the vector backwards, e.g. if bomb index 3 and 5 to be erased, you remove the one with index 5 and then 3, because if you erase sequentially from 0 to N-1, by the time you erase index 3, then the index 5 will become index 4, which this can lead to out of bound when reaching the final step of the loop.
try this:
int pivot = 0
void Level::updateBombs(float dt)
{
    for(int i = 0; i < m_bombs.size(); i++)
    {
        m_bombs[i].timer -= dt;
        if(m_bombs[i].timer <= 0)
        {
            m_bombs.erase(m_bombs.begin() + i - pivot);
            pivot++;
        }

    }
}

A: You could fix your code by using erase-remove-idiom.
m_bombs.erase(std::remove_if(m_bombs.begin(), m_bombs.end(),
                             [](const Bomb& b){ return b.timer < 0.0f;}),
                             m_bombs.end());

Better split updateBombs function into two function:
updateBombs() does bomb timer update only
removeBombs() removes bombs which expired

A: I had a similar problem when clearing or creating vectors.
The problem occurred because 2 different versions of dlls where being used at runtime. The clearing and creating took place when calling Open CV functions which seem to use different runtime libraries than my visual studio.
Changing visual studio finally fixed the problem (I tried a lot of old OpenCV builds before changing visual studio but to no avail). VS 2008 and 2013 didn't work, VS2010 did.

A: I would replace m_bombs.size() with an int variable of your own that you decrement after removing a bomb. I've personally had problems with .size(). It's supposed to return the number of elements in the vector but I've had an empty vector and .size() returned numbers greater than zero.  Maybe trying this would help narrow down your problem.


text:
Q: Volley Kotlin won't receive JSON Object from PHP I'm learning to use volley, currently making a login and a register form, using a MySQL database and PHP files. I can get the data sent from a POST request sending a JSON object containing the data, actually the data is inserted correctly in the database. I use the next PHP code for it.
<?php

try {

    // Incluímos archivo de la conexión a base de datos
    include 'database.php';

    // Tomando los datos enviados por json
    $json = file_get_contents('php://input');
    // Pasando a php
    $data = json_decode($json, JSON_UNESCAPED_UNICODE);

    // Obtenemos los datos enviados por POST
    $nombre = $data['nombre'];
    $apellido = $data['apellido'];
    $correo = $data['correo'];
    $contrasenia = $data['contrasenia'];
    $telefono = $data['telefono'];

    // Código para buscar si el email está en uso
    $sqlCorreoEnUso = "SELECT id FROM usuarios WHERE correo = '{$correo}'";

    // Comprobando
    $consultaCorreo = mysqli_query($cn, $sqlCorreoEnUso);
    if (mysqli_num_rows($consultaCorreo)){
        echo json_encode([
            'respuesta' => 'error',
            'razon' => 'EmailEnUso'
        ]);
        exit;
    }

    // Código SQL para la consulta de inserción
    $sqlInsertarUsuario = "INSERT INTO usuarios(nombre, apellido, correo, contrasenia, telefono) VALUES ('{$nombre}','{$apellido}','{$correo}','{$contrasenia}','{$telefono}')";

    // Realizando
    if (mysqli_query($cn, $sqlInsertarUsuario)) {
        echo json_encode([
            'respuesta' => 'ok',
            'razon' => 'usuarioInsertado'
        ]);
    }

} catch (Exception $e) {

    // Visualizando el error si existe
    echo 'Error al procesar';
}

The problem is when I try to process the JSON object that is sent using an echo in the PHP code, I would like to get that JSON object for always having a feedback according to what happened while the code execution. When I try to read this object in Kotlin, I always get this error:
com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

So I tought this could be a problem using echo in PHP, so I tried to use this file using POSTMAN, and it works, I get an answer either the field correo has an already taken value or not.
When using a correo value already taken:
{"respuesta":"error","razon":"EmailEnUso"}

When using a different one never used:
{"respuesta":"ok","razon":"usuarioInsertado"}

This is the Kotlin code:
// Cola de peticiones
        val queue = Volley.newRequestQueue(this)

        // Tomamos los datos
        val nombre = etextNombreRegistro.text.toString()
        val apellido = etextApellidoRegistro.text.toString()
        val correo = etextCorreoRegistro.text.toString()
        val contrasenia = etextContraseniaRegistro.text.toString()

        // Guardando parámetros en hash para mandarlos como JSON en post
        val params = HashMap<String, String>()
        params["nombre"] = nombre
        params["apellido"] = apellido
        params["correo"] = correo
        params["contrasenia"] = contrasenia
        val jsonObject = JSONObject(params as Map<String, String>)

        // Petición con volley
        val request = JsonObjectRequest(Request.Method.POST, Urls.ServicioRegistro, jsonObject,
                { response ->
                    Toast.makeText(this, response.toString(), Toast.LENGTH_LONG).show()
                }, { error ->
                    Toast.makeText(this, "Error: " + error.toString(), Toast.LENGTH_LONG).show()
                    Log.d("MENSAJE", error.toString())
            }
        )

        // Procesandola
        queue.add(request)

For getting a JSON object as an answer in Kotlin must I use another method or making another parse ?. As I said, actually the PHP code is working and is inserting new records, but how can I receive a JSON object as answer from PHP to Kotlin without getting this error?


text:
Q: WCF Desrialization of date with offset I am facing an issue where wcf response contains datetime stamp as
1978-05-20T11:12:00+2:00
I want to retrieve the response as the same like 1978-05-20T11:12:00.
Please note, this offset (+02:00 in the above example) value might change for different response.  So value might be
1978-05-20T11:12:00+2:00
1978-05-20T11:12:00+5:00
1978-05-20T11:12:00+6:00

A: Here is what I did to fix this...
update the wsdl file from
<xs:element name="start" type="xs:date"/>

to
<xs:element name="start" type="xs:string"/>

and generated the proxy.. now  the returned value with using this proxy was like 1978-05-20T11:12:00+2:00 in start field. they I used string function to extract  just the desired part.
Alternatively, proxy file can be updated from
[XmlAttribute( type = "Date", ElementName = "start" )]
    public DateTime start {
..

    }

to
[XmlAttribute( type = "string", ElementName = "start" )]
    public string start {
...

    }


text:
Q: How to safely pass a context object in an UIAlertView delegate? In my application I use a UIAlertView to display to the user a message and some options. Depending on the button pressed, I want the application to perform something on an object.
The sample code I use is...
-(void) showAlert: (id) ctx {
    UIAlertView *baseAlert = [[UIAlertView alloc]
                          initWithTitle: title
                          message: msg
                          delegate:self
                          cancelButtonTitle: cancelButtonTitle
                          otherButtonTitles: buttonTitle1, buttonTitle2, nil];
    //baseAlert.context = ctx;
    [baseAlert show];
    [baseAlert release];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        id context = ...;//alertView.context;
        [self performSelectorOnMainThread:@selector(xxx:) withObject: context waitUntilDone: NO];
    }
}

Is there any way to pass an object into the delegate as a context object? or maybe some other way?
I could add the property on the delegate but the same delegate object is being used by many different alert views. For this reason I would prefer a solution where the context object is attached to the UIAlertView instance and carried across to the delegate as part of the UIAlertView object.

A: you can also use the tag property (since it's a UIView subclass). This is just an int, but may be enough for you.

A: Subclassing UIAlertView is not a good idea.
http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIAlertView_Class/UIAlertView/UIAlertView.html

Subclassing Notes
The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.

UIAlertView with a user supplied context and [self autorelease] answers this question in a different way.

A: Instead of debating the meaning of "does not support subclassing", I'll provide a better answer. I created a generic contextInfo category for my job a couple months ago. I just put it on github: JLTContextInfo.
#import "objc/runtime.h"

@interface NSObject (JLTContextInfo)
- (NSMutableDictionary *)JLT_contextInfo;
@end
@implementation NSObject (JLTContextInfo)
- (NSMutableDictionary *)JLT_contextInfo
{
    static char key;
    NSMutableDictionary *contextInfo = objc_getAssociatedObject(self, &key);
    if (!contextInfo) {
        contextInfo = [NSMutableDictionary dictionary];
        objc_setAssociatedObject(self, &key, contextInfo, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return contextInfo;
}
@end

This creates a place to easily store extra data for any object derived from NSObject. Now the answer is nearly identical to the original question.
-(void) showAlert: (id) ctx {
    UIAlertView *baseAlert = [[UIAlertView alloc]
                          initWithTitle: title
                          message: msg
                          delegate:self
                          cancelButtonTitle: cancelButtonTitle
                          otherButtonTitles: buttonTitle1, buttonTitle2, nil];
    [[baseAlert JLT_contextInfo] setObject:ctx forKey:@"ctx"];
    [baseAlert show];
    [baseAlert release];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        id context = [[alertView JLT_contextInfo] objectForKey:@"ctx"];
        [self performSelectorOnMainThread:@selector(xxx:) withObject: context waitUntilDone: NO];
    }
}

A: I still think storing it locally is the best solution.  Create a class local NSMutableDictionary variable to hold a map of context objects, store the context with UIAlertView as the key and the context as the value.
Then when the alert method is called just look into the dictionary to see which context object is related.  If you don't want to use the whole Alert object as a key, you could use just the address of the UIAlertView object:
NSString *alertKey = [NSString stringWithFormat:@"%x", baseAlert];

The address should be constant on the phone.  Or you could tag each alert as the other poster suggested and use the tag to look up a context in the map.
Don't forget to clear out the context object when you are done!

A: A complete implementation that allows you to pass context:
@interface TDAlertView : UIAlertView
@property (nonatomic, strong) id context;
@end

@implementation TDAlertView
@end

And a usage example, note how we pre-cast the pointer:
@implementation SomeAlertViewDelegate
- (void)alertView:(TDAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
     NSLog(@"%@", [alertView context]);
}
@end

A: I did a mix between Kendall's answer and the uses of blocks in one of my base view controller classes. Now I can use AlertView and ActionSheets with blocks which improves greatly readability. Here is how I did it :
In the .h of my ViewController I declare a block type (optional but recommanded)
typedef void (^AlertViewBlock)(UIAlertView*,NSInteger);

Also I declare a mutable dictionnary that will store the blocks for each alertview :
NSMutableDictionary* m_AlertViewContext;

In the implementation file I add a method to create the AlertView and save the block :
-(void)displayAlertViewWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle withBlock:(AlertViewBlock)execBlock otherButtonTitles:(NSArray *)otherButtonTitles
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles: nil];
        for (NSString* otherButtonTitle in otherButtonTitles) {
            [alert addButtonWithTitle:otherButtonTitle];
        }
        AlertViewBlock blockCopy = Block_copy(execBlock);
        [m_AlertViewContext setObject:blockCopy forKey:[NSString stringWithFormat:@"%p",alert]];
        Block_release(blockCopy);
        [alert show];
        [alert release];
    }

Note that I receive the same attributes as the constructor of the UIAlertView but the delegate (which will be self). Also I receive a AlertViewBlock object that I save in the m_AlertViewContext mutable dictionnary.
Then I show the alert as I would usually do.
In the delegate callbacks, I call the block and give it the parameters :
#pragma mark -
#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString* blockKey = [NSString stringWithFormat:@"%p",alertView];
    AlertViewBlock block  = [m_AlertViewContext objectForKey:blockKey];
    block(alertView,buttonIndex);
    [m_AlertViewContext removeObjectForKey:blockKey];
}

- (void)alertViewCancel:(UIAlertView *)alertView {
    NSString* blockKey = [NSString stringWithFormat:@"%p",alertView];
    [m_AlertViewContext removeObjectForKey:blockKey];
}

Now, whenever I need to use an AlertView I can call it like this :
[self displayAlertViewWithTitle:@"Title"
                                message:@"msg"
                      cancelButtonTitle:@"Cancel"
         withBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
             if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"DO ACTION"]){
                 [self doWhatYouHaveToDo];
             }
         } otherButtonTitles:[NSArray arrayWithObject:@"DO ACTION"]];

I did the same for the ActionSheet and now it's really easy to use those.
Hope it helps.

A: From my other answer, here's a quick and clean solution that takes advantage of associated objects. I mention in my other answer that you could even replace UIAlertView with NSObject and effectively add a context property to any object:
#import <objc/runtime.h>

@interface UIAlertView (Private)
@property (nonatomic, strong) id context;
@end

@implementation UIAlertView (Private)
@dynamic context;
-(void)setContext:(id)context {
    objc_setAssociatedObject(self, @selector(context), context, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(id)context {
    return objc_getAssociatedObject(self, @selector(context));
}
@end

And then you'll be able to do something like:
NSObject *myObject = [NSObject new];

UIAlertView *alertView = ...
alertView.context = myObject;

IMPORTANT:
And don't forget to nil the context in dealloc!!

A: You could subclass UIAlertView and add the property there.


text:
Q: Auto updating when scrolling to bottom in asp.net C# I am currently developing an ASP.net C# project. I want to be able to display a set limit of data from a database, not using the grid view, I want to process the layout myself with code, onto a page. When the user scrolls to the bottom of the window, it loads up some more of the records, like the Twitter feed page does it.
I have no idea what this is called to be able to search for it.

A: You are thinking about lazy loading and or infinite scrolling. There are many way to implement lazy loading. A simple implementation would lazy load images only, which could be done with a jQuery plugin. Beyond that, you can implement lazy loading and infinite scrolling using AJAX calls which load data on demand, similar to how traditional pagination works.
If you search around you should be able to find examples. Implementing the service to provide data to the AJAX calls should be simple with ASP.NET MVC and ASP.NET WebForms as well though I've not actually done it with WebForms.

A: you will need to use some javascript/jQuery to find the scroll position, then load in more data using ajax.
jquery scrollTop can be used to determine the scroll position. Then look into jquery.ajax for loading in content.
the idea of loading more content is very similar to pagination. So the first chunk of data you can treat as page 1, then when you scroll to the bottom of the page load in page 2 and so on.


text:
Q: Storyboard instantiation not returning exception on fail I'm trying to create and return a Storyboard programmatically while preventing a crash checking for an exception per Apple's documentation on UIStoryboard.
This method should return an exception if the storyboard mentioned doesn't exist:
init(name name: String,
   bundle storyboardBundleOrNil: NSBundle?)

As it stands putting the following code:
do {
    let storyboard = try UIStoryboard(name: "tester", bundle: nil)
} catch {
    // Do something
}

in a do-catch clause is being met by the pre-compiler with the following warning that the method:

'catch' block is unreachable because no errors are thrown in 'do'
  block

Might this be a bug?
Edit: 2015/11/19
After sending a radar to Apple about it, they have responded with the fact the issue is known and that my report is a duplicate of an open one.

A: The UIStoryboard initializer is not marked with throws hence you don't need to put it in a do-try-catch block
init(name name: String,
   bundle storyboardBundleOrNil: NSBundle?)

is enough then to change your code to
let storyboard = UIStoryboard(name: "tester", bundle: nil)

Notice that do-try-catch only catches errors and not NSException
You could read more about it here
If you want still to try to catch the NSException in that case you could see this answer: Catching NSException in Swift