Q: Removing a portion of text using regex? Here is what I have up to this point:
The function .*? takes everything until the first "this character". For example $html = preg_replace('/alt=".*?"/', '', $html); replaces everything between alt=" and other quotation mark with nothing. My problem is now I have to deal with multiple characters. Here is the portion of text I want to replace :

Unlike last time I can't use quotation marks or other such character. I have to delete the whole line. One thing I thought about was to do something like this:
$html = preg_replace('/)/', '', $html);

I thought that using the above code would find the last portion in this segment and replace everything inside but it replaces nothing. Please suggest what should I do?
After running above line of code the output should be nothing. It should remove all this code block.

A:

or without quotation mark :

We match everything that starts by , before which you may have zero or one iteration of the string alt="" containing anything but a ".


Q: Who is the artist behind the US box art for the first Mega Man? I've tried looking around but I have failed miserably to find it myself. Who is the artist behind the box art for the US release of the first Mega Man?

Box art taken from Megaman wikia.

A: While we do not have the name, we do know who the person was and why it turned out like it did. Here's from an interview with the American MM team:
Quote:

The president of Capcom US said to his marketing guy: "We need a
  cover done tomorrow".
  He went out and got a friend of his to do it in like 6 hours.

Source (timestamp 05:33):


Q: How to create a button in unity from Input.GetMouseButtonDown How can I create a touch event or UI button that can execute the code below. I got that code from an asset that meant for PC i want to re-create that project for android mobile
using UnityEngine;

using System.Collections;
public class PlayerIO : MonoBehaviour {
RaycastHit hit;
int maxBuildDist = 10;
public Transform RetAdd;
public Transform RetDelete;
public Transform Player;
public GameObject Player_Camera;
Color Block_Color = Color.blue;
bool Block_Menu = false;

void Start(){
    RetAdd = GameObject.Find("RetAdd").transform;
    RetDelete = GameObject.Find("RetDel").transform;
    Player = GameObject.FindGameObjectWithTag("Player").transform;
    Player_Camera = GameObject.Find("Main Camera");
}

void Update(){
    if(Input.GetKeyDown(KeyCode.E))
        Block_Menu = !Block_Menu;
    if(Block_Menu){
        Time.timeScale = 0;
        Player.GetComponent<MouseLook>().enabled = false;
        Player_Camera.GetComponent<MouseLook>().enabled = false;
        //((MonoBehaviour)Player.GetComponent<FPSInputController>()).enabled = false;
    }
    if(!Block_Menu){
        Time.timeScale = 1;
        Player.GetComponent<MouseLook>().enabled = true;
        Player_Camera.GetComponent<MouseLook>().enabled = true;
        //((MonoBehaviour)Player.GetComponent<FPSInputController>()).enabled = true;
    }

    if(!Block_Menu){
        if(Physics.Raycast(Camera.main.ScreenPointToRay(new Vector3((Screen.width / 2), (Screen.height / 2), 0)), out hit, maxBuildDist)){
            RetAdd.GetComponent<Renderer>().enabled = true;
            if(hit.transform.tag == "Block"){
                RetAdd.transform.position = hit.transform.position + hit.normal;
                RetDelete.transform.position = hit.transform.position;
                RetDelete.GetComponent<Renderer>().enabled = true;
            }
            if(hit.transform.tag != "Block"){
                RetDelete.GetComponent<Renderer>().enabled = false;
                RetAdd.transform.position = new Vector3(hit.point.x, hit.point.y + 0.5f, hit.point.z);
            }
            if(Input.GetMouseButtonDown(0)){
                GameObject block = (GameObject)Instantiate(Resources.Load("Block01"), RetAdd.transform.position, Quaternion.identity);
                block.GetComponent<Renderer>().material.color = Block_Color;
            }
            else if(Input.GetMouseButtonDown(1) && hit.transform.tag != "Floor"){
                Destroy(hit.transform.gameObject);
            }
        }
        else{
            RetAdd.GetComponent<Renderer>().enabled = false;
            RetDelete.GetComponent<Renderer>().enabled = false;
        }
    }
}

void OnGUI(){
    if(Block_Menu)
        Block_Menu_GUI();
}

void Block_Menu_GUI(){
    GUILayout.BeginVertical();
    if(GUILayout.Button("Green"))
        Block_Color = Color.green;
    if(GUILayout.Button("Red"))
        Block_Color = Color.red;
    if(GUILayout.Button("Blue"))
        Block_Color = Color.blue;
    GUILayout.EndVertical();
}

}
this is the whole code of the script that I want to change. I already had a joystick control but the problem is since I'm using that OnMouseDown whenever I click my joystick the object is spawning


Q: How can I use Provider to provide a bloc to a PageView() without the child resubscribing everytime I switch page? I am using Provider to provide my bloc to a widget called TheGroupPage via a static create method
  static Widget create(BuildContext context, GroupModel group) {
    final database = Provider.of<DatabaseService>(context);
    return Provider(
      create: (_) => GroupMembersBloc(database, group),
      child: TheGroupPage(group),
      dispose: (BuildContext context, GroupMembersBloc bloc) => bloc.dispose(),
    );
  }

That widget has a PageView() with 3 pages
  PageView(children: [
    TheGroupNotificationsView(),
    TheGroupMembersView(group),
    TheGroupSettingsView(group),
  ])

The group members view looks for the GroupMembersBloc
GroupMembersBloc bloc = Provider.of<GroupMembersBloc>(context);

I also tried to put listen to false but this did not work. And I want the widget to listen for any changes. The page uses that bloc's stream to draw a list of group members
class GroupMembersBloc{

  StreamController<List<UserModel>> _controller = StreamController<List<UserModel>>();
  Stream<List<UserModel>> get stream => _controller.stream;

  GroupMembersBloc(DatabaseService database, GroupModel group)
  {
   _controller.addStream(database.groupMembersStream(group));
  }

  void dispose(){
    _controller.close();
  }
}

The problem is when I switch page inside the PageView() I get an error on the page after the first time it has been shown. The error says Bad state: Stream has already been listened to. how can I solve this?

A: That's because stream controllers allow only 1 Subscription (or 1 listener) , you could use the [StreamController<List<UserModel>>.broadcast()][1] constructor instead of StreamController>().

A: I ended up moving the StreamBuilder to the parent widget above the PageView() which fixed the problem.


Q: Getting Errors When Downloading Files From SQL Database I am running a website, and part of the site is allowing users to upload files to a SQL database, and then download them. The download itself works, but the file is getting corrupted.  Image files cannot be opened, doc files are showing up as blank.  I will attach below my uploading script and my downloading script.
  $classid = $_POST['uploadclass'];
$userid = $_SESSION['id'];
$view = $_POST['view'];

$filename = $_FILES['uploadfile']['name'];
$tmpname = $_FILES['uploadfile']['tmpname'];
$filesize = $_FILES['uploadfile']['size'];
$filetype = $_FILES['uploadfile']['type'];

$fp = fopen($tmpname, 'r');
$content = fread($fp, filesize($tmpname));
$content = addslashes($content);
fclose($fp);

if (!get_magic_quotes_gpc()){
 $filename = addslashes($filename);
}
$query = "INSERT INTO uploads VALUES('','$filename', '$filetype', '$filesize', '$content', '$userid', '$classid', '$view', 'no')";
$run = mysqli_query($connect, $query);

mysqli_close($connect);
header('location: files.php');

Below is the code for my download page.
$query = "SELECT * FROM uploads WHERE id=$id";
$run = mysqli_query($connect, $query);
while ($row = mysqli_fetch_assoc($run)){
$name = $row['name'];
$type = $row['type'];
$size = $row['size'];
$content = $row['content'];

}
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
?>

A: You are incorrectly handling the files and everything else when inserting them into the database. All files that are already there are damaged and probably destroyed.
addslashes() is no escaping function for a database. Always use the escaping function that comes with the DB extension you are using. If you are using mysqli, then the correct function must be mysqli_real_escape_string().
You should however have a look at prepared statements. These will use an different way of transferring the data that does not need escaping. Do pay attention however to the setting of magic quotes. The preferred setting is OFF, and the recent PHP versions starting with 5.4 have this feature removed already. So you have to deal with escaping the data you insert into the database anyway.


Q: Where in a "block" I am doing a program that have very similar code blocks, and I was trying to make a where in a "block".
Just an example
function "sum" x = x + a
function "product" x = x * a
  where
    a = 2

I want the 'a' to be replaced in both lines, but I didn't find out if this is possible using where
Thanks in advance

A: If you really need this, you need to merge the two function clauses. One way to do this:
func what x = case what of
        "add" -> x+a
        "mul" -> x*a
    where
       a = 2

A: You can also introduce a second function:
function fName x = function' fName x
   where
      a = 2
      function' "sum"     x = x + a
      function' "product" x = x * a

A: (Forgive me because I'm a newbie.)  I don't think this is possible.  The scope of the where "block" is the function it's defined in.  What you can do is this, though:
Prelude> let a = 2
Prelude> let sum x = x + a
Prelude> let product x = x * a
Prelude> sum 3
5

This is done in GHCi.  You may be concerned that everyone can see a, but if this were in a .hs file, you could make it a module and just not export a, and then only these functions could see it.

A: I think you can define a new function geta
geta=2

And then you can use the geta function in any other functions.
I don't think mix every functions is a good way,
maybe you will have 20 functions need the same value


Q: bash syntax - wrapping command inside sudo :: tail logs until string found with timeout using Terraform Goal: using sudo execute a one line cmd to tail a log until a string is found and then exit 0.  If the string is not found within a given timeout, exit anything but 0.
Attempted Solution 1: Originally I did not have timeout as a requirement and so after some research I landed on using:
sudo sh -c '( tail -n1 -f /path/to/nameOfLog.log & ) | grep -q "Started .*Application"'

However, now I do have timeout as a requirement.  I could not figure out how to get timeout to work with this command until I found Ondra Žižka's answer.  So my new cmd became:
Attempt Solution 2:
timeout 5 grep -q "Started .*Application" <(tail -n1 -f /path/to/nameOfLog.log &)
But this obviously is not using sudo permissions, which is the current issue I need to solve.  Below are some variations I've tried which failed
Try 1 : (add sudo in front of cmd)
sudo timeout 5 grep -q "Started .*Application" <(tail -n1 -f /path/to/nameOfLog.log &)

Output:
grep: /dev/fd/63: No such file or directory

Try 2: (try to wrap cmd in subshell)
sudo sh -c 'timeout 5 grep -q "Started .*Application" <(tail -n1 -f /path/to/nameOfLog.log &)'

Output:
sh: 1: Syntax error: "(" unexpected

Can someone show me and explain the issue and how to fix it so I can run this command using sudo?  Also, do I really need to restructure cmd from Attempted Solution 1 to get it to work with timeout as well?

A: Found Alexander Batischev's answer to use sudo su -c.
Solution (OLD):
sudo su -c 'timeout 200 grep -q "Started .*Application" <(tail -n1 -f /path/to/nameOfLog.log &)'

UPDATE:
Based on ilkkachu's answer I did some more testing and found a new solution.

*

*First, in response to ilkkachu's answer about sudo su being redundant. If I remove sudo from the command I'm prompted to enter a password.

*Second, in response to ilkkachu's answer about a subshell not being useful. This is true.  However, the command without the subshell only returns if the log is actively being written to for some reason. Otherwise it hangs. When using the subshell the cmd returns even if the log is not actively being written to.  So I prefer subshell command, but sh doesn't support subshells.
Also, I noticed when testing on an active log that the use of using bash vs. sh has different time. For some reason sh takes a second longer to respond then bash.
For these two reasons (using subshell and delay in sh over bash) I decided sh is not suitable solution.

*Third, in response to ilkkachu's answer regarding the unecessary & for tail.  That is correct, I removed it and it had no impact.
Summary:
sudo su vs. su
//prompts for password w/out sudo
su -c 'timeout 200 grep -q "Started .*Application" <(tail -n100 -f /path/to/nameOfLog.log &)''

//works
sudo su -c 'timeout 200 grep -q "Started .*Application" <(tail -n100 -f  /path/to/nameOfLog.log  &)'

using sh -c
//either works (sudo or not using sudo)
//but both won't work unless log is actively being written to for some reason

sudo sh -c 'tail -n100 -f /path/to/nameOfLog.log | grep -q "Started .*Application"'

sh -c 'tail -n100 -f /path/to/nameOfLog.log | grep -q "Started .*Application"'

using bash
//either works (sudo or not using sudo)

sudo bash -c 'timeout 5 grep -q "Started .*Application" <(tail -n100 -f /path/to/nameOfLog.log &)'

bash -c 'timeout 5 grep -q "Started .*Application" <(tail -n100 -f /path/to/nameOfLog.log &)'

NEW Solution:
I realized I left out one important detail. Which is that this was being executed via a terraform remote-exec provisioner.  Terraform creates a local .sh script under /tmp/ on the server for any inline commands.  The communicator/ssh/communicator.go sets #!/bin/sh at the top of the scripts which means they are using sh.  So since I'm using a subshell I need to use bash.  The use of sudo is not necessary and was my misunderstanding.  However, you can still use sudo.  So the answer I went with is either of the using bash commands listed under the Summary above.
P.S. my target servers in this case were running 14.04.1-Ubuntu.  Running ls -l /bin/sh shows /bin/sh -> dash so actually I'm not using sh but dash. So it appears dash has the same setbacks as sh.

A: 1) I'm not sure if the subshell (or backgrounding) is useful here:
sudo sh -c '( tail -n1 -f /path/to/nameOfLog.log & ) | grep -q "Started .*Application"'

