text:
Q: Having localized pagination in DevExpress printpreview I'm trying to have a localized pagination in the footer of all my pages in my print preview. I set my paging this way :
var PageOfPages = "[Page # of Pages #]";
//On n'a pas vraiment le choix de faire ça pour que ça fonctionne dans les différentes langues... :
//http://www.devexpress.com/Support/Center/p/CQ48170.aspx
switch (CultureManager.GetInstance().TwoLetterISOCultureName)
{
  case "fr":
        PageOfPages = "[Page # de pages #]";
        break;
  case "es":
        PageOfPages = "[Página # de Páginas #]";
        break;
}
var PageHeaderArea = new PageHeaderArea();
PageHeaderArea.Content.AddRange(new[] { "", "", "[Image 0]" });
var HeaderFooter = (PageHeaderFooter)LinkBase.PageHeaderFooter;
   HeaderFooter = new PageHeaderFooter(
   PageHeaderArea,
   new PageFooterArea(new[] { dateString, "", PageOfPages }, SystemFonts.DefaultFont, BrickAlignment.Far)
);

It works in english, but not in french or spanish. Tried with XtraPrinting Resources dll too.

A: You should be able to use the designer itself and its localization process in order to handle this, alterations directly in the code shouldn't be necessary.
To access the localizations in the designer, you open the report in design mode, and from there one of the properties is Language.  Changing that will create new .resx files which contain the localized resource strings.  That should automatically import the correct resource file, based on the users "CurrentUICulture" System.Threading.Thread.CurrentThread.CurrentUICulture.  It all works automatically on my system.
This is assuming however that you have all the structures defined in the designer.  this wont work with code generated controls.
for those...you really want to handle it manually...
Inside the BeforePrint event you should be able to check the CurrentUICulture against whatever you are looking for, and alter the text of various controls accordingly.
If you dont want to do that during the reports runtime, but instead during the declaration itself, then your code should be working.  I would check to see that you are referencing the correct value in the switch statement.  You should be looking for the CurrentUICulture from the running thread.  I am unsure if CultureManager.GetInstance() will actually get you the correct value for that.
Update: Added code example
Use this value for the switch:
switch( System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOCultureName )
{
    ...
}

A: just use
using DevExpress.XtraPrinting.Localization
PreviewLocalizer.GetString(PreviewStringId.PageInfo_PageNumberOfTotal)

this should give you the correct format string for your set language.
--reinhard


text:
Q: How to determine the classpath of an annotated element in an annotation processor? I have the annotation @Foo and the corresponding FooProcessor. There I will need the location of the project root, which I could parse from the location of the class/java file, if I figured out how to get it.
Eg.
  ...
   public class FooProcessor extends AbstractProcessor{
       ...
       void processElement(Element e, Foo foo){
           File f = getClassFileOrWhatever(e.getEnclosingElement());
           File projectRoot = getProjectRoot(f);
           doSomething(projectRoot);
       }
       File getClassFileOrWhatever(Element e){
           ???
       }
       ...
    }

and in a different project which has a jar containing Foo annotation and it's processor:
/this/part/might/change/someproject/src/Foobar.java
public class Foobar{
    @Foo public void foobar(){}
}

=> I need FooProcessor::getProjectRoot to return "/this/part/might/change/someproject/" which is obviously trivial if I have "/this/part/might/change/someproject/src/Foobar.java" from FooProcessor::getClassFileOrWhatever.
It seems like new File(".") refers to my home dir when I compile the class with annotated method with Eclipse. I could walk the file tree from there and hope that the class file denoted by element.getEnclosingElement() is somewhere out there. This however seems a) very slow and b) error prone due to different compiling environments.

A: This did the trick:
 FooProcessor.class.getProtectionDomain().getCodeSource().getLocation().toString();

This gave me essentially the path to the jar file used, which I could use to figure out the project root in my case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handling presentation logic in Django templates The description below is heavily simplified - it's only one part of a bigger problem that we are tackling but the innards can be safely left out for this question.
Suppose we have the following models: -
class Item(models.Model):
    name = models.CharField(max_length=150)
    value = models.DecimalField(max_digits=12,decimal_places=2)

class Person(models.Model):
    name = models.CharField(max_length=150)
    items = models.ManyToManyField(Item, through='AssignedItem')

class AssignedItem(models.Model):
    person = models.ForeignKey(Person)
    item = models.ForeignKey(Item)
    value = models.DecimalField(max_digits=12,decimal_places=2)

So basically a person may be assigned zero, one, or more items and each assigned item's value may be overridden for a particular person by specifying the new value in the through model.
What we are aiming to achieve is an html table which has all the Item.name as its header row, with one extra column in that header row for Person.name.
Each Person may have a different set of Person.items assigned to them so it is expected that if a Person has not been assigned an Item, the corresponding cell for that Person will be blank (please see attached image).

The question is how to place the correct AssignedItem value in the corresponding column. We have a Queryset of Items that we are looping over in the template to create the header row, and then we have a list of lists containing each person's items. But how do we ensure that the correct AssignedItem is displayed under the corresponding Item header?

A: You mentioned you are constructing the list in the view,

We have a Queryset of Items that we
  are looping over in the template to
  create the header row, and then we
  have a list of lists containing each
  person's items.

When constructing this list, make the list an ordered list, where if a particular value exists, assign it and if it doesnt, then insert None.
ie, the list for Jake should look like [78, 45, None, 94, 72]
Edit:
Since reordering is an issue, use a dictionary with the item as index
ie, the values for Jake should look like {'Item1':78, 'Item2':45, 'Item4':94, 'Item5':72}

A: Well, the main issue was to ensure that the correct AssignedItem is displayed under the corresponding Item header.
I tried a lot of things in the template, but it did not offer too much room to maneuver. I ultimately created the "table" in the view then passed the string to the template for rendering.


text:
Q: Make the date of answer more prominent Say a question has many answers. The typical user is not going to read all of them. Instead, they will naturally looks only at the accepted answer (if any) and perhaps a few of the mostly highly-voted answers.
And so if the newest answer happens to be better than all existing answers, it will probably not be read, because it languishes near the bottom.
I'm not sure what the solution to this is. But I think it would be great to alert users to the fact that an answer is relatively new (and thus hasn't had much opportunity to be upvoted). Right now the date of the answer is small and at the bottom right, together with the user name, where it is not very prominent.
A possibility is to place the date  of answer just under the vote count (and the upvote/downvote buttons). Or if the community feels there's not enough space and that'd be too much clutter, even just placing the year there would be great.

A: No.
That would be highly confusing and just wrong as design choice. (In my opinion.)
If users are interested to see newer answers first, there is already such an option:

The accepted answer will still be first, but those after it will be displayed sorted by last activity.
However, I do agree that the current sort is lacking, and new good answers might not get the attention they deserve. There is really no magic solution for  this, but worth to mention that SE staff are aware of that and looking for ways to change this.


text:
Q: login into two different areas on one login form I'm trying to get user login into two different areas on one login form based on a criteria. The problem I'm having is that if the correct passwords are provided, everything works fine but when a wrong password is provided, nothing happens, it doesn't even echo the password error alert! What could be wrong and is my code okay?
Thanks
        if(isset($_POST['login'])){

        $username=$_POST['username'];
        $password=$_POST['password'];

        $username = stripslashes($username);
        $password = stripslashes($password);
        $username = $username;
        $password = $password;

        //$pass = md5($password);

        $stmt = $pdo->prepare("SELECT password FROM table WHERE username=:username");
        $stmt->bindValue(':username', $username, PDO::PARAM_STR);
        $stmt->execute();

        if($stmt->rowCount()<1){

        echo 'INVALID USERNAME OR PASSWORD';

        }else{
        $password = $_POST['password'];
        list($hash) = $stmt->fetch(PDO::FETCH_NUM);

        if (password_verify($password, $hash)) {
        $_SESSION['username'] = $username;

        $status1 = "COMPLETED";
        $status2 = "UNCOMPLETED";

        $stmt = $pdo->query("SELECT status FROM table WHERE username ='$_SESSION[username]'");
        $check = $stmt->fetch(PDO::FETCH_ASSOC);
        $status = $check['status'];

        if(strcmp($status, $status1) == 0){

        header("location: completed/index.php");
        exit();
        }elseif(strcmp($status, $status2) == 0){

        header("location: uncompleted/index.php");
        exit();
        }else{

        echo 'INVALID USERNAME OR PASSWORD';

        }
        }
        }
        }

A: I think the problem is that you did not handle the condition where password_verify($password, $hash) returns false in your if-statement. I handled it below:
if (isset($_POST['login'])) {

    $username = $_POST['username'];
    $password = $_POST['password'];

    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = $username;
    $password = $password;

    //$pass = md5($password);

    $stmt = $pdo->prepare("SELECT password FROM table WHERE username=:username");
    $stmt->bindValue(':username', $username, PDO::PARAM_STR);
    $stmt->execute();

    if ($stmt->rowCount() < 1) {

        echo 'INVALID USERNAME OR PASSWORD';
    } else {
        $password = $_POST['password'];
        list($hash) = $stmt->fetch(PDO::FETCH_NUM);

        if (password_verify($password, $hash)) {
            $_SESSION['username'] = $username;

            $status1 = "COMPLETED";
            $status2 = "UNCOMPLETED";

            $stmt = $pdo->query("SELECT status FROM table WHERE username ='$_SESSION[username]'");
            $check = $stmt->fetch(PDO::FETCH_ASSOC);
            $status = $check['status'];

            if (strcmp($status, $status1) == 0) {

                header("location: completed/index.php");
                exit();
            } elseif (strcmp($status, $status2) == 0) {

                header("location: uncompleted/index.php");
                exit();
            } else {

                echo 'INVALID USERNAME OR PASSWORD';
            }
        } else {
            // handle wrong password here
            echo 'INVALID PASSWORD';
        }
    }
}

I hope this helps.

A: The problem was that my else was in the wrong place. I had it after the if/elseif strcmp statements. It should be after the  if (password_verify($password, $hash))  block.
it was noticed from phpfreak forum. Credits to him
thus the correct code:
            if(isset($_POST['login']))
            {
                $username = stripslashes($_POST['username']);
                $password = stripslashes($_POST['password']);

                $stmt = $pdo->prepare("SELECT password FROM table WHERE username=:username");
                $stmt->bindValue(':username', $username, PDO::PARAM_STR);
                $stmt->execute();

                if($stmt->rowCount()<1)
                {
                    echo '

<button type="button" class="close" aria-label="Close">×</button>INVALID USERNAME OR PASSWORD

';
                }
                else
                {
                    $password = $_POST['password'];
                    list($hash) = $stmt->fetch(PDO::FETCH_NUM);

                    if (password_verify($password, $hash))
                    {
                        $_SESSION['username'] = $username;

                        $status1 = "COMPLETED";
                        $status2 = "UNCOMPLETED";

                        $stmt = $pdo->query("SELECT status FROM table WHERE username ='$_SESSION[username]'");
                        $check = $stmt->fetch(PDO::FETCH_ASSOC);
                        $status = $check['status'];

                        if(strcmp($status, $status1) == 0)
                        {
                            header("location: completed/index.php");
                            exit();
                        }
                        elseif(strcmp($status, $status2) == 0)
                        {
                            header("location: uncompleted/index.php");
                            exit();
                        }
                    }
                    else
                    {
                        echo '

<button type="button" class="close" aria-label="Close">×</button>INVALID USERNAME OR PASSWORD again

';
                    }
                }
            }


