text:
Q: GoogleMap.setpadding() is undefined for the type GoogleMap I am using Eclipse and some methods do not appear to be available for GoogleMaps objects.
I have imported the google-play-services_lib, made sure I had the latest versions of Google Play Services and I am running the latest API (Version 4.4.2 (API 19). I removed all of them as well and re-installed them.  The Map Fragment works great on my test device. However when I try to implement methods such as .setPadding() I get an error that .setpadding is undefined for the GoogleMap object.
It should be in here:
https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/GoogleMap#setPadding(int, int, int, int)
Any ideas?
public class MapDemo extends Activity implements LocationListener {
GoogleMap googleMap;
GoogleMapOptions options = new GoogleMapOptions();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mapdemo);

    try {
        initilizeMap();
    } catch (Exception e) {
        Log.e("ERROR", "ERROR IN CODE: " + e.toString());
        e.printStackTrace();
    }

}

private void initilizeMap() {
    // Do a null check to confirm that we have not already instantiated the
    // map.
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        googleMap.setMyLocationEnabled(true);
        googleMap.setPadding(0,0,30,0); // **<--This method does not appear to be in the API!**

        // Check if we were successful in obtaining the map.
        if (googleMap != null) {
            // The Map is verified. It is now safe to manipulate the map.

              options.mapType(GoogleMap.MAP_TYPE_HYBRID)
              .compassEnabled(false) .rotateGesturesEnabled(false)
              .tiltGesturesEnabled(false) ;

        } else {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

A: Are you using the most recent version of the Google Play Services library project? According to the Maps API changelog, the setPadding() method was added in September 2013.

A: So I found the problem.  The google-play-services_lib that I had imported was imported from a copy I had manually downloaded instead of the google-play-services_lib that is maintained and updated by the Android SDK Manager. Now, magically, I have the new methods!


text:
Q: What does `import ...` mean in Python 3? From a quick search, I know that one dot means in the current directory, two dots mean in the parent directory, and three dots mean in the grandparent directory, but these examples are usually written as from .. import PackageName
What if the code was just import ...? Does this import every file in the grandparent directory? (The reason why I ask is that I'm working with some files that has this import statement at the top, but there is nothing in the grandparent directory to import).

A: The dots mimic the Unix file system that . refers to the current directory and .. refers to the parent. ... has no such conventional meaning. In Python, however, ... is the literal for the singleton value of the ellipsis class:
>>> type(...)
<class 'ellipsis'>

As such, import ... would be a syntax error, as ... is not a valid module name.

A: What if the code was just import ...?
as @chepner said, ... means <class 'ellipsis'>, but you can't import it.
in PyCharm "import ..." means it is a folded code block:

the full code is like this(click the "+" button):

Maybe other IDEs are like this too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How much capacity is left in my channel? Is there a way to see how much storage is left in my asynchronous channel in Go?
For example
a chan uint=make(chan bool, 5)
a<-true
fmt.Printf(a.capazity())

A: For example,
package main

import "fmt"

func main() {
    a := make(chan bool, 5)
    a <- true
    fmt.Println(cap(a) - len(a))
}

Output:
4


text:
Q: android: hiding media controller functions I have a videoview and when the video starts, the media controller is shown for 3 seconds. I want to hide the media controller unless i tap on the screen. I tried
MediaController mc= new MediaController();
mc.hide();
Videoview.setMediaController(mc);
..
..
..

But it didn't work.. Any suggestions please?

A: This isn't really a solution to hiding the MediaController, but if you want to get rid of the thing altogether, do this:
videoView.setMediaController(null);

You can have it initially hidden by doing the above, and then when you want it to show (onClick or onTouch or whatever), just make a new MediaController and set it on the videoView. I added a boolean to prevent the action from happening more than once.
@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        if (controllerCreated == false) {
            videoView.setMediaController(mc);
            mc.show();
            controllerCreated = true;
        }
        return true;
    } else {
        return false;
    }
}

A: Specifying videoView.setMediaController(null) is not necessary.
The problem is you cannot hide the controller till it fully prepared.
Use OnPreparedListener and in the callback onPrepared do your hide inderectly, like:
@Override
public void onPrepared (MediaPlayer mp)
{
    int childs = mediaController.getChildCount();
    for (int i = 0; i < childs; i++)
    {
        View child = mediaController.getChildAt (i);
        child.setVisibility (View.GONE);
    }
}

A: Unfortunately, this is hardcoded behavior in VideoView:
...
if (mTargetState == STATE_PLAYING) {
    start();
    if (mMediaController != null) {
        mMediaController.show();
    }
...

As a workaround, wrap the MediaController in your own class and suppress the initial show() call, like this:
package pkg.your;

import android.content.Context;
import android.widget.MediaController;

public class MyMediaController extends MediaController {

    private boolean suppressed = true;

    public MyMediaController(Context context) {
        super(context);
    }

    @Override
    public void show(int timeout) {
        if (! suppressed) {
            super.show(timeout);
        }
        suppressed = false;
    }
}

Then, simply hookup the MyMediaController above as usual, e.g.:
MyMediaController mc = mediaController = new MyMediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
videoView.setMediaController(mc);
....

Now, the controls are initially hidden, and they show up as expected when the user taps the screen.


text:
Q: Refactoring a header location function Should this function be:
check_login_session()
{
   if (!isset[$_SESSION['user_auth']) )
   {
      header('Location: login.php');
   }
   else
   {
      #  check against database here?
      return $_SESSION['user_auth'];
   }
}

Or, should a header be send out after the function has been called:
check_login_session()
{
   if (!isset[$_SESSION['user_auth']) )
   {
      return false;
   }
   else
   {
      #  check against database here?
      return $_SESSION['user_auth'];
   }
}

so, when it is called:
if (check_login_session === false)
{
   header('Location: login.php');
}

I know the code does essentially the same thing, but what is the most 'proper way' to refactor this?

A: The second approach seems more correct and flexible.
If what is $_SESSION['user_auth'] returns false, you would have to check the response anyway.
Renaming the function to something more like is_logged_in may be more readable, and understandable as to what the function does/returns.

A: I would use the second approach. Generally speaking functions should be something of a black box... you supply arguments and they return a value or modify something by reference, or if they are a method of an object they might modify that objects state or the state of another object. IF you need to take action based on the return value or modified object/argument then that should be done in the main control logic. There are obviously exceptions but this is a general rule for me.
If it were the case that you needed to send additional specific headers and so you wanted to encapsulate that in a function then that would be fine but i would say separate that from the logic checking if its an authenticated session.


text:
Q: XSLT - Preserving disable-output-escaping in a copy-of I seem to be having an issue preserving the disable-output-escaping when using that value inside of an xsl:copy-of.
Here's my code:
<xsl:call-template name="Display">
    <xsl:with-param name="text">
        <xsl:value-of select="content" disable-output-escaping="yes" />
    </xsl:with-param>
</xsl:call-template>

<xsl:template name="Display">
    <xsl:param name="text" />
    <xsl:copy-of select="$text" />
</xsl:template>

Any special characters that were kept as-is from the xsl:value-of statement are escaped when they're used in the xsl:copy-of statement.
For example:
<xsl:value-of select="$text" disable-output-escaping="yes"> will display this: è
<xsl:copy-of select="$text"> will display &#232
I'd like to know if there is any way around this?

A: As per Spec, the disable-output-escaping attribute can be specified only on <xsl:value-of> and the <xsl:text> instructions.
You need the DOE only on the xslt instruction that actually outputs the value, not on one that sets a parameter value.
Solution:
Replace:
<xsl:copy-of select="$text"/>

with:
<xsl:value-of select="$text"  disable-output-escaping="yes"/>

Do note: Typically one should avoid using DOE, as it breaks the XSLT architectural model and usually isn't needed. Also, the DOE feature isn't mandatory and not all XSLT 1.0 processors support it.
Note 2: You don't actually need DOE in your case at all. The output from the XSLT transformation should be displayed by the browser as expected.

A: disable-output-escaping controls the action of the serializer when handed a text node. It's meaningless when the text node isn't being handed to a serializer, for example when it is added to a temporary tree.


text:
Q: Angular Forms: Submit Button with HostListener on 'click' I have a reactive Angular form in which I am using a button of type="submit" in order to submit the form context.
Now I want to make further actions by adding a directive to the button. In the directive I am using using @HostListener('click']) to do some stuff...
My current problem is that the HostListener prevents the form-submit-event from being propergated to the form.
How do can I force the HostListener to propergate the submit event to the form?


text:
Q: Diferencia al agregar método Cual es la diferencia entre crear un método de un objeto con el prototipo y sin él?, tengo entendido que al crearlo con el prototipo, sus instancias heredan sus métodos y propiedades, entonces por eso sí puedo usar la función limpiar y la agregar no.
Entonces para que me serviría una función que no estuviese en el prototipo del constructor?

function Metodologia(){
  this.metodo = "Paso número 1";
}

Metodologia.prototype.limpiar = function()
{ this.metodo = "Paso número 2" };

Metodologia.agregar = function()
{ this.metodo = "Paso número PI" };

var i = new Metodologia();

console.log(i.metodo);
i.limpiar();
console.log(i.metodo);
// i.agregar(); <- Causará error

A: Lo que haces con el metodo agregar esta relacionado a una practica llamada Memoization o cache de metodos.
Cuando utilizas el operador new la instancia que es retornada solo tiene acceso a los objetos definido en el mismo con this y a la cadena del prototipo prototype.
Ahora bien cuando haces:
Metodologia.agregar = function() {
  this.metodo = "Paso número PI"
};

No estas definiendo el metodo agregar() ni al objeto en si y ni al prototype sino que lo estas agregando(attaching) a la definicion del objeto Metodologia.
Para poder acceder al metodo agregar, tendras que utilizar la notacion de puntos y enviarle la referencia del objeto Metodologia para que pueda acceder a las propiedades del objeto:

function Metodologia(){
  this.metodo = "Paso número 1";
}

Metodologia.prototype.limpiar = function()
{ this.metodo = "Paso número 2" };

Metodologia.agregar = function(metodologia){
 console.log(metodologia.metodo);
};

var i = new Metodologia();

console.log(i.metodo);
i.limpiar();
console.log(i.metodo);
Metodologia.agregar(i);

Digamos que el metodo agregar es "equivalente" al static de los lenguajes orientados a objetos: no estan presentes en el objeto, pero si en la definicion de la clase.


text:
Q: Show tags out of the loop Well I have a script that was just tab contains header information when clicked down that appears.
I put it into my code comes first, the group was shown as well as the subGroup ...
I see the code
Including ul tag that is located outside the loop
and also Including li and a tag that is located inside the loop
So far Right.
But I have

 tag which must be put out of
 tags that subgroup Show but can not?

  <?php
$sql="select * from category";
$stmt=$db->prepare($sql);
$stmt->execute();
echo '
';
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){
    $id=$result['id'];
    $name=$result['name'];

$sql2="select * from sub where catid='".$id."' ";
$stmt2=$db->prepare($sql2);
$stmt2->execute();
$num=$stmt2->rowCount();

echo '
 '.$name.'
';
echo '
';

while($result2=$stmt2->fetch(PDO::FETCH_ASSOC)){

$id2=$result2['id'];
$name2=$result2['name'];
echo ''.$name2.'';
}
}
echo '
';
echo '
';
?>