shouldn't a simple pipe do?
sudo sh -c 'tail -n1 -f /path/to/nameOfLog.log | grep -q "Started .*Application"'

2) Your "try 1":
sudo timeout 5 grep -q "Started .*Application" <(tail -n1 -f /path/to/nameOfLog.log &)

expands the input redirection <() on the command line that runs the sudo, not inside sudo. The filehandle it opens isn't passed through sudo to grep, so grep can't open the /dev/fd/63 pseudo-file.
Same thing about backgrounding the tail here, it shouldn't be necessary.

3) And, as phk commented, your "try 2":
sudo sh -c 'timeout 5 grep -q "Started .*Application" <(tail -n1 -f /path/to/nameOfLog.log &)'

...explicitly runs sh, and not bash or any other more featureful shell. Plain standard sh doesn't support <(), and neither does dash which is used as sh on Debian and Ubuntu.
When you run su instead, it runs root's login shell, which is likely to be bash on Ubuntu. But using both sudo and su is redundant, they're both made to elevate privileges, and after sudo you're already running elevated privilege, so no need for su. Instead, if you want to run a shell inside sudo, just say explicitly which one:
sudo bash -c 'timeout 5 grep -q "Started .*Application" <(tail -n1 -f /path/to/nameOfLog.log &)'


Q: Referring to a previously existing DataSet I'm working on a very basic VB.net frontend for an Access database and have stumbled upon a problem.

Dim ds As DataSet

MaxRows = ds.Tables("Course_assignmentsDataSet.tblCourse").Rows.Count
i = 0

Private Sub Navigate()
    txtCourseReference.Text = ds.Tables("Course_assignmentsDataSet.tblCourse").Rows(i).Item(1)
    txtCourseName.Text = ds.Tables("Course_assignmentsDataSet.tblCourse").Rows(i).Item(2)

End Sub

I get the error that Object Reference is not set to an instance of an Object. I think this is because I haven't defined the DataSet as "Course_assignmentsDataSet"- the one I want to use- but I'm not sure how to do this.
Can anyone help?

A: Your dataset needs to be instantiated using the "New" keyword. The object reference in this case is ds, and it's just set to type dataset. New creates an "instance" of the DataSet.
Dim ds as New Course_assignmentsDataSet

Then you'll want to do:
 txtCourseReference.Text = ds.Tables("tblCourse").Rows(i).Item(1)
 txtCourseName.Text = ds.Tables("tblCourse").Rows(i).Item(2)

Edit: As Jay said below, you'll want to fill the dataset first


Q: Resolve remote host names into ip addresses in codename one I'm interested in the ip address of remote hosts. Is there an easy way to resolve a host name into its ip address?
After searching in the codename one source code and reading through the documentation, the only way to achieve this seems by implement android/ios native features (e.g. using the InetAddress class).

A: Yes you would need to implement this using native code or thru the Socket API by implementing the DNS protocol calls.
The InetAddress class can be used in the Android/Desktop ports but other platforms (e.g. iOS) would need the Objective-C/C equivalent of that.


Q: R loop through name specific columns to check the value I want to achieve the following:

*

*loop through all CHECK columns, sometimes there are more (up to 20). The same goes for data (will definitely more than 3 observations). feel free to use my variables CHECKnum, CHECKstart or CHECKend

*check whether A001 is in it, if yes, return the column name, else return CHECK0

sample data
mydf <- data.frame(case = c(1, 2, 3),
                   id = c(10, 11, 12),
                   CHECK1 = c("A001", "B001", "C001"),
                   CHECK2 = c("Z001", "B001", "C001"),
                   CHECK3 = c("Z001", "B001", "C001"),
                   CHECK4 = c("Z001", "B001", "A001"),
                   CHECK5 = c("Z001", "B001", "C001"))

Trial:
CHECKnum = ifpol %>%
  colnames(.) %>%
  str_which("^CHECK") %>%
  length(.)

CHECKstart = which(colnames(ifpol) == "CHECK1")
CHECKend = CHECKstart + CHECKnum

for (i in 1:CHECKnum) {
  # giving out position and column name
  mydf = mydf %>% mutate(CHECK_Pos = case_when(mydf[paste0("CHECK", i)] == "A001" ~ i * 1,
                                               TRUE ~ 0),
                         CHECK_Name = case_when(mydf[paste0("CHECK", i)] == "A001" ~ paste0("CHECK", i),
                                               TRUE ~ "CHECK0"))
}

I want it to show something like
enter image description here

A: Here's a base R option using max.col :
#Select the columns to check
cols <- grep('CHECK', names(mydf), value = TRUE)
#Compare the value
mat <- mydf[cols] == 'A001'
#Find the column name where the value exist in each row
mydf$result <- cols[max.col(mat)]
#If the value does not exist in the row turn to `NA`.
mydf$result[rowSums(mat) == 0] <- NA
mydf

#  case id CHECK1 CHECK2 CHECK3 CHECK4 CHECK5 result
#1    1 10   A001   Z001   Z001   Z001   Z001 CHECK1
#2    2 11   B001   B001   B001   B001   B001   <NA>
#3    3 12   C001   C001   C001   A001   C001 CHECK4

A: As a supplement:
I think the long format is a nice option for this case.
Becase it's very clear to show the position "A001" and easy to filter even for more CHECK number.
I will use data.table as a demonstration.
library(data.table)
setDT(mydf)
dt <- melt(mydf, id = 1:2, measure.vars = patterns("CHECK*"))
dt

Long format
    case id variable value
 1:    1 10   CHECK1  A001
 2:    2 11   CHECK1  B001
 3:    3 12   CHECK1  C001
 4:    1 10   CHECK2  Z001
 5:    2 11   CHECK2  B001
 6:    3 12   CHECK2  C001
 7:    1 10   CHECK3  Z001
 8:    2 11   CHECK3  B001
 9:    3 12   CHECK3  C001
10:    1 10   CHECK4  Z001
11:    2 11   CHECK4  B001
12:    3 12   CHECK4  A001
13:    1 10   CHECK5  Z001
14:    2 11   CHECK5  B001
15:    3 12   CHECK5  C001

Filter A001
dt[value == "A001"]
  case id variable value
1:    1 10   CHECK1  A001
2:    3 12   CHECK4  A001


Q: Why does up key for retrieving the last command typed sometimes work and sometimes not $ man cpufreq-aperf
$  cpufreq-aperf
You must be root

Then when I type the up key, it gives me man cpufreq-aperf instead of cpufreq-aperf.
$ aaa
No command 'aaa' found, did you mean:
 Command 'aha' from package 'aha' (universe)
 Command 'ara' from package 'ara' (universe)
 Command 'jaaa' from package 'jaaa' (universe)
 Command 'aa' from package 'astronomical-almanac' (universe)
aaa: command not found

Then when I type the up key, it gives me aaa.
I wonder why there is such difference?
Thanks.

A: You possibly have ignorespace set in HISTCONTROL:

HISTCONTROL
   A colon-separated list of values controlling how commands are saved on the history list.  If the list of values includes ignorespace, lines which begin with a space character  are not saved in the history list.

Or an equivalent rule in HISTIGNORE. See variables used by Bash in the manual.


Q: NFC Permission Error I am working on an application that uses NFC and I keep getting this error,
`12-28 14:19:41.962: E/AndroidRuntime(27523): java.lang.RuntimeException: Unable to resume activity {com.example.clinkguitest/com.example.clinkguitest.MainActivity}: java.lang.SecurityException: NFC permission required: Neither user 10168 nor current process has android.permission.NFC.`

I have android:permission="android.permission.NFC" in my manifest so what is wrong? Thanks.

A: In my manifest permissions look like this:
    <uses-permission android:name="android.permission.NFC" />

Maybe that's the problem?


Q: $\Bbb R$-algebras of rank $1$ I am trying to understand the definition of an associative unital $R$-algebra (without assuming commutativity). Let $R=\Bbb R$ be the real numbers. Then I first want to understand $\Bbb R$-algebras with low rank.
To define an $\Bbb R$-algebra $A$ of rank $n$, I have to give an $\Bbb R$-basis to $A$, where I treat $A$ as an $\Bbb R$-module. Say I choose $\{x_1,\dots,x_n\}$. I do not assume that $A$ is commutative, so next I have to define all of the pair-wise products $x_ix_j=c_{ij}\in A$ for $i,j\in\{1,\dots,n\}$.
If I try to do this in rank $1$, I take $A$ to be generated by $x$ where $x$ is a formal symbol not in $\Bbb R$. Then all the elements are of the form $\{ax\mid x\in\Bbb R\}$. I also must $x\cdot x\in A$, so I choose $x\cdot x = qx$. Then if I want to check if this is just isomorphic as an $\Bbb R$-algebra to $\Bbb R$, I claim that I can define the map by $x\mapsto 1$ and use $\Bbb R$-linearity.
$$q=q\varphi(x)=\varphi(qx)=\varphi(x\cdot x)=\varphi(x)\varphi(x)=1,$$
so this is not an isomorphism unless $q=1$. Then there is an isomorphism class of $\Bbb R$-algebras of rank $1$ for every $q\in\Bbb R$?
Or I am doing something wrong, and there is only one $\Bbb R$-algebra of rank $1$ up to isomorphism for some reason (which is definitely true at the level of the module structure).