text:
Q: Отображение элементов по категориям Всем привет, у меня есть компонент категорий, при нажатии на которые, должны отображаться только те карточки, которые имеют данную категорию.
Вот собственно компонент категорий

General

Inbox

Work

Personal

Social

Вот я написал 2 метода для получения карточек по категориям, методы находятся в сервисе
 getTodosByCategory(category: Categories): void {
    this.todos$.next(
      this.todos$.value.filter((todo) => todo.category === category)
    );
  }

  filterTodoByCategory(category: Categories): Todo[] {
    return this.todos$.value.filter((todo) => todo.category === category);
  }

Есть enum с категориями
export enum Categories {
  GENERAL = 'General',
  INBOX = 'Inbox',
  WORK = 'Work',
  PERSONAL = 'Personal',
  SOCIAL = 'Social',
};

Как мне сделать так, чтобы при нажатии, отображались только подходящие карточки ?

A: Если я правильно понял ... то:

General

И аналогично для остальных строк.


text:
Q: Install Win7 from recovery - protect current lubuntu install I got a new laptop in December and immediately wiped Windows, installed Ubuntu (later tried XFCE, KDE, now LXDE and happy), and left the recovery partition intact. The idea was that if anything was wrong with the laptop, I could restore Win7 from the recovery for warantee purposes...
I'm having some major sound issues, and finally getting around to looking into it. I'd like to reinstall Win 7 to ensure the sound issues are not hardware (speakers), before pursuing lengthy troubleshooting (I've done the basic stuff already).

*

*Can I do this?

*Can I do this AND preserve my current Lubuntu install, with some degree of confidence? I understand there is always a risk when repartitioning.

*How?
Thanks!

A: If you have only two partition (RECOVERY partition and Ubuntu Partition with rest of the hard drive), you need to create a new partition and restore windows 7 on newly created partition. To create a partition you can use default partition manager tool in ubuntu OR any disk utilities like acronics disk director,EASUS PARTITION MANAGER (free).

These third party tools need to be installed in a windows system, and
  then you can create a boot able cd/usb for booting and managing.

*

*First re-size the current ubuntu partition and use free space to
create a new partition (ref link: - How to create new partitions in a brand new laptop easily and safely)

*After that you can use the tool called boot-repair to update the
grub. (ref Link- https://help.ubuntu.com/community/RecoveringUbuntuAfterInstallingWindows)

If you have installed ubuntu on a separate partition and you have a free partition (I mean no important data, as it will deleted while installing win 7), then install win 7 on that partition. Then use live cd/usb to update the grub using the tool mentioned above.

Note: I hope you got a restoration dvd created if you want factory
  image restore. If you want to use your factory image stored in
  RECOVERY partition. You need to extract the image file (with extension
  .vim) and "imagex" tool for re-deployment. Its a bit advanced task.


text:
Q: value size does not match register size specified by the constraint and modifier In arm64, compiling the inline assembly below causes a warning below:

value size does not match register size
        specified by the constraint and modifier [-Wasm-operand-widths].

This is because the arm64's register is 64bit.
int a = 1;
int b = 2;
asm volatile(
   "add %[a], %[a], %[b]  \n"
   :
   [a] "+r"(a)
   :
   [b] "r"(b)
   :
    );

And clang give the fix advice, use constraint modifier "w".

A:
value size does not match register size specified by the constraint and modifier

means:
your variable is 32bit not match with ARM64's 64bit register
you could:

*

*change your variable to 64bit
long a = 1;
long b = 2;
asm volatile(
   "add %[a], %[a], %[b]  \n"
   : [a] "+r"(a)
   : [b] "r"(b)
   :);

or

*

*use 32bit=Word register, by add prefix w

*

*which is clang suggested

int a = 1;
int b = 2;
asm volatile(
   "add %w[a], %w[a], %w[b]  \n"
   : [a] "+r"(a)
   : [b] "r"(b)
   :);

A: The key to this warning is unmatched. In arm64, the register is 64bit width, but the int/float variables are 32bit. And if the type is double/int64_t or the variable is a pointer, it will don't cause a warning. So, you can try the way.

A: As @David Wohlferd metioned in the commend, just use %w[a] replace %[a].
That is, on ARM64 platform, you still would like to use 32-bit register, then insert a w between % and corresponding number that represents register.
Thus the whole program is modified to this:
#include <stdio.h>
#include <arm_neon.h>

int main() {

    int a = 1;
    int b = 2;
    asm volatile(
        "add %w[a], %w[a], %w[b]  \n"
        :
        [a] "+r"(a)
        :
        [b] "r"(b)
        :
    );
    printf("after process, a=%d\n", a);

    return 0;
}

Btw, this CSDN blog (in Chinese) is worth reading if you know nothing about arm inline assembler and get similar confusion like the author of this question.


text:
Q: Re-bundle (or update) an EC2 AMI? I have bundled an AMI that I'm fairly satisfied with. However I know that eventually I'll need to modify it (e.g. for Debian security updates or to update other system software that I have in the AMI). Is it possible to update an image once it's been bundled? What if I bundled a new AMI with the same name, manifest, and S3 location? EC2 caches AMIs for a period of time; would it be thrown off guard by the fact that an AMI changed between launches?
I do understand that I can simply bundle an entirely new AMI, although I want to avoid a proliferation of images. Would I be better off storing at least some of my software (e.g. JRuby and such) on an EBS volume instead of the AMI itself?
Note that the "software" I'm referring to does not include my own deployable units, but is rather third-party software.

A: What I do is bundle the AMI with the same name. Then delete the AMI while the instance is running and the upload and register the new AMI. In terms of what's "better" for storing your software it really depends on how often you're going to updating or modifying it. If you don't mind going thru the bundle process then just leave it in the AMI.
p.s. Handy tip for bundling AMI's is do it inside a screen session so that you can walk away from the imaging process and not have to worry about a broken SSH connection.

A: Although it probably doesn't help you now.  It is much easier to bundle EBS backed instances.  It is as simple as "stopping" the instance somehow (Via ec2-stop-instances, or xfs freeze, or just try your luck with a running one) then just snapshot the EBS volume and register it.  The only tricky part is when launching the new instance to make sure you use the same AKI, which can be found in the info for the currently running instance.  Also, the AMIs from EBS Backed Images are not stored in your standard S3 bucket, so you do not need to worry so much about proliferation, just deregister them when you are done.
Alternatively, you can try writing the regular AMI bundle to an attached drive, then snapshot and register that, although I haven't had much success with this yet.  Moving instance-store to EBS backed isn't entirely smooth at the moment.

Amazon tracks AMI's by the AMI ID (ami-1a2s3d4f) not by the location and name in S3, so you will be fine to remove the old one and bundle the other one with the same name.


text:
Q: Is there a shortcut for /cygdrive/ Is there a shortcut for typing /cygdrive/ for every path? Is it possible to alias /cygdrive/ to /cd/ for example?

A: $ man alias
NAME
     alias, unalias - create or remove a pseudonym  or  shorthand
     for a command or series of commands

They are used for commands only.
if you want to create a shortcut to /cygdrive i recommend using environment variables:
export PROJECT_DIR=/cygdrive/c/path/to/project
export c_dir=/cygdrive/c
export d_dir=/cygdrive/d
Put these into the .profile file under your home directory.
Usage:
cd $c_dir
cd $d_dir
cd $PROJECT_DIR

A: You could use : mount --change-cygdrive-prefix
For example : mount --change-cygdrive-prefix / and cd /c/ will change the working directory to /cygdrive/c/.
For permanent change (not session's change), you need to change the Windows registry.

A: What I do is create symbolic links in the Cygwin home for those directories that I go to regularly, for example:
$ cd ~
$ ln -s /cygdrive/c/code

Then $ cd code takes me where I want to go.

A: Could you use tab completion? eg type cd /cy and then press TAB and it should hopefully complete to /cygdrive/

A: the following is a cygwin mount solution:
mount --change-cygdrive-prefix /

then instead of cd /cygdrive/c
cd /c

the earlier posts aliases are still useful for shortening "cd long-path" commands

A: I found a more correct answerlink after I used the accepted one here and felt it was way to hacky to be correct given all the stuff it broke.
edit /etc/fstab the current version as of this time is
none /cygdrive cygdrive binary,posix=0,user 0 0

make it look like
none / cygdrive binary,posix=0,user 0 0

and you are good to go, no hacks to replace stuff in $PATH or $HOME or anything else!


text:
Q: What data analysis tools I can apply on categorical variables such as movie genres in order to reduce dimentionality? So I am working on a final project where I have to use data analysis tools, ANNs, etc. My idea is that an agent will recognize the movie genres from a poster but the data set I have contains 28 separate genres but I want to work with the most important 10 of them for example. Is there any way I can use data analysis tools such as PCA/SVD, LDA etc to do this?
I tried one hot encoding all the different genres and applying PCA to them but a lot of people said it doesn't give a meaningful answer. I am new to all of this so any help would be appreciated.


text:
Q: Spring Security samples from official GitHub repository doesn't work I follow along with the tutorial Hello Spring Security with Boot to learn Spring Security.
After importing it into STS,I got build errors:
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-thymeleaf:jar is missing.
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-web:jar is missing.
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-test:jar is missing.

I thought the sample comes from official GitHub repository, so it should work well. Unfortunately, I encounter build errors.
Then I tried to fix the build errors. I appended <version>1.5.3.release</version> tags in POM file and the errors from POM file disappeared.
But I still encountered an error from main class:
The type org.springframework.context.ConfigurableApplicationContext cannot be resolved. It is indirectly referenced from required .class files

A: I have used all spring samples from official site and it works.
my sample pom file is as below,
https://github.com/Roshanmutha/rcmutha-springrest/blob/master/pom.xml
Only  will have addition and removal as per the sample you are trying.
Click the below link to see all sample which i have tried from spring repo :
https://github.com/Roshanmutha?utf8=%E2%9C%93&tab=repositories&q=rcmutha&type=&language=


text:
Q: Python - sqlalchemy - oracle connection fails to connect to SID I am trying to use sqlalchemy to connect to an oracle DB.  I was expecting the following to work given that it appears the exact syntax is shown in the sqlalchemy documentation.
oracle_db = sqlalchemy.create_engine('oracle://user:pass@server:1521/dev')

but this results in the error:

dsn = self.dbapi.makedsn(url.host, port, **makedsn_kwargs)
  TypeError: makedsn() takes no keyword arguments

The following call initially works without the service name
oracle_db = sqlalchemy.create_engine('oracle://user:pass@server:1521')

But when trying to connect it fails with an error complaining that the SERVICE_NAME was not provided.

ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

Oddly this works with cx_Oracle directly:
con = cx_Oracle.connect('user/pass@server:1521/dev')

How am I supposed to connect to the specific service?
Attempts
I have tried to use cx_Oracle.makedsn() explicitly from this question with no luck as well.
Trying to use ? options in the connection string
oracle_db = sqlalchemy.create_engine('oracle://user:pass@server:1521/?sid=dev')

works initially but when I try oracle_db.connect() I get the same ORA-12504 error shown above.

A: Based on the documentation at Sqlalchemy Documentation, you should probably use the cx_oracle engine.  The connect string is:
oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]

with an option of service_name or sid as follows:
oracle+cx_oracle://user:pass@host:1521/?service_name=hr
oracle+cx_oracle://user:pass@host:1521/?sid=hr

A: Try using this connection string:
engine = create_engine("oracle+cx_oracle://<username>:<password>@(DESCRIPTION = (LOAD_BALANCE=on) (FAILOVER=ON) (ADDRESS = (PROTOCOL = TCP)(HOST = <host>)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = devdb)))")

It worked for me.


text:
Q: What is the architecture behind Scratch programming blocks? I need to build a mini version of the programming blocks that are used in Scratch or later in snap! or openblocks.
The code in all of them is big and hard to follow, especially in Scratch which is written in some kind of subset of SmallTalk, which I don't know.
Where can I find the algorithm they all use to parse the blocks and transform it into a set of instructions that work on something, such as animations or games as in Scratch?
I am really interested in the algorithmic or architecture behind the concept of programming blocks.

A: This is going to be just a really general explanation, and it's up to you to work out specifics.
Defining a block
There is a Block class that all blocks inherit from. They get initialized with their label (name), shape, and a reference to the method. When they are run/called, the associated method is passed the current context (sprite) and the arguments.
Exact implementations differ among versions. For example, In Scratch 1.x, methods took arguments corresponding to the block's arguments, and the context (this or self) is the sprite. In 2.0, they are passed a single argument containing all of the block's arguments and context. Snap! seems to follow the 1.x method.
Stack (command) blocks do not return anything; reporter blocks do.
Interpreting
The interpreter works somewhat like this. Each block contains a reference to the next one, and any subroutines (reporter blocks in arguments; command blocks in a C-slot).
First, all arguments are resolved. Reporters are called, and their return value stored. This is done recursively for lots of Reporter blocks inside each other.
Then, the command itself is executed. Ideally this is a simple command (e.g. move). The method is called, the Stage is updated.
Continue with the next block.
C blocks
C blocks have a slightly different procedure. These are the if <> style, and the repeat <> ones. In addition to their ordinary arguments, they reference their "miniscript" subroutine.
For a simple if/else C block, just execute the subroutine normally if applicable.
When dealing with loops though, you have to make sure to thread properly, and wait for other scripts.
Events
Keypress/click events can be dealt with easily enough. Just execute them on keypress/click.
Something like broadcasts can be done by executing the hat when the broadcast stack is run.
Other events you'll have to work out on your own.
Wait blocks
This, along with threading, is the most confusing part of the interpretation to me. Basically, you need to figure out when to continue with the script. Perhaps set a timer to execute after the time, but you still need to thread properly.
I hope this helps!


text:
Q: php preg match a-zA-Z and only one space between 2 or more words For my PHP script I have this code:
if (!preg_match("/[^A-Za-z]/", $usersurname))
   $usersurname_valid = 1;

This worked untill I realized a surname can be two or more words... doh.
Anyone can tell me how to write this code if I want to allow 1 space between two worlds? For example:
Jan Klaas is now wrong and Jan Klaas should be allowed, also Jan Klaas Martijn and so on should be allowed.
Even better would be a preg replace, to replace two or more spaces with 1, so when you write: Jan(space)(space)Klaas or Jan(space)(space)(space)(space)Klaas, it would return Jan(space)Klaas.
I searched around for a while but somehow I just can't get this space matching to work..
PS: When I got this working, I will apply this for the mid and last name too ofcourse.
===========================================
EDIT: After you helping me out, I re-wrote my code to:
// validate usersurname
$usersurname = preg_replace("/\s{2,}/"," ", $usersurname);
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$usersurname))
    $usersurname_valid = 1;