Also html my code

shop

shop1

    info shop1

    info shop2


text:
Q: iOS Did URL Schemes has default value when i haven't define the url schemes? I know i should call below function to check if app installed :
[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"customURLSchemes://"]]

However, i made an application long time ago but have not define "URL Schemes", and now i would like to make another app and check if user has installed my app, i tried
[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"app://myAppName"]]
[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"app://com.company.appid"]]
[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"myAppName://"]]
[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"com.company.appid://"]]

and above all returned FALSE, how can i check my app installed ?

A: If your old app doesn't have an explicit custom URL scheme then there is no way to check if the app is installed.
Submit an update to the app and specify an URL scheme.

A: You can't. iOS apps are sandboxed. You can't raise some sort of periscope and look outside your sandbox; that would be a violation of security / privacy.


text:
Q: QueryOver use Projections.Concat on GroupBy (NHibernate 3.3.5) I'm trying to implement a bit complicated sql in QueryOver of NHibernate (3.3.5 version) that would be parsed in SQL Server as:
SELECT
    CASE WHEN LTR_ReciboCompania IS NULL
        THEN CAST(LTR_Id AS VARCHAR(255))
        ELSE LTR_ReciboCompania + '#' + LTR_NumPoliza
    END
FROM LotesRecibos
GROUP BY
    CASE WHEN LTR_ReciboCompania IS NULL
        THEN CAST(LTR_Id AS VARCHAR(255))
        ELSE LTR_ReciboCompania + '#' + LTR_NumPoliza
    END

I've tried a lot of combinations with Projections.Concat() and Projections.SqlFunction("concat", ...) without success.
Sample 1
var concatProjection = Projections.SqlFunction("concat", NHibernateUtil.AnsiString,
            Projections.Property<LoteRecibo>(x => x.ReciboCompania), Projections.Constant("#"), Projections.Property<LoteRecibo>(x => x.NumPoliza));

var groupBy = Projections.Conditional(Restrictions.IsNull(Projections.Property<LoteRecibo>(p => p.ReciboCompania)),
            Projections.Cast(NHibernateUtil.String, Projections.Property<LoteRecibo>(p => p.Id)),
            concatProjection);

var result = sessionScope.Session.QueryOver<LoteRecibo>()
    .Where(r => r.CreationDate.Value.YearPart() == 2021)
        .Select(Projections.GroupProperty(groupBy))
    .List<object[]>();

In that case, the generated query only generates a parameter for the separator in Select but not in Group By:
exec sp_executesql N'SELECT (case when this_.LTR_ReciboCompania is null then cast( this_.LTR_Id as NVARCHAR(255)) else (this_.LTR_ReciboCompania+@p0+this_.LTR_NumPoliza) end) as y0_ FROM LotesRecibos this_ WHERE datepart(year, this_.LTR_FC) = @p1 GROUP BY (case when this_.LTR_ReciboCompania is null then cast( this_.LTR_Id as NVARCHAR(255)) else (this_.LTR_ReciboCompania+?+this_.LTR_NumPoliza) end)',N'@p0 nvarchar(4000),@p1 int',@p0=N'#',@p1=2021

And more readable:
SELECT (
        CASE
            WHEN this_.LTR_ReciboCompania IS NULL
                THEN cast(this_.LTR_Id AS NVARCHAR(255))
            ELSE (this_.LTR_ReciboCompania + '#' + this_.LTR_NumPoliza)
            END
        ) AS y0_
FROM LotesRecibos this_
WHERE datepart(year, this_.LTR_FC) = 2021
GROUP BY (
        CASE
            WHEN this_.LTR_ReciboCompania IS NULL
                THEN cast(this_.LTR_Id AS NVARCHAR(255))
            ELSE (this_.LTR_ReciboCompania + ? + this_.LTR_NumPoliza)
            END
        )

var result = sessionScope.Session.QueryOver<LoteRecibo>()
    .Where(r => r.CreationDate.Value.YearPart() == 2022)
    .SelectList(list => list
        .SelectGroup(p => Projections.Concat(p.CodReciboCompania, "#", p.NumPoliza))
    )
    .List<object[]>();

Sample 2 (simplified without conditional)
var result = sessionScope.Session.QueryOver<LoteRecibo>()
    .Where(r => r.CreationDate.Value.YearPart() == 2022)
    .SelectList(list => list
        .SelectGroup(p => Projections.Concat(p.CodReciboCompania, "#", p.NumPoliza))
    )
    .List<object[]>();

It throws the following exception:
An unhandled exception of type 'System.Exception' occurred in NHibernate.dll
Unrecognised method call in expression Concat(new [] {p.CodReciboCompania, "#", p.NumPoliza})

But if I set in Select (not in SelectGroup) it works. And I can't understand how to set the Concat function in the group by part of the query.
I should use QueryOver, because we connect to SQL Server and Oracle DB Servers.

UPDATE (Workaround)
While I don't found a better solution, I'll use the first sample without the constant separator. Really I don't need to separate both fields, in my real query I only use the field to group.
var concatProjection = Projections.SqlFunction("concat", NHibernateUtil.AnsiString,
            Projections.Property<LoteRecibo>(x => x.ReciboCompania), Projections.Property<LoteRecibo>(x => x.NumPoliza));

var groupBy = Projections.Conditional(Restrictions.IsNull(Projections.Property<LoteRecibo>(p => p.ReciboCompania)),
            Projections.Cast(NHibernateUtil.String, Projections.Property<LoteRecibo>(p => p.Id)),
            concatProjection);

var result = sessionScope.Session.QueryOver<LoteRecibo>()
    .Where(r => r.CreationDate.Value.YearPart() == 2021)
        .Select(Projections.GroupProperty(groupBy))
    .List<object[]>();


text:
Q: windows, c++: send file to exe (c++ solution) and read data from sent file My goal is to send an arbitrary text file to a exe which is a build of a c++ project. In the c++ project I would like to read the file which was sent to the exe. Hence, I think I need to pass the path of the sent file to the application (exe).
My c++ code [is working!]:
#include "stdafx.h"
#include <string.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
  std::string readLineFromInput;

  ifstream readFile("input.txt"); // This is explizit.
                                  // What I need is a dependency of passed path.
  getline(readFile, readLineFromInput);

  ofstream newFile;
  newFile.open("output.txt");
  newFile << readLineFromInput << "\n";

  newFile.close();
  readFile.close();
}

My Windows configuration:
In the following path I created a shortcut to the exe (build of c++ project):
C:\Users{User}\AppData\Roaming\Microsoft\Windows\SendTo
Question:
I want to right click to an arbitrary text file and pass it (SendTo) to the exe. How can I pass the path of the sent file as an argument to the application such that the application can read the sent file?
When the path is passed as an argument the line of code should be like this, I guess:
ifstream readFile(argv[1]);

Much thanks!
David

A: Whether you use SendTo or OpenWith, the clicked filename will be passed to your executable as a command-line parameter.  As such, the argv[] array will contain the filename (at argv[1], unless your SendTo shortcut specifies additional command-line parameters, in which case you would have to adjust the argv[] index accordingly).
I just did a test with SendTo and argv[1] works fine.  Just make sure you check argc before attempting to open the filename, eg:
int _tmain(int argc, _TCHAR* argv[])
{
  if (argc > 1)
  {
    std::string readLineFromInput;

    std::ifstream readFile(argv[1]);
    if (readFile)
      std::getline(readFile, readLineFromInput);

    std::ofstream newFile(_T("output.txt"));
    if (newFile)
        newFile << readLineFromInput << "\n";
  }
}


text:
Q: ConnectionID in HSQL I'm looking for the id of the connection in hsqldb.
In oracle I use : SELECT Userenv('SESSIONID') from DUAL
In MySql I use : SELECT CONNECTION_ID()
In HSQL ?

A: In HSQLDB 2.x, session is the same as the connection. You can use:
CALL SESSION_ID()

When Oracle syntax compatibility mode is used, you can also use:
SELECT SESSION_ID() FROM DUAL

And in MySql syntax compatibility mode:
SELECT SESSION_ID()

See the list of related functions here:
http://hsqldb.org/doc/2.0/guide/builtinfunctions-chapt.html#builtin_functions_sysfunc-sect


text:
Q: Does fileprivate Extensions and Types in Swift improve compile time? If I keep my extension and private Types very confined inside one single Swift file because I will only ever need it inside that one file, will it improve compiler time and/or performance? Or is the Swift compiler so intelligent and doesn't matter at all?
Example:
One iOS Xcode project with over 600 Swift files (moderately huge project) with an already existing network class:
NetworkController.swift
class NetworkController {
    let queue = OperationQueue()

    func add(_ op: Operation) {
        queue.addOperation(op)
    }
}

Now I need to add a new class which only does a legacy operation. Which means that all the other components in the iOS app will never ever need it.
LegacyController.swift (everything put into same file)
internal final class LegacyController {
    let network = NetworkController()

    func start() {
        network.requestSomeLegacyStuff {
            print("blub")
        }
        // do lots of other work here ...
    }
}

extension NetworkController {
    fileprivate func requestSomeLegacyStuff(success: () -> Void) {
        let operation = RequestLegacyDataOperation()

        add(operation)
    }
}

fileprivate final class RequestLegacyDataOperation: Operation {
    // do lots of work here ...
}

VERSUS put them into their own files for better visibility and separation, but would then need to change to internal scope, which is not needed at all.
LegacyController.swift
internal final class LegacyController {
    let network = NetworkController()

    func start() {
        network.requestSomeLegacyStuff {
            print("blub")
        }
        // do lots of other work here ...
    }
}

NetworkController+LegacyStuff.swift
extension NetworkController {
    internal func requestSomeLegacyStuff(success: () -> Void) {
        let operation = RequestLegacyDataOperation()

        add(operation)
    }
}

RequestLegacyDataOperation.swift
internal final class RequestLegacyDataOperation: Operation {
    // do lots of work here ...
}


text:
Q: TODAY() function with specified time I need to get a date/time that represents the current day at 6:15 AM. The TODAY() function takes care of the date, but I can't figure out how to append the time constraint to that.
Usage will be in the form of:
IF(SOMEDATE <= TODAY@6:15AM, DoSomething(), DoSomethingElse())

A: Because Dates in Excel are whole number and times are decimals based on the 24 hour cycle being 1 we can add the two together to get a number by which we can compare.
=TODAY() + TIME(6,15,0)