edit: I just realised I forgot, I have to send $1_A$ to $1_{\Bbb R}$. So I determine what $1_A$ is. Let $1_A=ix$, then this satisfies $ax\cdot ix = aiqx\implies i=q^{-1}$. So that my $\Bbb R$-linear map just send $q^{-1}x$ to $1$. Then $$q^{-1}\varphi(x)=\varphi(q^{-1}x)=1\implies \varphi(x)=q.$$
Then $\varphi(ax)=aq$ and this is a bijective ring homomorphism as long as $q\in\Bbb R-\{0\}$. So maybe there are two isomorphism classes? One with $q=0$ and one with $q\ne 0$?

A: It's pretty easy to show, directly from definitions and first principles, that any $1$-dimensional $\Bbb R$-algebra having a non-trivial multiplication operation is isomorphic to $\Bbb R$ itself.  In fact, we may replace $\Bbb R$ by any field $F$ and obtain the analogous result; this we shall do below.
We recall that the multiplication of an algebra $\mathcal A$ is trivial provided the product of any two elements is zero,
$\forall a, b \in \mathcal A, \; ab = 0; \tag 1$
likewise, the multiplication is non-trivial when
$\exists a, b \in \mathcal A, \; ab \ne 0.\tag 2$
Now an arbitrary finite-dimensional algebra $\mathcal A$ over any field
$F$ has a basis of $n$ elements, where
$n = \dim_F \mathcal A;\tag 3$
if we denote the elements of a basis by
$x_1, x_2, \ldots, x_n \in \mathcal A, \tag 4$
then the multiplication on all of $\mathcal A$ may be specified by defining it on the $n^2$ basis products $x_ix_j$, and since
$\mathcal A = \text{span} \{ x_1, x_2, \ldots, x_n \}, \tag 5$
for every $1 \le i, j \le n$, we may find
$c_{ij}^k \in F, \; 1 \le i, j, k \le n, \tag 6$
such that
$x_i x_j = \displaystyle \sum_{k = 1}^n c_{ij}^k x_k; \tag 7$
in this way we define a product on all of $\mathcal A$, since the $e_i$ are a basis.
We may apply this program in the case
$\dim_F \mathcal A = 1, \tag 8$
a particularly simple undertaking since then there is only the coefficient $c_{11}^1$.
In light of (8), we may pick any
$0 \ne x \in \mathcal A, \tag 9$
and then (7) becomes
$x^2 = \beta x, \; \beta \in F; \tag{10}$
it is clear that the multiplication so specified is trivial if and only if $\beta = 0$; therefore we take
$\beta \ne 0. \tag{11}$
We may now consider the possible existence of a multiplicative unit in $\mathcal A$; such a unit must be of the form $\alpha x$, $\alpha \in F$, and satisfy
$(\alpha x)(\gamma x) = \gamma x \tag{12}$
for any $\gamma \in F$; then since
$\gamma x = (\alpha x)(\gamma x) = \alpha \gamma x^2 =\alpha \gamma \beta x,   \tag{13}$
taking
$\gamma \ne 0, \tag{14}$
we see that (13) forces
$\alpha \beta = 1; \tag{15}$
that is,
$\alpha = \beta^{-1}; \tag{16}$
we may check this against (12):
$(\alpha x)(\gamma x) = \alpha \gamma x^2 =  \alpha \gamma \beta x = \gamma x, \tag{17}$
verifying that $\alpha x$ is indeed a unit for $\mathcal A$.
Having established that $\mathcal A$ is unital, we search for multiplicative inverses; for
$\gamma x \ne 0, \tag{18}$
we seek $\delta \in F$ such that
$(\gamma x)(\delta x) = \alpha x, \tag{19}$
whence
$\gamma \delta \beta x = \gamma \delta x^2 = \alpha x; \tag{20}$
according to (16) this yields
$\gamma \delta \alpha^{-1}= \alpha, \tag{21}$
or
$\delta = \gamma^{-1} \alpha^2; \tag{22}$
we check:
$(\gamma x)(\delta x) = (\gamma x)(
\gamma^{-1} \alpha^2 x^2) = \alpha^2 \beta x = \alpha x, \tag{23}$
the unit of $\mathcal A$, and we have established the existence of inverses for the non-$0$ elements of $\mathcal A$, now seen to be a field.  We may thus present an isomorphism
$\theta: F \cong \mathcal A, \theta(1_F) = \alpha x, \tag{24}$
and extending to all of $F$ by linearity:
$\theta(\gamma1_F) = \gamma\theta(1_F) = \gamma \alpha x;
\tag{25}$
the reader may easily verify $\theta$ is an isomorphism, for example
$\theta(\gamma \delta) = \gamma \delta \alpha x =  \gamma \delta \alpha x \alpha x = (\gamma \alpha x)(\delta \alpha x) = \theta(\gamma)\theta(\delta);
 \tag{26}$
the other axioms for field isomorphisms may also be readily validated for $\theta$.
We have established that every $1$-dimensional $F$-algebra with a non-trivial multiplication is isomorphic
the the field $F$ itself.  As for $1$-d algebras over $F$ with trivial multiplication, any two $\mathcal A_1$ and $\mathcal A_2$ are isomorphic in a number of ways; indeed, for any $x \in \mathcal A_1$ and $y \in \mathcal A_2$ we may set
$\phi: \mathcal A_1 \to \mathcal A_2, \; \phi(x) = y, \tag{27}$
and extend $\phi$ to all of $\mathcal A_1$ via
$\phi(\gamma x) = \gamma \phi(x) = \gamma y; \tag{28}$
such $\phi$ are also additive, since
$\phi(\gamma_1x + \gamma_2x) = \phi((\gamma_1 + \gamma_2)x) =(\gamma_1 + \gamma_2) \phi(x) =\gamma_1 \phi(x) + \gamma_2 \phi(x) = \gamma_1y + \gamma_2y  ; \tag {29}$
as far as concerns multiplication, we have
$\phi((\gamma_1 x)(\gamma_2 x)) = \phi(0) = 0 = \phi(\gamma_1 x) \phi (\gamma_2 x); \tag{30}$
we thus see that any such $\phi$ as in (28) is an isomorphism of the $F$-algebras $\mathcal A_1$ and $\mathcal A_2$.
We remark that a one-dimensional $F$-algebra with non-trivial multiplication may also be examined in terms of the presence of non-vanishing idempotent elements; that is, we seek
$0 \ne \alpha \in F, \; (\alpha x)^2 = \alpha x, \tag{31}$
from which
$\alpha^2 \beta x = \alpha^2 x^2 = (\alpha x)^2 = \alpha x; \tag{32}$
thus again as above,
$\alpha \beta = 1, \tag{32}$
which as we have seen above ((12)-(17)) shows that $\alpha x$ is the multiplicative identity of $\mathcal A$. Similarly, in the event that $\mathcal A$ is multiplicatively trivial,
$x^2 = 0, \; \forall x \in \mathcal A; \tag{33}$
every element of $\mathcal A$ is nilpotent.
In summary, we see that $\mathcal A$ is always isomorphic to $F$ when considered as a mere $F$-vector space; when considered as an $F$-algebra, however, $\mathcal A$ may either be isomorphic to $F$ or to the multiplicatively trivial algebra in which every product is $0$.  There are thus precisely two isomorphism classes of $F$-algebras satisfying (8).

A: There is a unique associative unital $\Bbb{R}$-algebra of rank $1$.
Proof.
Let $A$ be an $\Bbb{R}$-algebra of rank $1$.
Since $\Bbb{R}$ is a field, the map $\Bbb{R}\to A$ defined by $r\mapsto r\cdot 1$ is a unital ring homomorphism and therefore injective (since $A\ne 0$, because it has rank 1). However, since $\Bbb{R}$ and $A$ both have dimension $1$, it must also be surjective. Thus it is an isomorphism.

In general, let $k$ be a field. All rank $n$ algebras over $k$ are quotients of $k\langle x_1,\ldots,x_{n-1}\rangle $. ($n \ne 0$)

Proof.
Let $A$ be a rank $n$ $k$-algebra. Since $A\ne 0$, $1\ne 0$ in $A$.
Extending $\{1\}$ to a basis, we let $1,X_1,\ldots,X_{n-1}$ be a basis for $A$. Then define $\phi:k\langle x_1,\ldots,x_{n-1}\rangle \to A$ by $x_i\mapsto X_i$. Since $1,X_1,\ldots,X_{n-1}$ are in the image of $\phi$, $\phi$ is surjective. Thus $A$ is a quotient of $k\langle x_1,\ldots,x_{n-1} \rangle$ by the first isomorphism theorem.
The reason this is a generalization is that when $n=1$, we have that every rank $1$ algebra is a quotient of $k$, which immediately tells us that the unique rank $1$ algebra over any field is just $k$.


Q: Print text when bibliography is empty With biblatex, I'm looking for a way to check if the bibliography is empty, and if so, print some custom text.
Something along the lines of this pseudocode:
\ifempty\thebibliography
    [[ no references found ]]
\else
    \printbibliography
\fi

I could not find any options in the biblatex documentation controlling the behavior on empty bibliographies. Did I overlook something? Is this at all possible?
EDIT: Here's a MWE with Ulrike's suggestion implemented:
\documentclass[twoside,a4paper,11pt]{report}

\usepackage{biblatex}
\makeatletter
    \def\blx@warn@bibempty{[THIS TEXT PRINTS WHEN NO BIBLIOGRAPHY IS PRINTED]}
\makeatother

\begin{filecontents}{\jobname.bib}
@BOOK{hectic,
  AUTHOR    = {Henry Hectic},
  TITLE     = {How Horticulturalists Howl},
  PUBLISHER = {Honorary Books: Henage},
  YEAR      = {2000}
}
@BOOK{flutter,
  AUTHOR    = {Frederick Flutter},
  TITLE     = {Fraternising with Flowers},
  PUBLISHER = {Frippery Pamphlets: Folkestone},
  YEAR      = {1995}
}
\end{filecontents}

\addbibresource{\jobname.bib}

\begin{document}

    % Comment back in to see the normal bibliography
    %See also \cite{hectic}.

    \printbibliography

\end{document}

A: biblatex warns you if the bib is empty. You could redefine the command used for the message \blx@warn@bibempty:
 \usepackage{biblatex}
 \makeatletter
 \def\blx@arn@bibempty{Try it out}
 \makeatother


Q: Powershell remotely register COM dll by using regsvr32 I found on Internet, this ps script may work. But the result I get is: no error pops up, but also DLL not found in registry after running the script.
Invoke-Command -ComputerName $servername -ScriptBlock {regsvr32.exe "\\uncpath\some.dll" }

I tried in both "run as administrator" and normal PS console window, and windows remote management service is on on remote server.
Any idea?

A: You need to use the silent option of regsrv32 (/s):

Syntax
        REGSVR32 [/U] [/S] [/N] /I:[CommandLine] DLL_Name
Key    /u          Unregister Server.
/s          Silent, do not display dialogue boxes.
/i          Call DllInstall to register the DLL.
                 (when used with /u, it calls dll uninstall.)
/n          Do not call DllRegisterServer, you must use this option
  with /i.
CommandLine  An optional command line for DllInstall
/c          Console output (old versions only).


Q: Why when passing parameters from one component to another it arrives undefined and then arrives again with the data? As will be shown below when passing properties from a parent component to a child component my code is executed first before the properties arrive and when trying to do a .map of an Array it returns the error "Cannot read properties of undefined (reading 'map')". Why does this happen?

As you can see in the image, first you get undefined values which generates the error in the .map and then you get the properties
Parent component:
import React, {useEffect, useState} from "react";
import ItemDetail from "./itemDetail";
import '../../App.css';
import { useParams } from "react-router-dom";