// validate usermidname
$usermidname = preg_replace("/\s{2,}/"," ", $usermidname);
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$usermidname))
    $usermidname_valid = 1;
// validate userforename
$userforename = preg_replace("/\s{2,}/"," ", $userforename);
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$userforename))
    $userforename_valid = 1;

and the error notifications
elseif ($usersurname_valid !=1)
    echo ("
Only alphabetic character are allowed for the last name. $usersurname $usermidname $userforename
");
// usermidname character validation
elseif ($usermidname_valid !=1)
    echo ("
Only alphabetic character are allowed for the middle name. $usersurname $usermidname $userforename
");
// userforename character validation
elseif ($userforename_valid !=1)
    echo ("
Only alphabetic character are allowed for the (EDIT) first name. $usersurname $usermidname $userforename
");

Replacing the spaces are working well and I need this preg_match to check on on A-Za-z + space. I think in this case it doesn't matter if it's matching more than 1 spaces because it's replaced anyway, right?
EDIT:
Solution for my case:
$usersurname = preg_replace("/\s{2,}/"," ", $usersurname);
if (!preg_match("/[^A-Za-z ]/", $usersurname))

This does the work. Thanks for helping out, J0HN

A: Well, solving the problem you have in mind:
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$usersurname)) { ... }

But, well, it's just a part of the solution, and it's not bulletproof. Look at the list of common mistakes when handling names.
So, you'd better to re-think on your validation approach.
Replacing the multiple spaces is simpler to achieve as a separate instruction, something like
$processed_usersurname = preg_replace("/\s{2,}/"," ", $usersurname);

This will match and replace any two or more consequent whitespace characters (space, tab, linebreak and carriage return) to single space


text:
Q: HTML5 History API just full load from index page im trying to implement in a Java MVC (using Vraptor) the history api,
if you click in a link from /index, it will load the content in the #content div (its ok)
but when you type /content1 and press enter in the url bar, it only display the content1, without the menu
this pages is only for test, in a real env i will use a .js file:
index.jsp(access from /index)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

menu.jsp (can be accessed by /menu)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

 Link 1

 Link 2

the content1(can be accessed by /content1)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

content1

the content2.jsp (accessed by /content2)
its the same of content1, i just changed the 1 by 2)
how can i make when i load by writing in the url bar /content1 or /content2, and pressing enter, it load the /menu too? (full site, link from index, but in the page of the content1) if i write content2, load menu but displaying content2 in the #content?


text:
Q: Adding Stock Status column to Manage Product Admin Page I'm trying to add 'stock status' column to the Admin Manage Product Grid.
Stock status is either "In Stock" or "Out of Stock".
Seems like I need to edit Adminhtml/Block/Catalog/Product/Grid.php 's _prepareColumns().
I added this line
$this->addColumn('stock',
        array(
            'header'=> Mage::helper('catalog')->__('Stock Avail.'),
            'width' => '70px',
            'index' => 'status',
            'type'  => 'options',

            'options' => Mage::getSingleton('cataloginventory/source_stock')->toOptionArray()

which just prints out Array,Array.
I'm guessing it's just printing out the type, so I would need to access the array value to get options. Am I on the right path? I can't find any good coding docs for magento, if anyone can share with me how they figured out magento, that would be really nice.

A: You should use a renderer: in the array of the addColumn, add:
'renderer' => 'YourNamespace_YourModule_Path_To_Renderer_File',

And the renderer file would be something like:
class YourNamespace_YourModule_Path_To_Renderer_File extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    public function render(Varien_Object $row)
    {
        //let's see what you have to work with
        Zend_Debug::dump($row->getData(), 'debug');

        $stockStatus = $row->getSomething();
        return $stockStatus;
    }
}

Let me know if that ain't clear


text:
Q: Trying to get Friendly URL's to work I have been working on getting friendly URLs to work.
On my site I have something like this:
http://www.example.com/blog/newpost.php?id=Reasons+to+Use+a+Small+Business+Consultant

I would like it to look something like this:
http://www.example.com/blog/Reasons+to+Use+a+Small+Business+Consultant

I have tried to edit both the httpd.conf and the .htaccess and get no response.
httpd.conf:
<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot /var/www/sites/example
    ServerName www.example.com
    <Directory /var/www/sites/example/blog>
        Options FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

.htaccess:
RewriteEngine On
RewriteRule ^blog/Reasons+to+Use+a+Small+Business+Consultant$ blog/newpost.php?id=Reasons+to+Use+a+Small+Business+Consultant

LogLevel alert rewrite:trace3
The trace log says it is apply the pattern however I still see:
http://www.example.com/blog/newpost.php?id=Reasons+to+Use+a+Small+Business+Consultant

[Thu Oct 25 18:39:17.821619 2018] [rewrite:trace3] [pid 27933] mod_rewrite.c(470): [client 123.321.64.56:58790] 123.321.64.56 - - [www.example.com/sid#558610b6a4a8][rid#558610d3d740/initial] [perdir /var/www/sites/example/blog/] strip per-dir prefix: /var/www/sites/example/blog/newpost.php -> newpost.php, referer: http://www.example.com/blog/
[Thu Oct 25 18:39:17.821648 2018] [rewrite:trace3] [pid 27933] mod_rewrite.c(470): [client 123.321.64.56:58790] 123.321.64.56 - - [www.example.com/sid#558610b6a4a8][rid#558610d3d740/initial] [perdir /var/www/sites/example/blog/] applying pattern '^blog/Reasons+to+Use+a+Small+Business+Consultant$' to uri 'newpost.php', referer: http://www.example.com/blog/
[Thu Oct 25 18:39:17.821654 2018] [rewrite:trace1] [pid 27933] mod_rewrite.c(470): [client 123.321.64.56:58790] 123.321.64.56 - - [www.example.com/sid#558610b6a4a8][rid#558610d3d740/initial] [perdir /var/www/sites/example/blog/] pass through /var/www/sites/example/blog/newpost.php, referer: http://www.example.com/blog/

A: This will probably work:
RewriteEngine On
RewriteRule /blog/(.*) %{HTTP_HOST}/blog/newpost.php?$1 [L]

Your regex starts with ^blog.... This will never match what you are sending it, as the initial / is missing. The regular expression you have says match a URL starting with blog/..., but in reality there is always a slash after the hostname:port.
Refer to the documentation for RewriteRule: specifically:

The Pattern will initially be matched against the part of the URL
  after the hostname and port, and before the query string (e.g.
  "/app1/index.html").

My example is more generic; if you need it to be for a very specific path, as you have, then by all means change it back and replace the (.*) grouping and $1 with what you had.


text:
Q: Applying a function to a column in pandas I am working on the movielens dataset, I would like to create a new column by applying a function , the basic idea is :
1) get corresponding movie id from the ratings_dataframe
2)use this movie id to find the name of the movie from moviesdata_frame
3)and copy this value to the corresponding cell in the ratings dataframe
My code consists of:
def getname(p):
    nm =  movies.loc[movies['movie_id'] == 'p']['title']
    return nm

ratings['title'] = ratings.apply(lambda row:getname(gg['movie_id']))

The error is :('invalid type comparison', u'occurred at index movie_id')

A: You don't need a function for this simple mapping:
ratings_dataframe['title'] = \
    ratings_dataframe['movie_id'].map(movies.set_index('movie_id')['title'])


text:
Q: Getting error on deploying the process definition in activiti-rest using java code Hi all i am trying to deploy process definiton in activiti-rest by using java rest.But getting error as 'Exception in thread "main" Bad Request (400)'.I have tried a lots in google but not found any solution for that.Please help me where is the actual fault in my code.Find below my java code and errors.
My Errors

Starting the internal HTTP client
Exception in thread "main" Bad Request (400) - The request could not be understood by the server due to malformed syntax
 at org.restlet.resource.ClientResource.doError(ClientResource.java:590)
 at org.restlet.resource.ClientResource.handleInbound(ClientResource.java:1153)
 at org.restlet.resource.ClientResource.handle(ClientResource.java:1048)
 at org.restlet.resource.ClientResource.handle(ClientResource.java:1023)
 at org.restlet.resource.ClientResource.post(ClientResource.java:1485)
 at org.restlet.resource.ClientResource.post(ClientResource.java:1424)
 at com.bizruntime.activiti.rest.Activiti_Rest_BuyEconomyOrBusinsessClassTIcket.TicketClass.createdeployment(TicketClass.java:40)
 at com.bizruntime.activiti.rest.Activiti_Rest_BuyEconomyOrBusinsessClassTIcket.Ticke_Test.main(Ticke_Test.java:13)

My Java Code

/**
*Client Resource
*/
private static ClientResource getClientResource(String uri){
 ClientResource resource=new ClientResource("http://localhost:8431/activiti-rest/service");
 resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC,kermit,kermit);
 return resource;
}

