text:
Q: LINQ .OrderBy creates nested casing I'm trying to query the table and return the rows in specified custom order based on a status column.
It's a very straight forward SQL query:
SELECT  * From Table1
WHERE Id = 1
ORDER by CASE
      WHEN [Status] = 'Status1' THEN 1
      WHEN [Status] = 'Status2' THEN 2
      WHEN [Status] = 'Status3' THEN 3
      WHEN [Status] = 'Status4' THEN 4
      WHEN [Status] = 'Status5' THEN 5
      WHEN [Status] = 'Status6' THEN 6
      WHEN [Status] = 'Status7' THEN 7
      WHEN [Status] = 'Status8' THEN 8
      WHEN [Status] = 'Status9' THEN 9
      WHEN [Status] = 'Satus10' THEN 10
      WHEN [Status] = 'Status11' THEN 11
      ELSE [Status] END ASC

I'm trying to accomplish the same query using LINQ.
var data = _myContext.Table1.Where(l => l.Id == 1).Select(lp =>
            new DataModel
            {
                Id = lp.Id,
                Status = lp.Status,
                ...
            })
            .OrderBy(l =>
                       l.Status == StatusEnum.Status1.ToString() ? 1 :
                       l.Status == StatusEnum.Status2.ToString() ? 2 :
                       l.Status == StatusEnum.Status3.ToString() ? 3 :
                       l.Status == StatusEnum.Status4.ToString() ? 4 :
                       l.Status == StatusEnum.Status5.ToString() ? 5 :
                       l.Status == StatusEnum.Status6.ToString() ? 6 :
                       l.Status == StatusEnum.Status7.ToString() ? 7 :
                       l.Status == StatusEnum.Status8.ToString() ? 8 :
                       l.Status == StatusEnum.Status9.ToString() ? 9 :
                       l.Status == StatusEnum.Status10.ToString() ? 10 :
                       l.Status == StatusEnum.Sattus11.ToString() ? 11 : 0
            );

But this query fails with:

Case expressions may only be nested to level 10.

Looking at the profiler, I see the EF creates the following query, which in return fails since I have more than 10 values specified:
exec sp_executesql N'SELECT [l].[Id],[l].[Status], ...
FROM [Table1] AS [l]
WHERE [l].[Id] = @__id_0
ORDER BY CASE
    WHEN [l].[Status] = @__ToString_1
    THEN 1 ELSE CASE
        WHEN [l].[Status] = @__ToString_2
        THEN 2 ELSE CASE
            WHEN [l].[Status] = @__ToString_3
            THEN 3 ELSE CASE
                WHEN [l].[Status] = @__ToString_4
                THEN 4 ELSE CASE
                    WHEN [l].[Status] = @__ToString_5
                    THEN 5 ELSE CASE
                        WHEN [l].[Status] = @__ToString_6
                        THEN 6 ELSE CASE
                            WHEN [l].[Status] = @__ToString_7
                            THEN 7 ELSE CASE
                                WHEN [l].[Status] = @__ToString_8
                                THEN 8 ELSE CASE
                                    WHEN [l].[Status] = @__ToString_9
                                    THEN 9 ELSE CASE
                                        WHEN [l].[Status] = @__ToString_10
                                        THEN 10 ELSE CASE
                                            WHEN [l].[Status] = @__ToString_11
                                            THEN 11 ELSE 0
                                        END
                                    END
                                END
                            END
                        END
                    END
                END
            END
        END
    END
END',N'@__id_0 int,@__ToString_1 nvarchar(4000),@__ToString_2 nvarchar(4000),@__ToString_3 nvarchar(4000),@__ToString_4 nvarchar(4000),@__ToString_5 nvarchar(4000),@__ToString_6 nvarchar(4000),@__ToString_7 nvarchar(4000),@__ToString_8 nvarchar(4000),@__ToString_9 nvarchar(4000),@__ToString_10 nvarchar(4000),@__ToString_11 nvarchar(4000)',@__id_0=1,@__ToString_1=N'Status1',@__ToString_2=N'Status2',@__ToString_3=N'Status3',@__ToString_4=N'Status4',@__ToString_5=N'Status5',@__ToString_6=N'Status6',@__ToString_7=N'Status7',@__ToString_8=N'Status8',@__ToString_9=N'Status9',@__ToString_10=N'Status10',@__ToString_11=N'Status11'

Is there a way to write this query, so it doesn't uses ELSE CASE and just matches the above SQL query?
I do have few options to bypass this. Write a stored procedure and get the output I need or store the query in a list without OrderBy and Order the list. But I'm currious to see if there's a way to do this in that query.

A: This is a known current EF Core limitation, tracked by #12729 Flatten CASE expressions to avoid error "Case expressions may only be nested to level 10".
Unfortunately not scheduled to be addressed at all and no workaround provided. Also using value converter doesn't work.
Probably the best you could do is to create, map and use a database scalar function.

A: Upgrade to version 3.1.4 (not available yet, but it will be soon). This issue has been fixed there.

A: This answer is not LINQ per say, but if you create a computed column that correspond to your CASE, you could sort by this column. You can use functions in a computed column and if that function is simple, the column can be stored and indexed.


text:
Q: gfortran run-time error when writing to stdout on Mac Big Sur Recently, I started using the gfortan-10.2-BigSur-Intel compiler and
observed ambiguous behavior when a function defined in a module is to
write a string to standard output.
Concretely, I have a module function "PrintToScreen" that prints a given
character string "str" to standard output, while returning an integer error code.
Then, I ask to write the error code in the calling program, using the
code
INTEGER (KIND = 4) :: ios

...

ios = PrintToScreen(str);
PRINT '(t1, a, i4)', 'ios = ', ios

...

As a result, "str" is displayed on screen by "PrintToScreen", followed by ios, as expected.
However, if I avoid the detour via "ios" by using the simpler code
...

PRINT '(t1, a, i4)', 'ios = ', PrintToScreen(txt)

...

the program stalls as soon as the function "PrintToScreen" is entered,
while also "str" is left unprinted.
Also, if I make "PrintToScreen" write "str" to a text file instead of
standard output, the two pieces of code yield the same result.
Finally, I checked the code on a Linux machine (Debian Buster) and no
problems occurred.
How do I fix this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need help implementing total random characters in C I am creating a program that prints out 1000 random occurrences of the letters "H" and "T" and my code implements rand()%2 but as i can see from running this program (code below) that its not completely random (the letters are random but always the same with every execution). I want to establish a more effective way by implementing RANDMAX to make every case of the program running completely random, how would I be able to do this?
#include <stdio.h>
#include<stdlib.h>

int main()
{
  int i=1,n;
  char ch ;
    for( i = 1; i <= 1000 ; i ++ )
    {
     n = rand()%2;
     if(n==0)
       ch = 'T';
     else
       ch = 'H';
       putchar(ch);
     }
      return 0;
  }

A: Just add
srand(time(NULL));