//Component Class
const ItemDetailContainer = () => {
    const [producto, productos] = useState([]);
    const { productId } = useParams();

    useEffect(() => {
        fetch('http://localhost:3000/productos/' + productId)
            .then(res=>res.json())
            .then(data=>productos(data))
    }, [productId]);

    console.log(producto);

    return (

            <ItemDetail
                nombre={producto.nombre}
                id={producto.id}
                precio={producto.precio}
                category={producto.category}
                imagenes={producto.imagenes}
                ancho={producto.ancho}
                alto={producto.alto} />

    )
}

export default ItemDetailContainer;

Child component:
import React from 'react';
import { Card } from 'react-bootstrap';
import ItemCount from '../itemCount';

const ItemDetail = ({ nombre, id, precio, category, imagenes, ancho, alto }) => {

    console.log(imagenes);

    return (

                     {imagenes.map((p) => (

                    ))}

                        <Card.Body>
                            <Card.Title>{nombre}</Card.Title>
                            <Card.Text>{category}</Card.Text>
                            <Card.Text>${precio}</Card.Text>
                            <ItemCount />
                        </Card.Body>

    );
};

export default ItemDetail;

A: Change your code to only execute if imagenes is an array. Personally I would rethink how you are structuring your initial state. Instead of it being an empty array, perhaps make it an object with all of those properties having default values.

    { Array.isArray(imagenes) && imagenes.map((p) => (

    ))}


Q: How do I add a foreach inside another foreach in this context? When a user registers on my platform, there's some code that removes invisible characters.
I wanted to go further and add ucwords into it. However, I need to have some exceptions, as some words in Portuguese names aren't supposed to be capitalized.
The code has one if statement and an else one. I don't know how to change the else statement to correspond to the same thing as my if statement, because it's already a foreach loop.
    $exceptions = array('DAS' => 'das', 'DA' => 'da', 'DE' => 'de', 'DOS' => 'dos', 'DO' => 'do');

    if ( !\is_array( $return ) )
    {
        $return = preg_replace( '/\p{C}+/u', '', $return );
        $return = ucwords( $return );
        foreach ( $exceptions as $exception => $fix )
        {
            $return = str_replace( $exception, $fix, $return );
        }
    }
    else
    {
        foreach( $return as $k => $v )
        {
            $return[ $k ] = preg_replace( '/\p{C}+/u', '', $v );
            $return[ $k ] = ucwords( $v );
            //What do I add below? How do I type another foreach instead this one?
        }
    }

EDIT:
Would this make sense? If so, why?
    else
    {
        foreach( $return as $k => $v )
        {
            $return[ $k ] = preg_replace( '/\p{C}+/u', '', $v );
            $return[ $k ] = ucwords( $v );
            //Does this make sense?
            foreach ( $exceptions as $k => $v )
            {
                $return = str_replace( $k, $v, $return );
            }
        }
        }

A: The code between array and non-array are the same, so you can write a single foreach
$return = (array)$return;
foreach ($return as $k => $v) {
    $return[ $k ] = preg_replace( '/\p{C}+/u', '', $v );
    $return[ $k ] = ucwords( $v );
    foreach ( $exceptions as $exception => $fix ) {
            $return[$k] = str_replace( $exception, $fix, $return[$k] );
    }
}

Alternatively, this is what you'd use a function for
function fix_things($s) {
    $exceptions = array('DAS' => 'das', 'DA' => 'da', 'DE' => 'de', 'DOS' => 'dos', 'DO' => 'do');

    $s = preg_replace( '/\p{C}+/u', '', $s );
    $s = ucwords( $s );
    foreach ( $exceptions as $exception => $fix )
        {
            $s = str_replace( $exception, $fix, $s );
        }
    return $s;
}