/**
 * Creating Deployment
 */
public static JSONObject createdeployment(){
 String uri=REST_URI+"/repository/deployments";
 log.debug("uri(Create Deploymnet):: "+uri);
 JSONObject my_data=new JSONObject();
 try {
  my_data.put("name","BuyTicket.bpmn20.xml");
  Representation response=getClientResource(uri).post(my_data);
  JSONObject object=new JSONObject(response.getText());
  if(object!=null){
    log.info("Deployed Successfully.....");
    return object;
  }

 } catch (JSONException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }
 return null;
}

A: cfr. http://activiti.org/userguide/index.html#_create_a_new_deployment: the body should not be a json multipart/form-data file that is a bpmn20.xml file (or a .zip in case of multiple files)


text:
Q: persist dropdownlist selection located in a control located in a masterpage I have default.aspx used masterpage, in master page i have a control called DefaultMenuContent, this control have a dropdownlist with autopostback, the problem is loosing the selection even if i use Is Not PostBack in control's load event,
every time it's new load, not postback in this scenario!
how to persist the dropdownlist selection?
In Master:
                   <asp:ContentPlaceHolder ID="MenuContentPlaceHolder" runat="server">
                          <art:DefaultArabicMenu ID="DefaultMenuContent" runat="server" />
                    </asp:ContentPlaceHolder>

In Default.aspx
Protected Sub ddl_Srv_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddl_Srv.Load
    If Not Page.IsPostBack Then
        Bind_List()
    End If
End Sub

A: Assuming that you only want to store the selection for the current user's session, you could save the selection in a session variable.
Protected Sub dropdownlist1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles dropdownlist1.SelectedIndexChanged
    ' save selection
    Session("ddl1_selection") = dropdownlist1.SelectedValue

    ' do rest of logic

End Sub

In Page Load event check the variable and make the selection
 Protected Sub ddl_Srv_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        Bind_List()

        If Session("ddl1_selection") IsNot Nothing Then
            dropdownlist1.SelectedValue = Session("ddl1_selection")
        End If
    End If
End Sub


text:
Q: Incomplete information about deadlock in Thread Stack Trace? Recently on the server of my project we encountered a deadlock condition and on checking the thread stack trace we could't find much information. Here is the stack trace:
Found one Java-level deadlock:
"pool-1-thread-70":
  waiting to lock Monitor@0x00007f60d40a0760 (Object@0x00000000b9c02a00, a com/hal/real/Real),
  which is held by "pool-17-thread-81"

"pool-17-thread-81":
  waiting to lock Monitor@0x00007f60d410b4e0 (Object@0x00000000b9c03980, a java/util/Collections$SynchronizedMap),
  which is held by "pool-1-thread-70"

Found a total of 1 deadlock.

Thread 23794: (state = BLOCKED)
 - sun.misc.Unsafe.park(boolean, long) @bci=0 (Compiled frame; information may be imprecise)
 - java.util.concurrent.locks.LockSupport.parkNanos(java.lang.Object, long) @bci=20, line=226 (Compiled frame)
 - java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(java.util.concurrent.SynchronousQueue$TransferStack$SNode, boolean, long) @bci=174, line=453 (Compiled frame)
 - java.util.concurrent.SynchronousQueue$TransferStack.transfer(java.lang.Object, boolean, long) @bci=102, line=352 (Interpreted frame)
 - java.util.concurrent.SynchronousQueue.poll(long, java.util.concurrent.TimeUnit) @bci=11, line=903 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor.getTask() @bci=141, line=1043 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor.runWorker(java.util.concurrent.ThreadPoolExecutor$Worker) @bci=17, line=1103 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor$Worker.run() @bci=5, line=603 (Interpreted frame)
 - java.lang.Thread.run() @bci=11, line=679 (Interpreted frame)

Thread 23792: (state = BLOCKED)
 - sun.misc.Unsafe.park(boolean, long) @bci=0 (Compiled frame; information may be imprecise)
 - java.util.concurrent.locks.LockSupport.parkNanos(java.lang.Object, long) @bci=20, line=226 (Compiled frame)
 - java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(java.util.concurrent.SynchronousQueue$TransferStack$SNode, boolean, long) @bci=174, line=453 (Compiled frame)
 - java.util.concurrent.SynchronousQueue$TransferStack.transfer(java.lang.Object, boolean, long) @bci=102, line=352 (Interpreted frame)
 - java.util.concurrent.SynchronousQueue.poll(long, java.util.concurrent.TimeUnit) @bci=11, line=903 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor.getTask() @bci=141, line=1043 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor.runWorker(java.util.concurrent.ThreadPoolExecutor$Worker) @bci=17, line=1103 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor$Worker.run() @bci=5, line=603 (Interpreted frame)
 - java.lang.Thread.run() @bci=11, line=679 (Interpreted frame)

Thread 23757: (state = BLOCKED)
 - com.hal.real.RealUser.getRegularSnapshot() @bci=15, line=646 (Interpreted frame)
 - com.hal.real.RealUser.getRealSnapshot() @bci=10, line=671 (Interpreted frame)
 - com.hal.real.RealUser.getRealUsers() @bci=9, line=618 (Interpreted frame)
 - com.hal.real.Real.getAvat() @bci=4, line=1146 (Interpreted frame)
 - com.hal.real.RealManager.getWebServers(com.hal.real.Real, java.util.List) @bci=184, line=220 (Interpreted frame)
 - com.hal.message.core.StreamUriReq.exec() @bci=398, line=108 (Interpreted frame)
 - com.hal.real.RealClientHandler.msgReceived(org.apache.mina.core.session.IoSession, java.lang.Object) @bci=91, line=83 (Interpreted frame)
 - org.apache.mina.core.filterchain.DefaultIoFilterChain$TailFilter.messageReceived(org.apache.mina.core.filterchain.IoFilter$NextFilter, org.apache.mina.core.session.IoSession, java.lang.Object) @bci=51, line=690 (Interpreted frame)
 - org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(org.apache.mina.core.filterchain.IoFilterChain$Entry, org.apache.mina.core.session.IoSession, java.lang.Object) @bci=22, line=417 (Interpreted frame)
 - org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(org.apache.mina.core.filterchain.DefaultIoFilterChain, org.apache.mina.core.filterchain.IoFilterChain$Entry, org.apache.mina.core.session.IoSession, java.lang.Object) @bci=4, line=47 (Interpreted frame)
 - org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(org.apache.mina.core.session.IoSession, java.lang.Object) @bci=18, line=765 (Interpreted frame)
 - org.apache.mina.core.filterchain.IoFilterEvent.fire() @bci=110, line=74 (Interpreted frame)
 - org.apache.mina.core.session.IoEvent.run() @bci=1, line=63 (Interpreted frame)
 - java.util.concurrent.ThreadPoolExecutor.runWorker(java.util.concurrent.ThreadPoolExecutor$Worker) @bci=46, line=1110 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor$Worker.run() @bci=5, line=603 (Interpreted frame)
 - java.lang.Thread.run() @bci=11, line=679 (Interpreted frame)

Any Way to tackle this problem. Clearly pool-1-thread-70 and pool-17-thread-81 are the threads responsible for deadlock but no information about which function were they accessing when this deadlock occurred and which synchronized map the thread has locked