after
int main()
{

That will initialize the random generate with a new seed every time you run the program. In this way, you'll get a new random sequence every time.


text:
Q: Can I rewrite this macro_rules! macro in a way that works with rustfmt? I would like to use a macro to generate identical impl blocks for multiple concrete types. My code currently looks something like this:
macro_rules! impl_methods {
    ($ty:ty, {  $($method:item);+} ) => {
        impl $ty { $($method)+ }
    };
    ($ty:ty, $($more:ty),+ {$($method:item);+}) => {
        impl_methods!($ty, {$($method);+});
        impl_methods!($($more),+, {$($method);+});
    };
}

struct Hi;
struct Hello;

impl_methods!(Hi, Hello {
    /// `true` if it works, good
    fn works_good(&self) -> bool {
        true
    };

    /// `true` if rustfmt is working
    fn gets_rustfmt(&self) -> bool {
        false
    }
});

assert!(Hi.works_good() && Hello.works_good());
assert!(!(Hi.gets_rustfmt() | Hello.gets_rustfmt()));

This works well enough (the impls get generated) but it has one frustrating problem; the methods that are defined inside the macro don't get formatted by rustfmt.
This is a small problem, but it's annoying enough that I'm curious about a solution. I know that rustfmt will format the contents of a macro if those contents have some form (are an expression?) and so for instance the following macro's contents will get formatted:
macro_rules! fmt_me {
    ($inner:item) => {
        $inner
    };
}

fmt_me!(fn will_get_formatted() -> bool { true });

And so I'm hoping that there is some way that I can write my macro like,
impl_methods!(Hi, Hello {
    fmt_me!(fn my_method(&self) -> bool { true });
    fmt_me!(fn my_other_method(&self) -> bool { false });
});

And have each individual method get covered by rustfmt.
Is this possible? Is there some magic incantation that will give me the lovely formatting I desire?
Answer
Thanks to the answer below (from @seiichi-uchida), I can get this working with the following code:
macro_rules! impl_methods {
    ($ty:ty, {  $($method:item)+} ) => {
        impl $ty { $($method)+ }
    };
    ($ty:ty, $($more:ty),+, {$($method:item)+}) => {
        impl_methods!($ty, {$($method)+});
        impl_methods!($($more),+, {$($method)+});
    };
}

macro_rules! fmt_me {
    ($inner:item) => {
        $inner
    };
}

// called like:

impl_methods!(Hi, Hello, {
    fmt_me!(fn this_is_a_method(&self) -> bool { true });
    fmt_me!(fn this_is_another_method(&self) -> bool { true });
});

A: Adding a comma between the last type and the impl block should do the trick:
impl_methods!(Hi, Hello, {
    fmt_me!(fn my_method(&self) -> bool { true });
    fmt_me!(fn my_other_method(&self) -> bool { false });
});

This will be formatted to:
 impl_methods!(Hi, Hello, {
-    fmt_me!(fn my_method(&self) -> bool { true });
-    fmt_me!(fn my_other_method(&self) -> bool { false });
+    fmt_me!(
+        fn my_method(&self) -> bool {
+            true
+        }
+    );
+    fmt_me!(
+        fn my_other_method(&self) -> bool {
+            false
+        }
+    );
 });

In general, rustfmt can only format macro calls whose arguments can be parsed as valid Rust AST node (with some exceptions).


text:
Q: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated on Azure I have an smtp client on a windows azure application, the client works fine on the simulator but throws an exception on the cloud instance.
The exception message is :
The SMTP server requires a secure connection or the client was not authenticated
The server's response was 5.5.1 authentication required
I made sure that the credentials are correct on the cloud by printing them in command line, i also disabled the firewall.
P.S: i'm using gmail smtp server.
Here is my code:
 private void SetupClient()
    {
        _emailSetting = new EmailSetting();
        _smtpClient = new SmtpClient(_emailSetting.SMTP_Server, _emailSetting.Port);
        _smtpClient.EnableSsl = true;
        _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        _smtpClient.Credentials = new NetworkCredential(_emailSetting.EmailUser, _emailSetting.EmailPass);
    }

    public void Report(String msg)
    {
        MailMessage mailMessage;

        if (_smtpClient == null)
        {
            SetupClient();
        }

        String receivers = String.Join(",", Receivers);
        mailMessage = new MailMessage(_emailSetting.EmailUser, receivers, "Error", msg);
        _smtpClient.Send(mailMessage);

    }

A: I similar problem. The solution was quite "strange", gmail block my emails from azure, because   your app is trying to log in from "strange" location. Try to check if you get notification/email in your gmail with information about block login.

A: One way to fix this is to RDP onto your Azure VM and log into your Gmail account from there.
Google will ask you to confirm your account as it things it's a "strange" location.
Once verified your email will work fine.


text:
Q: Using Which and Switch in a function I'm having hard time trying to make use of Which or Switch. I'm trying
f[n_Integer] := Witch[
    n == 0, "zero"
  , n == 1, "one"
  , EvenQ[n], "even"
  , OddQ[n], "odd"
  , True, n
  ]

and
f[n_Integer] := Switch[n
  , 0, "zero"
  , 1, "one"
  , _Even, "even"
  , _Odd, "odd"
  , _, n
  ]

Neither of them works. What am I missing?

A: There was a simple typo, Witch instead of Which.  The second issue is with a malformed pattern, _Even, which will only match something with the head Even like Even[x].  You need to use something like _?EvenQ where EvenQ is a single-argument function that returns True or False.
See PatternTest and this pattern tutorial for more information.
fswitch[n_Integer] :=
  Switch[n,
    0, "zero",
    1, "one",
    _?EvenQ, "even",
    _?OddQ, "odd",
    _, n
  ];

fwhich[n_Integer] :=
  Which[
    Equal[n, 0], "zero",
    Equal[n, 1], "one",
    EvenQ[n], "even",
    OddQ[n], "odd",
    True, n
  ];

fwhich /@ Range[6]
(* {"one", "even", "odd", "even", "odd", "even"} *)

fswitch /@ Range[6]
(* {"one", "even", "odd", "even", "odd", "even"} *)


text:
Q: Problem with creating a function that checks for two variables and updates another variable My variables in the mysql table are "usersEmail" "usersRefer and "usersPoint". I want to check the whole table if usersEmail = usersRefer on different rows then UPDATE the integer usersPoint on the row of both usersEmail and usersRefer. I want to check for one specific user, that is the value of the usersRefer checks the entire column of usersEmail to check if it matches.
Here's something that I tried out:
$sql = "SELECT * FROM walitlist";
    if($result = $conn->query($sql)){
        while ($row = $result->fetch_assoc()){
            $pointSys = $row ["usersPoint"];
            if ($row ["usersEmail"] = $row ["usersRefer"]){
                $pointSys = "UPDATE waitlist SET usersPoint = usersPoint+100";
            }

        }
    }

How can I make this work?


text:
Q: R package RD2PDF error I am having a problem utilizing the answer presented in this question about diagnosing "LaTeX errors when creating PDF version". The solution presented there is to do the following:

Try R CMD Rd2pdf mypackage to create the manual, and possibly also set the --no-clean option to keep the temporary files. This should allow you to debug the LaTeX code triggering the error.

Where should I type in that: cmd or R? There is no Rd2pdf in my latex.

A: The command R CMD Rd2pdf mypackage should be executed on the shell command line (Command Prompt if windows, terminal if Mac OS, shell if Linux/Unix) when you are in the directory where the root of your package is.
This command starts R and runs a specific set of commands that have been written to do this.


text:
Q: Using MongoDB $arrayToObject and $map operators in java spring boot I have a query in mongodb with aggregation framework, which returns number of topics in my documents. This is done by utilizing the $group operator and the result looks like:
{
postsByTopics: [
        {
            "_id" : "Topic 1",
            "count" : 3.0
        },
        {
            "_id" : "Topic 2",
            "count" : 1.0
        }
    ]
}

I use projection to get a better shaped results
{
"$project": {
        "postsByTopics": {
            "$arrayToObject": {
                "$map": {
                    "input": "$postsByTopics",
                    "as": "el",
                    "in": {
                        "k": "$$el._id",
                        "v": "$$el.count",
                    }
                }
            }
        },

}

which returns much nicer shaped result:
{
postsByTopics: {
    "Topic1" : 3.0,
    "Topic2" : 1.0
    }
}

Now I would like to turn this projection in a java spring boot code. I found
 project().and(ArrayOperators.ArrayToObject.arrayToObject("postsByTopics"))
and
project().and(VariableOperators.Map.itemsOf("postsByTopics").as("el")
but I am struggling to combine them to achieve the desired result

A: Spring-data syntax for "complex" query is not friendly.
Workaround 1: Implement AggregationExpression for .andApply method.
ProjectionOperation project = Aggregation.project().and(
    ArrayOperators.ArrayToObject.arrayValueOfToObject(
      Map
       .itemsOf("postsByTopics")
       .as("el")
       .andApply(agg -> new Document("k", "$$el._id").append("v", "$$el.count"))
    )
).as("postsByTopics");

Workaround 2: Implement AggregationOperation with MongoDB JSON syntax
Aggregation agg = Aggregation.newAggregation(
    exp -> new Document("$project",
               new Document("postsByTopics",
                   new Document("$arrayToObject",
                       new Document("$map",
                           new Document("input", "$postsByTopics")
                               .append("as", "el")
                               .append("in",
                                   new Document("k", "$$el._id")
                                        .append("v", "$$el.count")
                           )
                       )
                   )
               )
           )
);

A: Code above is NoSQL Query and down is almost similiar with MongoTemplate Cirteria Query. Maybe same propertieies are different, hope it will help someone ! Important is to save List as projection new property, i didnt find solution with arrayOf(List ... always inserted List in list with input: { elemetnAt: [[ .... whci hwas really wrong.
   $project {
     stats: {
         $map: {
             input: [ "2018-09-01", "2022-01-24", "2022-01-22", "2018-09-04", "2018-09-05" ],
             as: "date",
             in: {
             $let: {
                 vars: { dateIndex: { "$indexOfArray": [ "$days.day", "$$date" ] } },
                 in: {
                     $cond: {
                         if: { $ne: [ "$$dateIndex", -1 ] },
                         then: { $arrayElemAt: [ "$days", "$$dateIndex" ] },
                         else: { _id: "$$date", date: "$$date", distance: 0 }
                     }
                 }
                }
             }
         }
     }

project("_id", "days", "category").andArrayOf(timearray).as("daysEmpty"),
                project("category").and(
                        mapItemsOf("daysEmpty")
                                .as("date")
                                .andApply(new AggregationExpression() {
                                    @Override
                                    public Document toDocument(AggregationOperationContext context) {
                                       return new Document("$let",
                                                new Document("vars",
                                                        new Document("dateIndex",
                                                                new Document("$indexOfArray", asList("$days.day", "$$date"))))
                                                        .append("in",
                                                                new Document("$cond",
                                                                        new Document("if",
                                                                                new Document("$ne", asList("$$dateIndex", -1L)))
                                                                                .append("then",
                                                                                new Document("$arrayElemAt", asList("$days", "$$dateIndex")))
                                                                                .append("else",
                                                                                new Document("_id", "$$date")
                                                                                .append("date", "$$date")
                                                                                .append("distance", 0L)
                                                                                )
                                                                )
                                                        )
                                        );
                                    }
                                })).as("data")


text:
Q: Can't return from activity started from CordovaPlugin My app starts an activity from a plugin. The activity has to start, there's no other way around it. It then gathers some data and sends it back to the plugin.
Everything works perfect, I start the activitywith
this.cordova.startActivityForResults((CordovaPlugin)this,i,0);

and finish it with finish(); after returning some data via intent...
Everything works, the activity sends the data, the plugin receives the data, but then the whole app just closes... I cant return from the called activity back to the main one. The same thing happens when I press "back" in the called activity.
Any ideas?


text:
Q: Solve $y'=y$, $y(0)=1$ using method of successive approximations, obtaining the power series expansions of the solution Solve $y'=y$, $y(0)=1$ using method of successive approximations, obtaining the power series expansions of the solution.

Solving the above initial value problem is equivalent to solving (for $\psi$) the integral equation:
$$\psi(x)=\int_0^x \psi(t)dt + 1 \mbox{.}$$
Consider a continuous map $F: C(\mathbb{R})\rightarrow C(\mathbb{R})$ defined by
$$(F(\psi))(x)=\int_0^x \psi(t)dt +1 \mbox{.}$$
I have already proved that such $F$ is a contraction (it's easy in this case). Thus there exist a unique fixed point $\phi$.
Start the iterative procedure with $\psi_0=0$.
$$(F(\psi_0))(x)=1$$
$$\psi_1=1$$
$$(F(\psi_1))(x)=x+1$$
$$\psi_2=x+1$$
$$(F(\psi_2))(x)=\frac{x^2}{2}+x+1$$
$$\psi_3=\frac{x^2}{2}+x+1$$
$$(F(\psi_3))(x)=\frac{x^3}{6}+\frac{x^2}{2}+x+1$$
$$\ldots$$
As we suspected, it looks similiar to the expansion of $y(x)=e^x$ in Taylor series. Using induction we can prove that it is indeed the solution.
Honestly speaking, I have found this method of finding solutions to ODEs in some old book. I have never done this before (using the contraction theorem). I would be happy is someone verified this.

A: Your work is correct (assuming that your proof of contractiveness is correct). This is part of a general theory which includes the Picard-Lindelöf theorem, and using fixed-point theorems is a very standard way of proving existence results.


text:
Q: Python 3.10 read from playlist file, wrong first character of first line File: main_nested.aimppl
#Name:Διάφορα εκκλησιαστικά
#Cursor:-1
#Flags:2047
#Group:/home/chris/Documents/papinhio-player/src/python+/menu-1/playlists/test-playlists/mp3/|1
#Track:1|/home/chris/Documents/papinhio-player/src/python+/menu-1/playlists/test-playlists/mp3/ΥΜΝΟΙ/ΑΓΙΟΙ ΑΓΓΕΛΟΙ.mp3||||ΑΓΙΟΙ ΑΓΓΕΛΟΙ|0|0|||0|0|0|
#Track:1|/home/chris/Documents/papinhio-player/src/python+/menu-1/playlists/test-playlists/mp3/ΥΜΝΟΙ/Αγνή Παρθένε Δέσποινα.mp3||||Αγνή Παρθένε Δέσποινα|0|0|||0|0|0|
#Track:1|/home/chris/Documents/papinhio-player/src/python+/menu-1/playlists/test-playlists/.aimppl/nested/ΑΝΑΣΤΑΣΙΜΑ.aimppl||||ΑΝΑΣΤΑΣΙΜΑ|0|0|||0|0|0|
#Track:1|/home/chris/Documents/papinhio-player/src/python+/menu-1/playlists/test-playlists/.aimppl/nested/ΥΜΝΟΙ.aimppl||||ΥΜΝΟΙ|0|0|||0|0|0|

File: read_playlist_file.py
import os
import sys

with open("main_nested.aimppl") as f:
    lines = f.readlines()
    for line in lines:
        print(line[0])

Output:
chris@chris-Inspiron-3847:~/Desktop$ python3 read_playlist_file.py

#
#
#
#
#
#
#

Expected output:
chris@chris-Inspiron-3847:~/Desktop$ python3 read_playlist_file.py
#
#
#
#
#
#
#
#

As you can see in the first line there is no # print.
This file was created from python3.10.
Maybe you can't reproduce this problem.
Maybe it's a utf-bom character issue.
This code works:
import io

f = io.open('main_nested.aimppl', 'rt', encoding='utf_8_sig')
lines = f.readlines()
for line in lines:
    print(line[0])

What's the problem with the first code, and what it's the appropriate solution?

A: "Maybe it's a utf-bom character issue." Yes, that's it. You can check your file with e.g. hexdump -c on the command line. The first 3 bytes should be 0xEF, 0xBB, 0xBF if it's a utf8-with-BOM file.
"what it's the appropriate solution?" What you did is exactly right. encoding='utf_8_sig' is for utf8-with-BOM files.


text:
Q: Can not run EXCEL.EXE with "runas", it says: "1312: A specified logon session does not exist. It may already have been terminated." I need to run EXCEL.EXE with a user different than current one; previously I have been doing this without any issues using "runas", but after updating the system to Windows 10 Pro version 2004 (19041.508) this method is not working anymore.
This is what I am doing:
C:\Users\forla>runas /profile /user:probanduela "C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE"
Escriba la contraseña para probanduela:
Intentando iniciar C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE como usuario "DESKTOP-PGDBNMB\probanduela" ...
ERROR RUNAS: no se puede ejecutar - C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE
1312: Una sesión de inicio especificada no existe. Es posible que haya finalizado.

I am getting all times the error (english version):
1312: A specified logon session does not exist. It may already have been terminated.
Similar issue happens if I try to run it through PowerShell or through win32 API, or through c# API.
This method was working before upgrading to Windows 10 2004 version, I've reproduced this on different computers.
What's the issue? How can I achieve what I want to do ?
-Edit-
Just discovered that using Excel v2002 build 12527.21104 it works; but with Excel v2008 build 13127.20408 it fails.
So apparently is a combination of Windows 10 v2004 + Office 2019 v2008 what causes the issue.
-Edit2-
If I make a copy of EXCEL.EXE and give it another name, like "EXCEL_COPY.EXE" it works. But still not work with WINWORD.EXE.

A: I reported that issue to Microsoft and, after raising up few levels, they have worked on it and fixed. It's fixed on Windows 10 Build 19042.844


text:
Q: Axis Orientation in 3D plot I am having trouble creating a 3D plot, with the x-axis horizontal, the z-axis vertical, and the y-axis angled into the page.  For example:

I tried to use the view function and camera orientations, but I don't think that's helping. Any help would be welcomed.


text:
Q: Compile Jython3 sources on Windows CONTEXT :

*

*I need to call a "file.py", where is implement my class "myClass", by the Python language OR the JAVA language through Jython.

I do in my "file.py" :
try :
    # Jython source file
    from com.local.mylocal.jython import ImyClass
except :
    ImyClass = None

from threading          import Thread

class myClassMetaClass(type) :
    def __new__() :
        if IClient is None :
            bases = (Thread,)
        else :
            bases = (Thread, ImyClass,)
    return type.__new__(metacls, nom, bases, dict)

class myClass(metaclass=myClassMetaClass) :
    pass

*When I run my PYTHON code, my class : myClass is instance with all metaclass she need. My code run.

*When I run my JAVA code who call my PY class through Jython, my code error is :

Exception in thread "main" SyntaxError: ("mismatched input '='
  expecting RPAREN", ('../file.py', 52, 22, 'class
  myClass(metaclass=myClassMetaClass) :\n')) Blockquote

INVESTIGATION :

*

*I see in "https://github.com/jython/jython3" isaiah solved my probleme.

PROBLEME :

*

*I can't compile the source code on my Windows environement (need : POSIX ...).

*I need the "jython3.jar" file.
REQUEST :

*

*How compile jython3 souces on my Windows environement ?

*Is it possible to acces to a "jython3.jar" file ?


text:
Q: reading details from bar code i am trying to read all information hidden in a bar code , i have implemented the zxing lib in android app , but it is giving me code_128 and all unclear details , i want the exact details , for example if i am scanning a bar code of a book it should give me details of the name of the book and all ..please help where i am going wrong . Is the zxing the right library , i want to develop this app where on scanning all details of the book got  displayed.
Below is the code that i am using to read the details
 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
 //retrieve scan result

    IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    if (scanningResult != null) {

        String scanContent = scanningResult.getContents();
        scanningResult.toString();
        String scanFormat = scanningResult.getFormatName();
        formatTxt.setText("FORMAT: " +  scanningResult.toString());
        contentTxt.setText("CONTENT: " + scanContent);
  //we have a result
    }else{
        Toast toast = Toast.makeText(getApplicationContext(),
                "No scan data received!", Toast.LENGTH_SHORT);
        toast.show();
    }
}

A: https://en.wikipedia.org/wiki/Code_128
https://en.wikipedia.org/wiki/International_Standard_Book_Number
Barcode is actually a very small String with a special look as strips. I am not sure what/which barcode you are scanning on the book. I will use ISBN as an example, ISBN is a 13 digit code, e.g. 978-3-16-148410-0, you can get no information simply by looking at this.

An ISBN is assigned to each edition and variation (except reprintings)
  of a book. For example, an e-book, a paperback and a hardcover edition
  of the same book would each have a different ISBN.

However, they are actually unique. Only if you have a library to map the code to the corresponding book, you can get the information you need.
I.e. Without a library, the code gives almost no information.


text:
Q: jQuery - Improving selector performance when processing XML I am processing an XML file that has very slow performance when selecting Nodes with XPath style selectors.
Here is part of the code that runs particularily slow
for (i=0;i<lanes.length;i++)
    htmlContents += GetLaneInfo($(this).find("Lane[num='"+lanes[i]+"']").attr('avg'));

I believe the slowest part of this code is the Lane[num=X] selector, how can I improve the performance of this? Can I cache $(this).find("Lanes") and then search through them later on?
XML Sample:
<Data time="10:50">
    <Lane num="102" avg="2.0"/>
    <Lane num="103" avg="2.0"/>
    <Lane num="104" avg="2.0"/>
    <Lane num="112" avg="2.0"/>
    <Lane num="113" avg="2.0"/>
    <Lane num="114" avg="2.0"/>
    <Lane num="115" avg="2.0"/>
    <Lane num="122" avg="0.9"/>
    <Lane num="123" avg="1.0"/>
    <Lane num="124" avg="1.0"/>
    <Lane num="132" avg="0.7"/>
    <Lane num="134" avg="0.7"/>
    <Lane num="142" avg="0.8"/>
    <Lane num="153" avg="0.4"/>
    <Lane num="154" avg="0.6"/>
</Data>

A: try this :
http://jsperf.com/1f
Ive managed to increase the speed.

p.s. it is based on the fact that all lanes are in the same order in each xml node.

A: Using XML parsing for such simple markup is a waste. If you want speed using indexOf and substring is the superior method.
http://jsperf.com/1f/2
I edited @Royi Namir 's jsperf and added my own version (aptly named "screw xml"). It runs 2x faster than his optimized XML parsing version.
Here's the code that would aline with the OP's example from the question. The "xml" variable is just a string that represents the XML.
var find = '';
var start = -1;
var end = -1;
var skip1 = 0;
var skip2 = ' avg="'.length;
//
for (i=0;i<lanes.length;i++) {
  find = 'num="' + lanes[i] + '"';
  skip1 = find.length;
  end = -1;
  start = xml.indexOf(find, 0);
  while (start != -1) {
    start = start + skip1 + skip2;
    end = xml.indexOf("\"/>", start);
    htmlContents += GetLaneInfo(xml.substring(start, end));
    start = xml.indexOf(find, end);
  }
}

In reality you probably don't want to use a version like the above because it hinges on the XML being formatted uniformly (see: "skip2" variable/constant). But if you really want performance/speed doing it this way is the fastest by far.

A: I know this is late, but here's a viable high performance solution:
http://jsperf.com/1f/3

A: Well, in your example xml data we could see that num attribute is sorted, if so try implement http://en.wikipedia.org/wiki/Bisection_method for that data :)


text:
Q: Bootstrap: when checkbox inside label.btn, change event is not working. I have Bootstrap v3.3 and I have the following checkboxes styled as buttons:

                <input type="checkbox" autocomplete="off" checked="checked">Draft

                <input type="checkbox" autocomplete="off" checked="checked">Finalised

                <input type="checkbox" autocomplete="off">Voided

Using jQuery, I seem to have problem getting the checkbox events.
I have tried:
$('.transactionSheetToolbarShowDraft input[type="checkbox"]').change(function() {...});

but it doesn't seem that the event had been triggered.
I have also tried:
$('.transactionSheetToolbarShowDraft input[type="checkbox"]').click(function() {...});

but, again, it doesn't seem that the event had been triggered.
Then I have this:
$('.transactionSheetToolbarShowDraft').click(function() {...});

the event was triggered, but there seems to be something wrong...
The problem appears when I tried to get the :checked status of the checkbox.
$('.transactionSheetToolbarShowDraft').click(function() {
    var checkbox = $(this).find('input[type="checkbox"]');
    if (checkbox.is(':checked')) {
        console.log('is checked!');
    } else {
        console.log('not checked...');
    }
});

The :checked status seems to be opposite! I did some debugging and traced the problem. The reason behind this is that, the label was clicked and its click event was triggered, the checkbox has not been updated yet. Basically the change event handler was called before the checkbox updated its checked status.
Being desperate, I came up with the following hack:
$('.transactionSheetToolbarShowDraft').click(function() {
    var checkbox = $(this).find('input[type="checkbox"]');
    setTimeout(function() {
        if (checkbox.is(':checked')) {
            console.log('is checked!');
        } else {
            console.log('not checked...');
        }
    }, 10);
});

This seems to work... except that with a setTimeout calll to handle the event, it is definitely not a good practice.
So I just want to see if anyone has a better solution to this? Or am I doing something wrong?

A: This will trigger checked/Unchecked event.

$('.transactionSheetToolbarShowDraft').on('click','input',function() {
  var checkStatus = ($('input').prop('checked'))? 'is checked!': 'not checked...';
  console.log(checkStatus);

});

                <input type="checkbox" autocomplete="off" checked="checked">Draft

                <input type="checkbox" autocomplete="off" checked="checked">Finalised

                <input type="checkbox" autocomplete="off">Voided


text:
Q: Oauth work in localhost but doesn't work in production I have some questions, I run my web in localhost not have a problem at all but when I decide to deploy web in my VPS server Oauth doesn't work when I try to login web response with this

** I watch these clips for Oauth reference: https://www.youtube.com/watch?v=idqhYcXxbPs&t=126s


text:
Q: Route pattern in middleware Slim v3 How can I get route pattern inside middleware:
routes.php:
$app->get('/myroute/{id}', function($req, $res, $args) {
//DO STUFF HERE
})->add(new MyMiddle());

middle.php:
class MyMiddle {
    public function __invoke($req, $res, $next) {
         //DO STUFF
    }
}

In routes.php I can get {id} with $args['id'], but how can I get it inside MyMiddle.php?
Thank you,
Cristian Molina

A: *

*Enable the determineRouteBeforeAppMiddleware setting:
$config = ['settings' => [
    'determineRouteBeforeAppMiddleware' => true,
    'displayErrorDetails' => true,
]];
$app = new \Slim\App($config);

*You can now access the Route object from the Request, using getAttribute() and, from the route, get at the arguments:
$app->add(function ($request, $response, $next) {
    $id = $request->getAttribute('route')->getArgument('id');
    return $next($request, $response);
});

A: I decided to included a Slim v2 example as that is what I was looking for when I came across this post.  You can use $this->app->router()->getCurrentRoute()->getPattern() from the slim.before.dispatch callback hook to accomplish the same thing.


text:
Q: Powershell: Exception calling "AttachDatabase" with "3" argument(s) I 'm trying to backup the mdf file using the following approach but the script fails when attaching the database back to the server. I have started facing this issue in our new server (Windows Server 2008 R2). The following is the scriplet.
#load assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null

write-host "Initializing..."
#Initialization section
$serverName = "sqlserver\SQL2005"
$databaseName = "myDatabase"
$sourceLocation = "\\sqlserver\dbPath\myDatabase"
$attachDBSourceLocation = "D:\Sql 2005 Databases\dbPath\myDatabase"
$mdfFileName = $sourceLocation + "\" + $databaseName + ".mdf"
$attachMDFFileName = $attachDBSourceLocation + "\" + $databaseName + ".mdf"
$ldfFileName = $sourceLocation + "\" + $databaseName + "_log.ldf"
$destLocation = read-host -prompt "Enter the destination location"
#End of Initialization section
write-host "Initialization completed"

#create a new server object
$serverConn = New-Object ("Microsoft.SqlServer.Management.Common.ServerConnection")
$serverName, "psuser", "psuser"
$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $serverConn
write-host "Server object created"

$server.Databases["myDatabase"].ExecuteNonQuery("ALTER DATABASE myDatabase SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE", [Microsoft.SqlServer.Management.Common.ExecutionTypes]::Default)

#detach the database to be copied. Drop connections if any by changing the connection mode to single user mode
$server.DetachDatabase($databaseName, $true)
write-host "Database $databaseName detached"

#copy the database (backup)
write-host "Started copying database '$mdfFileName' to '$destLocation'. Please wait..."
copy-item $mdfFileName -Destination $destLocation
write-host "Database '$databaseName' copied to '$destLocation'"

#delete the log file
remove-item -path $ldfFileName
write-host "Database LDF file deleted" #attach the mdf file without ldf so that a new ldf is automatically created
write-host "Attaching Database '$databaseName'. Please wait..."
$strColl = New-Object ("System.Collections.Specialized.StringCollection")
[void]$strColl.Add($attachMDFFileName)
$server.AttachDatabase($databaseName, $strColl, [Microsoft.SqlServer.Management.Smo.AttachOptions]::NewBroker)
write-host "Database attached successfully"

write-host "Shrinking Database '$databaseName'. Please wait..."
$server.Databases[$databaseName].ExecuteNonQuery("DBCC SHRINKDATABASE ($databaseName, 5)")

write-host "Database shrinked successfully"
write-host "Database backup successful"

A: Are you sure you need that attachmentoptions overload? From the overload list for that method:
http://msdn.microsoft.com/en-US/library/microsoft.sqlserver.management.smo.server.attachdatabase(v=SQL.90).aspx
it doesn't appear that you need to specify that if you're re-attaching an existing database, just the database name and the file collection.


text:
Q: How to handle multiple submit request at a time in laravel I have a Laravel website which is hosted in EC2 instance already, but the problem is, I have page for uploading the data by taking Excel files as input. If 2 users logged in to the website and they are trying to load the data from their end, if 2 user gave submit at a time we are getting some random errors in database. I have used SQL Server as my database.
Can somebody tell me how I can resolve this issue?


text:
Q: Compiling a stored procedure with local functions on Oracle 9i I have a legacy application that is still running on Oracle 9i. We'll me migrating to 11g later this year, but for the moment, I need to run some test scripts on the current environment.
My test uses a stored procedure, but when I try to compile the procedure I get the following error.

"PLS-00103: Encountered the symbol "end-of-file" when expecting one of
  the following:"

This is strange as the stored procedure compiled on the same server about two years ago. The only difference is that the database has been overwritten with a copy of the production database since (this procedure is only used in test, so is not present in the production database).
The problem seems to stem from local functions within the procedure. Here's a very simple procedure that illustrates the error I'm getting:
create or replace procedure test
as
  l_dt date;

  function dt
  return date
  is
  begin
    return sysdate;
  end;

begin
  l_dt := dt;
  dbms_output.put_line(to_char(l_dt, 'dd-mm-yyyy'));
end;

Edit: Here's the complete output when I try to compile this:
1   ORA-24344: success with compilation error
10  PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
10
10     begin function package pragma procedure form
13  ORA-06550: line 2, column 3:
13  PLS-00201: identifier 'L_DT' must be declared
13  ORA-06550: line 2, column 3:
13  PL/SQL: Statement ignored
14  ORA-06550: line 3, column 32:
14  PLS-00201: identifier 'L_DT' must be declared
14  ORA-06550: line 3, column 3:
14  PL/SQL: Statement ignored
14  SQL parse error location

It definitely seems to be the local function that's causing it, as if I take it out, it compiles just fine. Here's the above procedure with the local function removed, and that working:
create or replace procedure test
as
  l_dt date;
begin
  l_dt := sysdate;
  dbms_output.put_line(to_char(l_dt, 'dd-mm-yyyy'));
end;

I wonder if anyone else has encountered this problem, or knows if there's any reason local functions wouldn't compile under Oracle 9i?
Thanks,
James

A: The error is being reported against line 10, after the end of the function, so the enclosing procedure isn't being parsed properly. What you're doing is fine though, and works through other clients, and with the version of SqlDbx I tried. It looks like the procedure is being treated as two statements, and sent to the database in two chunks, neither of which is valid on its own.
This problem is reported on the SqlDbx Oracle forum, which mentions the bug exists in versions 3.64 and 4.0. It doesn't appear to be specific to the Oracle version. On 2014-04-14 the response was:

This is a bug and it will be fixed in a follow up to the latest release in about two weeks.

The release notes for version 4.1 include:

Fixes:
  1. Corrupted text returned in Unicode version
  2. Error parsing nested function (Oracle)
  ...

So you need to upgrade to version 4.1 or later; the current version is 4.3, and I don't see this problem with that version against a 9i or 11g database.


text:
Q: Alert customization I'm reading "How to create a custom e-mail alert handler in Microsoft Office SharePoint Server" right now and as follow the how-to-guide, I found out that  every time you need to modify alerts you have to go through the whole process again (from registering the dll to the GAC to restarting the Windows SharePoint Services Timer service). I was wondering if you can create a feature to do all this. When the feature is activated the custom alert template file will be used. If the feature is deactivated, it will revert to the original file. Is this possible? Can somebody show me how to do this?

A: I have achieved this with my custom alerts using nothing but a feature and a feature reciever.
NB: Upgrading your solution package using STSADM (or deploying directly from Visual Studio 2010) will automatically upgrade all your assemblies and provisioned files and recycle your app pool, so all you need to do is connect your custom alert tempates. Here's how:
Step 1: Inside your Visual Studio solution, right click your project and select "Add -> SharePoint Mapped Folder" then select the "TEMPLATE\XML" folder. Place your custom alert template files in here (they should be XML files).
That takes care of deploying your files to the SharePoint root, now you need to instruct SharePoint to parse these files when your feature activates....
Step 2: Inside your feature receiver, just add the following code:
SPAlertTemplateCollection alertTemplates = new SPAlertTemplateCollection((SPWebService)(siteCollection.WebApplication.Parent));

alertTemplates.InitAlertTemplatesFromFile(SPUtility.GetGenericSetupPath("TEMPLATE\\XML\\") + "CustomAlertTemplate.xml");
alertTemplates.InitAlertTemplatesFromFile(SPUtility.GetGenericSetupPath("TEMPLATE\\XML\\") + "CustomAlertTemplate_SMS.xml");

That's it!
These custom alert templates will now be available to use anywhere within your application using the following code:
// Retrieve your custom alert template.
SPAlertTemplateCollection alertTemplates = new SPAlertTemplateCollection((SPWebService)(listItem.ParentList.ParentWeb.Site.WebApplication.Parent));
SPAlertTemplate customAlertTemplate = alertTemplates["CustomAlertTemplateName"];

if (customAlertTemplate == null)
    throw new ApplicationException("The alert template \"CustomAlertTemplateName\" has not been registered.");

// Create the alert without sending a confirmation email.
SPAlert newAlert = listItem.ParentList.ParentWeb.CurrentUser.Alerts.Add();
newAlert.Title = "Title";
newAlert.AlertTemplate = customAlertTemplate;
newAlert.Update(false);


text:
Q: What exactly is computer resolution? Maybe It's a bit trivial question, but I am confused over the computer resolution. What is it?
If the resolution is say 150 X 100 then does it mean that 150 pixels will cover up the entire length of my system, (horizontally). And does it mean that the size of a pixel is not fixed? Since 300 X 200 will mean 300 pixels covering the same length.
Also, say I take up a pixel and draw a circle around it. Now is it possible that the circle passes through the centre of all the pixels it covers, or there will/can be some pixels for which the boundary does not pass through the centre. [Passing from the centre as in, if I take the extreme point on the diameter,for that the boundary passes through the centre. So like that].
That is, Can I say that taking up a pixel, if it is inside the circle or outside? [Again, the extreme point on the diameter is inside].
EDIT Also, In a normal X-Y axis; the points on the boundary are in decimals too, but if I consider the indices of pixels, in a window, then it will increase as a unit value only. So how do we decide, what all pixels get coloured when drawing a circle?

A: When you read 1024x768 1024 is the horizontal resolution and 768 is the vertical resolution in pixels.
A Pixel can be a square or an rectangle, its not specified.
To determine if a pixel is inside a Circle, you (simplified) calculate the distance of the center of that pixel to the center of the circle and check if it is below or equal the radius, if it is, it is inside.


text:
Q: Java/Android Biased Number Generator I have been set a task to create a Android app in which the user chooses four numbers (1-6), I then compare it against four randomly generated numbers and then tell them how many of there numbers were correct.
My problem is that whenever I generate any numbers the first three shown are always the same, except from the last number.
    Random a1 = new Random();
    random1 = new ArrayList<Integer>();

    for (int index = 0; index < 6; index++)
    {
        random1.add(a1.nextInt(5)+ 1);
    }

    Random a2 = new Random();
    random2 = new ArrayList<Integer>();

    for (int index = 0; index < 6; index++)
    {
        random2.add(a2.nextInt(5)+ 1);
    }

This is the code I use for the random number generation, each number uses the exact same code, which makes it even more confusing, if they were all the same I could understand that because it's the same code it generates the same number or something along those lines but the last one is always different, any help would always be appreciated.

A: Try not create two Random instances but reuse single instance instead. May be two Randoms with close seeds produces close output.

A: Check if below code works for you. Code taken from http://www.javapractices.com/topic/TopicAction.do?Id=62. Modified according to your requirements.
public final class RandomRange {

public static final void main(String... aArgs) {

    int START = 1;
    int END = 6;
    Random random = new Random();
    List<Integer> first = new ArrayList<Integer>();
    List<Integer> second = new ArrayList<Integer>();
    for (int idx = 1; idx <= END; ++idx) {
        first.add(showRandomInteger(START, END, random));
        second.add(showRandomInteger(START, END, random));
    }
    System.out.println(first);
    System.out.println(second);
    first.retainAll(second);//Find common
    System.out.println(first);

}

private static int showRandomInteger(int aStart, int aEnd, Random aRandom) {
    if (aStart > aEnd) {
        throw new IllegalArgumentException("Start cannot exceed End.");
    }
    // get the range, casting to long to avoid overflow problems
    long range = (long) aEnd - (long) aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long) (range * aRandom.nextDouble());
    int randomNumber = (int) (fraction + aStart);
    return randomNumber;
}

}


text:
Q: Why do Twitter notifications in Notification Center open in Safari? Is it possible to load Twitter.app instead of opening Safari when clicking Twitter notifications in the Notification Center?
The current behaviour really annoys me because it keeps making me sign in and I don't want it to remember my credentials.

A: Indeed, the Twitter notifications will always redirect you to the web application, even if you have a native Twitter client installed. In fact, Twitter notifications also work without Twitter.app as long as you have your Twitter account configured.
There currently is no way to change this behaviour.

A: If you use Choosy, you can redirect twitter.com links from anywhere to the official Twitter app (which Choosy recognizes as a browser). It won't open the specific tweet you've clicked on, but it will at least open the client.


text:
Q: Gap between objects (images) in unity I am working on a clicker game, which implies the interaction of 2 players. One of the objects (images made with ui) becomes larger if one of the players taps more. But I ran into a problem, for some reason unity creates a gap between objects. Also, if the red object becomes larger than blue - the problem disappears. I have attached the code and video with the problem.
The problem isn't in random values.
Also i tried to fix it with Transform.SetSiblingIndex, and it didn't work either.
There's a link to screenshot with the problem
there's a link to video with the problem
The code from GameCore:
public void OnPointerClick(PointerEventData eventData)
{
    ScaleEvents();
    Vector3 clickPosition = Camera.main.ScreenToWorldPoint(eventData.position);
    if (eventData.rawPointerPress == Player1)
    {
        Player1.transform.localScale += scaleChange;
        Player2.transform.localScale -= scaleChange;
    }
    else if(eventData.rawPointerPress == Player2)
    {
        Player2.transform.localScale += scaleChange;
        Player1.transform.localScale -= scaleChange;
        Player1.transform.SetSiblingIndex(0);
    }
    Debug.Log(clickPosition);
    Debug.Log(eventData.rawPointerPress);
    Debug.Log(randomScaleChange);
}

private void ScaleEvents()
{
    randomScaleChange = Random.Range(0.05f, 0.3f);
    scaleChange = new Vector3(0.0f, randomScaleChange, 0f);

}

}

A: From what I understand, should you rather use RectTransform.deltaSize.y, and adjust the actual height of your UI elements, instead of the scale. Someone smarter than me can explain to you why. If I tried to explain it, I would probably cause more confusion.
Your blue element should be anchored to the top, and your red element should be anchored to the bottom. If you now add 50 pixel to the height of your blue element, and substract 50 from the height of your red element, it should work out, without a gap in between.
Also, please note that with your current solution, your red bar grows bigger than the amount of which your blue bar shrinks. So yes, you don't have a gap. But your Red bar is actually overdrawing over your blue bar.

Edit:
Below I present you a possible solution that hopefully gets you on the right track.
For it to work, blue needs to be anchored to the top of your screen. Anchors Min: 0, 1; Max; 1, 1; Pivot 0.5, 1.
Red needs to be anchored to the bottom of the screen. Anchors Min: 0,0; Max; 1, 0; Pivot 0.5, 0.
Set the hight for both elements so that they touch seamlessly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class ClickGame : MonoBehaviour, IPointerClickHandler
{
    public RectTransform Player1;
    public RectTransform Player2;
    float randomScaleChange;

    public void OnPointerClick(PointerEventData eventData)
    {
        ScaleEvents();
        Vector3 clickPosition = Camera.main.ScreenToWorldPoint(eventData.position);

        if (clickPosition.y > 0f) // Blue clicked
        {
            Player1.sizeDelta = new Vector2(100f, Player1.sizeDelta.y + randomScaleChange);
            Player2.sizeDelta = new Vector2(100f, Player2.sizeDelta.y - randomScaleChange);

        }

        if (clickPosition.y < 0f) // Red clicked
        {
            Player2.sizeDelta = new Vector2(100f, Player2.sizeDelta.y + randomScaleChange);
            Player1.sizeDelta = new Vector2(100f, Player1.sizeDelta.y - randomScaleChange);
        }
    }

    private void ScaleEvents()
    {
        randomScaleChange = Random.Range(5f, 50f);
    }
}

A: There's what a code looks like now and still didn't work:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class ClickerZone : MonoBehaviour, IPointerClickHandler
{
[SerializeField] private GameObject _Player1;
[SerializeField] private GameObject _Player2;
private RectTransform _player1Rect;
private RectTransform _player2Rect;
private Vector3 _scaleChange;
private float _randomScaleChange;

private void Awake()
{
    _player1Rect = _Player1.GetComponent<RectTransform>();
    _player2Rect = _Player2.GetComponent<RectTransform>();
}

public void OnPointerClick(PointerEventData eventData)
{
    ScaleEvents();
    Vector3 clickPosition = Camera.main.ScreenToWorldPoint(eventData.position);
    if (eventData.rawPointerPress == _Player1)
    {
        _Player1.transform.localScale += _scaleChange;
        _player1Rect.sizeDelta = new Vector2(0f, _player1Rect.sizeDelta.y + _randomScaleChange);
        _Player2.transform.localScale -= _scaleChange;
        _player2Rect.sizeDelta = new Vector2(0f, _player2Rect.sizeDelta.y - _randomScaleChange);

    }
    else if(eventData.rawPointerPress == _Player2)
    {
        _Player2.transform.localScale += _scaleChange;
        _player2Rect.sizeDelta = new Vector2(0f, _player2Rect.sizeDelta.y + _randomScaleChange);
        _Player1.transform.localScale -= _scaleChange;
        _player1Rect.sizeDelta = new Vector2(0f, _player1Rect.sizeDelta.y - _randomScaleChange);
    }
    Debug.Log(clickPosition);
    Debug.Log(eventData.rawPointerPress);
    Debug.Log(_randomScaleChange);
}

private void ScaleEvents()
{
    _randomScaleChange = Random.Range(0.05f, 0.3f);
    _scaleChange = new Vector3(0.0f, _randomScaleChange, 0f);
}
}


text:
Q: Angular 4 + AdminLTE. Treeview-menu isnt working So, im working in a plataform and im using Angular 4 and AdminLTE. After logging into the dashboard, my treeview menu doesnt work. Looks like it only works at the first loading after Ng Serve, and to get it working again I need to restart my ng serve and reopen my browser.
Please help, im getting crazy with this.
(Console doesnt show me an error or something, i already Jquery installed in my project with npm install jquery, npm install @types/jquery and stuff like that)

A: You need to place the admin css and js files in the angulaar-cli.json
like
"styles": [
    "styles.css",
    "./../src/assets/css/AdminLTE.css",
    "./../src/assets/css/_all-skins.min.css"
  ],
  "scripts": [
    "./../src/assets/js/adminlte.min.js"
  ],

and write the bellow code in the home page ngOnInit function
ngOnInit() {
$(document).ready(() => {
  const trees: any = $('[data-widget="tree"]');
  trees.tree();
});}

and the html ul should be like this
<ul class="sidebar-menu" data-widget="tree">


text:
Q: Is there an analytic way to tell if a system of ordinary differential equations is conservative? I don't know the exact definition of conservative, but we can assume that conservative means the sum of Lyapunov exponents is zero. Is there an analytic method to show that a given system is conservative?
I came to this question by reading Sprott's Elegant Chaos. A system of interest could be e.g.:
$$U''' + U' + \frac{1}{3}U^3 - Uc=0$$
where $c$ is constant, $U(t)$ is a function of time. It can be described as system of three equations:
$$\begin{align}
U' &= X \\
X' &= Y  \\
Y' &= -X - \frac{1}{3} U^3 +Uc
\end{align}$$
Then I think (but cannot prove it) that the trace of the Jacobian $\operatorname{Tr}(J)$ shows the conservativeness.
$$\operatorname{Tr}(J) = \frac{\partial U'}{\partial U} + \frac{\partial X'}{\partial X} + \frac{\partial Y'}{\partial Y} = 0 + 0 + 0 = 0$$
It also means that if $\operatorname{Tr}(J) < 0$, the system is dissipative, and if $\operatorname{Tr}(J) > 0$, the system diverges, i.e., it is not bounded. Can you say if I am right or wrong?

A: Your hunches are absolutely right. In dynamical-systems theory, systems are often classified via their divergence (i.e., the trace of the Jacobian). In this context, if your dynamics is $\dot{x} = f(x)$, then $\operatorname{div} f = 0$ defines a conservative system; and $\operatorname{div} f < 0$ defines a dissipative one.
The only difficulty is that divergence may be inhomogeneous and thus you have to look at the average over a trajectory, which brings us to the sum of Lyapunov exponents.
However, conservative usually implies $\operatorname{div} f = 0$ everywhere.
A system with $\operatorname{div} f = 0$ on average would have to be carefully constructed.
This is linked with conservativity in the sense of energy conservation via one of Liouville's Theorems and Noether's Theorem: $\operatorname{div} f = 0$ implies a conserved phase-space volume, which imples symmetry with respect to the direction of time, which in turn implies conservation of energy (or a similar quantity). On the other hand, for Hamiltonian systems (which are energy-conserving), you have $\operatorname{div} f = 0$.

if $\operatorname{Tr}(J) > 0$, the system diverges, i.e., it is not bounded.

Exactly. Your phase-space volume of an arbitrary set of initial conditions would always expand and thus you would the dynamics would have to be unbounded.


text:
Q: jQuery plugin static method $.fn.plugin.method vs $.plugin.method The official jQuery resource seems to indicate that you create a static method for your plugin using $.fn.plugin.staticMethod but that means that your public API requires calling $.fn.plugin.staticMethod(), which I find cumbersome.
Is there anything wrong with defining $.fn.plugin for your plugin and $.plugin.staticMethod for your static method, and what's the difference?
Further, what's the difference between:
$.extend({
  plugin : {
    staticMethod : function(){ }
  }
});

and
$.plugin = {
  staticMethod : function(){ }
};


text:
Q: how can I deploy my mern website from my local machine? I have a fully functioning MERN app working. I was wondering, how would I deploy my mern app to the world wide web from my local machine?
My research has concluded with XAMPP as a possible tool, but it seems the backend tooling is PHP not nodejs. Any ideas you guys have helps!
the idea is to host it locally not externally on the cloud.

A: Firstly, you need to buy vps server. After you need to upload full project to the server through ftp software and need to upload packages with npm install/update. After these are finished download nginx server to the server and be carefull about port of project. If your project will running for example on 3000 port you may change nginx configuration like this and restart nginx with followed command:
systemctl restart nginx
and nginx configuration write like this (added example domain):
server {
    listen 80;
    listen [::]:80;

    server_name yourdomain.com;

    root /var/projects/your_project_name;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html;

    charset utf-8;

    location / {
          proxy_pass http://localhost:3000/;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection 'upgrade';
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_cache_bypass $http_upgrade;
    }

}

For additional information about nginx configurations you may visit Nginx configurations


text:
Q: Javascript and 3d games I was just wondering. Is there a game engine available for creating 3d games? because I am planning to create a PhoneGap game so that it is playable inside a magazine app that I am creating and of course, take advantage of PhoneGap's fast deployment on several devices.

A: Javascript is NOT the way to go for this. Use flash if you can.
Though, I did stumble across: http://raphaeljs.com/scape/
Welcome to svg hell.


text:
Q: PHP: How to check if post when normal link I have this
          <form action="profiles.php" method="POST" name="SearchAdvanced" id="SearchAdvanced">
            <a style="display: inline-block; width: 100px; font-weight: bold; cursor: pointer;" id="submitSearchAdvanced">Sök </a>
            <script>
                        $('#submitSearchAdvanced').click(function() {
    javascript:document.SearchAdvanced.submit();
        });
            </script>
</form>

How should i call it? should i do if($_POST["SearchAdvanced"])

A: Check $_SERVER['REQUEST_METHOD'], which will be "GET" or "POST".
The manual page for $_SERVER describes the indices in detail.

A: Besides checking request method, you can also do a check for variable being set in POST:
isset($_POST['SearchAdvanced'])

Offtopic:
Also, "pro" tip: never uset double quotes ( " ) if you do not have variable definition in it.. There is a difference between single and double quotes in PHP.
http://www.php.net/manual/en/language.types.string.php

A: If what you posted is the entire form, you don't need to submit it using POST, because you are not altering a resource on the server. Instead, you should remove the form and leave only the link - and maybe style it using CSS like you did.


text:
Q: Access asking for password when going to Tools/References I'm trying to go to the references on an Access Database.  I'm not very familiar with this database but here's my history with it:
I tried to open the code files once and it asked for a password
Prior developer assured me there was no password on it and he was able to get into the code files just fine.
I then tried and, to my surprise, it no longer asked me for a password
Today I try to get into Tools/References and the password box is back.
Allegedly this mdb is not supposed to be protected.  Any help if figuring out how to get past this would be greatly appreciated!

A: The original programmer removed the password that was required to get into the code, but then we found there was another level of security protecting the project references.  The original programmer couldn't figure out how to remove that password, but he was instead able to change it to something that wasn't personal.
So I never really got the answer I was looking for but I think the moral of the story is that people need to not use personal passwords for their work stuff so that when I take over their work they can just tell me what it is instead of making me wait a month for them to come back and change it.


text:
Q: Get column names of multiple tables and insert it to another table + PHP MySQL I have this code:
$createFields="CREATE TABLE temp_field (fld text NOT NULL, tablename char(50) NOT NULL)";
mysql_query($createFields);

$fields=array();

$campaign=mysql_query("SELECT campaignid FROM campaign ORDER BY campaignid");

while($row=mysql_fetch_array($campaign)){

    $table="'campaign_".$row['campaignid']."'";

    $temp_field="SELECT COLUMN_NAME,TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=".$table;

    $temp_fieldquery = mysql_query($temp_field);

    while($rowL=mysql_fetch_array($temp_fieldquery)){

        $fields[]="'".$rowL['COLUMN_NAME']."'";

    }
$field=implode(",",$fields);

$insertFields='INSERT INTO temp_field (fld,tablename) VALUES ("'.$field.'","'.$table.'")';

    mysql_query($insertFields);

and I need to have this kind of output:
fld                       | tablename
=====================================
fld1,fld2,fld3,fld4...    |  table1
fld1,fld2,fld3,fld4...    |  table2

but what I get is:
fld                                          | tablename
========================================================
fld1,fld2,fld3,fld4...                       |  table1
fld1,fld2,fld3,fld4,fld1,fld2,fld3,fld4...   |  table2

The second table gets the values of first table
What am I doing wrong with my code, please help

A: Just initialize your $fields array right before the while loop.
$fields = array();
while($rowL=mysql_fetch_array($temp_fieldquery)){
  $fields[]="'".$rowL['COLUMN_NAME']."'";
}
$field=implode(",",$fields);

What happened in your code is that the $fields array continues to add new fields for each succeeding table due to $fields[] so resetting to a new array should fix it.

A: INSERT INTO temp_field
SELECT
GROUP_CONCAT(COLUMN_NAME separator ",") AS fld
TABLE_NAME AS tablename
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'campaign_%'
GROUP BY TABLE_NAME

Your code sample is much to complicated.
Just use the query above.


text:
Q: What is the shortcut for invert color on Mac OS X Yosemite? I did some search but find the most discussed shortcut  Command-Option-Control-8 is not working anymore. Is it changed or do I need to set it manually?
Thanks

A: Go to Apple Menu -> System Preferences. Click on Keyboard and then click the tab Keyboard shortcuts.
Then scroll select the Acessability option in the left pane and scroll down and check the box beside Invert color.

A: Try hitting: CMD-Shift-F5.
That's how I get it.


text:
Q: Find the generating function to determine the number of ways to choose k objects from n objects when the ith object appears at least n + i times Find the generating function to determine the number of ways to choose k objects from n objects when the ith object appears at least n + i times for 1 ≤ i ≤ n.
the generating function for picking k objects from n objects is $(1+x)^{n}$,but I'm  not sure how to go from this to taking into account "the ith object appears at least n + i times"
I am a beginner to this so if you could explain your steps to help me understand why it is things happen, I'd appreciate it

A: The generating function to ensure that the $i^\text{th}$ object appears at least $n+i$ times is as follows:
\begin{equation}
g(x) = \underset{1^{\text{st}} \text{ object}}{\underbrace{(x^{n+1}+x^{n+2}+\ldots+x^k)}}\underset{2^{\text{nd}} \text{ object}}{\underbrace{(x^{n+2}+x^{n+3}+\ldots+x^k)}}\ldots\underset{n^{\text{th}} \text{ object}}{\underbrace{(x^{2n}+x^{2n+1}+\ldots+x^k)}}.
\end{equation}
Here, the power of $x$ in the first term of the product represents the number of times the first object is picked. Since the first object appears at least $n+1$ times, the smallest power of $x$ in the first term is $n+1$. The maximum number of objects to be chosen is $k$, and hence, the maximum power is $k$. Similarly, we get the later terms. Finally,  the number of ways to choose $k$ objects is the coefficient of $x^k$ in the generator function $g(x)$.


text:
Q: Download data for multiple variables from Eurostat I have a variable_list and a country_list that I want to download data for. I'd like to automate that as I don't want to push each download on it's own.
I want the code to iterate through the variable_list, download data for the respective country_list and store them as "variable"_data. I use get_eurostat for the downloads.
I tried:
variable_list <- list("demo_r_d3area", "demo_r_d3dens", "demo_r_fagec")
country_list <- list("AT","BE","DK")
for (i in variable_list) {
  (assign(paste("data_", i, sep = ""), variable_list[[i]])) <-
    get_eurostat(id = variable_list, time_format = "num",
                 filters = list(geo = country_list))
}

But I don't think I'm heading into the right direction with that.

A: I believe the right way to read in the data is with a lapply loop into a list.
library(eurostat)

variable_list <- list("demo_r_d3area", "demo_r_d3dens", "demo_r_fagec")
country_list <- list("AT","BE","DK")

data_list <- lapply(variable_list, function(v){
  get_eurostat(
    id = v,
    time_format = "num",
    filters = list(geo = country_list)
  )
})

names(data_list) <- variable_list
str(data_list)
#List of 3
# $ demo_r_d3area: tibble [156 × 5] (S3: tbl_df/tbl/data.frame)
#  ..$ unit   : chr [1:156] "KM2" "KM2" "KM2" "KM2" ...
#  ..$ landuse: chr [1:156] "L0008" "L0008" "L0008" "L0008" ...
#  ..$ geo    : chr [1:156] "AT" "AT" "AT" "AT" ...
#  ..$ time   : num [1:156] 1990 1991 1992 1993 1994 ...
#  ..$ values : num [1:156] 82528 82528 82523 82518 82512 ...
# $ demo_r_d3dens: tibble [90 × 4] (S3: tbl_df/tbl/data.frame)
#  ..$ unit  : chr [1:90] "PER_KM2" "PER_KM2" "PER_KM2" "PER_KM2" ...
#  ..$ geo   : chr [1:90] "AT" "AT" "AT" "AT" ...
#  ..$ time  : num [1:90] 1990 1991 1992 1993 1994 ...
#  ..$ values: num [1:90] 93 94 95 95.8 96.2 96.3 96.5 96.6 96.7 96.9 ...
# $ demo_r_fagec : tibble [3,780 × 5] (S3: tbl_df/tbl/data.frame)
#  ..$ unit  : chr [1:3780] "NR" "NR" "NR" "NR" ...
#  ..$ age   : chr [1:3780] "TOTAL" "TOTAL" "TOTAL" "TOTAL" ...
#  ..$ geo   : chr [1:3780] "AT" "AT" "AT" "AT" ...
#  ..$ time  : num [1:3780] 1990 1991 1992 1993 1994 ...
#  ..$ values: int [1:3780] 90454 94629 95302 95227 92415 88669 88809 84045 81233 78138 ...

The data sets can now be accessed with the standard extractor operators. Here is an example of accessing demo_r_d3area.
head(data_list$demo_r_d3area)
## A tibble: 6 x 5
#  unit  landuse geo    time values
#  <chr> <chr>   <chr> <dbl>  <dbl>
#1 KM2   L0008   AT     1990 82528.
#2 KM2   L0008   AT     1991 82528.
#3 KM2   L0008   AT     1992 82523.
#4 KM2   L0008   AT     1993 82518.
#5 KM2   L0008   AT     1994 82512.
#6 KM2   L0008   AT     1995 82519.

A: Are you trying to do this?
for (i in variable_list) {
  variable_list[[i]] <- get_eurostat(
    id = i,
    time_format = "num",
    filters = list(geo = country_list)
    )

  assign(paste("data_", i, sep = ""), variable_list[[i]])
}

If this is not what you are trying to do, please clearify your question.


text:
Q: unattended software installation using PowerShell GUI I want to create a GUI using PowerShell, that will allow users to select software to install. The software will be installed using unattended (silent) options, so the user doesn't have to do anything more that select the desired software, and click OK.
Since the installation is silent and there will be plenty of software to install, I want to give some feedback to the user, as to the status of the installation. So I put a textbox showing which software have been installed and which software is currently installing.
My problem is that all the text appears at the same time in the textbox and it also looks messy.

I want it to be like this:

*

*installing 7-zip...OK

*installing notepad ++...OK

*installing visual studio code...OK

This is the script
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# software name
$software1 = "7-Zip"
$software2 = "Notepad++"
$software3 = "Visual Studio Code"

# installation status
$software1status = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where {$_.DisplayName -like "*$software1*"}
$software2status = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where {$_.DisplayName -like "*$software2*"}
$software3status = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where {$_.DisplayName -like "*$software3*"}

# set form size
$Form = New-Object System.Windows.Forms.Form
$Form.width = 500
$Form.height = 500
$Form.Text = 'Install Software'

# set font
$Font = New-Object System.Drawing.Font("Verdana",10)
$Form.Font = $Font

# results textbox
$ResultsTextBox = New-Object System.Windows.Forms.TextBox
$ResultsTextBox.Location = New-Object System.Drawing.Size(200,30)
$ResultsTextBox.Size = New-Object System.Drawing.Size(250,350)
$ResultsTextBox.Multiline = $true
$ResultsTextBox.Text = "make your selections on the left"
$Form.Controls.Add($ResultsTextBox)

# checkbox software1
$checkbox1 = new-object System.Windows.Forms.checkbox
$checkbox1.Location = new-object System.Drawing.Size(30,30)
$checkbox1.Size = new-object System.Drawing.Size(120,20)
$checkbox1.Text = "$software1"
if ($software1status -eq $null) {$checkbox1.Checked = $false} Else {$checkbox1.Checked = $true}
$Form.Controls.Add($checkbox1)

# checkbox software2
$checkbox2 = new-object System.Windows.Forms.checkbox
$checkbox2.Location = new-object System.Drawing.Size(30,50)
$checkbox2.Size = new-object System.Drawing.Size(120,20)
$checkbox2.Text = "$software2"
if ($software2status -eq $null) {$checkbox2.Checked = $false} Else {$checkbox2.Checked = $true}
$Form.Controls.Add($checkbox2)

# checkbox software3
$checkbox3 = new-object System.Windows.Forms.checkbox
$checkbox3.Location = new-object System.Drawing.Size(30,70)
$checkbox3.Size = new-object System.Drawing.Size(120,20)
$checkbox3.Text = "$software3"
if ($software3status -eq $null) {$checkbox3.Checked = $false} Else {$checkbox3.Checked = $true}
$Form.Controls.Add($checkbox3)

# ok button
$OKButton = new-object System.Windows.Forms.Button
$OKButton.Location = new-object System.Drawing.Size(130,400)
$OKButton.Size = new-object System.Drawing.Size(100,40)
$OKButton.Text = "OK"
$Form.Controls.Add($OKButton)

# close button
$CloseButton = new-object System.Windows.Forms.Button
$CloseButton.Location = new-object System.Drawing.Size(255,400)
$CloseButton.Size = new-object System.Drawing.Size(100,40)
$CloseButton.Text = "Close"
$CloseButton.Add_Click({$Form.Close()})
$Form.Controls.Add($CloseButton)

$OKButton.Add_Click{

if($checkbox1.Checked -and $software1status -eq $null) {Start-Process -FilePath $PSScriptRoot\software\7z1900-x64.msi /passive ; $ResultsTextBox.Text += "installing 7-zip"}
if($checkbox1.Checked -eq $false -and $software1status -ne $null ) {Start-Process MsiExec.exe "/x{23170F69-40C1-2702-1900-000001000000} /passive" ; $ResultsTextBox.Text += "removing 7-zip"}

if($checkbox2.Checked -and $software2status -eq $null) {Start-Process -FilePath $PSScriptRoot\software\npp.7.8.1.Installer.x64.exe /S ; $ResultsTextBox.Text += "installing notepad ++"}
if($checkbox2.Checked -eq $false -and $software2status -ne $null ) {Start-Process -FilePath "${env:ProgramFiles}\Notepad++\uninstall.exe" /S ; $ResultsTextBox.Text += "removing notepad ++"}

if($checkbox3.Checked -and $software3status -eq $null) {Start-Process -FilePath $PSScriptRoot\software\VSCodeSetup-x64-1.40.2.exe "/SILENT /NORESTART /MERGETASKS=!runcode" ; $ResultsTextBox.Text += "installing visual studio code"}
if($checkbox3.Checked -eq $false -and $software3status -ne $null ) {Start-Process -FilePath "${env:ProgramFiles}\Microsoft VS Code\unins000.exe" /SILENT ; $ResultsTextBox.Text += "removing visual studio code"}

}

# activate form
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()

A: Use AppendText instead. you need to send carriage returns and new line characters also using that method:
$ResultsTextBox.AppendText("`r`nInstalling new file...")

However, you can only do things like this during an event like a button click. If you want to update more often you need to create events for that.


text:
Q: ssas tabular project property not show query mode can anyone help this?
the SSAS project property not showing query mode?
have i messed with anything?
thanks

A: Try clicking on the .bim file in Solution Explorer and looking at the Properties pane. I assume this is the property you meant:

A: i am using Visual Studio  2015, and i expect the property page would like this as the enter image description hereattachment.
not sure whether the tool install correctly or anything wrong else.
cheers


text:
Q: Invoke Static Generic Method via delegate via Emit I try to create a deleagte to invoke a  static generic Method. But I got the error: Invalid code detected! nyone a idea what is wrong with my IL?
The FindStaticMethod Call in the Example Code is working and Returning a Method Info, with the given Type arguments!
 public delegate object GenericStaticInvoker(params object[] arguments);

 public static GenericStaticInvoker GenericMethodInvokerStaticMethod(Type type, string methodName, Type[] typeArguments, Type[] parameterTypes)
    {
        MethodInfo methodInfo;
        ParameterInfo[] parameters;

        // find the method to be invoked
        FindStaticMethod(type, methodName, typeArguments, parameterTypes, out methodInfo, out parameters);

        string name = string.Format("__MethodInvoker_{0}_ON_{1}", methodInfo.Name, methodInfo.DeclaringType.Name);

        DynamicMethod dynamicMethod;
        dynamicMethod = new DynamicMethod(name, typeof(object), new Type[] { typeof(object[]) }, methodInfo.DeclaringType);

        ILGenerator generator = dynamicMethod.GetILGenerator();

        // define local vars
        if (methodInfo.ReturnType != typeof(void))
            generator.DeclareLocal(methodInfo.ReturnType);

        for (int i = 0; i < parameters.Length; i++)
        {
            // load paramters they are passed as an object array
            generator.Emit(OpCodes.Ldarg_1);

            // load array element
            generator.Emit(OpCodes.Ldc_I4, i);
            generator.Emit(OpCodes.Ldelem_Ref);

            // cast or unbox parameter as needed
            Type parameterType = parameters[i].ParameterType;
            if (parameterType.IsClass)
            {
                generator.Emit(OpCodes.Castclass, parameterType);
            }
            else
            {
                generator.Emit(OpCodes.Unbox_Any, parameterType);
            }
        }

        // call method
        generator.EmitCall(OpCodes.Call, methodInfo, null);

        // handle method return if needed
        if (methodInfo.ReturnType == typeof(void))
        {
            // return null
            generator.Emit(OpCodes.Ldnull);
            generator.Emit(OpCodes.Ret);
        }
        else
        {
            // box value if needed
            if (methodInfo.ReturnType.IsValueType)
            {
                generator.Emit(OpCodes.Box, methodInfo.ReturnType);
            }

            // store to the local var
            generator.Emit(OpCodes.Stloc_0);

            // load local and return
            generator.Emit(OpCodes.Ldloc_0);
            generator.Emit(OpCodes.Ret);
        }

        // return delegate
        return (GenericStaticInvoker)dynamicMethod.CreateDelegate(typeof(GenericStaticInvoker));
    }

A: *

*In an instance method, the "this" parameter can be loaded onto the evaluation stack by Ldarg_0 and then the "actual" parameters can be loaded with Ldarg_{x} (with x 1 through N).

*When you have a static method (also the case of any lambda, be it reflection.emitted or not) the "actual" parameters can be loaded with Ldarg_{x} (with x 0 through N-1).

*To wrap it all up for the general case: the "this" reference is a parameter in its own right.
Its absence does not leave an empty slot onto the stack (the ldarg.0 will and must be used for the first non-"this" parameter).
So in your particular case, you can't use OpCodes.Ldarg_1 do load your params object[] parameters unique parameter:
// ...etc...
for (int i = 0; i < parameters.Length; i++)
{
    // load paramters they are passed as an object array
    generator.Emit(OpCodes.Ldarg_1);

    // ...etc...

You should use OpCodes.Ldarg_0:
// ...etc...
for (int i = 0; i < parameters.Length; i++)
{
    // load paramters they are passed as an object array
    generator.Emit(OpCodes.Ldarg_0);

    // ...etc...


text:
Q: Matrices and polynomials: MMA 8 vs. 9? I want a function to take a polynomial from a list, plug a certain matrix T into that polynomial, and return the answer as another matrix. My program uses the applyPoly function suggested by a user in response to:
https://stackoverflow.com/questions/17394035/in-mathematica-how-calculate-pa-where-p-is-a-polynomial-and-a-is-a-square-mat
Here is my code:
applyPoly[poly_, var_, A_?MatrixQ] :=
  With[{c = CoefficientList[poly, var]},
    c.MapIndexed[MatrixPower[A, #2[[1]] - 1] &, c]]

Compute[a_, b_, c_] := (
  p[x_] := x^4 - c*x^3 - b*x^2 - a*x;
  T := {{0, 0, 0, 0}, {1, 0, 0, a}, {0, 1, 0, b}, {0, 0, 1, c}};
  L := FactorList[p[x]]; s = Length[L]; R = {};
  Do[R = Append[R, Simplify[p[x]/L[[i + 1, 1]]]], {i, s - 1}];
  u = Length[R];
  Do[r[x_] := R[[i]]; Print[applyPoly[r[x], x, T]], {i, u}])

Compute[1,2,3]

In Mathematica 8, this returns the correct matrix output:
{{-1,0,0,0},{-2,0,0,0},{-3,0,0,0},{1,0,0,0}}

{{0,0,0,0},{1,0,0,1},{0,1,0,2},{0,0,1,3}}

But in Mathematica 9, I get an error:

Dot::rect: Nonrectangular tensor encountered. >>
{-1,-2,-3,1}.{MatrixPower[{{0,0,0,0}, {1,0,0,1},{0,1,0,2},{0,0,1,3}},0],{{0,0,0,0},       {1,0,0,1},{0,1,0,2},{0,0,1,3}}, {{0,0,0,0}, {0,0,1,3},{1,0,2,7}, {0,1,3,11}}, {{0,0,0,0},   {0,1,3,11}, {0,2,7,25}, {1,3,11,40}}}
Dot::rect: Nonrectangular tensor encountered. >>
{0,1}.{MatrixPower[{{0,0,0,0},{1,0,0,1},{0,1,0,2},{0,0,1,3}},0],{{0,0,0,0},{1,0,0,1},{0,1,0,2},{0,0,1,3}}}

I understand that 8 and 9 must handle matrix or list objects in different ways. What is the difference, and how can I alter my program so that it works in 9?

A: MatrixFunction is the way to go... for example:
MatrixFunction[#^5 + 2 #^2 + 1 &, {{a, 1}, {0, b}}]

gives the polynomial function x^5+2x^2+1 when x is the symbolic matrix {{a, 1}, {0, b}}. It also works for more complicated functions such as trigonometric functions. And of course, it works on numerical matrices as well. It does require that the matrices be square, which makes sense because otherwise the x^n terms don't make any sense.

A: Don't use Print for output; change Do to Table.  Then the output will be the matrices (with the Root objects), and N will work.
applyPoly[poly_, var_, A_?MatrixQ] :=  MatrixFunction[poly /. var -> # &, A]

Compute[a_, b_, c_] := (p[x_] := x^4 - c*x^3 - b*x^2 - a*x;
  T := {{0, 0, 0, 0}, {1, 0, 0, a}, {0, 1, 0, b}, {0, 0, 1, c}};
  L := FactorList[p[x]]; s = Length[L]; R = {};
  Do[R = Append[R, Simplify[p[x]/L[[i + 1, 1]]]], {i, s - 1}];
  u = Length[R];
  Table[(*r[x_] := R[[i]];*) applyPoly[(*r[x]*)R[[i]], x, T], {i, u}])

Edit: I commented out the (unnecessary) definition of r, thanks to sebhofer, and replaced it with R[[i]].

Example
Compute[1, 2, 3] // N

(* {{ {-1. + 0. I, 0., 0., 0.},
      {-2. + 0. I, 2.53644*10^-16 + 0. I, 3.20011*10^-16 + 0. I, 1.68815*10^-15 + 0. I},
      {-3. - 4.93038*10^-32 I, 7.28119*10^-16 + 0. I, 8.93665*10^-16 + 0. I, 3.69631*10^-15 + 0. I},
      {1. + 0. I, 3.20011*10^-16 + 0. I, 1.68815*10^-15 + 0. I, 5.95812*10^-15 + 0. I}},
    { {0., 0., 0., 0.},
      {1. + 0. I, 0. + 0. I, 0. + 1.38778*10^-17 I, 1. + 0. I},
      {-3.40006*10^-16 + 0. I, 1. + 5.55112*10^-17 I, 0. + 0. I, 2. + 2.77556*10^-17 I},
      {-4.996*10^-16 + 0. I, 2.77556*10^-17 + 0. I, 1. + 0. I, 3. + 0. I}}} *)

There are other ways (1, 2, 3) to turn a polynomial poly into a function, but the above was the easiest, given your setup.

The above was rather too long to put into a comment, but I think bill s deserves the credit for pointing out MatrixFunction.


text:
Q: Hide OK button based on radiobutton selection I have a Sharepoint List with Radio-button field. If someone checks no then it should disable the ok button, but if yes is selected the ok button should be enabled.
I need to write a javascript in CEWP to achieve this with no access to SPD, can some one please advise?

A:

<input type = "radio" id = "id" onchange = "test_enable('id','id2')" value = "No">

<input type = "button" id = "id2" onclick = "foo()" value = "click me!">

Simple!

A: You can do somehting like this
function show_hide(show, hide)
{
document.getElementById(show).style.display="block";
document.getElementById(hide).style.display="none";
}

<form method="post" action="aaa.php">
<input type="radio" name="search" value="standard" onClick="show_hide('standard', 'advanced')" checked />Standard Search

Standard search div

<input type="radio" name="search" value="advanced" onClick="show_hide('advanced', 'standard')" />Advanced search

Advanced search div

<input type="submit" value="Submit" />
</form>


text:
Q: Spark streaming join Kafka topics comparison We needed to implement join on Kafka topics with consideration of late data  or "not in join", meaning data  that come late on the stream or not  in join will not be dropped/lost but will be marked as a timeout,
the result of the join is produced to output Kafka topic ( with a timeout filed if occurred).
(spark 2.1.1 in standalone deployment, Kafka 10 )
Kafka in topics: X, Y,...  out  topics result will look like:
{
    "keyJoinFiled": 123456,
    "xTopicData": {},
    "yTopicData": {},
    "isTimeOutFlag": true
}

I found three solutions wrote them here, 1 and 2 from spark streaming official documentation but are not relevant to us ( data not in join Dtsream, arrive "business time" late, is dropped/lost) but I wrote them for comparison.
From what we saw there are not too many examples for Kafka join topic with a stateful operation add some code here for review:
1) According to spark streaming documentation,
https://spark.apache.org/docs/2.1.1/streaming-programming-guide.html:
 val stream1: DStream[String, String] =
 val stream2: DStream[String, String] =
 val joinedStream = stream1.join(stream2)

This will join data from both stream batches duration, but data arrive "business time" late/not in join will be dropped/lost.
2) Window join:
val leftWindowDF = kafkaStreamLeft.window(Minutes(input_parameter_time))
val rightWindowDF = kafkaStreamRight.window(Minutes(input_parameter_time))
leftWindowDF.join(rightWindowDF).foreachRDD...

2.1) In our case we need to use Tumbling window in consideration for
       spark streaming batch interval.
  2.2) Need to save a lot of data in Memory/Disk, for example, 30-60 min
       window
  2.3) And again data arrive late/not in the window/not in the join is
       dropped/lost.
       * Since spark 2.3.1 Structured streaming stream to stream join is
         supported, but we encounter a bug with not cleaning HDFS state
         store, as a result, a job was falling every few hours on OOM,
         resolved in 2.4
        ,https://issues.apache.org/jira/browse/SPARK-23682
        (use of Rocksdb ,or CustomStateStoreProvider HDFS state store).
3) Using stateful operation mapWithState for join Kafka topics Dstreams
   with tumbling window and 30 min timeout for late data,
   all data produced to output topics contains joined messages from all
   topics if join occurred or part of topic data if no
   join occurred in 30 min ( mark with is_time_out flag)
3.1) Creating 1..n Dstream per topic, convert to Key value/Unioned
     records with join filed as a key and tumbling window.
     creating a catch-all scheme.
 3.2)Union all streams
 3.3)Run on union stream mapWithState with function - will actually do the
     join/ mark timeout.
Great example for stateful join from databricks (spark 2.2.0):
https://www.youtube.com/watch?time_continue=1858&v=JAb4FIheP28
Adding a sample code that is running/testing.
 val kafkaParams = Map[String, Object](
    "bootstrap.servers" -> brokers,
    "key.deserializer" -> classOf[StringDeserializer],
    "value.deserializer" -> classOf[StringDeserializer],
    "group.id" -> groupId,
    "session.timeout.ms" -> "30000"
  )

  //Kafka xTopic DStream
  val kafkaStreamLeft = KafkaUtils.createDirectStream[String, String](
    ssc,
    PreferConsistent,
    Subscribe[String, String](leftTopic.split(",").toSet, kafkaParams)
  ).map(record => {
    val msg:xTopic = gson.fromJson(record.value(),classOf[xTopic])
    Unioned(Some(msg),None,if (msg.sessionId!= null) msg.sessionId.toString else "")
  }).window(Minutes(leftWindow),Minutes(leftWindow))

  //Kafka yTopic DStream
  val kafkaStreamRight = KafkaUtils.createDirectStream[String, String](
    ssc,
    PreferConsistent,
    Subscribe[String, String](rightTopic.split(",").toSet, kafkaParams)
  ).map(record => {
    val msg:yTopic = gson.fromJson(record.value(),classOf[yTopic])
    Unioned(None,Some(msg),if (msg.sessionId!= null) msg.sessionId.toString else "")
  }).window(Minutes(rightWindow),Minutes(rightWindow))

  //convert stream to key, value pair and filter empty session id.
  val unionStream = kafkaStreamLeft.union(kafkaStreamRight).map(record =>(record.sessionId,record))
    .filter(record => !record._1.toString.isEmpty)
  val stateSpec = StateSpec.function(stateUpdateF).timeout(Minutes(timeout.toInt))

  unionStream.mapWithState(stateSpec).foreachRDD(rdd => {
    try{
      if(!rdd.isEmpty()) rdd.foreachPartition(partition =>{
        val props = new util.HashMap[String, Object]()
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers)
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")

        val producer = new KafkaProducer[String, String](props)
        //send to kafka result JSON.
        partition.foreach(record => {
          if(record!=null && !"".equals(record) && !"()".equals(record.toString) && !"None".equals(record.toString) ){
            producer.send(new ProducerRecord[String, String](outTopic, null, gson.toJson(record)))
          }
        })
        producer.close()
      })
    }catch {
      case e: Exception  => {
        logger.error(s""""error join topics :${leftTopic} ${rightTopic} to out topic ${outTopic}""")
        logger.info(e.printStackTrace())
      }
    }})

//mapWithState function that will be called on each key occurrence with new items in newItemValues and state items if exits.

def stateUpdateF = (keySessionId:String,newItemValues:Option[Unioned],state:State[Unioned])=> {
    val currentState = state.getOption().getOrElse(Unioned(None,None,keySessionId))

    val newVal:Unioned = newItemValues match {
      case Some(newItemValue) => {
        if (newItemValue.yTopic.isDefined)
          Unioned(if(newItemValue.xTopic.isDefined) newItemValue.xTopic else currentState.xTopic,newItemValue.yTopic,keySessionId)
        else if (newItemValue.xTopic.isDefined)
          Unioned(newItemValue.xTopic, if(currentState.yTopic.isDefined)currentState.yTopic else newItemValue.yTopic,keySessionId)
        else newItemValue
      }
      case _ => currentState //if None = timeout => currentState
    }

    val processTs = LocalDateTime.now()
    val processDate = dtf.format(processTs)
    if(newVal.xTopic.isDefined && newVal.yTopic.isDefined){//if we have a join remove from state
      state.remove()
      JoinState(newVal.sessionId,newVal.xTopic,newVal.yTopic,false,processTs.toInstant(ZoneOffset.UTC).toEpochMilli,processDate)
    }else if(state.isTimingOut()){//time out do no try to remove state manually ,it's removed automatically.
        JoinState(newVal.sessionId, newVal.xTopic, newVal.yTopic,true,processTs.toInstant(ZoneOffset.UTC).toEpochMilli,processDate)
    }else{
      state.update(newVal)
    }
  }

  //case class for kafka topics data.(x,y topics ) join will be on session id filed.
  case class xTopic(sessionId:String,param1:String,param2:String,sessionCreationDate:String)
  case class yTopic(sessionId:Long,clientTimestamp:String)
  //catch all schema : object that contains both kafka input fileds topics and key valiue for join.
  case class Unioned(xTopic:Option[xTopic],yTopic:Option[yTopic],sessionId:String)
  //class for  output result of join stateful function.
  case class JoinState(sessionId:String, xTopic:Option[xTopic],yTopic:Option[yTopic],isTimeOut:Boolean,processTs:Long,processDate:String)

I will be happy for some review.
sorry for the long post.

A: I was under the impression this use case was solved by the Sessionization API?:
StructuredSessionization.scala
And Stateful Operations in Structured Streaming
Or am I missing something?


text:
Q: Getting the current state of a tag config = canvas.itemconfig(line)

This will pull off the entire current configuration state of a line on a canvas.
I want to pull off the 'tags' item and examine the current state of it, typically either '0' or 'current'.  How do I do it?  I'm not good at all with tuples/dictionaries and in the research I've been doing over the past hour or so hasn't helped any so I figured stop wasting the time and ask.

A: You need to use itemcget to get the value of a single configuration item.
tags = canvas.itemcget(tag_or_id, "tags")

Note: if tag_or_id refers to more than one item, this will return the configuration value for the first item.
Here's one place where it's documented:

*

*http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.itemcget-method


text:
Q: JDBC MySQL url with Liquibase is wrong I am using Liquibase using a MySQL database.
I provide the following URL:
const db_url = `jdbc:mysql://${process.env.MYSQL_HOST}:${process.env.MYSQL_PORT}/${process.env.MYSQL_DB}?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC`;

Please ignore process.env.<XXX> because I guarantee it is valid and underline values are finally provided.
This gives me an error:
 Liquibase Community 4.0.0-beta1 by Datical
Errors:
  No command was passed.

By the way, if I provide the following URL:
const db_url = `jdbc:mysql://${process.env.MYSQL_HOST}:${process.env.MYSQL_PORT}/${process.env.MYSQL_DB}?serverTimezone=UTC`;

It does work, so basically I figured out the URL has problems with multiple queries.
I've read some threads in Stack Overflow and among comments there was one stating that I should use & instead of & char:
const db_url = `jdbc:mysql://${process.env.MYSQL_HOST}:${process.env.MYSQL_PORT}/${process.env.MYSQL_DB}?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC`;

Still, error:
 Liquibase Community 4.0.0-beta1 by Datical
Errors:
  No command was passed.

 /bin/sh: 1: amp: not found
/bin/sh: 1: amp: not found
/bin/sh: 1: --username=admin: not found

So how can I solve it?

A: Are you providing the jdbc url in the liquibase.properties file?
I found a detailed document about configuring and creating the liquibase.properties file where you add the jdbc url > Here
BTW you can be a part of Liquibase Forum, where everyone from the Liquibase Community can ask/answer questions, all about Liquibase. >> Liquibase Forum


text:
Q: ASP MVC DependencyResolver with UnityContainer for Unit testing I'm building an ASP MVC 3 application in which I use Unity as IOC container and I register it on the DependencyResolver.  In my controller I can then do this:
DependencyResolver.Current.GetService(GetType(IViewAllPersonsHandler))

Then when I write my unit tests I redefine my mappings in my test to use mocked objects.
A colleague of mine told me that doing this is considered as an Anti Pattern.
Can anyone tell me whether this is the case and why?
I know that normally I should inject my dependencies in the constructor, but as my controller grows the constructors parameters get lengthy.
Thx

A: Most folks consider the service locator pattern an anti-pattern.  Probably since one can get around it with some leg-work.
If you are doing it to limit the constructor parameters you could try something different.  I use property injection.  Since I use castle windsor the container injects public properties by default.  Last I looked Unity did not do this and you had to use some extension to get that to work.
Other than that you could split your controller or delegate to tasks within your actions.
But I would also stay away from service locator from within you controller.
HTH

A: You can use System.Web.Mvc.DependencyResolver.SetResolver(resovlveDependencyMock);

A: It's easy with Moq:
DependencyResolver.SetResolver(Mock.Of<IServiceLocator>(s => s.GetInstance(It.IsAny<Type>()) == cacheMock.Object));


text:
Q: Make Android App (Random Colors) What I need to do is an application that when you click on the screen it will just show random colours on the screen; press the screen again and you will get other random colours  (colours that are not only Red, Blue, Green).

A: If you need only bright, saturated colors, use Color.HSVToColor() instead of setting R, G and B components directrly:
float[] hsvColor = {0, 1, 1};
// randomly generate only hue component,
// leaving saturation and brightness maximum possible
hsvColor[0] = new Random().nextFloat() * 360;
view.setBackgroundColor(Color.HSVToColor(hsvColor));


text:
Q: I have an application i want to generate 3d models in canvas, but i dont know which tool to use User selects multiple options and depending on it the application generates 3d model.
Comments:
1. It's must be canvas.
2. Models must be generated on live, not stored in database because there can be millions of them.
What have I came up to:

*

*Looks like threejs almost fits my needs, but all my experience is toying with webgl and canvas renderer. I have a background in 3d so its not a problem. I don't know can threejs generate 3d models onlive using canvasrenderer? I'm not talking about particles or spheres or smth, my  models are complicated. Threejs doc is good, but there are a lot of blank spaces. Intuition tells me to do something with dynamically creating Object3d and fill it with geometry and vertices but I haven't find any manual or example how to do it.

*Maybe, I can have some sketch models in collada and then modify them via threejs?

*Maybe there is another library?

*Maybe I should face impossibility and use flash?
Thank you, stay cool.

A: This is a fairly general question, so it's kind of hard to answer, but I think, basically, that YES, Three can probably do the job you're looking for. For example, are you thinking about doing something like this:
http://workshop.chromeexperiments.com/machines/#
?
And, BTW, yes, you'd probably do a lot of Object3D creation and loading into the scene. You might well want to start with some small, predefined models that get loaded into the scene and then modified. If it looks like what you're after, try taking the google sketch apart and understanding it.