Then call that function from your main code
if (!\is_array($return)) {
    $return = fix_things($return);
else {
    foreach ($return as $k => $v) {
        $return[$k] = fix_things($v);
    }
}


Q: Shopify customers/account.liquid Create for loop sort of order I'm trying to sort orders in customers/account.liquid by shipping_address.name
{% assign orders = customer.orders | sort: 'shipping_address.name' %}
{% for order in orders %}

    {{ order.name | link_to: order.customer_url }}
    {{ order.shipping_address.name }}
    {{ order.created_at | date: format: 'month_date_year' }}
    {{ order.financial_status }}
    {{ order.fulfillment_status }}
    {{ order.total_price | money }}

{% endfor %}

see screen shot

A: You forgot to use the sorted array! I made it easier to follow by renaming the variables a bit.
{% assign sortedOrders = customer.orders | sort: 'order.shipping_address.name' %}
{% for order in sortedOrders %}
  ...
{% endfor %}

Hope you're getting enough sleep!


Q: An ordered pair as a set. I have been looking at some of the posts here about expressing the ordered pair (a,b) in terms of sets as:
$$ (a,b) = \{\{a\},\{a,b\}\} $$
By definition, (a,b) is a set, so it should not 'care' about the order in which they are presented, so (a,b) should be equal to (b,a). I understand that the main property of ordered sets is that
(a,b) = (c,d) ,if and only if, a = c and b = d.
So
$$ (a,b) = \{\{a\},\{a,b\}\}  = \{\{a, b\},\{a\}\} = \{\{c, d\},\{c\}\} = \{\{c\},\{c, d\}\} $$
How can I check the property of the set? Since they are sets I do not see how their order would now matter if it should not?
If you can refer me to other sources, I have started a discrete book of math from scratch and they just showed the set definition without really explaining how it worked differently. Please keep your answer as simple as possible, I started this book as a recommendation from a math major to start learning math 'from scratch'.
What if we say $$ (a,b) = \{\{a\},\{b\}\} $$
wouldn't this obey the property such that if (a,b) = (c, d) then a= c and b =d?


Q: Understanding a derivative in a biology article From this biology article (5th page, right column)
They have...
$$1-P_t ≈ 1-(1+s)P_{t+1}+\frac{p_{t+1}^2}{2}$$
and they conclude that...
$$\frac{dP}{dt} ≈ -sP + \frac{P^2}{2}$$
I don't really understand this link. How did they do that?

A: I think that $1$ is small when compared to $t$, so they read $P_{t+1}$ as $P_t + dP/dt$. The first equation then becomes
$$1 - P \approx 1 - (1 + s)(P + dP/dt) + \tfrac{1}{2}(P + dP/dt)^2.$$
Solving this for $dP/dt$ and ignoring the term $(dP/dt)^2$ gives their result.


Q: MS SQL Server pivoting without aggregation I have this table:
   CREATE TABLE Sales (idx int, variable varchar(50), value varchar(50));
   INSERT into Sales (idx, variable, value) VALUES(1, 'column1', '34');
   INSERT into Sales (idx, variable, value) VALUES(1, 'column2', 'text value');
   INSERT into Sales (idx, variable, value) VALUES(1, 'column3', 'another text');

   INSERT into Sales (idx, variable, value) VALUES(2, 'column1', '14');
   INSERT into Sales (idx, variable, value) VALUES(2, 'column2', 'text value2');
   INSERT into Sales (idx, variable, value) VALUES(2, 'column3', 'another text2');

And I want to transform it into this:
   CREATE TABLE SalesPivoted (column1 varchar(50), column2 varchar(50), column3 varchar(50));

   INSERT INTO SalesPivoted (column1, column2, column3) VALUES ('34', 'text value', 'another text');
   INSERT INTO SalesPivoted (column1, column2, column3) VALUES ('14', 'text value2', 'another text2');

Maybe there is a way to do that by pivot expression but I don't need any aggregation here

A: For pivot you do need an aggregate function. But even with that, you can get the requested results.
SELECT pivot_table.column3,
       pivot_table.column2,
       pivot_table.column1
FROM
(SELECT idx, variable, value FROM dbo.Sales) t
PIVOT
(
    MIN(value)
    FOR variable IN (column1, column2, column3)
) AS pivot_table;


Q: Nokogiri 1.6.8 is installed but gives error for previous Nokogiri when running "bundle install" We had a server shutdown and Redmine stopped working, so I had to reinstall Bundler and run bundle install.
While running bundle install I get this error:
c:\APPS\webapps\redmine-3.2.0>bundle install
Fetching gem metadata from https://rubygems.org/.............
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies....
Using rake 12.3.2
Using concurrent-ruby 1.1.5
Using i18n 0.9.5
Using json 1.8.6
Using minitest 5.11.3
Using thread_safe 0.3.6
Using tzinfo 1.2.5
Using activesupport 4.2.5
Using builder 3.2.3
Using erubis 2.7.0
Using mini_portile2 2.4.0
Fetching nokogiri 1.9.1 (x64-mingw32)
Installing nokogiri 1.9.1 (x64-mingw32)
Gem::RuntimeRequirementNotMetError: nokogiri requires Ruby version >= 2.2, <
2.6. The current ruby version is 2.0.0.
An error occurred while installing nokogiri (1.9.1), and Bundler cannot
continue.
Make sure that `gem install nokogiri -v '1.9.1' --source
'https://rubygems.org/'` succeeds before bundling.

In Gemfile:
  rails was resolved to 4.2.5, which depends on
    actionmailer was resolved to 4.2.5, which depends on
      actionpack was resolved to 4.2.5, which depends on
        actionview was resolved to 4.2.5, which depends on
          rails-dom-testing was resolved to 1.0.9, which depends on
            nokogiri

I already installed Nokogiri 1.6.8. I'm not sure why it cannot read the Nokogiri version that I installed and still fetches 1.9.1 because I need Ruby v. 2 for Redmine 2.3.0, however my bundle is still telling me that it is looking for 1.9.1. While doing bundle install I tried changing the Gemfile based on my research to gem "nokogiri", ">= 1.4.2" however 1.9.1 is persisting. How can I successfully upgrade Nokogiri?
I used:
gem "nokogiri", "1.6.8"

In my Gemfile I have:
c:\APPS\webapps\redmine-3.2.0>bundle update nokogiri
Fetching gem metadata from https://rubygems.org/.............
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies....
Bundler could not find compatible versions for gem "nokogiri":
  In Gemfile:
    nokogiri (= 1.6.8) java

    roadie-rails java was resolved to 1.2.0, which depends on
      roadie (~> 3.1) java was resolved to 3.5.0, which depends on
        nokogiri (~> 1.8) java

If I run what gem install nokogiri -v '1.9.1', I get an error that my Ruby version is lower than expected and I cannot have a higher Ruby version because Redmine is an old version.
Here are all the Nokogiri versions I have:
c:\APPS\webapps\redmine-3.2.0>gem uninstall nokogiri
YAML safe loading is not available. Please upgrade psych to a version that supports safe loading (>= 2.0).

    Select gem to uninstall:
    1. nokogiri-1.6.8.rc3-x64-mingw32
    2. nokogiri-1.6.8-x64-mingw32
    3. nokogiri-1.6.8.1-x64-mingw32
    4. All versions

A: I could not fix this issue. It was looping through upgrades and downgrades, so after much frustration I tried Ruby 2.6 that Redmine 4.2 claimed to be compatible, which still had issues. I downgraded to Ruby 2.3 and it worked, then I migrated my database according to the redmine.org documentation and almost everything is functional, and I got a feedback that it is much faster.
According to my experience, you will have your Redmine database still working so don't worry that it s the same version.


Q: Suggestions for Writing Map as JSON file in Scala I have a simple single key-valued Map(K,V) myDictionary that is populated by my program and at the end I want to write it as JSON format string in a text file - as I would need parse them later.
I was using this code earlier,
Some(new PrintWriter(outputDir+"/myDictionary.json")).foreach{p => p.write(compact(render(decompose(myDictionary)))); p.close}

I found it to be slower as the input size increased. Later, I used this var out = new
var out = new PrintWriter(outputDir+"/myDictionary.json");
out.println(scala.util.parsing.json.JSONObject(myDictionary.toMap).toString())

This is proving to be bit faster.
I have run this for sample input and found that this is faster than my earlier approach. I assuming my input map size would reach at least a million values( >1GB text file) (K,V) hence I want to make sure that I follow the faster and memory efficient approach for Map serialization process.What are other approaches that you would recommend,that I can look into to optimize this.

A: The JSON support in the standard Scala library is probably not the best choice. Unfortunately the situation with JSON libraries for Scala is a bit confusing, there are many alternatives (Lift JSON, Play JSON, Spray JSON, Twitter JSON, Argonaut, ...), basically one library for each day of the week... I suggest you have a look at these at least to see if any of them is easier to use and more performative.

Here is an example using Play JSON which I have chosen for particular reasons (being able to generate formats with macros):
object JsonTest extends App {
  import play.api.libs.json._

  type MyDict = Map[String, Int]

  implicit object MyDictFormat extends Format[MyDict] {
    def reads(json: JsValue): JsResult[MyDict] = json match {
      case JsObject(fields) =>
        val b = Map.newBuilder[String, Int]
        fields.foreach {
          case (k, JsNumber(v)) => b += k -> v.toInt
          case other => return JsError(s"Not a (string, number) pair: $other")
        }
        JsSuccess(b.result())

      case _ => JsError(s"Not an object: $json")
    }

    def writes(m: MyDict): JsValue = {
      val fields: Seq[(String, JsValue)] = m.map {
        case (k, v) => k -> JsNumber(v)
      } (collection.breakOut)

      JsObject(fields)
    }
  }

  val m       = Map("hallo" -> 12, "gallo" -> 34)
  val serial  = Json.toJson(m)
  val text    = Json.stringify(serial)
  println(text)
  val back    = Json.fromJson[MyDict](serial)
  assert(back == JsSuccess(m), s"Failed: $back")
}

While you can construct and deconstruct JsValues directly, the main idea is to use a Format[A] where A is the type of your data structure. This puts more emphasis on type safety than the standard Scala-Library JSON. It looks more verbose, but in end I think it's the better approach.
There are utility methods Json.toJson and Json.fromJson which look for an implicit format of the type you want.
On the other hand, it does construct everything in-memory and it does duplicate your data structure (because for each entry in your map you will have another tuple (String, JsValue)), so this isn't necessarily the most memory efficient solution, given that you are operating in the GB magnitude...

Jerkson is a Scala wrapper for the Java JSON library Jackson. The latter apparently has the feature to stream data. I found this project which says it adds streaming support. Play JSON in turn is based on Jerkson, so perhaps you can even figure out how to stream your object with that. See also this question.


Q: d3 v4 Positioning labels without touching polygon boundaries I'm working on a d3 v4 map that needs short labels positioned within each poloygon generated from topojson.
You can see where I've got to here:
http://bl.ocks.org/oroojo/9afff90bdb85deb78359a0d5e87a3f31/7606b296a1a47de3b9370d757182386fa35ac650
You'll see that I have the labels centered using path.centroid(d).
This is not ideal as the center is not always the best place to put the label due to random polygon shapes.
I'm sure there is a way of finding a position that does not touch the boundary, though calculation..
Any thoughts?


Q: Bash execute another command and enter input automatically I have a script when running it with ./script.sh it prints something in the console, then asks for a user input username?. After writing my username it asks a lot of other things which I have to write to the console.
I have one case where I have exactly the same input over and over again.
I want to write a second script that calls the first one and automatically puts in this input into the first script, so I only need to call the second script.
How can I achieve that? I know how I can call the first script from the second script but I have no idea where to put the input.

A: If it's reading from stdin for things like the password too, then you should be able to just put all your answers as lines in a file and redirect the script input from there.
./script.sh < answers.txt

A lot of apps won't accept passwords that way, though...


Q: why do i get: IndexError: tuple index out of range? i've been trying to create a tictactoe agent and when i ran the training loop i got an error pointing towards the (.0) in the function that checks whether someone won(check_game_status).
if you need the whole environment let me know.
here is the way the board was created:
board = [0] * 9

which means the 0 means empty spot, 1 for O and 2 for x.
here is after_action_state function:
def after_action_state(state, action):
    """Execute an action and returns resulted state.

    Args:
        state (tuple): Board status + mark
        action (int): Action to run

    Returns:
        tuple: New state
    """

    board, mark = state
    nboard = list(board[:])
    nboard[action] = tocode(mark)
    nboard = tuple(nboard)
    return nboard, next_mark(mark)

tocode function basically converts 'X' to 2 and 'O' to 1
this is the function that the error pointed at:
def check_game_status(board):
"""Return game status by current board status.

Args:
    board (list): Current board state

Returns:
    int:
        -1: game in progress
        0: draw game,
        1 or 2 for finished game(winner mark code).
"""
for t in [1, 2]:
    for j in range(0, 9, 3):
        if [t] * 3 == [board[i] for i in range(j, j+3)]:
            return t
    for j in range(0, 3):
        if board[j] == t and board[j+3] == t and board[j+6] == t:
            return t
    if board[0] == t and board[4] == t and board[8] == t:
        return t
    if board[2] == t and board[4] == t and board[6] == t:
        return t

for i in range(9):
    if board[i] == 0:
        # still playing
        return -1

# draw game
return 0

this is the play_one_step function that takes experience and puts it in a replay buffer using greedy epsilon policy.
 def play_one_step(self, env ,state, available_actions, agents_model ,epsilon= 0.2):
    action = self.greedy_policy(state, available_actions, agents_model ,epsilon= epsilon)
    next_state, reward, done, info = env.step(action)
    self.replay_buffer.append((state, action,reward, next_state, done))
    return next_state, reward, done, info

and this is the epsilon greedy policy :
def greedy_policy(self, state ,available_actions, agents_model ,epsilon = 0.2):
        if np.random.rand() < epsilon:
            return np.random.choice(available_actions)

        else:

            for next_action in available_actions: # checking if the next possible action wins the game and if it does then it returns it
                next_state = after_action_state(state, next_action)
                game_status = check_game_status(next_state)
                if game_status > 0 & tomark(game_status)==self.mark:
                    return next_action

            Q_values = agents_model.predict(state[np.newaxis])
            return np.argmax(Q_values[0])

this is the training loop:
agent_1 = Agent('X', model_1)
agent_2 = Agent('O', model_2)
agent_1_rewards = []
agent_2_rewards = []
agents = [agent_1, agent_2]

n_episodes = 600
start_mark = 'O'
batch_size = 15

for episode in range(n_episodes):
    env = TicTacToeEnv()
    env.set_start_mark(start_mark)
    state = env.reset()
    while not env.done:
        _ , mark = state
        available_actions = env.available_actions()
        epsilon = max( 1 - episode/500 , 0.01)
        agent = agent_by_mark(agents, mark)
        agents_model = agent.agents_model

        next_state, reward, done, _ = agent.play_one_step(env, state, available_actions, agents_model  ,epsilon)
        state = next_state
        if agent is agent_1:
            agent_1_rewards.append(reward)
        else:
            agent_2_rewards.append(reward)

        env.render()

    if episode > 60:
        agent.training_step(15)

this is the error trace:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17792/1466320926.py in <module>
     26
     27
---> 28         next_state, reward, done, _ = agent.play_one_step(env, state, available_actions, agents_model  ,epsilon)
     29         state = next_state
     30         if agent is agent_1:

~\AppData\Local\Temp/ipykernel_17792/3137506088.py in play_one_step(self, env, state, available_actions, agents_model, epsilon)
     60
     61     def play_one_step(self, env ,state, available_actions, agents_model ,epsilon= 0.2):
---> 62         action = self.greedy_policy(state, available_actions, agents_model ,epsilon= epsilon)
     63         next_state, reward, done, info = env.step(action)
     64         self.replay_buffer.append((state, action,reward, next_state, done))

~\AppData\Local\Temp/ipykernel_17792/3137506088.py in greedy_policy(self, state, available_actions, agents_model, epsilon)
     35                 for next_action in available_actions: # checking if the next possible action wins the game and if it does then it returns it
     36                     next_state = after_action_state(state, next_action)
---> 37                     game_status = check_game_status(next_state)
     38                     if game_status > 0 & tomark(game_status)==self.mark:
     39                         return next_action

g:\Code\TicTacToe\gym-tictactoe\gym_tictactoe\env.py in check_game_status(board)
     66     for t in [1, 2]:
     67         for j in range(0, 9, 3):
---> 68             if [t] * 3 == [board[i] for i in range(j, j+3)]:
     69                 return t
     70         for j in range(0, 3):

g:\Code\TicTacToe\gym-tictactoe\gym_tictactoe\env.py in <listcomp>(.0)
     66     for t in [1, 2]:
     67         for j in range(0, 9, 3):
---> 68             if [t] * 3 == [board[i] for i in range(j, j+3)]:
     69                 return t
     70         for j in range(0, 3):

IndexError: tuple index out of range

does anyone know what causes this issue? i already tried to rewrite the function only and give it a few cases and it worked absolutely fine with no index problem.
if you need more of the code let me know.
thanks in advance!

A: It is not a fix but explains the cause of bug...
In the below snippet, you are trying to access board[i] with index i > 9 but your board is of size 9. For instance, check for j=9.
for j in range(0, 9, 3):
        if [t] * 3 == [board[i] for i in range(j, j+3)]:
            return t


Q: Serving static files in django 1.8 My 404.html page does not reference my finale.css file.
My directory structure
musicworld/
   musicworld/
           __pycache__
           __int__.py
           settings.py
           urls.py
           wsgi.py
   feature/
           __pycache__
           migrations
           static/
                 feature/
                        finale.css
           templates/
                 feature/
                        about.html
                        detail.html
                 404.html
                 500.html
                 index.html
                 template.html
            __init__.py
            admin.py
            models.py
            tests

This is where in index.html I'm referencing the css
    <link rel="stylesheet" type="text/css" href="{% static 'feature/finale.css' %}" />

But 404.html that extends index.htmlis not referencing the css
{% extends "index.html" %}
{% load staticfiles %}
{% block 404page %}

Oh No! Something went wrong.Punish the developer by clicking here.

{% endblock %}

static reference in settings.py
STATIC_URL = '/static/'

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, "media")

Both the index.htmland template.html are placed in the same folder and are properly referencing the css.Plus all the html pages in feature that are extending index.html are also referencing the css.But both 404.html and 500.htmlare not.


Q: FMOD: Cleaning up duplicate platform warning FMOD for Unity 2.01.07 (Unity 2019.4.18f1 - running on MacOS Catalina) seems to have broken their FMODStudioSettings class.
I can't save in the editor without getting these errors:
FMOD: Cleaning up duplicate platform: ID  = playInEditor, name = 'Play In Editor Settings', type = PlatformPlayInEditor
ArgumentException: An item with the same key has already been added. Key: playInEditor
FMOD: Cleaning up duplicate platform: ID  = default, name = 'Default Settings', type = PlatformDefault
ArgumentException: An item with the same key has already been added. Key: default
NullReferenceException: Object reference not set to an instance of an object
FMODUnity.SettingsEditor.DisplayPlugins (System.String title, FMODUnity.Platform platform, FMODUnity.Platform+PropertyAccessor`1[T] property, System.Collections.Generic.Dictionary`2[TKey,TValue] expandState, System.String warning) (at Assets/Plugins/FMOD/src/Editor/SettingsEditor.cs:1028)