text:
Q: What happens to an electron who enters constant circular motion in a magnetic field? If an electron enters a magnetic field and then goes into circular motion, what happens to it and its energy? I think the electron begins to emit electromagnetic radiation due to its acceleration that is perpendicular to the circular motion. This, I think I've heard it said, should result in the electrons radius of orbit getting smaller until some point. Can someone please try from the viewpoint of conservation of energy, charge and momentum etc. and explain to me what happens in this phenomenon so that I could understand it intuitively? I only have a grasp of high school physics so I would appreciate it if is possible to adjust the explanation to around my level.
Thank you in advance.
EDIT: If I were to explain my current understanding of what exactly happens it would be the following (I would appreciate if you'd help me correct it in any way): The electron enters circular motion and begins "losing" energy by electromagnetic radiation due to its centripetal acceleration. This will result in its radius of circular motion (r=mv/qB) getting smaller due to it losing kinetic energy; velocity. Now this is where I am not quite sure what happens, but if I were to take an uneducated guess: does the electron just hit zero velocity and come to stop after releasing all its kinetic energy as em-radiation?

A: From this article here is  an electron crossing a magnetic field perpendicular to it direction, in a bubble chamber.

In a bubble chamber the electron loses energy also by ionizing the hydrogen, which is why one can see its track,(small bubbles) larger scatters leave the ionization electrons as small spirals. There are two mechanisms of energy loss to create the spiral. Because there is a time interval where the picture of the tracks can be taken, before resetting the chamber for the next events, the spiral seen does not have the time to end at a point.
In this bubble chamber picture , an ionization electron from the beam track  is seen to spiral down to a  point.

In vacuum, the only energy loss will be radiation, as in the circular colliders , for example LEP, , there is radiation, called synchrotron radiation in the region where there are circular paths for the electron and positron, that have to be compensated to keep the energy constant.
An electron in a circular path in vacuum, in a magnetic field would spiral down to a point, all its kinetic energy going into radiation.


text:
Q: Vertical alignment of left/right subscripts Using mathtools's \prescript, the subscripts in $\prescript{}{n}X_m$ are not vertically aligned.  The problem does not seem to appear when using ${}_n X_m$, but this is undesirable for other reasons.
It seems \prescript does not take into account empty sub/superscripts, like TeX's mechanism does?
Of course I can do $\prescript{}{n}X^{\mbox{}}_m$, but I'd rather have the n up than the m down...

A: It's a bit more complicated than \prescript can deal with. One should add a "phantom" superscript on the other side, if one superscript is present.
\documentclass{article}
\usepackage{xparse}

\NewDocumentCommand{\xprescript}{e{_^}me{_^}}{%
  \makexprescript{#1}{#2}{#3}{#4}{#5}%
}

\ExplSyntaxOn
\NewDocumentCommand{\makexprescript}{mmmmm}
 {
  \bool_lazy_and:nnTF { \tl_if_novalue_p:n { #2 } } { \tl_if_novalue_p:n { #5 } }
   {% there is neither a presuperscript nor a postsuperscript
    \vphantom{#3} % the nucleus for the prescripts
    \tl_if_novalue:nF { #1 } { \sb{#1} } % the presubscript
    #3 % the nucleus
    \tl_if_novalue:nF { #4 } { \sb{#4} } % the postsubscript
   }
   {% there is either a presuperscript or a postsuperscript
    \vphantom{#3} % the nucleus for the prescripts
    \sp{\tl_if_novalue:nF { #2 } { #2 } }
    \tl_if_novalue:nF { #1 } { \sb{#1} } % the presubscript
    #3 % the nucleus
    \sp{\tl_if_novalue:nF { #5 } { #5 } }
    \tl_if_novalue:nF { #4 } { \sb{#4} } % the postsubscript
   }
 }
\ExplSyntaxOff

\begin{document}

$\xprescript_n{X}_m + \xprescript_n^2{X}_m + \xprescript_n{X}_m^2$

\end{document}


text:
Q: Trying to get the data from a site, which does not have an API, using BeautifulSoup So, I am making a scraper, which would scrape tabular data from a site, and then would upload this into an azure database. I am trying to scrape the data using Beautiful Soup. The site is https://www.pgcb.org.bd/PGCB/?a=pages/hourly_generation_loadshed_display.php The issue is that the html code for this site is rough.

Date
Time
Generation
Demand
Shortage
Loadshed
Remark

10-10-2019
09:00:00
7600.4
7600
0
0

10-10-2019
08:00:00
7165.2
7165
0
0

I have tried the following so far and got the above results, and some other text, which I can remove later. However, I need to get the text from
    Date
    Time
10-10-2019
09:00:00

in tabular format like,
Date | Time |
10-10-2019 | 9:00:00|
This is what I have done so far:
#import requests
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq # webclient

#scrapping from
page_url = "https://www.pgcb.org.bd/PGCB/?a=pages/hourly_generation_loadshed_display.php"
uclient = uReq (page_url)

#parsing the html

page_soup = soup (uclient.read(), "html.parser")
uclient.close()

table1 = page_soup.findAll("table",{"class":"layout display responsive-table"})

Please let me know how I can improve this and get the expected results.

A: BeautifulSoup is a great tool. But in this particular case, you can do it the long way with beautifulsoup, or anytime I see
 tags, I just use pandas' .read_html() to do the work (it uses BeautifulSoup under the hood), then just need to clean up the table a bit. It will return a list of all the tables tags. In this case, there are 2 table tags, and the table you want is in index position 1:
import pandas as pd

url = 'https://www.pgcb.org.bd/PGCB/?a=pages/hourly_generation_loadshed_display.php'

tables = pd.read_html(url)
df = tables[1]

df = df[:-1]
df = df.dropna(axis=1,how='all')

Output:
print (df.to_string())
          Date      Time Generation Demand Shortage Loadshed        Remark
0   10-10-2019  18:00:00       9182   9182        0        0           NaN
1   10-10-2019  17:00:00     8091.3   8091        0        0           NaN
2   10-10-2019  16:00:00     8277.7   8278        0        0           NaN
3   10-10-2019  15:00:00     8465.8   8466        0        0           NaN
4   10-10-2019  14:00:00     8394.7   8395        0        0           NaN
5   10-10-2019  13:00:00     8553.4   8553        0        0           NaN
6   10-10-2019  12:00:00       8376   8376        0        0      Day Peak
7   10-10-2019  11:00:00     8169.9   8170        0        0           NaN
8   10-10-2019  10:00:00     7900.9   7901        0        0           NaN
9   10-10-2019  09:00:00     7600.4   7600        0        0           NaN
10  10-10-2019  08:00:00     7165.2   7165        0        0           NaN
11  10-10-2019  07:00:00     6980.4   6980        0        0           NaN
12  10-10-2019  06:00:00     7017.1   7017        0        0           NaN
13  10-10-2019  05:00:00       7328   7328        0        0           NaN
14  10-10-2019  04:00:00       7504   7504        0        0           NaN
15  10-10-2019  03:00:00       7877   7877        0        0           NaN
16  10-10-2019  02:00:00       8071   8071        0        0           NaN
17  10-10-2019  01:00:00       8400   8400        0        0           NaN
18  09-10-2019  24:00:00       8847   8847        0        0           NaN
19  09-10-2019  23:00:00       9093   9093        0        0           NaN
20  09-10-2019  22:00:00       9483   9483        0        0           NaN
21  09-10-2019  21:00:00       9852   9852        0        0           NaN
22  09-10-2019  20:00:00      10284  10284        0        0  Evening Peak
23  09-10-2019  19:30:00      10229  10229        0        0           NaN
24  09-10-2019  19:00:00      10211  10211        0        0           NaN
25  09-10-2019  18:00:00       9538   9538        0        0           NaN

ADDITIONAL
If you want to see how it works with BeautifulSoup, to show how to iterate through. QHarr also provides another/better way above as well.
import pandas as pd
from bs4 import BeautifulSoup
import requests

url = 'https://www.pgcb.org.bd/PGCB/?a=pages/hourly_generation_loadshed_display.php'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

tables = soup.find_all('table')
table = tables[1]

headers = table.find_all('th')
columns = [ td.text for td in headers ]

df = pd.DataFrame()
rows = table.find_all('tr')
for row in rows:
    tds = row.find_all('td')
    data = [ td.text for td in tds ]
    temp_df = pd.DataFrame([data])

    df = df.append(temp_df, sort=True).reset_index(drop=True)

df = df.dropna(axis=1,how='all')
df = df.dropna(axis=0,how='all')
df.columns = columns
df = df[:-1]

A: I would target the single table rather than retrieve all; with faster css class selector
import pandas as pd
from bs4 import BeautifulSoup as bs
import requests

r = requests.get('https://www.pgcb.org.bd/PGCB/?a=pages/hourly_generation_loadshed_display.php')
soup = bs(r.text, 'html.parser')
df = pd.read_html(str(soup.select_one('.responsive-table')))
print(df)


text:
Q: Pandas - Excess return dataframe Got a dataframe with the return of some assets, df. I want to create a new one with the excess of returns, i.e., the difference between each column and 1m_Tbill.
In[2]: df
Out[2]:
               sp500  1m_Tbill       MCD       LUV       AIG
Period
1997-01-31  0.061317    0.0045  0.002755  0.000000  0.118938
1997-02-28  0.005928    0.0039 -0.047802  0.068707 -0.001032
1997-03-31 -0.042614    0.0043  0.092486 -0.058511 -0.029132
1997-04-30  0.058406    0.0043  0.132275  0.242938  0.094782
1997-05-30  0.058577    0.0049 -0.059206 -0.063216  0.053502
1997-06-30  0.043453    0.0037 -0.038557  0.004854  0.104155
1997-07-31  0.078123    0.0043  0.112549  0.120773  0.069456
1997-08-29 -0.057446    0.0041 -0.118233 -0.034084 -0.113850

I've tried to do this with the following code
R0 = df['1m_Tbill']
Re = df[['MCD','LUV','AIG','sp500']]
Re['sp500'] -= R0

However, this is throwing me the following warning
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  Re['sp500'] -= R0

How's the proper way to do this?


text:
Q: Getting "TypeError: Cannot read property 'slice' of undefined" when returning an object inside a map I have a large text file, that I am looping through so I can format it to a JSON format and then dump it, It works perfectly when I am using slice to make the fields start a different position, but as soon as I use slice, I get the following error:
TypeError: Cannot read property 'slice' of undefined.
This is the current code:
var fs = require('fs');
let words;

fs.readFile('dictionary.txt', "utf-8", function(error, contents) {
    if(error) throw error;
    words = contents.split('\n\n');

    words = words.map(value => value.split('\n'))
    .map((column, index) => {
        return {
            id: index+1,
            word: column[0].slice(10, -1),
            translation: column[2].slice(7, -1),
            description: column[3].slice(10, -1)
        }
    });

    fs.writeFileSync('words.json', JSON.stringify(words));
});

Keep in mind, when I use console.log(column[0].slice(10, -1), it works perfectly, but when I use it inside the returned object I get that error, the code also works when I remove the slice functions, but that is not what I want.
This is an example of what the text file looks like:
English : To obliterate
لقی:  هونەر
كوردی: خاپووركردن
وردەكاری: خاپووركردن

English : to one's credit
لقی:  گشتی
كوردی: جێی شانازی بوون بۆ كەسێك
وردەكاری: جێی شانازی بوون بۆ كەسێك

English : To outline
لقی:  هونەر
كوردی: كورتە نەخشەی كێشا
وردەكاری: كورتە نەخشەی كێشا

English : To paint without a model
لقی:  هونەر
كوردی: وێنەكێشانی بێ مۆدێل
وردەكاری: وێنەكێشانی بێ مۆدێل

English : To paste again
لقی:  هونەر
كوردی: سەرلەنوێ لكاندنەوە
وردەكاری: سەرلەنوێ لكاندنەوە

English : To patronize
لقی:  هونەر
كوردی: چاودێری
وردەكاری: چاودێری (هونەرمەندێكی) كرد

English : To pick
لقی:  هونەر
كوردی: پیككاری كرد
وردەكاری: پیككاری كرد (بەردەكەی تەختكرد)

English : To pick out by color
لقی:  هونەر
كوردی: دیاریكردن بەدژایەتی ڕەنگ
وردەكاری: دیاریكردن بەدژایەتی ڕەنگ

English : To plane
لقی:  هونەر
كوردی: دەپێكی سازكرد
وردەكاری:  (دەپێك)ی سازكرد

A: In case there's a \n\n at the end of the file add a filter to remove that last invalid "block"
Also, if there's \n\n\n or more somewhere in the file, you may want to fix that up too
var fs = require('fs');
let words;

fs.readFile('dictionary.txt', "utf-8", function(error, contents) {
    if(error) throw error;
    //               in case there's \n\n\n
    words = contents.replace(/\n{3,}/g, '\n\n').split('\n\n');

    words = words.map(value => value.split('\n'))
    // filter out last block if file ends in \n\n
    .filter(({length}) => length === 4)
    .map((column, index) => {
        return {
            id: index+1,
            word: column[0].slice(10, -1),
            translation: column[2].slice(7, -1),
            description: column[3].slice(10, -1)
        }
    });

    fs.writeFileSync('words.json', JSON.stringify(words));
});

This is a little more robust, but still probably not perfect


text:
Q: Images not found when testing website on mobile I am attempting to test a website created in Dreamweaver on my phone. I have a copy of the folder with all the html/images in my Dropbox. Let's say that filename is "website". Inside of "website" I have a folder called "images" with all the images for the site, as well as my stylesheet.
My html files link to images like this:   src="images/pic1.png"
A couple of the images are in the CSS, and are referenced like this: url(images/pic2.png)
On my computer, this works and all the images show up. On my phone in a folder that is an EXACT COPY, all of the images are broken links.
Anybody know what could be causing this?
Thank you!

A: I think that the problem is that your Dropbox is on your computer, and not on your phone. Based on what you said, you are accessing the images locally, therefore the phone doesn't see files on your computer. Try transporting all images from Dropbox to the server where you host your website. Then the phone should be able to see the images.


text:
Q: Cannot close stream until all bytes are written c# This is my first c# attempt in a while, but I have gotten myself to this point and maybe I think I need some expert eyes on it.
I keep getting the error mentioned in the title. I am guessing there is something obvious I am missing?
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace API_Call
{
    class Program
    {
        static void Main(string[] args)
        {
            var watch = new Stopwatch();
            HttpWebRequest request = HttpWebRequest.Create("http://bk-pim/Perfion/GetData.asmx") as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.Headers.Add("SOAPAction","http://perfion.com/ExecuteQuery");
            //FileInfo info = new FileInfo(@"C:\Users\dcoats\Desktop\mytestfile.txt");
            //long size = info.Length;
            //request.ContentLength = size;

            using (var stream = request.GetRequestStream())
            using (var writer = new StreamWriter(stream))
            {
                var body = WebUtility.HtmlEncode(File.ReadAllText(@"C:\Users\dcoats\Desktop\mytestfile.txt"));
                body = "<?xml version=\"1.0\" encoding=\"utf - 8\"?>< soap:Envelope xmlns:soap = \"http://schemas.xmlsoap.org/soap/envelope/\" xmlns: xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xmlns: xsd = \"http://www.w3.org/2001/XMLSchema\" >< soap:Body >< ExecuteQueryResponse xmlns = \"http://perfion.com/\" >< ExecuteQueryResult >" + body + "</ExecuteQueryResult></ ExecuteQueryResponse ></ soap:Body ></ soap:Envelope > ";

            }

            watch.Start();
            var response = request.GetResponse(); //bombs here
            watch.Stop();
            response.GetResponseStream();

            Console.WriteLine();
            Console.ReadLine();
            Console.WriteLine(watch.ElapsedMilliseconds);
            Console.ReadLine();
        }
    }
}

A: You asked for a better way to interact with a webservice:

*

*Right click REFERENCES in SOLUTION EXPLORER

*Choose ADD SERVICE REFERENCE

*Enter the URL where your service is located - example http://bk-pim/Perfion/GetData.asmx or http://www.dneonline.com/calculator.asmx

*Choose a namespace/set other options

*Click OK

*Create a client (I couldn't use your webservice, so this answer now switches to using DNEOnline's calculator, with a chosen namespace of "Calc" ):

Calc.CalculatorSoapClient sc = new Calc.CalculatorSoapClient();

*

*Call methods on the client:

int result = sc.Add(1,2);
That's it - no sockets, no building XML etc - the service reference creates a set of objects and classes that do all of that


text:
Q: Android Emulator removed by Visual Studio 2017 15.5.6 I was developing a Xamarin Android app, and happily using the Android emulator to test. My environment included Android Emulator Manager (AVD), Android SDK Manager, Android device monitor (DDMS) and more. After having worsening build problems and inexplicable build error messages, I decided to finally update Visual Studio to version 15.5.6 (The last time I had updated was late last year).
After updating, my Xamarin application is not even recognized as a Xamarin application any more, and my environment seems to have been severely corrupted. All the buttons to launch the Android tools are disabled. If I select them from the start menu, or run the EXE (AVD Manager.exe) directly from the file system, it says that tools\android.bat is not found. If I try to debug the application, I get the following output:
1>Starting deploy AVD_for_Nexus_6_by_Google ...
1>Starting emulator AVD_for_Nexus_6_by_Google ...
1>An error occured. See full exception on logs for more details.
1>This property is not valid when the SDK is not installed
========== Deploy: 0 succeeded, 1 failed, 0 skipped ==========

Why and how did a Visual Studio update screw up my environment so badly, and how do I fix it?

A: I opened Visual Studio Installer (from the Start menu) and selected the Repair command from the "More" dropdown. That fixed it.


text:
Q: Enabling libmp3lame for FFMPEG on elastic beanstalk I am trying to enable libmp3lame with FFMPEG in elastic beanstalk (Amazon Redhat Linux machine).
I am able to successfully install FFMPEG in /ffmpeg.config with the following script:
# .ebextensions/ffmpeg.config

packages:
  yum:
    autoconf: []
    automake: []
    cmake: []
    freetype-devel: []
    gcc: []
    gcc-c++: []
    git: []
    libtool: []
    make: []
    nasm: []
    pkgconfig: []
    zlib-devel: []
sources:
  /usr/local/src: http://ffmpeg.org/releases/ffmpeg-3.2.tar.bz2
commands:
  ffmpeg_install:
      cwd: /usr/local/src/ffmpeg-3.2
      command: sudo ./configure --prefix=/usr && make && make install

I need to install libmp3lame however. I've tried to do this with an --enable-libmp3lame flag and the directions here. The modified script:
packages:
yum:
    autoconf: []
    automake: []
    cmake: []
    freetype-devel: []
    gcc: []
    gcc-c++: []
    git: []
    libtool: []
    make: []
    nasm: []
    pkgconfig: []
    zlib-devel: []
sources:
  /usr/local/src: http://ffmpeg.org/releases/ffmpeg-3.2.tar.bz2
commands:
  01-install_libmp3lame:
      cwd: /usr/local/src/
      command: curl -L -O http://downloads.sourceforge.net/project/lame/lame/3.99/lame-3.99.5.tar.gz && tar xzvf lame-3.99.5.tar.gz && cd lame-3.99.5 && ./configure --prefix="$HOME/ffmpeg_build" --bindir="$HOME/bin" --disable-shared --enable-nasm && make && make install
  02-ffmpeg_install:
      cwd: /usr/local/src/ffmpeg-3.2
      command: sudo ./configure --enable-libmp3lame && --prefix=/usr && make && make install

This doesn't work. Command 01-install_libmp3lame completes. Command 02-ffmpeg_install fails because:
[2017-10-12T20:55:19.324Z] INFO  [24606] - [Application update app-8fe3-123456_7895@111/AppDeployStage0/EbExtensionPreBuild/Infra-EmbeddedPreBuild/prebuild_3_clover_platform/Command 02-ffmpeg_install] : Activity execution failed, because: ERROR: libmp3lame >= 3.98.3 not found

I have tried installing libmp3lame in /ffmpeg-3.2 and got the same issue.

A: *

*You used --prefix="$HOME/ffmpeg_build", but you didn't tell ffmpeg to look there for it. You can omit this and it will probably use /usr/local/ by default.

*You are trying to run --prefix=/usr as an independent command instead of part of your ffmpeg ./configure. You can omit this.

*If you're going to use a release branch of ffmpeg instead of the git snapshot you should use the latest version which is currently 3.3, not 3.2. However, 3.4 is due very soon (within days or a week I'm guessing).

*No need for sudo to configure, but you may need it for make install depending on your system and user.
Below are commands you can adapt. I didn't verify the paths are correct to the directories containing the source for lame and ffmpeg.
cd lame-3.99.5
make uninstall
make distclean
./configure --disable-shared --enable-nasm
make
make install
cd ../ffmpeg
make uninstall
cd ../
rm -f ffmpeg
curl -O http://ffmpeg.org/releases/ffmpeg-3.3.4.tar.bz2
cd ffmpeg
./configure --enable-libmp3lame
make
make install


text:
Q: JTextArea - are 2 different highlight colors possible? I want to highlight the text in a JTextComponent with two different colors. Is this possible with JTextArea (and if yes how?) - or do I need to use JTextPane or JEditorPane (if latter: which one is to recommend if the only thing I really want to 'style' are different background colors)?
thanks in advance


text:
Q: How to read data from a websocket hosted on Azure API Management using a C# ClientWebSocket? I have the following architecture piece that I am trying to test.

My goal is to read data published to Azure API Management through the AzurePubSub using a WebSocket client from my C# Console App. Azure PubSub is another element you are seeing on green that exposes a WebSocket endpoint that I am not going to make public for my clients. As part of Azure Api Management, I can expose it to external clients using a subscription key and my organization URL.
Using code from this repo: azure pubsub examples I was able to tap into the Azure PubSub element directly to read and write data from there. Here is my AzurePubSubSubscriber using the above repo
using System;
using System.Threading.Tasks;

using Azure.Messaging.WebPubSub;

using Websocket.Client;

namespace subscriber
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var connectionString = "Endpoint=https://pubsub.webpubsub.azure.com;AccessKey=myaccesskey;Version=1.0;";
            var hub = "myhub";

            // Either generate the URL or fetch it from server or fetch a temp one from the portal
            var serviceClient = new WebPubSubServiceClient(connectionString, hub);
            var url = serviceClient.GetClientAccessUri();

            using (var client = new WebsocketClient(url))
            {
                // Disable the auto disconnect and reconnect because the sample would like the client to stay online even no data comes in
                client.ReconnectTimeout = null;
                client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
                await client.Start();
                Console.WriteLine("Connected.");
                Console.Read();
            }
        }
    }
}

Here is my AzurePubSubPublisher
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Messaging.WebPubSub;

namespace publisher
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await Method1();
        }

        public static async Task Method1()
        {
            var connectionString = $"Endpoint=https://pubsub.webpubsub.azure.com;AccessKey=myaccesskey;Version=1.0;";
            var hub = "myhub";

            while (true)
            {
                Console.WriteLine("Write your message");
                var message = Console.ReadLine();

                if (string.IsNullOrEmpty(message))
                {
                    return;
                }

                // Either generate the token or fetch it from server or fetch a temp one from the portal
                var serviceClient = new WebPubSubServiceClient(connectionString, hub);
                await serviceClient.SendToAllAsync(message);
            }
        }
    }
}

Now when I expose the endpoint through the Azure API Management to consume content from my Console C# App is where I am not receiving data and am not sure what I am missing here.
Here is the C# code I used from my Console App to read data from Azure API Management endpoint:
   static async Task Main()
    {
        await StartWebSocketClient4();
        Console.ReadLine();
    }

    static async Task StartWebSocketClient4()
    {
        try
        {
            Console.Write("Connecting....");
            var cts = new CancellationTokenSource();
            var socket = new ClientWebSocket();

            string wsUri = "wss://myorganization.com/sub?subscription-key=ac3529b7619a383dc6ce6e618dbc9b7614a66";

            await socket.ConnectAsync(new Uri(wsUri), cts.Token);
            Console.WriteLine(socket.State);

            await Task.Factory.StartNew(
                async () =>
                {
                    var rcvBytes = new byte[1024 * 1024];
                    var rcvBuffer = new ArraySegment<byte>(rcvBytes);
                    while (true)
                    {
                        WebSocketReceiveResult rcvResult = await socket.ReceiveAsync(rcvBuffer, cts.Token);
                        byte[] msgBytes = rcvBuffer.Skip(rcvBuffer.Offset).Take(rcvResult.Count).ToArray();
                        string rcvMsg = Encoding.UTF8.GetString(msgBytes);
                        Console.WriteLine("Received: {0}", rcvMsg);
                    }
                }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


text:
Q: A generalisation of a well known result in information theory It is well known that Entropy is additive, and that it is the only sensible choice for measuring uncertainty if we want additivity to hold, i.e.
$H(XY) = H(X)+H(Y)$
or more explicitly, if we have the constraint that
$\int_\chi\int_\chi p_1(x)p_2(x) f(p_1(x)p_2(x)) dx^2 = \int_\chi p_1(x) f(p_1(x)) dx + \int_\chi p_2(x) f(p_2(x))dx$
with $\int_\chi p_1 dx = \int_\chi p_2 dx = 1$. The only choice is $f(u) = k \log(u)$.
There is a similar problem concerning f-divergences, where we can introduce an additivity constraint:
$\int_\chi\int_\chi p_1(x)p_2(x) f\left(\frac{p_1(x)p_2(x)}{q_1(x)q_2(x)}\right) dx^2 = \int_\chi p_1(x) f\left(\frac{p_1(x)}{q_1(x)}\right) dx + \int_\chi p_2(x) f\left(\frac{p_2(x)}{q_2(x)}\right)dx$
I am pretty sure that the only valid functions $f$ are
$f(u) = (A/u+B)\log(u)$
but I do not know how to show that (or even if) this exhausts all the possibilities.
EDIT:
Corrected u to 1/u, to fit the definition of $u = p/q$ (usually it is $q/p$).
How I get to $(\frac{A}{u}+B)\log(u)$
First of all, if $f(u)$ and $g(u)$ are solutions, so is their linear combination: $a f(u) + b g(u)$. I can find two solutions that are not linearly related
1) $f(u) = k_1 \log u$
2) $f(u) = k_2 \frac{\log u}{u}$  (this effectively switches p and q)
these can be shown to work, making all the solutions of the form I proposed valid as they are linear combinations of (1) and (2). The problem I have is that I am not sure that there are not other functions that are not linearly related to either (1) or (2).

A: Edited:
With due permission I am completely rewriting the proof.
Let $$D_f(P|Q)=\sum_i p_if(q_i/p_i)$$ where $f$ is a strictly convex function such that $f(1)=0$, satisfy additivity, i.e., $D_f(P_1\star P_2|Q_1\star Q_2)=D_f(P_1|Q_1)+D_f(P_2|Q_2)$ with $D_f((1,0)|(1/2,1/2))=1$, where $P\star Q$ is the product distribution, i.e., $(p_iq_j)_{i,j}$.
This proof is just a by product of Renyi's work.
Let $ P_1=P_2=(1,0),Q_1=(q_1,1-q_1), Q_2=(q_2,1-q_2)$.
Then $D_f(P_1\star P_2|Q_1\star Q_2)=f(q_1q_2)$, $D_f(P_1|Q_1)=f(q_1)$, and $D_f(P_2|Q_2)=f(q_2)$
So by additivity, $f(q_1q_2)=f(q_1)+f(q_2)$. And from $D_f((1,0)|(1/2,1/2))=1$, $f(1/2)=1$. Also from Jensen's inequality $D_f(P|Q)\ge f(1)=0$, hence $f$ is non negative.
The only $f$ satisfying the above three properties is $f(q)=-\log q$ and we are done.


text:
Q: Joining two lists in java I have lists of different classes, say A and B respectively. Definition of these classes is as follows-
class A {
 int field1;
 int field2;
}

class B {
 int field1;
 int field3;
}

class C {
 int field1;
 int field2;
 int field3;
}

I want to perform a join operation (similar to database join) on A and B, over field1 and populate the result in C.
I can iterate over the lists and do it. But, just wanted to check whether there are any library methods which does similar sort of thing.

A: If these are the only fields you're using, just iterate manually.
For larger data sets, group your data into Collections and apply a Cartesian Product algorithm.

A: You can add objects of any class to the list(if your list is not generic-specified). But when you get each object back from the list, you will not know the object is of which type.

A: Maybe by using a method in library in apache collections:
import org.apache.commons.collections.ListUtils;

List<?> newListC = ListUtils.intersection(list1, list2);

Hope it helps.


text:
Q: Regular expression for splitting JSON text in lines after symbols I am trying to use a regular expression to have this kind of string
{
 "key1"
:
value1
,
"key2"
:
"value2"
,
"arrayKey"
:
[
{
"keyA"
:
valueA
,
"keyB"
:
"valueB"
,
"keyC"
:
[
0
,
1
,
2
]
}
]
}

from
JSONObject.toString()

that is one long line of text in my Android Java app
{"key1":"value1","key2":"value2","arrayKey":[{"keyA":"valueA","keyB":"valueB","keyC":[0,1,2]}]}

I found this regular expression for finding all commas.
/(,)(?=(?:[^"]|"[^"]*")*$)/

Now I need to know:
0- if this is reliable, that is, does what they say.
1- if this is works also with commas inside double-quotes.
2- if this takes into account escaped double-quotes.
3- if I have to take into account also single quotes, as this file is produced by my app but occasionally it could be manually edited by the user.
5- It has to be used with the multi-line flag to work with multi-line text.
6- It has to work with replaceAll().
The resulting regular expression will be be used for replacing each symbol with a two-char sequence made of the symbol itself plus \n character.
The resulting text has to be still JSON text.
Subsequent replace actions will take place also for the other symbols
: [ ] { }

and other symbols that can be found in JSON files outside the alphanumeric sequences between quotes (I do not know if the mentioned symbols are the only ones).

A: Its not that much simple, but yes if you want to do then you need to filter characters([,{,",',:) and replace then with a new line character against it.
like:
[ should get replaced with [\n

Answer to your question is Yes its very much reliable and good to implement its just a single line of code doing all. Thats what regex is made for.

A:
0- if this is reliable, that is, does what they say.

Let's break down the expression a little:

*

*(,) is a capturing group that matches a single comma

*(?=...) would mean a positive lookahead meaning the comma would need to be followed by a match of that group's content

*(?:...)* would be a non-capturing group that can occur 0 to many times

*[^"]|"[^"]*" would match either any character except a double quote ([^"]) or (|) a pair of double quotes with any character in between except other double quotes ("[^"]*")

As you can see especially the last part could make it unreliable if there are escaped double quotes in a text value, so the answer would be "this is reliable if the input is simple enough".

1- if this is works also with commas inside double-quotes.

If the double quote pairs are correctly identified any commas in between would be ignored.

2- if this takes into account escaped double-quotes.

Here's one of the major problems: escaped double quotes would need to be handled. This can get quite complex if you want to handle arbitrary cases, especially if the texts could contain commas as well.

3- if I have to take into account also single quotes, as this file is produced by my app but occasionally it could be manually edited by the user.

Single quotes aren't allowed by the JSON sepcification but many parsers support them because humans tend to use them anyway. Thus you might need to take them into account and that makes no. 2 even more complex because now there might be an unescaped double quote in a single quote text.

5- It has to be used with the multi-line flag to work with multi-line text.

I'm not entirely sure about that but adding the multi-line flag shouldn't hurt. You could add it to the expression itself though, i.e. by prepeding (?m).

6- It has to work with replaceAll().

In its current form the regex would work with String#replaceAll() because it only matches the comma - the lookahead is used to determine a match but won't result in the wrong parts being replaced. The matches themselves might not be correct though, as described above.
That being said, you should note that JSON is not a regular language and only regular languages are a perfect fit for regular expressions.
Thus I'd recommend using a proper JSON parser (there are quite a lot out there) to parse the JSON into POJOs (might just be a bunch of generic JsonObject and JsonArray instances) and reformat that according to your needs.
Here's an example of how Jackson could be used to accomplish that: https://kodejava.org/how-to-pretty-print-json-string-using-jackson/
In fact, since you're already using JSONObject.toString() you probably don't need the parser itself but just a proper formatter (if you want/need to roll your own you could have a look at the org.json.JSONObject sources ).


text:
Q: Determine when an ASP.NET Forms Authentication will expire Is it possible to determine the date & time when an ASP.NET session will expire when using Forms Authentication?
I would like to warn users when their sessions are about to expire. There is no session state & sliding expiration is disabled. Here are some of the system.web settings:
<authentication mode="Forms">
  <forms defaultUrl="Default.aspx" loginUrl="Login.aspx" requireSSL="false" enableCrossAppRedirects="true" cookieless="AutoDetect" timeout="2" slidingExpiration="false"/>
</authentication>

<sessionState mode="Off"/>

The timeout / lifetime of a session is easy to determine, but should the user refresh the page within the session windows, adding the lifetime value to the date-time at reload will not be accurate.
Using an authentication cookie with FormsAuthenticationTicket ticket encrypted as its value, one can decrypt it to get the expiration date-time.
Although some AJAX calls may be made, the user might interact with the UI without any post back or request to the webserver.
Any ideas on how I can achieve this type of behavior without the use of cookies?

A: I have a similar problem. In my case given the low number of users, im opting for a better user experience with a polling ajax call on the page to call back into the server and check the expiration ticket. You may be able to get away with tweaking the below code and including expiration info in the page via http and keeping track of time in client javascript if you dont want to go the ajax route.
        if (User.Identity.IsAuthenticated)
        {
            var identity = (FormsIdentity)User.Identity;
            viewModel.UtcInactivityExpiryDate = identity.Ticket.Expiration.ToUniversalTime();
        }

If you go the ajax route, there is another gotcha. You have to stop the ajax call itself from renewing the inactivity timeout if you are using one. You can do that by overwriting the new authentication cookie with the original one. at the end of your ajax request.
            var requestCookie = HttpContext.Current.Request.Cookies[".ASPXAUTH"];
            if (requestCookie != null)
            {
                HttpContext.Current.Response.Cookies.Add(requestCookie);
            }


text:
Q: Unable to load a file from drawables- open CV I have my image file under drawable folder, I am trying to read the image to process it further.This is the method I am using ,image.width() always return 0,I am not getting any errors in the log cat.
public Mat loadImageFromFile(String fileName) {

        Mat rgbLoadedImage = null;

        File root = Environment.getExternalStorageDirectory();
        File file = new File(root, fileName);

        // this should be in BGR format according to the
        // documentation.
        Mat image = Highgui.imread(file.getAbsolutePath());

        if (image.width() > 0) {

            rgbLoadedImage = new Mat(image.size(), image.type());

            Imgproc.cvtColor(image, rgbLoadedImage, Imgproc.COLOR_BGR2RGB);

            if (DEBUG)
                Log.d(TAG, "loadedImage: " + "chans: " + image.channels()
                        + ", (" + image.width() + ", " + image.height() + ")");

            image.release();
            image = null;
        }
        return rgbLoadedImage;

    }

I am calling this method after open CV has been loaded
private BaseLoaderCallback  mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully...................");
                    loadImageFromFile("pedestrian");

                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };

I have also tried  Mat m = Highgui.imread("/pedestrian"); here also m.width() is 0.

A: This is how it works ,
Mat img = Utils.loadResource(context, R.drawable.pedestrian, Highgui.CV_LOAD_IMAGE_COLOR);


text:
Q: Simple deep copying method in Java I am trying my hand at deep copying in Java. So far I have implemented the following method in the class (Example) whose objects I would like to get deep copies of (parameter1 and parameter2 being the parameters needed by the constructor of the Example-class to create an object of the latter):
public Example clone(){
   Example clone = new Example(this.parameter1, this.parameter2);
   return clone;
   }

So basically I clone an object by calling the constructor of the corresponding class and by using its current attributes as parameters for that constructor.
My problem is that this seems a bit too simple to be true. Especially since the solutions I looked up online were much more complex. So I'm wonderin what the hook is with my method.
Any hint/explanation will be greatly appreciated.
EDIT:
This is the constructor for the Example-class:
public Example(double parameter1, double parameter2){
    this.parameter1 = parameter1;
    this.parameter2 = parameter2;
    }

A: With primitives it is relatively simple. But if you had any fields that were not primitive, just using that copy constructor would only result in a shallow copy of that object. Meaning you would be using the same object for your field between the classes.


text:
Q: How to I dispatch a state value to an const variable in Redux-toolkit? I am trying get an error to show in my component which is being dispatched from my actions and assigned to my errorAlert constent, however it always comes back as null even when there is content in my state as per console.log. I have shared the console log results below.
Is there an issue when assigning a redux state variable to a const?
slice.js
const auth = createSlice({
    name: "auth",
    initialState: verifiedResult: {},
    reducers: {
        verifySuccess(state, { payload }) {
            state.verifiedResult = payload;
            state.isLoading = false;
            state.error = null;
        }
    }

action.js
...
if (result.state === "pending") {
    await new Promise((resolve) => setTimeout(resolve, 10000));
       } else if (result.state === "failed") {
            dispatch(verifySuccess(result));
    break;

component.js
....
const errorAlert =
        auth.verifiedResult.cel_number === false
            ? "The number associated with your account is not a valid."
            : auth.verifiedResult.prepaid_number === false
            ? "Mobile number is not Prepaid or is not active."
            : auth.verifiedResult.has_recharged === false
            ? "Mobile number must be recharged in the past 30 days"
            : null;
return (
<>
{errorAlert && <div>{errorAlert}</div>}
</>
)}

console.log
::auth.verifiedResult::
{
state: "failed"
cel_number: 'XXX XXX XXX'
prepaid_number: false
recharged: false
}

:::errorAlert::: null

A: It shows Mobile number is not Prepaid or is not active. in my case. Make sure your auth.verifiedResult is correctly written(you don't use comma after every object property).

const auth = {};

auth.verifiedResult = {
  state: 'failed',
  cel_number: 'XXX XXX XXX',
  prepaid_number: false,
  recharged: false,
};

const errorAlert =
  auth.verifiedResult.cel_number === false
    ? 'The number associated with your account is not a valid.'
    : auth.verifiedResult.prepaid_number === false
    ? 'Mobile number is not Prepaid or is not active.'
    : auth.verifiedResult.has_recharged === false
    ? 'Mobile number must be recharged in the past 30 days'
    : null;

console.log(errorAlert); // Mobile number is not Prepaid or is not active.

A: Did you mean
if (result.state === "pending")?


text:
Q: Unable to access host created by Nancy using external IP I am creating a Nancy Module that will eventually be hosted inside of a Windows Service. To start the Nancy hosting, I am using Nancy.Hosting.Self. Below is the code to start Nancy host.
string strHostProtocol = Convert.ToString(ConfigurationManager.AppSettings["HostProtocol"]);
string strHostIP = Convert.ToString(ConfigurationManager.AppSettings["HostIP"]);
string strHostPort = Convert.ToString(ConfigurationManager.AppSettings["HostPort"]);

//Here strHostProtocol="https", strHostIP = "192.168.100.88" i.e. System IPv4, strHostPort = "9003"

var url = strHostProtocol + "://" + strHostIP + ":" + strHostPort;
//url ="https://192.168.100.88:9003"

this.host = new NancyHost(new Uri(url));
this.host.Start();

Now once the windows service starts, it will start the above host and I could see this in netstat -a command. When I browse this in browser using https://192.168.100.88:9003 I will get proper response.
The problem arises when the same is browsed using its external IP. Say this system has been assigned with external IP of 208.91.158.66 and when I try browsing this as https://208.91.158.66:9003 I will just get a browser default loading progress continuosly which does not stop and without any error thrown. I have also added the below command and reserved URL successfully.
netsh http add urlacl url=https://192.168.100.88:9003/ user=everyone
But even after this the host cannot be browsed using external IP assigned to that system. Is there any restricting Nancy is putting up? Firewalls are turned off, defenders are turned off. Anyone has any idea on this?
UPDATE
The duplicate linked question talks about LAN but here I am trying through external IP and I've tried answer mentioned over there and also specified the same in question

A: Alright. This issue was also posted to GitHub Nancy Repo and below is what @Khellang had to say.

When you bind to https://192.168.100.88:9003, the
  TcpListener/HttpListener won't listen on other interfaces. You either
  have to bind to https://208.91.158.66:9003 or https://localhost:9003
  and set RewriteLocalhost = true (default).

Further he also said that

If you also want to listen to requests coming to the external IP, yes.
  Or you could use a wildcard, like https://+:9003/, https://*:9003/ or
  https://localhost:9003/ (with RewriteLocalhost = true, this will
  result in https://+:9003/). You can read more about them in the link I
  posted.

and thanks to @TimBourguignon as he suggested the same in his comments. Hope this helps someone in future.
He has also suggested to read this link to know more about the Strong Wildcard and Weak Wildcard


text:
Q: Let $m$ be the length of the diagonal of a regular four-sided prism which closes an angle $\alpha$ with the side of the prism Let $m$ be the length of the diagonal of a regular four-sided prism which closes an angle $\alpha$ with the side of the prism. Calculate the surface of the perimeter.
I guessed the angle is the diagonal of the side of the prism and the diagonal of the whole prism. I then just guessed it was a right angle and got everything I need with simple trigonometry formulas and Pythagoreans theory and I got the correct answer. But the thing is that I just guessed and I don't really know why the angle is right or why that is the angle in the first place. If somebody can please help explain how and why it is like that I would really appreciate it.

A: Let $a$ be the edge of the base and $h$ the height of the prism. The diagonal of the prism is also a diagonal of the rectangle having as sides the diagonal of the base (length $\sqrt2a$) and a lateral edge (length $h$). Hence:
$$
h=m\cos\alpha,\quad \sqrt2 a=m\sin\alpha,
$$
and the surface of the pyramid is:
$$
S =2a^2+4ah=m^2\sin^2\alpha+2\sqrt2 m^2 \sin\alpha\cos\alpha.
$$


text:
Q: DI in JEE7 / JAX-RS and DI for embeded server What is the best way for use Dependency Injection in JEE6 / JAX-RS without Jersey? We would use CDI, but we also need it for a embeded server (Jetty or Grizzly). It is for tests.

A: DI is not a part of JAX-RS spec. JAX-RS is a spec only and Jersey is an implementation of it. There are other implementations like Apache CXF which play nicer with other DI frameworks (like Spring) or not use any at all.
Does this answer your question? It's not clear what you're trying to do.

A: You should be able to continue using Jersey in Websphere 8.5 by disabling the jax-rs engine and using a Isolated Classloader with shared library for jersey library/jars and referring the same in your application.
Another thread with more details on same.


text:
Q: bash/zsh input process substitution gives syntax error in conjunction with while These work fine and do what they should (print the contents of the file foo):
cat <foo
while read line; do echo $line; done <foo
cat <(cat foo)

However this gives me a syntax error in zsh:
zsh$ while read line; do echo $line; done <(cat foo)
zsh: parse error near `<(cat foo)'

and bash:
bash$ while read line; do echo $line; done <(cat foo)
bash: syntax error near unexpected token `<(cat foo)'

Does anybody know the reason and maybe a workaround?
Note: This is obviously a toy example. In the real code I need the body of the while loop to be executed in the main shell process, so I can't just use
cat foo | while read line; do echo $line; done

A: You need to redirect the process substitution into the while loop:
You wrote
while read line; do echo $line; done <(cat foo)

You need
while read line; do echo $line; done < <(cat foo)
# ...................................^

Treat a process substitution like a filename.

A: bash/zsh replaces <(cat foo) by a pipe (kind of file) having a name as /dev/fd/n where n is the file descriptor (number).
You can check the pipe name using the command echo <(cat foo).
As you may know, bash/zsh also runs the command cat foo in another process. The output of this second process is written to that named pipe.
without process substitution:
while ... do ... done   inputfile #error
while ... do ... done < inputfile #correct

same rules using process substitution:
while ... do ... done   <(cat foo) #error
while ... do ... done < <(cat foo) #correct

Alternative:
cat foo >3 & while read line; do echo $line; done <3;

A: I can suggest only workaround like this:
theproc() { for((i=0;i<5;++i)) do echo $i; }

while read line ; do echo $line ; done <<<"$(theproc)"