This will create a number equal to today at 6:15 this morning.
So incorporating that into your pseudo formula we get:
IF(SOMDATE <= TODAY() + TIME(6,15,0),...)


text:
Q: ASP.NET MVC Session variables become null through HTML.Action ChildAction I'm developing a simple test website using ASP.NET MVC3 and Razor syntax. It has _LayoutPage.cshtml as master template which uses @HTML.Action to print user id at the top of the site for each page.
I implemented a childAction named userInfo for this partial view which reads the user id from HTTPContext.Session and prints it out. The child action is implemented in a controller called CommonActionController derived from Controller. In addition to user id it also reads two more variables from session and prints it.
public class CommonActionController: Controller
{

    [ChildActionOnly]
    public ActionResult userInfo()
    {

        if(HTTPContext.Session["x-user-id"] != null)
        {
            ViewBag.UserId = (string)(HTTPContext.Session["x-user-id"]);
            ViewBag.UserFirstName = (string)(HTTPContext.Session["x-user-first-name"]);
            ViewBag.UserLastName = (string)(HTTPContext.Session["x-user-last-name"]);
            ViewBag.UserLoggedinSince = (DateTime)(HTTPContext.Session["x-user-logon-timestamp"]).ToString("f");
        }

        return PartialView();
    }
}

My main page controller called HomeController has the dashboard functionality implemented in Dashboard action (currently it just prints the word "Dashboard"). In this controller I have overridden Controller.OnActionExecuting() method which validates that the user id exists in session. It reads total three variables from session just like the aforementioned childAction.
public class HomeController: Controller
{

    public HomeController()
    {

    }

    protected override void OnActionExecuting(ActionExecutingContext ctx)
    {

        base.OnActionExecuting(ctx);

        if(HTTPContext.Session["x-user-id"] == null)
            ctx.Result = new RedirectResult("logon/userlogon");

        if(HTTPContext.Session["x-user-logon-timestamp"] == null)
            ctx.Result = new RedirectResult("logon/userlogon");

        if(HTTPContext.Session["x-user-internal-flag"] == null)
            ctx.Result = new RedirectResult("logon/userlogon");

    }

    public ActionResult Dashboard()
    {
        // nothing to see here
        return View();
    }

}

I have cleaned up the code little bit to remove the debug.print statements.
As per the logs I see that the OnActionExecuting() method and userInfo child action are invoked simultaneously. At one point OnActionExecuting() gets nulls for session variables. In the log I can see that until the point ChildAction is invoked, session variables hold their value within OnActionExecuting(). Once the childaction accesses them, they become null.
When I comment the code that accesses session from child action, everything works fine. What am I doing wrong? Is there some precaution I have to take while accessing session variables? Is this due to my ignorance about how to access Session asynchronously?
I also have following in my web.config:
<modules runAllManagedModulesForAllRequests="true"/>

A: 1) Start–> Administrative Tools –> Services
2) right click over the ASP.NET State Service and click "start"
*additionally you could set the service to automatic so that it will work after a reboot.
For more details you can check my blog post: http://jamshidhashimi.com/2011/03/16/unable-to-make-the-session-state-request-to-the-session-state-server/
ref:
Unable to make the session state request to the session state server


text:
Q: Dynamic navbar for mobile I'm doing a mobile App with jQuery mobile 1.4.3. I'm trying to build a navigation bar that  changes dynamically, If the user has logged in the navigation bar will show 4 options, if not it will show 3 options. The problems:

*

*Once I click the bar some times it turns all blue.

*I'm sure I'm not using the correct code.

*The navigation bar disappears for some time when I click in a button.

*The blue click highlight is not persistent for the page click.