I believe this is a regression that basically makes the Unity integration unusable.  Something to do with de-duplicating platforms in the Platforms map.  At runtime there's a series of NPEs related to platforms so actually I can't run the game properly. Has anyone else run into this?
I'm evaluating FMOD as a middleware option for our game, and have run into at least two serious bugs in the Unity integration.  See other bug here.
UPDATE:
I haven't found out why this doesn't happen for everyone, but an easy fix for anyone else running into this issue has been applying this diff:
diff --git a/Assets/Plugins/FMOD/src/Runtime/Settings.cs b/Assets/Plugins/FMOD/src/Runtime/Settings.cs
index 2641e926..c2843145 100644
--- a/Assets/Plugins/FMOD/src/Runtime/Settings.cs
+++ b/Assets/Plugins/FMOD/src/Runtime/Settings.cs
@@ -817,6 +817,10 @@ namespace FMODUnity

         private void PopulatePlatformsFromAsset()
         {
+            Platforms.Clear();
+            PlatformForBuildTarget.Clear();
+            PlatformForRuntimePlatform.Clear();
+
 #if UNITY_EDITOR
             string assetPath = AssetDatabase.GetAssetPath(this);
             UnityEngine.Object[] assets = AssetDatabase.LoadAllAssetsAtPath(assetPath);
@@ -827,36 +831,8 @@ namespace FMODUnity

             foreach (Platform newPlatform in assetPlatforms)
             {
-                Platform existingPlatform = FindPlatform(newPlatform.Identifier);
-
-                if (existingPlatform != null)
-                {
-                    // Duplicate platform; clean one of them up
-                    Platform platformToDestroy;
-
-                    if (newPlatform.Active && !existingPlatform.Active)
-                    {
-                        Platforms.Remove(existingPlatform.Identifier);
-
-                        platformToDestroy = existingPlatform;
-                        existingPlatform = null;
-                    }
-                    else
-                    {
-                        platformToDestroy = newPlatform;
-                    }
-
-                    Debug.LogWarningFormat("FMOD: Cleaning up duplicate platform: ID  = {0}, name = '{1}', type = {2}",
-                        platformToDestroy.Identifier, platformToDestroy.DisplayName, platformToDestroy.GetType().Name);
-
-                    DestroyImmediate(platformToDestroy, true);
-                }
-
-                if (existingPlatform == null)
-                {
-                    newPlatform.EnsurePropertiesAreValid();
-                    Platforms.Add(newPlatform.Identifier, newPlatform);
-                }
+                newPlatform.EnsurePropertiesAreValid();
+                Platforms.Add(newPlatform.Identifier, newPlatform);
             }

 #if UNITY_EDITOR

A: So this was a bug in the integration they fixed in 2.01.10.


Q: Name lookup in using-declaration via using-directive Is the following program well-formed or ill-formed according to the c++ standard?
namespace N { int i; }
using namespace N;
using ::i;
int main() {}

I get different results with different compilers:

*

*Clang (http://melpon.org/wandbox/permlink/c8vl7XbumyyS6vsw): No errors.

*GCC (http://melpon.org/wandbox/permlink/immhNeWFCMcCA800): Error: 'i' not declared.

Is this program well-formed or ill-formed according to the c++ standard? References to the c++ standard needed.
I'm trying to figure out for which compiler I should file a bug.

A: Well-formed.
The using-directive doesn't introduce the name i in the global namespace, but it is used during lookup. The using-declaration uses qualified lookup to find i; qualified lookup in the presence of using-directives is specified in [3.4.3.2 p1, p2] (quotes from N4527, the current working draft):

If the nested-name-specifier of a qualified-id nominates a namespace
  (including the case where the nested-name-specifier is ::, i.e.,
  nominating the global namespace), the name specified after the
  nested-name-specifier is looked up in the scope of the namespace. [...]
For a namespace X and name m, the namespace-qualified lookup set
  S(X,m) is defined as follows: Let S'(X,m) be the set of all
  declarations of m in X and the inline namespace set of X (7.3.1). If
  S'(X,m) is not empty, S(X,m) is S'(X,m); otherwise, S(X,m) is the
  union of S(Ni,m) for all namespaces Ni nominated
  by using-directives in X and its inline namespace set.

So, for qualified lookup, the first step is to look for declarations of i made directly in the namespace indicated by the nested-name-specifier (:: in this case). There are no such declarations, so lookup then proceeds to the second step, which is to form the set of all declarations of i found by qualified lookup in all namespaces nominated by using-directives in the global namespace. That set is comprised of N::i, which is the result of name lookup, and is introduced as a name in global namespace by the using declaration.
I find it worth noting (although pretty obvious) that this definition of qualified lookup is recursive: using the notation in the quote, qualified lookup in each namespace Ni will first look for declarations made directly in Ni, then, if none is found, will in turn proceed to look in the namespaces nominated by using-directives in Ni, and so on.

For what it's worth, MSVC accepts the code as well.

A: GCC is wrong. Qualified name lookup does consider N::i; §3.4.3.2/2 & /3:

For a namespace X and name m, the namespace-qualified lookup set
  S(X, m) is defined as follows: Let S'(X, m) be the set of all
  declarations of m in X and the inline namespace set of X
  (7.3.1). If S'(X, m) is not empty, S(X, m) is S'(X, m);
  otherwise, S(X, m) is the union of S(Ni, m) for all namespaces Ni nominated by using-directives in X
  and its inline namespace set.

  Given X::m (where X is a user-declared namespace), or given ::m (where
  X is the global namespace), […] if S(X, m) has exactly one member, or if the
  context of the reference is a using-declaration (7.3.3), S(X, m) is
  the required set of declarations of m.

There is only one namespace nominated by a using-directive in your program: N. It's therefore included in the union and ::i is resolved to N::i.
Note that GCC is inconsistent with its lookup: Using ::i in another context is fine.
namespace N { int i; }
using namespace N;

int main() {
    ::i = 5;
}

This compiles. The only difference that a using-declaration makes as a context is shown in the above quote and does not affect the established conclusion.


Q: find data type of the output column An Example:
sel  date '2008-03-07'- date '2009-04-10'

    (2008-03-07-2009-04-10)
1   -399

What would be the data type of the result here?
It's INTERVAL DAY (please correct if this is wrong) here in this case I know but, is there a function available to return the data type characteristics of the resultant column?

A: The mistery function is called TYPE :-)
select  type(date '2008-03-07'- date '2009-04-10')

It's not INTERVAL DAY, it's an INTEGER.
You only get INTERVALS when you request them explicitly, but they're hardly used as the maximum number of digits is only 4:
select  date '2008-03-07'- date '2009-04-10' MONTH(4)


Q: How to make Geany highlight smarty block comments? How to make Geany highlight smarty block comments ?
Smarty block comments are:

*

*start {*

*end *}
Thanks.


Q: Mathematical structure of a dictionary. Please correct me if I am wrong. I understand that during the last couple of centuries we have put a lot of effort in trying to understand structures, and for most of them we have been able to reduce them to sets. So we have translated mathematical structures to the language of sets, that is we define other stuff using sets.
I was wondering how an effort of this style would look like if we tried to give a hierarchical meaning to a dictionary. Modern dictionaries (I Think) are prone to alot of circular arguments. I would like to know if we could just take some words for granted and then build (define) everything else up from there. What do you think those words would be? Has this question been asked before?
regards.

A: I would picture a dictionary as a long list of words where each word has its synonyms beside it. A synonym is a word with the same / similar or related meaning.
E.G:

*

*flammable / inflammable

*alike / similar

*bright / clever / dazzling

A: Start with the concept of 'is' or 'to be' or think of it as some type of equality.  I think that's the beginning, and go from there.
But ... the best thing is that this would be a multi-valued function.  Then you want to consider the projection of this to one word with the pull-back being all the synonyms.  From there you can consider a particular choice for the synonyms on the pull-back in such a way to form a continuous function (assuming that you have a continuous function from words in the projective space) and form a section.


Q: Multiple polygon edit in matplotlib I am trying to make plot that it has two polygon patches over it. I want to use the example given in Matplotlib.org web page called PloygonInteractor. My code as follows;
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.artist import Artist
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

def dist(x, y):
    """
    Return the distance between two points.
    """
    d = x - y
    return np.sqrt(np.dot(d, d))

def dist_point_to_segment(p, s0, s1):
    """
    Get the distance of a point to a segment.
      *p*, *s0*, *s1* are *xy* sequences
    This algorithm from
    http://geomalgorithms.com/a02-_lines.html
    """
    v = s1 - s0
    w = p - s0
    c1 = np.dot(w, v)
    if c1 <= 0:
        return dist(p, s0)
    c2 = np.dot(v, v)
    if c2 <= c1:
        return dist(p, s1)
    b = c1 / c2
    pb = s0 + b * v
    return dist(p, pb)

class PolygonInteractor:
    """
    A polygon editor.

    Key-bindings

      't' toggle vertex markers on and off.  When vertex markers are on,
          you can move them, delete them

      'd' delete the vertex under point

      'i' insert a vertex at point.  You must be within epsilon of the
          line connecting two existing vertices

    """

    showverts = True
    epsilon = 5  # max pixel distance to count as a vertex hit

    def __init__(self, ax, poly):
        if poly.figure is None:
            raise RuntimeError('You must first add the polygon to a figure '
                               'or canvas before defining the interactor')
        self.ax = ax
        canvas = poly.figure.canvas
        self.poly = poly

        x, y = zip(*self.poly.xy)
        self.line = Line2D(x, y,
                           marker='o', markerfacecolor='r',
                           animated=True)
        self.ax.add_line(self.line)

        self.cid = self.poly.add_callback(self.poly_changed)
        self._ind = None  # the active vert

        canvas.mpl_connect('draw_event', self.on_draw)
        canvas.mpl_connect('button_press_event', self.on_button_press)
        canvas.mpl_connect('key_press_event', self.on_key_press)
        canvas.mpl_connect('button_release_event', self.on_button_release)
        canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
        self.canvas = canvas

    def on_draw(self, event):
        self.background = self.canvas.copy_from_bbox(self.ax.bbox)
        self.ax.draw_artist(self.poly)
        self.ax.draw_artist(self.line)
        # do not need to blit here, this will fire before the screen is
        # updated

    def poly_changed(self, poly):
        """This method is called whenever the pathpatch object is called."""
        # only copy the artist props to the line (except visibility)
        vis = self.line.get_visible()
        Artist.update_from(self.line, poly)
        self.line.set_visible(vis)  # don't use the poly visibility state

    def get_ind_under_point(self, event):
        """
        Return the index of the point closest to the event position or *None*
        if no point is within ``self.epsilon`` to the event position.
        """
        # display coords
        xy = np.asarray(self.poly.xy)
        xyt = self.poly.get_transform().transform(xy)
        xt, yt = xyt[:, 0], xyt[:, 1]
        d = np.hypot(xt - event.x, yt - event.y)
        indseq, = np.nonzero(d == d.min())
        ind = indseq[0]

        if d[ind] >= self.epsilon:
            ind = None

        return ind

    def on_button_press(self, event):
        """Callback for mouse button presses."""
        if not self.showverts:
            return
        if event.inaxes is None:
            return
        if event.button != 1:
            return
        self._ind = self.get_ind_under_point(event)

    def on_button_release(self, event):
        """Callback for mouse button releases."""
        if not self.showverts:
            return
        if event.button != 1:
            return
        self._ind = None

    def on_key_press(self, event):
        """Callback for key presses."""
        if not event.inaxes:
            return
        if event.key == 't':
            self.showverts = not self.showverts
            self.line.set_visible(self.showverts)
            if not self.showverts:
                self._ind = None
        elif event.key == 'd':
            ind = self.get_ind_under_point(event)
            if ind is not None:
                self.poly.xy = np.delete(self.poly.xy,
                                         ind, axis=0)
                self.line.set_data(zip(*self.poly.xy))
        elif event.key == 'i':
            xys = self.poly.get_transform().transform(self.poly.xy)
            p = event.x, event.y  # display coords
            for i in range(len(xys) - 1):
                s0 = xys[i]
                s1 = xys[i + 1]
                d = dist_point_to_segment(p, s0, s1)
                if d <= self.epsilon:
                    self.poly.xy = np.insert(
                        self.poly.xy, i+1,
                        [event.xdata, event.ydata],
                        axis=0)
                    self.line.set_data(zip(*self.poly.xy))
                    break
        if self.line.stale:
            self.canvas.draw_idle()

    def on_mouse_move(self, event):
        """Callback for mouse movements."""
        if not self.showverts:
            return
        if self._ind is None:
            return
        if event.inaxes is None:
            return
        if event.button != 1:
            return
        x, y = event.xdata, event.ydata

        self.poly.xy[self._ind] = x, y
        if self._ind == 0:
            self.poly.xy[-1] = x, y
        elif self._ind == len(self.poly.xy) - 1:
            self.poly.xy[0] = x, y
        self.line.set_data(zip(*self.poly.xy))

        self.canvas.restore_region(self.background)
        self.ax.draw_artist(self.poly)
        self.ax.draw_artist(self.line)
        self.canvas.blit(self.ax.bbox)

x1 = np.array([-1.5, -1.5, -1.0, -1.0])
y1 = np.array([-1.0, -1.5, -1.5, -1.0])
poly1 = Polygon(np.column_stack([x1, y1]),  color='gray', fill=False, animated=True)

x2 = np.array([-1.5, -1.5, -1.0, -1.0])
y2 = np.array([ 0.0, 0.5, 0.5, 0.0])
poly2 = Polygon(np.column_stack([x2, y2]), color='b', fill=False, animated=True)

fig, ax = plt.subplots()
ax.add_patch(poly1)
ax.add_patch(poly2)

p1 = PolygonInteractor(ax, poly1)
p2 = PolygonInteractor(ax, poly2)

ax.set_xlim((-2, 2))
ax.set_ylim((-2, 2))
plt.show()

and this creates a plot like this:

My problem is that when trying to adjust polygon 2 (bottom), polygon 1 (upper) disappears. What should I do for this?


Q: I need to write a query which repeats the rows by incrementing the values I have a table with three columns say ID with identity, name and location and for this columns say I have values as
(1,'RAM','CA'),
(2,'SAM','IA'),
(3,'PAM','MI')
etc....

Now want to get 100 rows, say after 3rd row, the 4th row should again start with same name and same location but adding one value to it, say 4th row will be values
(4,'RAM1','CA1'), similarly 5th row will be (5,'SAM1','IA1') and 6th row will be (6,'PAM1','MI1'). Again for 7th row it should give values as (7,'RAM2','CA2') and so on. So it should continue like this till 100th row, for that I need to write the code, I could not able to figure it out, can you please help me in this.
Thanks,
Aparanjit

A: Try this:
Fiddle demo
--Your table
create table t (id int identity(1,1), col1 varchar(10),
                                  col2 varchar(10))
--Insert query
insert into t
select c1 + case when number = 1 then '' else convert(varchar(10),number-1) end col1,
       c2 + case when number = 1 then '' else convert(varchar(10),number-1) end col2
from master..spt_values cross join
    (values ('RAM','CA'),('SAM','IA'),('PAM','MI')) AS temp (c1,c2)
where type='p' and number between 1 and 100

--Results
|  ID |  COL1 | COL2 |
------|-------|------|--
| 1 |   RAM |   CA |
| 2 |   SAM |   IA |
| 3 |   PAM |   MI |
| 4 |  RAM1 |  CA1 |
| 5 |  SAM1 |  IA1 |
| 6 |  PAM1 |  MI1 |
| 7 |  RAM2 |  CA2 |
| 8 |  SAM2 |  IA2 |
| 9 |  PAM2 |  MI2 |
| 10 |  RAM3 |  CA3 |
| 11 |  SAM3 |  IA3 |
| 12 |  PAM3 |  MI3 |
...

A: Using a recursive CTE You could try something like
DECLARE @Table TABLE(
        ID INT IDENTITY(1,1),
        [name] VARCHAR(20),
        location varchar(20)
)
INSERT INTO @Table VALUES ('RAM','CA'), ('SAM','IA'), ('PAM','MI')

DECLARE @NumberOfRows INT = 100

;WITH RowIDs AS (
        SELECT  1 RowID
        UNION ALL
        SELECT RowID + 1
        FROM    RowIDs
        WHERE   RowID + 1 <= @NumberOfRows
)
, JoinIDs AS (
        SELECT  RowID,
                ((RowID - 1) % 3 + 1) JoinID
        FROM    RowIDs
)
SELECT  j.RowID,
        t.name,
        t.location

FROM    JoinIDs j INNER JOIN
        @Table t    ON  j.JoinID = t.ID
OPTION (MAXRECURSION 0)

SQL Fiddle DEMO


Q: PhpStorm understanding of magic methods Our classes don't have explictic getPropertyName() and setPropertyName() methods. Instead we're using trait, which implements combination of magic __get(), __set() and __call() methods, so, we can have following as result:
class Device {
use ModelAttributes;

/**
 * @var \string
 */
protected $title;

/**
 * @var \string
 */
protected $subtitle;

}

$device = new Device();
$device->setTitle('PC');
$device->getTitle();

But the problem is, that now PhpStorm can't recognize and highlights these methods.
I know, that I can add @method string getTitle() into class phpDoc, but this will mean, taht I again need to add all get-ers and set-ers, but in form of phpDoc commetns, and I want to avoid this.
It would be really great, if I could do something like:
/**
 * @var \string
 * @get
 * @set
 */
protected $title;

Does someone have experience with such situation?


Q: Can't set properly my Dialog Window size and placement target I've built a dialog window that i plan to use in my whole application instead of using a message box. Whenever i need to use it, i would call it in the code behind of my Window i'm currently working with this syntax:
public void ShowDialogWindow(object sender, DialogEventArgs e)
{
    DialogWindow dialog = new DialogWindow(e.MessageToShow, DialogType.Error, ButtonsType.OkOnly, this.ActualWidth, this.ActualHeight, this);
    dialog.ShowDialog();
}

this is the constructor of my Dialog Window
public DialogWindow(string messageToDisplay, DialogType dialog, ButtonsType buttons, double width, double height, object Owner)
{
    InitializeComponent();
    this.DataContext = this;
    this.Owner = Owner as Window;
    AWidth = width;
    AHeight = height;
    -----
}

and this is the opening Window tag in the xaml
<Window x:Class="DialogWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        ---
        mc:Ignorable="d" WindowStyle="None"
        WindowStartupLocation="CenterOwner"
        AllowsTransparency="True"
        Width="{Binding AWidth}" Height="{Binding AHeight}"
        MinHeight="720" MinWidth="1080">

Now my problem is. When i call this dialog when the owner is Minimized (having set MinWidth = 1080 and MinHeght = 720) the dialog "kinda" fits (ActualWidth and Actual Height of both Window and DialogWindow are the same, but visually the DialogWindow seems a little bit bigger than the Owner)

But when i go full screen it happens this:

Not only the ActualHeight is different to the property AHeight (which is set correctly to the ActualHeight of the Owner), but also is not centered on the Owner window at all, but overflow on my second screen. What cause this, and how can i solve it?

A: So i'm going to post what it solved my problem, but i have absolutely no idea why that happened, so if anyone has a better answer i will check that as accepted.
To solve my problems i removed the binding for width and height and simply added in the constructor of the DialogWindow
this.Width = OwnerActualWidth;
this.Height = OwnerActualHeight;

since i am passing those parameter in input


Q: Proving something is $1$-Lipschitz
(1) Let $(X,d)$ be a metric space, and let A be a non-empty subset. Show that the function $$D_A :X \to [0,\infty ]$$ defined by $$D_A (x) =\inf \{d(x,y) : y \in A\}$$ is $1$-Lipschitz (when $[0,\infty)$ is given the standard metric.
(2) Now suppose that A is compact. Prove that, for each $x \in X$, there is some $a \in A$, such that $D_A (x) = d(a,x)$.

This is part of a review sheet for an exam I am taking, not graded just some practice problems. I am having trouble with this question. I am not sure how to show something is Lipschitz. Do I want to show that $$d_{[0,\infty)} (D_A(x),D_A(x')) \le d_x(x,x')$$for all $x,x' \in X$? I am not entirely sure how to go about this.
For the second part, will I have to use something about A being a compact subset of a metric space implies A closed and bounded?

A: Use the triangular inequality on the definition of $D_A(x)$ to show that
$$ D_A(x) \leq d(x,x')  + D_A(x').   $$
Now by switching the roles of $x$ and $x'$ you can prove $(1)$.
For $(2)$ show that $y \mapsto d(x,y)$ is continuous for all $x$ and use that a continuous function on a compact reaches its infimum.

A: Hints: For $D_A$ to be $1$-Lipschitz (also known as a non-expanding function) you need to show that $d(D_A(x),D_A(x'))\le d(x,x')$. Here the first $d$ is the distance function in $[0,\infty]$, which is taken to be the usual Euclidean distance (with proper conventions regarding $\infty $). The second $d$ refers to the distance function of the metric space $X$. That is, for given $x,x'\in X$, you need to show that $|\inf \{d(x,y)\mid y\in A\}-\inf \{d(x',y)\mid y\in A\}|\le d(x,x')$. To prove this you'll need to use the triangle inequality at some point.
For part 2, use the fact that any sequence in $A$ has a convergent subsequence. Construct a suitable sequence that is trying to converge to the inf. Then take a convergent subsequence of it.


Q: I need sql query for getting the Required format i am having table Category with the columns like
id(AutoIncrement),Parent_id,Level,Name
initially for level 1 datas has Parent_id is 0. autoincrement id will be Parent_id for next levels .my table table table datas will bw like this
id     Parent_id    Level    Name
1       0             1      Indian
2       0             1      International
3       0             1      Nri
4       1             2      BC
5       2             2      Christian
6       2             2      Muslim
7       4             3      MBC-1
8       7             4      OBC-2
9       1             2      FC

i want to show records in this format (its like a tree view)
id     Parent_id    Level    Name
1       0             1      Indian
4       1             2      BC
7       4             3      MBC-1
8       7             4      OBC-2
9       1             2      FC
5       2             2      Christian
6       2             2      Muslim
2       0             1      International
3       0             1      Nri
4       1             2      BC

Can any one should help me to get this arrangement of datas using sql Query?

A: If it does not have a set number of branches you likely want to loop over a query in your app or write an SP to obtain all nodes. Some good reading here:
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/


Q: omitempty does not work in encoding/xml when using pointers? I am consuming a REST API that returns XML and am trying to Unmarshal the XML and am having issues that appear that the omitempty is not working. Here is an example of a working XML file:
<?xml version='1.0' encoding='UTF-8'?>
<customer uri="/api/customers/339/" id="339">
    <name>
        <first>Firstname</first>
        <last>Lastname</last>
    </name>
    <email>myemail@example.com</email>
    <billing>
        <address>
            <address1>123 Main St.</address123>
            <address2></address2>
            <city>Nowhere</city>
            <state>IA</state>
            <country>USA</country>
            <zip>12345</zip>
        </address>
    </billing>
</customer>

Here is an example of a "bad" record
<?xml version='1.0' encoding='UTF-8'?>
<customer uri="/api/customers/6848/" id="6848">
    <name>
        <first>Firstname</first>
        <last>Lastname</last>
    </name>
    <email/>
    <billing/>
</customer>

Now I have my structs set up like the following:
 type Customer struct {
     ID      int      `xml:"id,attr"`
     Name    *Name    `xml:"name,omitempty"`
     Billing *Billing `xml:"billing,omitempty"`
 }

 type Billing struct {
     Address *Address `xml:"address,omitempty"`
 }

 type Address struct {
     address_1 string `xml:",omitempty"`
     address_2 string `xml:",omitempty"`
     city      string `xml:",omitempty"`
     postal    string `xml:",omitempty"`
     country   string `xml:",omitempty"`
 }

 type Name struct {
     first, last string
 }

Reading through all of the records it works when the XML follows the pattern of the first example <billing></billing> but when it hits a record that has something like <billing/> it throws the following error: panic: runtime error: invalid memory address or nil pointer dereference
Can someone help me figure out what's going on and how to resolve it?

A: You're probably misunderstanding what ,omitempty means. It takes effect when marshalling data, only. If you unmarshal <billing/> onto a pointer field with ,omitempty, it will still initialize the field. Then, since the XML element is empty, the fields of Billing itself won't be set. In practice, if you assume that customer.Billing != nil means customer.Billing.Address != nil, you'll get the observed panic.
Note: http://play.golang.org/p/dClkfOVLXh


Q: Use @CachePut in springmvc project,but get the key and the value two separate data in redis In the spring MVC project, I'm try to cache data with @CachePut, but in redis, there are two separate data for key and value:

At the same time, I did the same thing with the springboot project and got the normal results:

The configuration in springmvc project:
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxTotal" value="${spring.redis.pool.maxTotal}"></property>
    <property name="maxIdle" value="${spring.redis.pool.maxIdle}"></property>
    <property name="minIdle" value="${spring.redis.pool.minIdle}"></property>
    <property name="maxWaitMillis" value="${spring.redis.pool.maxWait}"></property>
</bean>

<bean id="connectionFactory"
      class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="poolConfig" ref="poolConfig"></property>
    <property name="hostName" value="${spring.redis.host}"></property>
    <property name="port" value="${spring.redis.port}"></property>
    <property name="password" value="${spring.redis.password}"></property>
    <property name="database" value="${spring.redis.database}"></property>
    <property name="timeout" value="${spring.redis.timeout}"></property>
</bean>

<bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
    <constructor-arg name="redisOperations" ref="redisTemplate" />
</bean>

<bean class="redis.clients.jedis.JedisPool">
    <constructor-arg ref="poolConfig"/>
    <constructor-arg value="${spring.redis.host}"/>
    <constructor-arg type="int" value="${spring.redis.port}"/>
    <constructor-arg type="int" value="${spring.redis.timeout}"/>
    <constructor-arg type="java.lang.String" value="${spring.redis.password}"/>
    <constructor-arg type="int" value="${spring.redis.database}"/>
</bean>

and
@Bean
public RedisTemplate<String , Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

    ObjectMapper mapper = new ObjectMapper();
    JavaTimeModule javaTimeModule = new JavaTimeModule();

    javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(properties.dateFormatter()));
    javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(properties.timeFormatter()));
    javaTimeModule.addSerializer(YearMonth.class, new YearMonthSerializer(properties.yearMonthFormatter()));
    javaTimeModule.addSerializer(MonthDay.class, new MonthDaySerializer(properties.monthDayFormatter()));
    javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(properties.dateTimeFormatter()));
    javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(properties.dateFormatter()));
    javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(properties.timeFormatter()));
    javaTimeModule.addDeserializer(YearMonth.class, new YearMonthDeserializer(properties.yearMonthFormatter()));
    javaTimeModule.addDeserializer(MonthDay.class, new MonthDayDeserializer(properties.monthDayFormatter()));
    javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(properties.dateTimeFormatter()));
    mapper.registerModule(javaTimeModule);
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    serializer.setObjectMapper(mapper);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(serializer);
    template.afterPropertiesSet();
    return template;
}

Is there a problem with the configuration ？

A: In RedisCacheManager ,property usePrefix default value is false,so we should set usePrefix=true in JavaConfig:
@Bean
public RedisCacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    cacheManager.setUsePrefix(true);
    return cacheManager;
}


Q: Django Allauth saving profile information with signup form I am new in Django, I am using allauth app to create a user registration. There are some extra field I wish to have in my signup form. Not only (username, first_name, last_name) I wish to also include info to the registration form.
When I submit the registration form only the first_name and the last_name are saved in database, info is not saved. I guess it should be saved in Profile Model, but its not there.
class Profile(models.Model):
    user = models.OneToOneField(User)
    info = models.CharField(max_length=128)

class CustomSignUpForm(Signup Form):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    info = forms.CharField(max_length=50)

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()
        user.profile.info = self.cleaned_data['info']
        user.profile.save()

ACCOUNT_FORM = 'signup' 'myapp.forms.CustomSignupForm'

A: Are you sure the Profile object exists for that user and you are not getting RelatedObjectDoesNotExist error in logs? If yes then you have to create a Profile object, in the above signup form.
Profile.objects.update_or_create(user=user, defaults={"info":self.cleaned_data['info']})


Q: Igraph Identifying nodes based on centrality scores I'm running the igraph package for some network analysis on this example dataset
structure(list(ï..Column1 = c(NA, NA, NA, NA), Column2 = c(NA,
NA, NA, NA), Column3 = c(NA, NA, NA, NA), Column4 = c(NA, NA,
NA, NA), Column5 = structure(c(2L, 1L, 4L, 3L), .Label = c("Eric ",
"Jim", "Matt", "Tim"), class = "factor"), Column6 = c(NA, NA,
NA, NA), Column7 = structure(c(1L, 3L, 2L, 3L), .Label = c("Eric",
"Erica", "Mary "), class = "factor"), Column8 = structure(c(3L,
2L, 1L, 3L), .Label = c("Beth", "Loranda", "Matt"), class = "factor"),
    Column9 = structure(c(2L, 3L, 1L, 3L), .Label = c("Courtney ",
    "Heather ", "Patrick"), class = "factor"), Column10 = structure(4:1, .Label = c("Beth",
    "Heather", "John", "Loranda "), class = "factor"), Column11 = c(NA,
    NA, NA, NA), Column12 = c(NA, NA, NA, NA), Column13 = c(NA,
    NA, NA, NA), Column14 = c(NA, NA, NA, NA), Column15 = c(NA,
    NA, NA, NA)), class = "data.frame", row.names = c(NA, -4L
))