What I need is a fixed navigation bar that smoothly changes pages when clicked :)
http://jsfiddle.net/claire89/toxtcbhe/14/
var statusLogin = null;
$(document).on('pagecontainershow', function (e, ui) {
    var myNavbar = null;
    if (statusLogin == null) {

        myNavbar = $('

Menu

Sugestions

History

Settings

');
        $('.ui-content').append(myNavbar).trigger('create');
    } else {
        myNavbar = $('

Menu

History

Settings

').appendTo('.ui-content');
        $('.content').append(myNavbar).trigger('create');
    }

    $("[data-role='navbar']").navbar();
    $("[data-role='header'], [data-role='footer']").toolbar();

    var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
    var activePageId = activePage[0].id;
    switch (activePageId) {
        case 'listMenuPage':
            alert("listMenuPage");
            break;
        case 'sugestionsPage':
            alert("sugestionsPage");
            break;
        case 'settingsPage':
            alert("settingsPage");
            break;
        case 'historyPage':
            alert("historyPage");
            break;
        default:
    }
});

A: footer div should be a direct child of page div, you should not place it inside content div. Moreover, you need to .remove() footer or navbar once you leave a page before you inject a new one. Otherwise, you will end up adding duplicating both footer and navbar in same page whenever the same page is shown.
Another note, when you inject toolbar dynamically, you need to reset the height of active page $.mobile.resetActivePageHeight() as toolbars adds padding to page, if height isn't reset, the page will scroll.
For better results, use pagecontainerbeforeshow to inject footer and navbar, and pagecontainerhide to remove them.
var statusLogin = null;

$(document).on('pagecontainerbeforeshow', function (e, ui) {
   /* ui.toPage was introduced in 1.4.3
    * can be used instead of "getActivePage"
    * on pagecontainer events
    */
   var activePage = $(ui.toPage),
       activePageId = activePage[0].id,
       myNavbar = "";

   if (statusLogin == null) {
       myNavbar = $('<tags></tags>');
       activePage.append(myNavbar);

   } else {

       myNavbar = $('<tags></tags>');
       activePage.append(myNavbar);
   }

   /* create footer and navbar
    * add active class to button based on page's ID
    */
    $("[data-role='footer']")
        .toolbar()
        .find("a[href=#" + activePageId + "]")
        .addClass("ui-btn-active");
   /* reset height of active page */
   $.mobile.resetActivePageHeight();

}).on("pagecontainerhide", function (e, ui) {
   /* remove footer once page is hidden */
   $(".ui-footer", ui.prevPage).remove();
});

Demo


text:
Q: Memory allocation in Oracle VirtualBox I have installed Oracle VirtualBox in my laptop that has 1 GB of RAM.
In VirtualBox, I have created two virtual machines with 4 GB of RAM.
So my question is: How is it possible to allocate amount of RAM that my laptop, i.e. host system, does not have, and also running applications which uses entire memory space in each of VMs.
Please help me to understand this concept.

A: TL;dr; Paging (aka swap).
Longer answer:
Ignore the VM part for a bit. I can start a normal process and map more memory than a really have. The OS will grant me the requested (large) space in the virtual address space. When it lacks the physical memory to back that up it will page data to the swap partition.
If I can do that with any program I can also do that with a virtual machine emulator, or with a hyper visor.
Note that performance wise this might not be a good idea. However I do not see a reason why it would not work.


text:
Q: Why view functions require a request parameter In Django? Example from Django documentation:
def index(request):
    return HttpResponse('
hellworld!
')

def detail(request, question_id):
    return HttpResponse("Question: %s" % question_id)

Since the request argument is never used, why should I include it in each function signature?

A: The purpose of a web server is to reply to HTTP requests (In simple terms). Django being a web framework generates responses depending on the request that it receives.
The business logic of handling the requests is done by Django Views, it is their purpose. This is why Django supplies the request to the view function, so the code can access the request data and choose what actions it should take and which response it should send back (even though that specific view doesn't make use of it).
The decision of requiring the view to receive the request as an argument is an implementation decision made by Django developers, making it part of the interface the view has with the rest of the "system". Other frameworks might choose making it available globally and not suplying it to the views/controllers directly, but the merits of one or another approach is other discussion.

A: Many of the examples in Django's documentation (and any documentation, really) are necessarily contrived. They're simple because the complexity of a real example would take away from the point that's being made.
In real use cases, you'll frequently want access to the request object. You may want to know which User is attached to the request (request.user) or whether the request is a GET or a POST (request.method).
You can also inspect the headers (request.headers), decode the JSON object sent with a POST request (json.loads(request.body)), etc.

A: Those are just examples. In real world a programmer would want to find request GET arguments, decode JSON POST body, inspect headers, get user or session data, etc.


text:
Q: How to create custom panel without framing via Python in Nuke? Could you tell me how to create custom panel in NUKE having no spacing (i.e. frameless window)?
At the moment it looks like this:

But I need it to look like this:

A: This is happening because the panel has several nested widgets each adding their own margin, so you'll need to iterate through the parent widgets and setContentsMargins on each.
"""
Get rid of the margins surrounding custom Panels
"""

import nuke
import PySide.QtCore as QtCore
import PySide.QtGui as QtGui
from nukescripts import panels

def set_widget_margins_to_zero(widget_object):

    if widget_object:
        target_widgets = set()
        target_widgets.add(widget_object.parentWidget().parentWidget())
        target_widgets.add(widget_object.parentWidget().parentWidget().parentWidget().parentWidget())

        for widget_layout in target_widgets:
            try:
                widget_layout.layout().setContentsMargins(0, 0, 0, 0)
            except:
                pass

class Example_Window(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        layout = QtGui.QVBoxLayout()
        label = QtGui.QLabel('Margins be-gone!')
        label.setStyleSheet('QLabel{background: #eeffcc}')

        layout.setContentsMargins(0,0,0,0)
        layout.addWidget(label)
        self.setLayout(layout)

        expandingPolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                            QtGui.QSizePolicy.Expanding)
        label.setSizePolicy(expandingPolicy)
        self.setSizePolicy(expandingPolicy)

    def event(self, event):
        if event.type() == QtCore.QEvent.Type.Show:

            try:
                set_widget_margins_to_zero(self)
            except:
                pass

        return QtGui.QWidget.event(self, event)

panels.registerWidgetAsPanel('Example_Window', 'Example Widget',
                             'mwbp.Example_Widget')

to give credit where it's due, I found the solution a while ago here : https://gist.github.com/maty974/4739917 and have posted an integrated example widget.

A: The only way to make a panel that I know via Python is this (but it's with frame):
class myCustomPanel( nukescripts.PythonPanel ):

    def __init__( self ):

        nukescripts.PythonPanel.__init__( self, 'myCustomPanel' )
        self.update = nuke.PyScript_Knob( 'update', 'Update Info' )
        self.info = nuke.Multiline_Eval_String_Knob( 'info', 'Info' )
        self.info.setEnabled( True )
        self.addKnob( self.update )
        self.addKnob( self.info )

def addInfoPanel():

    global iPanel
    iPanel = myCustomPanel()
    return iPanel.addToPane()

paneMenu = nuke.menu( 'Pane' )
paneMenu.addCommand( 'myCustomPanel', addInfoPanel )


text:
Q: Converting dataframe to TimeSeries in Python is giving Invalid type of `time_col` error I am writing Python code in Kaggle. The csv file has 8 columns in which column 0 is 'date' and column1 is 'stringency_index'
    series = pd.read_csv("<csv path>",
                         na_values=['nan','?'], parse_dates = ['date'])
    series1 = series.iloc[:, [0,1]]
    series1

Some of the rows of series1 are:
    date        stringency_index

0   2020-01-29      2.78

1   2020-01-30      2.78

2   2020-01-31      2.78

3   2020-01-02      2.78

4   2020-02-02      2.78

... ... ...

716 2022-01-14      58.33

717 2022-01-15      58.33

718 2022-01-16      58.33

719 2022-01-17      NaN

720     2022-01-18      NaN

Then, I convert series1 to TimeSeries as follows
series1 = TimeSeries.from_dataframe(series1, 'stringency_index')

I have already imported TimeSeries from darts. I am getting the following error
AttributeError: Invalid type of `time_col`: it needs to be of either 'str', 'datetime' or 'int' dtype.

How can I fix this error?

A: Referring to the API doc, the first argument is the DataFrame, the second argument is the name of the time column, and the third is the name(s) of the value column(s). From the shape of your data, it looks like you should call
TimeSeries.from_dataframe(series1, time_col='date', value_cols='stringency_index')

A: To call the method correctly, if you have datetime index already set in pandas dataframe, you should use the positional value_cols parameter and skip time_col altogether.
Something like this:
time_series = TimeSeries.from_dataframe(series1, value_cols = 'stringency_index')
Otherwise it will assign stringency_index to time_col and inevitably fail because it's neither a datetime value, nor datetime index


text:
Q: Не работает php на LAMP Установил LAMP на ubuntu 14.04. Все встало хорошо. "Привет, мир!" выводит спокойно. Но когда ставлю сайт, подключаю к бд, то выводит такое.
Помогите пожалуйста, а то уже второй день сижу с этим.

A: Добрый день.
Скорей всего у Вас отключено использование коротких тегов "<?".
Проверьте, какие теги используются в файлах php сайта.
И, или включите поддержку коротких тегов или исправьте "<?" на "<?php"


text:
Q: Strip // Comments From Files What's the best way to strip all code comments in a given directory?  I'd like to strip out all // ... EOL comments, and /* blah \*/ (or /** ... \*/) comments as well.
This is a PHP project, and I'd like to go a little further than what is outlined below, yet for security purposes rather than efficiency.

*

*Zend Frameword: Documentation Class Loading - Strip require_once calls with find and set.

A: A quick google search returns a similar question at stackoverflow.

A: This will do it in Perl:
//will delete all comments starting at the beginning of the line with //
perl -p -i -e "s#^//.*$##" <your php file>
//will delete all comments starting somewhere in a line with //
perl -p -i -e "s#^(.*)//.*$#\$1#" <your php file>
//will delete all comments starting somewhere in a line with /* or /**
perl -p -i -e "s#^(.*)/\*+.*$#\$1#" <your php file>
//will delete all comments starting at the beginning of the line with /* or /**
perl -p -i -e "s#^/\*+.*$##" <your php file>

These commands will not delete comments with multiple lines, like
/**
 *
 *
 */

It is possible to do this, but multi line regex are way more difficult.
There will also be solutions for awk, sed, python, ... But this should also do it.


text:
Q: iOS app hangs forever when going to "CS50" or "CS50 Meta" When I go to the "CS50" or "CS50 Meta" sites (which can be reached from the left drawer → More Sites), the app hangs forever.

I'm forced to kill the app. No good.
Version: Stack Exchange iOS App Version 1.0.0, 1.0.1.70

A: Fixed in the next build.  There was a problem in some code that used to run in a background thread that said filter and if there's not enough results load the next page of results.  This of course spun forever if that was the last page of results.
I was halfway through fixing those problems when I saw a FIXME saying I could just nuke that whole block.


text:
Q: sql squery writing Here I wanted to run the same query on multiple databases using a while loop.

*

*I created a table with the name '@database' and added the names of the database that I want to traverse through in  it

*used while loop to traverse through databases names to run that particular query in each database

It didn't work.(it's running twice for the database which has been selected on the left dropdown of SQL management studio )
Tables in both databases are the same.
DECLARE @database TABLE (id INT,name varchar(50))

insert into @database values (1, 'Databse_one'), (2, 'Database_two')

DECLARE @cnt INT =2, @int INT=1,@dbname NVARCHAR(MAX)

while(@int <=@cnt)

 begin

select @dbname='use '+name from @database
where id=@int

EXEC sp_sqlexec @dbname
select top 10 db_name() DB_NAME, req_number, record Type,order_date from ORDER_DOCUMENT order by order_date desc

set @int = @int+1

end

A: It wouldn't work like that even after you corrected the typos you already have. After use dbName, it would require a GO or be that in a different batch on the same connection. Instead you could write that as:
DECLARE @database TABLE(id INT, name VARCHAR(50));
INSERT INTO @database VALUES(1, 'Databse_one'), (2, 'Database_two');
DECLARE @cnt INT=2, @int INT=1, @dbname NVARCHAR(MAX);
WHILE(@int<=@cnt)BEGIN
    SELECT @dbname=name FROM @database WHERE id=@int;
    DECLARE @sql NVARCHAR(MAX);
    SET @sql=N'select top(10) '''+@dbname+N''',req_number, record Type,order_date from '+QUOTENAME(@dbname)+N'.dbo.ORDER_DOCUMENT order by order_date desc;';
    EXEC sys.sp_executesql @stmt=@sql;
    SET @int=@int+1;
END;

A: USE doesn't work here, because the dynamic batch is a different scope. You would need to put the whole SELECT into the dynamic SQL.
But you don't need a WHILE at all. Just create one big UNION ALL query and run it.
DECLARE @database TABLE(name sysname);
INSERT INTO @database(name) VALUES(1, );

DECLARE @sql nvarchar(max);

SELECT @sql = 'SELECT *
FROM (
' + STRING_AGG(CAST('
    SELECT TOP (10)
      ' + QUOTENAME(d.name, '''') + ' DB_NAME,
      req_number,
      record Type,
      order_date
    FROM ' + + QUOTENAME(d.name) + '..ORDER_DOCUMENT
    ORDER BY
      order_date DESC
'  AS nvarchar(max)), '
') + '
);
'

FROM sys.databases d
WHERE d.name IN ('Databse_one', 'Database_two');

EXEC sp_executesql @sql;

Alternatively if you want separate SELECT statements then remove the UNION ALL
DECLARE @database TABLE(name sysname);
INSERT INTO @database(name) VALUES(1, );

DECLARE @sql nvarchar(max);

SELECT @sql = STRING_AGG(CAST('
SELECT TOP (10)
  ' + QUOTENAME(d.name, '''') + ' DB_NAME,
  req_number,
  record Type,
  order_date
FROM ' + + QUOTENAME(d.name) + '..ORDER_DOCUMENT
ORDER BY
  order_date DESC;
'  AS nvarchar(max)), '
')

FROM sys.databases d
WHERE d.name IN ('Databse_one', 'Database_two');

EXEC sp_executesql @sql;


text:
Q: Socketpair() in C/Unix I have 2 applications on the same system that I need to communicate back and forth. From my research I believe this is called Inter Process Communication and the use of socketpair() is the best method for my problem.
I am tearing my hair out (literally) trying to get started with creating sockets with socketpair() in C. From what I understand, sockets are a very complex topic and me being a novice C programmer is surely not helping the situation.
I googled for the last 48 hours, read tutorials, etc, but I still can't get it. I understand the concept, but the code is just too confusing. I've read this article a few times: http://beej.us/guide/bgnet/html/single/bgnet.html, but it's not simple enough.
Can someone provide some example (so simple a 5th grader could understand) or point me to a good tutorial?

A: socketpair creates an anonymous pair of sockets, usually unix/local sockets, which are only useful for communication between a parent and child process or in other cases where the processes that need to use them can inherit the file descriptors from a common ancestor.
If you're going to do communication between unrelated (in the sense of parentage) processes, you need to use socket, bind, and connect to create a listening socket in one process and create a client socket to connect to it in the other process.

A: You can use socketpair only where you create both processes, like so:

*

*call socketpair - now you have two socket file descriptors (two ends of a single pipe)

*

*nominate one end to be the parent and one to be the child end. It doesn't matter which, just make a choice and stick to it later

*call fork - now you have two processes

*

*if fork returned zero, you are the child. Close the parent file descriptor, keep the child descriptor, and use it as this process's end of the pipe

*if fork returned non-zero, you are the parent.  Close the child file descriptor, keep the parent one and use it as your end of the pipe

*you now have two processes, each has one file descriptor representing different ends of the same pipe. Note that both processes are running the same program, but they followed a different branch after calling fork. If parent calls write on its socket, child will be able to read that data from its socket, and vice-versa

Here is a straight translation into code:
void child(int socket) {
    const char hello[] = "hello parent, I am child";
    write(socket, hello, sizeof(hello)); /* NB. this includes nul */
    /* go forth and do childish things with this end of the pipe */
}

void parent(int socket) {
    /* do parental things with this end, like reading the child's message */
    char buf[1024];
    int n = read(socket, buf, sizeof(buf));
    printf("parent received '%.*s'\n", n, buf);
}

void socketfork() {
    int fd[2];
    static const int parentsocket = 0;
    static const int childsocket = 1;
    pid_t pid;

    /* 1. call socketpair ... */
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fd);

    /* 2. call fork ... */
    pid = fork();
    if (pid == 0) { /* 2.1 if fork returned zero, you are the child */
        close(fd[parentsocket]); /* Close the parent file descriptor */
        child(fd[childsocket]);
    } else { /* 2.2 ... you are the parent */
        close(fd[childsocket]); /* Close the child file descriptor */
        parent(fd[parentsocket]);
    }
    exit(0); /* do everything in the parent and child functions */
}

Please note that this is just sample code: I've left out all error-checking and a sensible stream protocol.

If you want two separate programs to communicate (eg. you have an executable called client, and one called server), you can't use this mechanism. Instead, you might:

*

*use UNIX sockets (where an IPC pipe on one host is identified by a filename - this only works if client and server run on the same machine)

*or use TCP/IP sockets (where an IP address and port identify the pipe, and the client and server can be on different machines)

If you don't specifically need sockets, and you're happy to require that client and server run on the same machine, you can also use shared memory, or message queues.

A: For communicating between two processes, yes, Inter Process Communication or IPC is what you should look for.
Sockets are just one of the methods for communicating and is useful if you have to implement one-to-many connection. Means, one server process which communicates with many client processes in a request-response fashion. As you are a newbie to IPC, it is understandable that socket addresses and the details involved might look difficult to grasp. (Though you will find them easy in due time :-))
For your problem, I suggest you use simpler IPC mechanisms like Pipe, FIFO, Message Queue.
I am not sure how you came to the conclusion to use socketpair. Since you have not mentioned anything around the design or kind of IPC you need AND bassed on usage level I strongly recommend to look into Pipe or FIFO sample codes in some book or internet. They should look way easier to implement and work faster than sockets.

A: Use TCP/IP.   While there are other IPC mechanisms available (such as Unix domain sockets and SYSV IPC) you're better off with TCP/IP for many reasons.  Here are some:

*

*There are lots of tutorials and other information on the web describing how to do TCP/IP

*Modern systems, and especially Linux and *BSD, impose no significant penalty for using TCP/IP compared to, say, Unix domain sockets or even SYSV IPC.

*There are a number of libraries and frameworks that you may be able to make use of for applications communicating over TCP/IP.

The only case where I would not use TCP/IP to communicate between two "programs" is for the case where they are really threads rather than separate programs.


text:
Q: Is there any way to interface html with RCP(E4) application using Javascript? I have html application with javascript api and I want to communicate and control RCP application via this javascript. What is the best approach to deal with such case.
HTML -> Javascript -> .... -> RCP (E4) application
More details added
Here I have an RCP calculator application. Where User Interface and the Logic (Background function) is implemented. Now the usecase is that user want to have Logic(background function) to be exposed to outside so that the HTML can be use javascript to make call to the logic (Background function).
One problem is that the RCP application is already created and I dont want too much change to the RCP application. Rather just expose the functionality to be called from javascript.
One option I figured out is that I can have
HTML >> Javascript >> webserive call   <<->> webservice >> RCP application.

A: Finally I resolved the problem with following approach:
HTML - Javascript   <===>  Java server (with Jetty/Jackson)
Client side:

*

*I made JQuery (ajax) call from the javascript to localhost:port

*Javascript objects converted to JSON before
making ajax calls. (If you need dynamic data from server while using
GET you can turn on the cache off).

Server side:
 listening to the port.

*

*I used Jetty (servlet embedded within the RCP application). Hence no apache configuration required.

*I used jackson (Jax-rs) to convert the JSON objects to java object and did the needed processing in RCP application.


text:
Q: Direct to specific part of page on load in LWC I have a community page name 'global-device' which has a LWC component and it has a child LWC.
parentLWC.html
<template>
....

    <template if:true={showChild}>
      <c-child-lwc para1={para1value}></c-child-lwc>
     </template>

</template>

Now, when I land on this page, URL looks like this:
s/global-device?linkId=5&mypageid=5003M000001fMQHQA2#notifpage
I am using #notifpage to direct to notifpage section of the page when the page loads. Page gets loaded as expected but does not get directed to this section.
In the connectedcallback method of parentLWC, I am making a server call to set value of showchild and para1value, but I think this should not have any affect on the issue.

A: LWCs load and render asynchronously, yet the # fragment identifier is applied at the time the page is loaded. Thus the named anchor with the fragment identifier you have used doesn't exist at the appropriate time and the browser cannot scroll to it.
You would need to have code that waits for the page's loading (including the LWC rendering) to complete and then apply some code that finds and "scrolls to" the named element.

A: As mentioned by @Phil, I am now using renderedCallback method to check if the URL has fragment identifier #notifpage and then move to that section using scrollIntoView.
ParentLWC.html
<template>
....

    <template if:true={showChild}>
      <c-child-lwc para1={para1value}></c-child-lwc>
     </template>

</template>

'parentLWC.js'
renderedCallback(){
  if(location.href.includes('#notifpage') ){
    var elmnt = this.template.querySelector('.notifpage');
    elmnt.scrollIntoView();
  }
}


text:
Q: Using browser cache of chrome, IE and Mozilla for multi page forms I want to my cache my webpage in all browsers. After browsing in stack overflow lot of sites suggested to put headers like below:
    response.setHeader("Cache-Control","public");
    response.setHeader("Pragma","public");
    response.setDateHeader ("Expires", System.currentTimeMillis() + 604800000L);

Even after setting that i am not able to cache my web pages. when i hit back all the values in the textboxes disappears. But in Mozilla values are not disappearing. please suggest how to cache web pages in all web browsers or any reference example.


text:
Q: Displaying TabularData in Windows Forms C Sharp Currently In Windows Form C Sharp we have data grid View for displaying tabular.
Now supposing you wanted to create a summary of your data as below. In a Table.
Think of a HTML Table summary as a example. But in this case you are doing it on a Windows Form Interface.

Name
Amount

Name 1
2500

Name 2
4500

Total
6500

Then display this in windows form. Currently I don't know of any control in Windows Form that can achieve this.


text:
Q: What data issue can cause "AmbiguousBaseClassException: Multiple classes found in type hierarchy that map to [...]"? Apparently out of the blue, my Springboot/Neo4j application started getting this exception upon startup (around the first time Neo is accessed):
AmbiguousBaseClassException: Multiple classes found in type hierarchy that map to [Audit, AppInfo]
After trying various things unsuccessfully, in desperation I dumped the database
(with MATCH (n) DETACH DELETE n)
then restarted.
Suddenly it was working again.  In other words, this error was not due (solely) to code, but to rather to data.
It's as if the "type hierarchy" that is being referred to is something that's being read out of the database, and I seem to have been able to "break it".
Now I'm worried that I can have this pop up out of the blue, at a time when I won't be able to just dump the data.
So how can I work out what causes this, and what less sledgehammer approach would resolve it?
Edit:  I had not originally pasted the specifics of the structure involved, because I had hoped that this was a "class" of problem that could be described, defended against, and diagnosed, without reference to my instance of it.  Maybe this is naive.
Here are the two classes named in the error message:
definition
queries
Edit 2:  The problem recurred today, with a different pair.
stack trace
newly affected node class

A: Here is another question with what may be the same issue. In that particular question, all Actor and Director nodes in the DB also have the Person label. And the developer had mimicked that dual-label situation by implementing Actor and Director classes that subclassed a Person class. As a result, when PersonRepository.findActorsOfMovie() is invoked, the OGM library does not know whether to return a Set of Person instances or Actor instances. A similar issue exists with PersonRepository.findDirectorOfMovie(). Other methods may not have a similar issue, leading to failures that may appear intermittent (but are actually due to different methods being used for different use cases).
You may have similar issues with your class hierarchy (with respect to your specific DB data model). If so, your OGM method signatures should probably never use the relevant base class.

A: Thanks for all the help.   The accepted answer is correct, but some details, and a different "cause" are laid out in case someone else struggles with it as I did...
What it is:
Described in Java/spring-data-neo4j terms, this situation does indeed arise when nodes from two "classes" end up with "properties" that have the same name.
How it can happen:
This can (apparently) happen if you have two classes with the same Property name, as described in the accepted answer.
But it also it can happen if you continue to use (in Java) a node that has been deleted.
The deleted node is like a pointer to memory that has been freed - if you continue to use it after that, the results are undefined.   And can result in properties from the deleted node being written onto other nodes in the post-deletion save.
How to find the culprit:
It seems you will get a pair of classes from the error message.   All you have to do is find the instances from one class that have a property from the other.
In the Neo web browser, I found this as easy as clicking on properties from the class with the least properties, causing it to run the "show me instances that have this property" query.
I didn't have to trawl through every result in the output, because the app kindly lists at the top of the results the number and type of nodes with this property.   So all you are doing is looking for one a query that results in more than one type of node, and the culprit is in there.

A: I had the same issue re stale data. Upgraded ogm lib from 3.0.X to 3.2.1 and the issue went away.


text:
Q: boost msm submachine current_state for accessing sub state any idea how, using boost msm 1_60, I can get the current_state(s) of a submachine? Consider the following code, describing an outer state machine that allows for chosing between two different traffic lights (standard red, yellow, green one and another with alternating two yellow lights for instance):
class SMBigMom : public msmf::state_machine_def<SMBigMom>
{
public:
SMBigMom() {};

using initial_state = SMSelectorState;

class SMLightBase : public msmf::state_machine_def<SMLightBase>
{
public:
    SMLightBase() {};

    using initial_state = BaseState;
    struct transition_table : mpl::vector<> {};
};
using SMBaseBackend = msm::back::state_machine<SMLightBase>;

class SMCommonRYG : public SMLightBase
{
public:
    SMCommonRYG() = default;
    ~SMCommonRYG() {};

    using initial_state = Red; // init state

    struct transition_table : mpl::vector<
        //         Start, Event, Target, Action, Guard
        msmf::Row< Red, evNext, RedYellow, msmf::none, msmf::none >,
        msmf::Row< RedYellow, evNext, Green, msmf::none, msmf::none >,
        msmf::Row< Green, evNext, Yellow, msmf::none, msmf::none >,
        msmf::Row< Yellow, evNext, Red, msmf::none, msmf::none >
    > {};
};
using SMCommonRYGBackend = msm::back::state_machine<SMCommonRYG>;

class SMYellowAlternate : public SMLightBase
{
public:
    SMYellowAlternate() = default;
    ~SMYellowAlternate() {};

    using initial_state = Yellow; // init state

    struct transition_table : mpl::vector<
        //         Start, Event, Target, Action, Guard
        msmf::Row< Yellow, evNext, Yellow2, msmf::none, msmf::none >,
        msmf::Row< Yellow2, evNext, Yellow, msmf::none, msmf::none >
    > {};
};
using SMYellowAlternateBackend = msm::back::state_machine<SMYellowAlternate>;

struct transition_table : mpl::vector<
    msmf::Row< SMSelectorState, evSelectCommonRYG, SMCommonRYGBackend, msmf::none, msmf::none >,
    msmf::Row< SMSelectorState, evSelectYellowAlternate, SMYellowAlternateBackend, msmf::none, msmf::none >
> {};

};
using SMBackend = msm::back::state_machine<SMBigMom>;

Now, I can skip into the RYG via
SMBackend oSM. oSM.process_event(evSelectCommonRYG());

But how can I get the current state of the RYG submachine?
oSM.current_state()[0]

returns 1 only (as this is the state of the outer state machine BigMom...)...
Thanks for help!

A: I figured it out meanwhile, the solution is rather simple. Just, using the functor front end, add an action (4th column in a ROW) function which is called like this:
struct submachineAction
{
  toNext() {};
  ~toNext() {};
  template<class TFsm, class TEvent, class TStateIn, class TStateOut>
  void operator() (const TEvent& p_rEV, const TFsm& p_rFSM, TStateIn&   p_rStateIn, TStateOut& p_rStateOut)
  {
    std::cout << "Substate: " << p_rFSM.current_state()[0] << std::endl;
  }
};

If you have several "master" machines running and need to know which one called the submachineAction, you can define, for instance, a base front end class with an additional identifier (string, int, you name it) and derive the submachines from that class. Then, following this thread, you can set the identifier, which can be accessed via p_rFSM in the above functor: How to Pass data to the current boost meta state machine(MSM) substate
Hope this helps someone else sometime.


text:
Q: Expectation of the exponential of the sum of Brownian motion and the time it spent above certain threshold Let $(B_t)_{t\geq 0}$ be a standard Brownian motion and $c\in\mathbb{R}$ be a constant. Calculate the following expectation:
$$\mathbb{E}\left[\exp\left\{-\int_0^t\mathbb{1}_{\{B_u>c\}}du-\frac{1}{2}t+B_t\right\}\right].$$
Observe that $e^{-\frac{1}{2}t+B_t}$ is a martingale, however, due to the dependence with the term $\int_0^t\mathbb{1}_{\{B_u>c\}}du$ (which is the time of B spent above the barrier $c$), we cannot directly take the advantage of the martingale property. Moreover, the expectation of $\mathbb{E}\left[\exp\left\{-\int_0^t\mathbb{1}_{\{B_u>c\}}du\right\}\right]$ is explicit and is given by formula 1.4.3 Borodin and Salminen.


text:
Q: Understanding numpy.where I want to get first index of numpy array element which is greater than some specific element of that same array. I tried following:
>>> Q5=[[1,2,3],[4,5,6]]
>>> Q5 = np.array(Q5)
>>> Q5[0][Q5>Q5[0,0]]
array([2, 3])
>>> np.where(Q5[0]>Q5[0,0])
(array([1, 2], dtype=int32),)
>>> np.where(Q5[0]>Q5[0,0])[0][0]
1

Q1. Is above correct way to obtain first index of an element in Q5[0] greater than Q5[0,0]?
I am more concerned with np.where(Q5[0]>Q5[0,0]) returning tuple (array([1, 2], dtype=int32),) and hence requiring me to double index [0][0] at the end of np.where(Q5[0]>Q5[0,0])[0][0].
Q2. Why this return tuple, but below returns proper numpy array?
>>> np.where(Q5[0]>Q5[0,0],Q5[0],-1)
array([-1,  2,  3])

So that I can index directly:
>>> np.where(Q5[0]>Q5[0,0],Q5[0],-1)[1]
2

A: Using argmax with a boolean array will give you the index of the first True.
In [54]: q
Out[54]:
array([[1, 2, 3],
       [4, 5, 6]])

In [55]: q > q[0,0]
Out[55]:
array([[False,  True,  True],
       [ True,  True,  True]], dtype=bool)

argmax can take an axis/dimension argument.
In [56]: np.argmax(q > q[0,0], 0)
Out[56]: array([1, 0, 0], dtype=int64)

That says the first True is index one for column zero and index zero for columns one and two.
In [57]: np.argmax(q > q[0,0], 1)
Out[57]: array([1, 0], dtype=int64)

That says the first True is index one for row zero and index zero for row one.

Q1. Is above correct way to obtain first index of an element in Q5[0] greater than Q5[0,0]?

No I would use argmax with 1 for the axis argument then select the first item from that result.

Q2. Why this return tuple

You told it to return -1 for False values and return Q5[0] items for True values.

Q2 ...but below returns proper numpy array?

You got lucky and chose the correct index.

A: In [58]: A = np.arange(1,10).reshape(3,3)
In [59]: A.shape
Out[59]: (3, 3)
In [60]: A
Out[60]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

np.where with just the condition is really np.nonzero.
Generate a boolean array:
In [63]: A==6
Out[63]:
array([[False, False, False],
       [False, False,  True],
       [False, False, False]])

Find where that is true:
In [64]: np.nonzero(A==6)
Out[64]: (array([1]), array([2]))

The result is a tuple, one element per dimension of the condition.  Each element is an indexing array, together they define the location of the True(s)
Another test with several True
In [65]: (A%3)==1
Out[65]:
array([[ True, False, False],
       [ True, False, False],
       [ True, False, False]])
In [66]: np.nonzero((A%3)==1)
Out[66]: (array([0, 1, 2]), array([0, 0, 0]))

Using the tuple to index the original array:
In [67]: A[np.nonzero((A%3)==1)]
Out[67]: array([1, 4, 7])

Using the 3 argument where to create a new array with a mix of values from A and A+10
In [68]: np.where((A%3)==1,A+10, A)
Out[68]:
array([[11,  2,  3],
       [14,  5,  6],
       [17,  8,  9]])

If the condition has multiple True, nonzero isn't the test tool for finding the "first", since it necessarily finds all.
The nonzero tuple can be turned into a 2d array with a transpose.  It actually may be easier to get the "first" from this array:
In [73]: np.argwhere((A%3)==1)
Out[73]:
array([[0, 0],
       [1, 0],
       [2, 0]])

You are looking in a 1d array, a row of A:
In [77]: A[0]>A[0,0]
Out[77]: array([False,  True,  True])
In [78]: np.nonzero(A[0]>A[0,0])
Out[78]: (array([1, 2]),)            # 1 element tuple
In [79]: np.argwhere(A[0]>A[0,0])
Out[79]:
array([[1],
       [2]])
In [81]: np.where(A[0]>A[0,0], 100, 0)     # 3 argument where
Out[81]: array([  0, 100, 100])

So whether you are searching a 1d array or a 2d (or 3 or 4), nonzero returns a tuple with one array element per dimension.  That way it can always be used to index a like sized array.  The 1d tuple might look redundant, but it is consistent with other dimensional results.
When trying understand operations like this, read the docs carefully, and look at individual steps.  Here I look at the conditional matrix, the nonzero result, and its various uses.

A: numpy.where() is like a for loop with an if.
numpy.where(condition, values, new_value)

condition - just like if conditions.
values - The values to iterate on
new_value - if the condition is true for a value, its going to change to the new_value

If we would like to write it for a 1-dimensional array it should look something like this:
[xv if c else yv for c, xv, yv in zip(condition, x, y)]

Example:
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.where(a < 5, a, 10*a)
array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])

First we create an array with numbers from 0 to 9 (0, 1, 2 ... 7, 8, 9)
and then we are checking for all the values in the array that are greater from 5 and multiplying their value by 10.
So now all the values in the array that are less then 5 stayed the same and all the values that are greater multiplied by 10


text:
Q: Wasserstein Loss is very sensitive to model architecture I am working on a class project where I compare the performance of GAN and WGAN. Since the only difference between GAN and WGAN is the Wasserstein loss, I chose one neural network model architecture and trained both GAN and WGAN (so, only the loss functions differ).
However, WGAN performs much worse than GAN, and I'm not sure why. Is the performance of Wasserstein loss model dependent? If had to compare GAN and WGAN, holding the NN architecture fixed, what architecture should I choose?

A: Usually, the same architecture and parameters would not be good for training both GAN and WGAN.
In a typical GAN, you want to avoid making the discriminator more powerful than the generator, and you want to avoid training the discriminator so much that it "overpowers" the generator and always finds the fakes.
In WGAN, you want to make the discriminator as powerful as possible, possibly by giving it a larger network, and you also want to train it for as long as computationally feasible -- several iterations for every one iteration the generator trains. The theory behind WGAN requires that the discriminator has converged to the optimal discriminating function, so this is important.
If for some reason, you really need to fix one architecture, choose one where the generator is about the same size as the discriminator, and then make sure when you're training the WGAN that you really train the discriminator a lot -- maybe 10x more than the generator.

A: Try to substitute gradient clipping with gradient penalty in WGAN, if you haven't done so yet. The important thing is that you should NOT use batch normalization in WGAN discriminator, as it breaks the whole idea. The authors of the WGAN paper suggest to use layer norm.


text:
Q: (Solution) - Ubuntu 20.04 - Incorrect Display Settings EDIT: I've successfully managed to correct the issue. More details in the end of the post.
Whenever I install Ubuntu 18.04 or higher (currently at 20.04), my display settings get messed up. Most notably, the screen as a whole gets very blurry.
I took some pics to demonstrate what exactly this problem is. Sorry for the quality, but the prints would not show the issue. Links below:
Grub examples:

Ubuntu Menu examples:

From what I found during some searches, it appears to be caused by an incorrect pixel format setup. But I have no idea on how to change it.
SOLUTION: I've followed some simple steps described at a post from TecDicas. All translated below:
1) Type sudo nano /etc/default/grub to edit the grub file.
2) Localize the line that says GRUB_CMDLINE_LINUX_DEFAULT.
3) Just after quiet-splash, add amdgpu.dc=0 and save the file.
4) Run sudo update-grub to apply the changes. Then, reboot the system.
Done!


text:
Q: Couldn't Redirecti page after form action submit to node server.(react front) I'm currently building a web with react, and in this app I'm also building a register functionality, since the user is mainly going to type Chinese in the input tag, I use a form action to submit the form instead of using onChange property in each input (as far as I know, React community haven't found a proper way to deal with the onChange bug when typing Chinese).
And the main problem is that since I'm using the form action to submit the form data, I couldn't get response from the server, and that cause me unable to authenticate and redirect the page.
I would like to know whether there is something wrong with my logic or how to solve this problem by code, thank you;.
I tried using "redirect" in the backend, it works partially, by partially I mean that I couldn't receive response in the front end because I used a form action to submit instead of fetch or axios, so that I don't know how to authenticate in this case.
Front End using React
<form action='http://localhost:8000/' method='post'>
.....</form>

Back End Using Node with Express
db.collection('memberProfiles').insertOne(userModel)
.then(response => {res.redirect('http://localhost:3000/memberProfile').send('token');})
                .catch(err => res.send('Page ERROR'));
client.close();


text:
Q: Border-radius circle loses shape when scaling at different browser zoom levels I have a small circle at 4px and I want to scale its size using anime.js. It works great at 100% zoom (default), but I also want it to behave the same at default zooms from 50-100%.
Example fiddle: https://jsfiddle.net/6x4ry3no/1/
As seen in the example fiddle, if you 'CMD' + '-' or equivalent on Windows to zoom out, you will notice the circle becomes a rounded quadrilateral at other zoom levels between 50-100%, which is undesirable.
It seems to be loosely related to the divisibility of the zoom percentage by the width/height as at some percentages it seems to be fine.
Ideally I'd just use an SVG to avoid this but, as far as I'm aware, scaling SVGs also requires a transform to keep the shape in the same place which I'd like to avoid.
Any ideas?

A: None of the tricks I tried worked to preserve the roundness of the circle when zoomed out—super weird.  However, if I replace the div in your fiddle with the an SVG (and remove the border-radius and bg-color from CSS), things do seem to work correctly:

#circle {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 4px;
  height: 4px;
}
<svg viewBox="0 0 100 100" id="circle">
  <circle cx="50" cy="50" r="40" fill="red" />
</svg>


text:
Q: how to save sql value in some variable in jenkinfile pipeline I am creating a jenkins pipeline where I want to execute a sql script then store that value to some variable as below
String value = sql sql: "SELECT * FROM jobs WHERE id = ?", parameters: [1]

Getting a error at above point java.lang.NoSuchMethodError: No such DSL method 'sql' found among steps [ArtifactoryGradleB
then use that value to build
build job: 'build_Test', parameters: [validatingString(name: 'version', value: '$value'), string(name: 'TASK', value: 'build')]

Is this a correct way to do it?

A: Yes, that looks correct. You should remove the single quotes surrounding the variable and use double quotes instead, or just use the variable name.
build job: 'build_Test', parameters: [validatingString(name: 'version', value: "$value"), string(name: 'TASK', value: 'build')]


text:
Q: dataloader does not return correct target tensor I am writing custom dataset but the dataloader does not return correct target tensors.
where the label is 010 I am getting 10.
I am converting the labels into int before converting to tensor.
  y_label = torch.tensor(int(self.annotations.iloc[index, 1]))

iterating through dataloader:
Batch idx 0, data shape torch.Size([1, 1, 56, 128, 128]), target shape torch.Size([1])
tensor([1])
Batch idx 1, data shape torch.Size([1, 1, 56, 128, 128]), target shape torch.Size([1])
tensor([100])
Batch idx 2, data shape torch.Size([1, 1, 56, 128, 128]), target shape torch.Size([1])
tensor([10])
Batch idx 3, data shape torch.Size([1, 1, 56, 128, 128]), target shape torch.Size([1])
tensor([1])

csv file looks like the following:
1 p0.npy, 100
2 pl.npy, 001
3 p2.npy, 001
4 p3.npy, 001
5 p4.npy, 100
6 p5.npy, 010
7 p6.npy, 100
8 p7.npy, 100
9 p8.npy, 100
10 p9.npy, 010
11 plO.npy, 010
12 pll.npy, 010
13 p12.npy, 010
14 p13.npy, 100

code:
class patientdataset(Dataset):

    def __init__(self, csv_file, root_dir, transform=None):

            self.annotations = pd.read_csv(csv_file)
            self.root_dir = root_dir
            self.transform = transform

    def __len__(self):
        return len(self.annotations)

    def __getitem__(self, index):

        img_path = os.path.join(self.root_dir, self.annotations.iloc[index,0])
        # np_load_old = np.load
        # np.load = lambda *a, **k: np_load_old(*a, allow_pickle=True, **k)

        image= np.array(np.load(img_path))

        # y_label = torch.tensor(np.asarray(self.annotations.iloc[index,1]))

        y_label = torch.tensor(int(self.annotations.iloc[index, 1]))

        if self.transform:
            imagearrays = self.transform(image)
            image = imagearrays[None, :, :, :]
            imaget = np.transpose(image, (0, 2, 1, 3))
            image = imaget

        return (image, y_label)

A: It seems your labels are in binary form.
Convert them into decimal and then into tensor should do the trick for you.
y_label = torch.tensor(int(self.annotations.iloc[index, 1], 2))

doing so will convert 010 into 2, 100 into 4 and so on.


text:
Q: How to use User Input in python discord.py Disord Bot Discord.py User Input for rock, paper, scissors game.
I would like to create a Discord Bot that is able to play rock, paper, scissors. I think that the basic code of the game isn't complicated but the discord.py implementation is hard for me.
The Problem is probably this line of code player = await bot.wait_for('message'). I have read the discord.py docs, but it doesn't seem to work correctly.
This is my Code:
@bot.command(pass_context=True, aliases=['g', 'ga', 'gam'])
@commands.guild_only()
async def game(ctx):
    await ctx.send(
        'Hallo, wie gehts denn so ' + ctx.message.author.mention + '? Lust auf eine Runde Schere, Stein, Papier?')

    wins = 0
    losses = 0
    ties = 0

    while True:
        await ctx.send('%s Siege, %s Niederlagen, %s Unentschieden \n' % (wins, losses, ties))
        while True:
            await ctx.send('Auf was setzt du? (s)tein, (p)apier, (sc)here oder (q)uit')
            player = await bot.wait_for('message')
            print(str(player))
            if player == 'q':
                return
            if player == 's' or player == 'p' or player == 'sc':
                break
            await ctx.send('Schreib s, p, sc oder q!')

        if player == 's':
            await ctx.send('Stein gegen...')
        elif player == 'p':
            await ctx.send('Papier gegen...')
        elif player == 'sc':
            await ctx.send('Schere gegen...')

        randomnum = random.randint(1, 3)
        if randomnum == 1:
            computer = 's'
            await ctx.send('Stein!')
        elif randomnum == 2:
            computer = 'p'
            await ctx.send('Papier!')
        elif randomnum == 3:
            computer = 'sc'
            await ctx.send('Schere!')

        if player == computer:
            await ctx.send('Unentschieden!')
            ties = ties + 1
        elif player == 's' and computer == 'sc':
            await ctx.send('Du gewinnst!')
            wins = wins + 1
        elif player == 's' and computer == 'p':
            await ctx.send('Ich habe gewonnen!')
            losses = losses + 1
        elif player == 'p' and computer == 's':
            await ctx.send('Du gewinnst!')
            wins = wins + 1
        elif player == 'p' and computer == 'sc':
            losses = losses + 1
            await ctx.send('Ich habe gewonnen!')
        elif player == 'sc' and computer == 'p':
            await ctx.send('Du gewinnst!')
            wins = wins + 1
        elif player == 'sc' and computer == 's':
            await ctx.send('Ich habe gewonnen!')
            losses = losses + 1

A: You may want to write a check so that it knows who the author is.
def check(author):
    def inner_check(message):
        return message.author == author
    return inner_check

Then you would pass the inner_check to wait_for by calling the outer_check with the appropriate argument:
playerChoice = await bot.wait_for('message', check=check(context.author), timeout=30)

A: I found a solution. Just change the player variable to player.content an it should work.
if player.content ==

Thanks for the effort!


text:
Q: tiles game . I can't act I am trying to make 8-tiles problem in prolog but my code is not
running .
To be more specific when I type an action then I take false.
move([0, Y, Z], [Y, 0, Z], right).
move([X, 0, Z], [0, X, Z], left).
move([X, 0, Z], [X, Z, 0], right).
move([X, Y, 0], [X, 0, Y], left).

arc_horiz([X, Y, Z], [X1, Y, Z], Direction) :- move(X, X1, Direction).
arc_horiz([X, Y, Z], [X, Y1, Z], Direction) :- move(Y, Y1, Direction).
arc_horiz([X, Y, Z], [X, Y, Z1], Direction) :- move(Z, Z1, Direction).

switch([[X1, Y1, Z1], [X2, Y2, Z2], [X3, Y3, Z3]], [[X1, X2 , X3], [Y1, Y2 , Y3], [Z1, Z2, Z3]]).

arc_vert(RowState1, RowState2, up) :- switch(RowState1, ColState1),
                                      arc_horiz(ColState1, ColState2, left),
                                      switch(RowState2, ColState2).
arc_vert(RowState1, RowState2, down) :- switch(RowState1, ColState1),
                                        arc_horiz(ColState1, ColState2, right),
                                        switch(RowState2, ColState2).

arc(State1, State2,left) :- arc_horiz(State1, State2, left).
arc(State1, State2,up)   :- arc_vert(State1, State2, up).
arc(State1, State2,right):- arc_horiz(State1, State2, right).
arc(State1, State2,down) :- arc_vert(State1, State2, down).

search([[1,2,3],[8,0,4],[7,6,5]]) :- write('Goal'),nl,nl.

search(X) :- writeln('Actions : left, right, up, down'),
            read(Action),
            arc(X,State2,Action),
            write(State2),
            search(State2).

start :-
           INITIAL = start([[2, 8, 3], [1, 6, 4], [7, 0, 5]]),
           writeln(INITIAL),
           assert(INITIAL),
           search(INITIAL).

For example
1?- start.
start([[2,8,3],[1,6,4],[7,0,5]])
Actions : left, right, up, down
|: left.
false.

Thanks a lot in advance


text:
Q: Create waf rule if environment is nonprod Terraform I'm trying to create an IP whitelist in nonprod for load testing, the WAF is dynamically created in prod and nonprod based on the envname/envtype:
resource "aws_waf_ipset" "pwa_cloudfront_ip_restricted" {
  name = "${var.envname}-pwa-cloudfront-whitelist"
  dynamic "ip_set_descriptors" {
    for_each = var.cloudfront_ip_restricted_waf_cidr_whitelist
    content {
      type  = ip_set_descriptors.value.type
      value = ip_set_descriptors.value.value
    }
  }
}

resource "aws_waf_rule" "pwa_cloudfront_ip_restricted" {
  depends_on  = [aws_waf_ipset.pwa_cloudfront_ip_restricted]
  name        = "${var.envname}-pwa-cloudfront-whitelist"
  metric_name = "${var.envname}PWACloudfrontWhitelist"

  predicates {
    data_id = aws_waf_ipset.pwa_cloudfront_ip_restricted.id
    negated = false
    type    = "IPMatch"
  }
}

resource "aws_waf_ipset" "pwa_cloudfront_ip_restricted_load_testing" {
  name  = "${var.envname}-pwa-cloudfront-whitelist_load_testing"
  count = var.envtype == "nonprod" ? 1 : 0
  dynamic "ip_set_descriptors" {
    for_each = var.cloudfront_ip_restricted_waf_cidr_whitelist_load_testing
    content {
      type  = ip_set_descriptors.value.type
      value = ip_set_descriptors.value.value
    }
  }
}

resource "aws_waf_rule" "pwa_cloudfront_ip_restricted_load_testing" {
  depends_on  = [aws_waf_ipset.pwa_cloudfront_ip_restricted_load_testing]
  count = var.envtype == "nonprod" ? 1 : 0
  name        = "${var.envname}-pwa-cloudfront-whitelist-load_testing"
  metric_name = "${var.envname}PWACloudfrontWhitelistload_testing"

  predicates {
    data_id = aws_waf_ipset.pwa_cloudfront_ip_restricted_load_testing[count.index].id
    negated = false
    type    = "IPMatch"
  }
}

resource "aws_waf_web_acl" "pwa_cloudfront_ip_restricted" {
  name        = "${var.envname}-pwa-cloudfront-whitelist"
  metric_name = "${var.envname}PWACloudfrontWhitelist"

  default_action {
    type = "BLOCK"
  }

  rules {
    action {
      type = "ALLOW"
    }

    priority = 1
    rule_id  = aws_waf_rule.pwa_cloudfront_ip_restricted.id
    type     = "REGULAR"
  }

    rules {
    action {
      type = "ALLOW"
    }

    priority = 2
    rule_id  = aws_waf_rule.pwa_cloudfront_ip_restricted_load_testing.id
    type     = "REGULAR"
  }
}

The second rules block throws and error in the terraform plan:
Error: Missing resource instance key

  on waf.tf line 73, in resource "aws_waf_web_acl" "pwa_cloudfront_ip_restricted":
  73:     rule_id  = aws_waf_rule.pwa_cloudfront_ip_restricted_load_testing.id

Because aws_waf_rule.pwa_cloudfront_ip_restricted_load_testing has "count" set,
its attributes must be accessed on specific instances.

For example, to correlate with indices of a referring resource, use:
    aws_waf_rule.pwa_cloudfront_ip_restricted_load_testing[count.index]

However if I add [count.index] :
Error: Reference to "count" in non-counted context

  on waf.tf line 73, in resource "aws_waf_web_acl" "pwa_cloudfront_ip_restricted":
  73:     rule_id  = aws_waf_rule.pwa_cloudfront_ip_restricted_load_testing[count.index].id

The "count" object can only be used in "module", "resource", and "data"
blocks, and only when the "count" argument is set.

Is there a way to do this that doesn't use the count param? Or am I missing something in the way that I am using it?

A: Since there is difference between the prod and non-prod environment, the way this should be tackled is by using dynamic [1] and for_each meta-argument [2]:
resource "aws_waf_web_acl" "pwa_cloudfront_ip_restricted" {
  name        = "${var.envname}-pwa-cloudfront-whitelist"
  metric_name = "${var.envname}PWACloudfrontWhitelist"

  default_action {
    type = "BLOCK"
  }

  dynamic "rules" {
    for_each = var.envtype == "nonprod" ? [1] : []
    content {
      action {
        type = "ALLOW"
     }
      priority = 1
      rule_id  = aws_waf_rule.pwa_cloudfront_ip_restricted[0].id
      type     = "REGULAR"
    }
  }

  dynamic "rules" {
    for_each = var.envtype == "nonprod" ? [1] : []
    content {
      action {
        type = "ALLOW"
      }
      priority = 2
      rule_id  = aws_waf_rule.pwa_cloudfront_ip_restricted_load_testing[0].id
      type     = "REGULAR"
    }
  }
}

[1] https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks
[2] https://developer.hashicorp.com/terraform/language/expressions/for


text:
Q: Do mathematicians have jobs in Star Wars? I'm an aspiring Mathematician i.e. a pure/applied math major with a minor in comp sci and econ.  I'm sure you star-wars fans (at least I do) fantasize what it would be like if I existed in the Star-Wars Universe.  Usually I imagine being someone else, i.e. I imagine being a jedi, sith or bounty hunter.
But this time I considered what if I existed in the Star Wars Universe and I was me, an aspiring mathematician.  Do mathematicians even exist in Star Wars?  I'm under the impression all technical jobs in Star Wars are interested solely in Technology (Engineering) and Hacking (Comp. Sci).

A: Funny that you should ask this now, I just finished reading X-Wing: Mercy Kill which deals with a Mathematician feeling out of place.
A Gamorrean male named Voort "Piggy" saBinring is a professor of mathematics at a University on some planet.
"I'm a math instructor now. I take mathematical concepts, I shape them into spikes, and I spend months hammering them into the heads of students who's much rather be involved in amorous pursuits or playing games,..." So there are for sure professors and students of mathematics.
So there is a need for living professors rather than just having droids do the teaching, "'A teacher droid can do everything you're doing for your students...' 'A droid can't instill into them a love for mathematics'". Chapter 2 page 30ish.
As for real world job applications for mathematicians, especially with minors in comp sci., I believe there would be even more opportunities, not less.  Don't underestimate the practical applications of Mathematics. I'm a computer Engineer, so not that different from your educational background, and I see math EVERYWHERE. There's not a day that goes by where I don't use calculus, or at least some form of math, in technical designs. We often use mathematicians as consultants for some of the more complex problems. IMO in a world full of starships, droids, and battle stations, mathematicians would never be out of the job.
There are also countless examples of scientists/mathematicians in many SW video games. They usually design advanced technologies however.
As a side note, Engineers often work side by side with mathematicians and other scientists in the real world.

A: Mathematitians definitely have their place in Star Wars galaxy - ironically, in capacities similar to today's earth.

*

*The biggest single employer for mathematicians today is No Such Agency National Security Agency.
It employs mathematicians - to put it in layman crude terms - as code makers and code breakers.
In Star Wars, the same exact thing happens in canon: the new Disney canon book "Star Wars: Heir to the Jedi" has Drusil, a member of mathematically inclined Givin specis. The central plot revolves around Empire trying to get her to break Rebel Alliance codes, and Rebels trying to save her from Imperials to do the reverse.

*Other mathematically inclined people get snapped up by more of an applied side of things, to become quants for financial companies and build financial models.
In Star Wars, enter mathematically inclined Muuns, who were prominent in banking. They founded InterGalactic Banking Clan (source: AotC and CW) as well as served as a kind-of-Federal-Reseve, backing Galactic Credit (source: "Darth Plagueis" book, EU/Legends canon).

*Many statistically inclined mathematicians end up doing actuarial work, especially for insurance companies.
In Star Wars, we have no less than five known insurance companies. Makes sense, with all the risks.

*Besides, think of what would happen if Star Wars universe didn't have mathematicians? THIS:


text:
Q: In javascript, how do you change the value of a property whose type is "number"? typeof document.getElementById('foo').bar('value') //returns "number"

I want to change the 'value'.
console.log(document.getElementById('foo').bar('value')) // 10

I can't just the value to a number, it will rightfully throw an errror:
document.getElementById('foo').bar('value')) = 12 // ReferenceError: Invalid left-hand side in assignment
10 = 12 // ReferenceError: Invalid left-hand side in assignment

How would you set the value of bar?
This particular instance is for the slider offered by jquery, so the actual code (with me attempting to change its value looks like this:
$('#slider').slider.val(function (index, value) {
  return value + '' + deltaY + '%'})

However I'm returned a long error which is pasted here: https://gist.github.com/2e65bbf1578f7ea27bb0

"...}has no method 'val'"

A: If you want to set the value property of input elements, it always is a string (and will be converted to one when setting).
The invocation of the bar() method returns a value (not a "pointer"), and you cannot assign to that of course. What you need to do that the function returns a different result obviously depends heavily on that function.

The error you get comes from the expression $('#slider').slider.val... - $.fn.slider, the function you access here, has no property "val" (which you therefore cannot invoke). What are you trying to do there? Read the documentation for that slider plugin you use carefully.

A: Whatever this is:
$('#slider').slider

Has not method call val()
Therefore calling $('#slider').slider.val(...) is obviously not going to work.
Haven't tested it, but maybe slider should be a function that returns an object?
$('#slider').slider().val(...)

A: I think that the title and the first part of this question are a red herring.
I believe that you are trying to use the JQuery UI slider method? If so then do as Bergi suggests and read the docs. If I'm understanding your needs correctly then you should pay attention to the following found here:
 http://jqueryui.com/demos/slider/
under 'options' tab in the 'value' section:
Code examples
Initialize a slider with the value option specified.
$( ".selector" ).slider({ value: 37 });

Get or set the value option, after init.
//getter
var value = $( ".selector" ).slider( "option", "value" );
//setter
$( ".selector" ).slider( "option", "value", 37 );


text:
Q: Python regular expression doesn't match group when ORed with other expressions I've been trying to debug a strange problem with regular expressions.  I've reduced it down to a simple case here.  I'm checking a string for any of four regular expressions.  My string matches the regular expression but the grouping value in parenthesis that I'm trying to extract doesn't work with what I have coded up.  What I can't figure out is that if I just search for one expression both the entire string that i'm trying to match on and the value I want to extract are calculated correctly.  However, when I search using all four expressions the string still matches [group(0)] but I don't get the field that I need [group(1)].
#!/usr/bin/python3

import re

data = '<w:t xml:space="preserve">More </w:t>'

text = re.search("<w:p>|<w:p .*?>|<w:t>(.*?)</w:t>|<w:t .*?>(.*?)</w:t>", data)
print("First RE")
print("group(0) " + text.group(0))
try:
    print("group(1) " + text.group(1))
except:
    pass

print("Second RE")
text = re.search("<w:t .*?>(.*?)</w:t>", data)
print("group(0) " + text.group(0))
try:
    print("group(1) " + text.group(1))
except:
    pass

When I run it I get this result:
First RE
group(0) <w:t xml:space="preserve">More </w:t>
Second RE
group(0) <w:t xml:space="preserve">More </w:t>
group(1) More

I would expect both regular expressions to return the same results.  Could someone explain why they don't?  According to the documentation the OR "|" has a low precedence so i'm not why/if the other regular expressions are impacting it.  Thanks!

A: Your first regex has two capture groups in it and your second regex only has one. In your first regex your using or's so when it reches the expression with the first capture group, it doesnt match so this capture group is empty, your second capture group matches so the value is stored in your 2nd capture group.
So after the first regex runs the first capture group is empty and the second is populated.
import re

data = '<w:t xml:space="preserve">More </w:t>'
text = re.search("<w:p>|<w:p .*?>|<w:t>(.*?)</w:t>|<w:t .*?>(.*?)</w:t>", data)
print("First RE")
print(text.groups())
print("Second RE")
text = re.search("<w:t .*?>(.*?)</w:t>", data)
print(text.groups())

OUTPUT
First RE
(None, 'More ')
Second RE
('More ',)

So your issue is your only looking at the first capture group but in your first regex that capture group is empty. So when your inside the try block, your trying to concatenate "group(1) with the value from the first capture group. However you can only concat two strings and the type of your value in the first capture groups is None so this would trigger an exception TypeError: can only concatenate str (not "NoneType") to str which you then catch and ignore.
thats why you dont see the print.


text:
Q: Parsing unique values in a CSV where the primary key is not unique This seems pretty trivial. Generally, I'd do something like the following:
results = []
reader = csv.reader(open('file.csv'))
for line in reader:  # iterate over the lines in the csv
    if line[1] in ['XXX','YYY','ZZZ']:  # check if the 2nd element is one you're looking for
        results.append(line)    # if so, add this line the the results list

However, my data set isn't so simply formatted. It looks like the following:
Symbol,Values Date
XXX,8/2/2010
XXX,8/3/2010
XXX,8/4/2010
YYY,8/2/2010
YYY,8/3/2010
YYY,8/4/2010
ZZZ,8/2/2010
ZZZ,8/3/2010
ZZZ,8/4/2010

Essentially what I am trying to do is parse the first date for each unique Symbol in the list such that I end up with the following:
XXX,8/2/2010
YYY,8/2/2010
ZZZ,8/2/2010

A: Pandas may help. ;-)
import pandas
pandas.read_csv('file.csv').groupby('Symbol').first()

A: Here is a simple solution using a set of already found 1st element:
results = []
reader = csv.reader(open('file.csv'))
already_done = set()
for line in reader:  # iterate over the lines in the csv
    if line[1] in ['XXX','YYY','ZZZ'] and line[0] not in already_done:
        results.append(line)    # if so, add this line the the results list
        already_done.add(line[0])