Here is the edgelist for anyone who wants to skip the step of finding that
structure(c("Jim", "Eric ", "Tim", "Matt", "Jim", "Eric ", "Tim",
"Matt", "Jim", "Eric ", "Tim", "Matt", "Jim", "Eric ", "Tim",
"Matt", "Eric", "Mary ", "Erica", "Mary ", "Matt", "Loranda",
"Beth", "Matt", "Heather ", "Patrick", "Courtney ", "Patrick",
"Loranda ", "John", "Heather", "Beth"), .Dim = c(16L, 2L), .Dimnames = list(
    NULL, c("Column5", "value")))

I'm trying to calculate centrality for each of the nodes in the network using this code (mat is my edgelist matrix)
g1=graph_from_edgelist(mat)
degree.cent <- centr_degree(g1, mode = "all")
degree.cent

My output is something like this
> degree.cent
$`res`
 [1] 4 1 4 2 4 1 6 1 2 1 2 1 1 1 1

$centralization
[1] 0.1479592

$theoretical_max
[1] 392

I know 'degree$res` is my centrality score measures, but what isn't clear to me is which nodes are actually receiving that score. I looked up a tutorial here, but all it says is the first score is "node 1". There's no indication of what node 1 is or an easy way to identify that

A: Firstly, you are getting incorrect results as some of the names contain spaces (Eric, Marry, Heather, ...). So, let
mat <- gsub(" ", "", mat)
g1 <- graph_from_edgelist(mat)
degree.cent <- centr_degree(g1, mode = "all")

Now we may extract the corresponding names of vertices and combine them with your result:
setNames(degree.cent$res, V(g1)$name)
#      Jim     Eric     Mary      Tim    Erica     Matt  Loranda     Beth  Heather
#        4        5        2        4        1        6        2        2        2
#  Patrick Courtney     John
#        2        1        1


Q: VBA - String changes when SaveAs My code creates a new Excel file, and gathers data into it. Then it should save it into a specified folder (on the hard drive), with a specified name.
The path - with the file name at the end - is built up by the code and stored in a string.
Right before the SaveAs command, I use Debug.Print to check the string, and it's a 100% good.
Still the SaveAs line runs to this error:
"Run-time error '1004':
Microsoft Excel cannot access the file
[here comes the entire path]
There are several possible reasons:

*

*The file name or path does not exist.

*The file is being used by another program.

*The workbook you are trying to save has the same name as a"

(The rest is not visible because of the size of the window, but whatever.)
The path in the error message is ok, but instead of the file name there is a 6-character code made of (seemingly) random numbers and letters. And it changes with every run.
How does the filename string get exchanged to that? Can it have anything to do with cloud-based stuff and/or sharepoint and/or syncronization (of which I'm not expert)?
Are there any solutions?
Thanks


Q: Camel route xpath filter i m stuck with xpath filter in camel route, and i don t find solution...
here is my xml message
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"
xmlns:ct="http://com/fr/test">
<env:Header>
    <receptionTime xmlns="http://com/fr/test">2016-02-12T14:40:56+0100
    </receptionTime>
    <correlationId xmlns="http://com/fr/test">944689bc-9605-4292-929a-3b2e8a5eddd7
    </correlationId>
    <equipmentType xmlns="http://com/fr/test">WCA</equipmentType>
    <messageType xmlns="http://com/fr/test">Reservation</messageType>
</env:Header>
<env:Body>
<content xmlns="http://com/fr/test"></content>
</env:Body>

and my route lokk like this :
 from("activemq-ext-in:queue:" + queueName)
    .id("amq-transfert-downward-route")
    .filter().xpath("/env:Envelope/env:Header/equipmentType/text()='WCA'")
    //.when(body().contains("WCA"))
    .to("activemq-ext-out:topic:" + topicName);

and my message never arrived in my out topic :( if i uncomment the when clause, and comment the filter, my message is correctly send, but i want to use filter
can someone help me how to find the good xpath expression?
possibly i can use .choice().when(xpath...).to(...)?
i just need a correct solution :)
thanks a lot!

A: Looks like a namespace prefix issue. You're qualifying Envelope with "env:" which is good as long as that prefix is mapped to the right namespace. However, you are missing a suitable qualifier on equipmentTest which is in a different namespace.
See the Camel docs on how to configure a namespaces.
Namespaces ns = new Namespaces("ct", "http://com/fr/test")
    .add("env", "http://www.w3.org/2003/05/soap-envelope");

from("activemq-ext-in:queue:" + queueName)
   .id("amq-transfert-downward-route")
   .filter(
      ns.xpath("/env:Envelope/env:Header/ct:equipmentType/text()='WCA'")
   ).to("activemq-ext-out:topic:" + topicName);

Updated: changed to use the OP example instead of the one from the Camel docs. I haven't tested this but it looks about right.