text:
Q: Pandas add column from list with bigger index I have a dataframe that only has 1 row:
TotalCount                 Percentage
57                              34

List1:
['Group1','Group2','Group3','Group4']

I have a list which contains 4 values. I want to add another column to my dataframe which contains the list:.
Desired Output:
TotalCount                 Percentage               Group
57                              34                  Group1
                                                    Group2
                                                    Group3
                                                    Group4

I have tried pd.Series(List1) but it only gives me 1 result
and if I try df['Group'] = List1 I get Length of values (4) does not match of length of index (1)
I want to be able to add the list to the DataFrame in a new column and ignore the index

A: Use pd.concat
df = pd.DataFrame({'a': {0: 57}, 'b': {0: 34}})
Group = ['Group1','Group2','Group3','Group4']
pd.concat([pd.DataFrame(Group),df], axis=1)

df being your dataframe and Group being your list.


text:
Q: Doing calculations, using mulitple rows, pandas Expanding on my previous question. Return only the last day of the year with pandas?
my current table is this
name of the table is last_six_years
   symbol   date    close
44  MMM 2014-12-31  139.6180
45  MMM 2015-12-31  131.3644
46  MMM 2016-12-30  159.8925
47  MMM 2017-12-29  215.7010
48  MMM 2018-12-31  179.2494
49  MMM 2019-12-31  171.5581

i need to create a new column(named "capital_gains_yield") which calculates a value, that is derived from using the next row to it with the following formula:
capital_gains_yield = (current year close - previous year close) / previous year close
meaning, the outcome would look something like this:
   symbol   date    close      capital_gains_yield
44  MMM 2014-12-31  139.6180   ...
45  MMM 2015-12-31  131.3644   -0.057
46  MMM 2016-12-30  159.8925   0.2137
47  MMM 2017-12-29  215.7010   0.3522
48  MMM 2018-12-31  179.2494   -0.16
49  MMM 2019-12-31  171.5581   -0.04

How can i do that?

A: Check the pandas.DataFrame.pct_change() function.
Assuming you already sorted the dataframe by time:
df = pd.DataFrame({'close':np.random.uniform(0, 10, 5)})
df['yield'] = df['close'].pct_change()

    close       yield
0   9.836278    NaN
1   5.059823    -0.485596
2   0.842129    -0.833566
3   5.670353    5.733358
4   5.906502    0.041646

A: Adding to the very good answer from Z Li, if you can't use pct_change(), you may try:
Creating a column with the previous values to compare, ie the values shifted by one.
df['prev_year_close'] = df['close'].shift(1)

Define a function we'll use to get the yield:
def getCGY(row):
    difference = row["close"] - row["prev_year_close"]
    return difference/row["prev_year_close"]

Use pandas' apply() to perform the above function on each row:
df['capital_gains_yield'] = df.apply( lambda x: getCGY(x), axis=1)

Optionally delete the comparison column:
df = df.drop("prev_year_close",axis=1)

Will output:
      close  capital_gains_yield
0  139.6180                  NaN
1  131.3644            -0.059116
2  159.8925             0.217168
3  215.7010             0.349038

This will give you a bit of flexibility in case you need to change the way calculation is made, etc. by editing the getCGY function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I write data from python lists with various lengths of tuples inside to a file? I have data coming from a function giving a tuple of x-y position of a circle, and then a single entry for the radius of a circle.  When I print the output of the function it gives me the output below, where the data is float:
((308.5, 221.0), 7.861134052276611)

How can I write this data to a file in a tab-delimited format, for example:
x1, "\t", y1, "\t", r, "\n"

If it's useful to you, the function I am working with is cv2.minEnclosingCircle(contour).  I want to save my circle tracking data in a text file so that I can analyze it later.

A: (x, y), r = ((308.5, 221.0), 7.861134052276611)
line = "{0}\t{1}\t{2}".format(x, y, r)

file_ = open("some.txt", "w")
file_.write(line)

You can then write a function for saving data to a file:
def save(data, filename):
    """
    Here data is a tuple with the form: ((x, y), r)
    """
    (x, y), r = ((308.5, 221.0), 7.861134052276611)
    line = "{0}\t{1}\t{2}".format(x, y, r)

    # Open the file with 'w+' mode in order to add the new lines
    # at the end.
    file_ = open(filename, "w+")
    file_.write(line)
    file_.close()

If you use this function a lot, you might want to consider out the open-close-file code outside this function.

A: x = ((308.5, 221.0), 7.861134052276611)

print '{0[0]}\t{0[1]}\t{1}'.format(*x)

result
308.5   221.0   7.86113405228

A: Try this
fileName.write("%f\t%f\t%f\n"%(tupleName[0][0],tupleName[0][1],tupleName[1]))

where tupleName contains the output of the function and fileName is your file object.


text:
Q: Is it safe to protect SQL Database (.mdf) by checking the last modified date? I want to protect the SQL Database (.mdf) file by checking if the last modified date of the database file matches my Application's record. So that if user edit any data from the database it can be identified. So is it safe to use this method? Or is there any better method?

Please don't suggest store .mdf file on different machine and access it by using LAN connection.

A: The database file modified date does not change when a user performs an update or delete according to this link: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/b7db6744-cd7b-42b5-a84e-5e511a5e8e59/mdf-ldf-files-last-modified-date-not-increasing-as-expected?forum=sqldisasterrecovery
What are you concerned about? Are you concerned about a DBA making modifications or an application user making modifications? If you want to know what users are doing then could you create a table called dbAudit, which contains four fields i.e. ID (Primary Key), Username, datecreated and sqlquery.  You could log all of the sql queries run against the database by the application.
It may also be worth looking into Transparent Data Encryption: https://learn.microsoft.com/en-us/sql/relational-databases/security/encryption/transparent-data-encryption-tde


text:
Q: how to properly write a sum What is the correct way to write a sum? I want to write a general formulation for the voltage at the last node of a line of an electrical grid. Here is an example line:

I have written:
\begin{equation}
u_\mathrm{last}=u_0-\sum_{l\in\mathcal{L}}\Big(Z_l\cdot\sum_{\substack{n\in\mathcal{N}\\n\geq l}}I_n\Big)
\end{equation}
where $\mathcal{L}=\{1, 2, 3, 4\}$ is the set of lines  and $\mathcal{N}=\{1, 2, 3 , 4\}$ is the set of nodes. $Z_l$ is the impedance of the $l$-th line and $I_n$ is the current into the $n$-th node (attached loads, that are not depicted in the picture). $u_0$ is the voltage at the transformer low voltage side. So for example the last voltage node of a line with 3 nodes would be:
$$
u_3=u_0-\big(Z_1\cdot(I_1+I_2+I_3)+Z_2\cdot(I_2+I_3)+Z_3\cdot I_3 \big)
$$
Is my general formulation above correct? Because my Professor (he is not a mathematician, just like me) thinks, that sum operators allways need upper and lower bounds, like:
$$
\sum_{l_0}^{l_n}
$$
But with these upper and lower bounds, Im not sure how to properly express, that the sum of $I$ is getting one element shorter each iteration of the outer sum.
Thanks for any help in advance!

A: There are usually more than one way to represent a sum and your approach is fine. In fact considering $3$ nodes with index sets
\begin{align*}
\mathcal{N}=\{1,2,3\}=\mathcal{L}
\end{align*}
together with a special node $u_0$ we have the equality chain
\begin{align*}
\color{blue}{u_3}&=u_0-\left(Z_1\cdot(I_1+I_2+I_3)+Z_2\cdot(I_2+I_3)+Z_3\cdot I_3 \right)\\
&\color{blue}{=u_0-\sum_{l\in\mathcal{L}}Z_l \sum_{\substack{n\in\mathcal{N}\\n\geq l}}I_n}
\color{blue}{=u_0-\sum_{l=1}^3Z_l\sum_{n=l}^3 I_n}\tag{1}
\end{align*}

*

*As we can see at the left-hand side of (1), lower and upper bound need not be explicitly stated. They are nevertheless implicitly given by definition of $\mathcal{N},\mathcal{L}$ and the constraint $n\geq l$.

*Another aspect is, that $l\in\mathcal{L}$ does not imply any order of summation. We just have to take each element from $\mathcal{L}$ in any order we like. This is admissible since addition is commutative.
Hint: You might find chapter 2: Sums in Concrete Mathematics by R.L. Graham, D.E. Knuth and O. Patashnik helpful. It provides a thorough introduction in the usage of sums.


text:
Q: what is a HTTP response code variant in Panels 3 Drupal Dear Friends.I am using Panels 3 in drupal 6.2.
While creating page panel i get the option variant type where i can either select panel or HTTP response Code.
My query is what is this HTTP response code option for.I tried to add a panel using this option but nothing seems like working.Please help me.
Thanks and Regars

A: Creating a page variant using a HTTP Response code allows you to redirect the display for the intended path to a 404 page not found, 403 Access denied, or 301 redirect. You would use the first two to keep a user from accessing a specific site display page or you could redirect them to another page that you choose.
If it is not working, check the defined path for the page definition, the position of the variant in the list (panels will display the first variant that meets the criteria), or the contexts you are applying to the page


text:
Q: Renumber duplicates to make them unique        Table "public.t"
 Column |  Type   | Modifiers
--------+---------+-----------
 code   | text    |
 grid   | integer |

The codigo column, although of type text, has a numeric sequence which has
duplicates. The grid column is a unique sequence.
select * from t order by grid;
 code | grid
------+------
 1    |    1
 1    |    2
 1    |    3
 2    |    4
 2    |    5
 2    |    6
 3    |    7

The goal is to eliminate the duplicates in the code column to make it unique. The result should be similar to:
 code | grid
------+------
 1    |    1
 6    |    2
 4    |    3
 2    |    4
 7    |    5
 5    |    6
 3    |    7

The version is 8.2 (no window functions).
create table t (code text, grid integer);
insert into t values
 ('1',1),
 ('1',2),
 ('1',3),
 ('2',4),
 ('2',6),
 ('3',7),
 ('2',5);

A: This is the solution that worked.
drop sequence if exists s;
create temporary sequence s;
select setval('s', (select max(cast(code as integer)) m from t));

update t
set code = i
from (
    select code, grid, nextval('s') i
    from (
        select code, max(grid) grid
        from t
        group by code
        having count(*) > 1
        order by grid
    ) q
) s
where
    t.code = s.code
    and
    t.grid = s.grid

The problem with it is that the update command must be repeated until there are no more duplicates. It is just a "it is not perfect" problem as it is a one time operation only.

A: Export (and remove) everything but code column (maybe you could subquery for export, and remove just duplicated row). Make code primary with something such auto increment behaviour and reimport everything. code column should be automatically generated.


text:
Q: Angular2: implementing the tabs I want to implement tabs on my page and therefore went through this tutorial
https://dzone.com/articles/learning-angular-2-creating-a-tabs-component but somehow its not working for me with Plunker:
http://plnkr.co/edit/jwBB7jd8KDXmndGBz4ZN?p=preview
import { Component, OnInit,Input } from '@angular/core';

@Component({
  selector: 'tab',
  template: '

  <ng-content></ng-content>

',
  styleUrls: ['./tab.component.css']
})
export class Tab{
  @Input('tabTitle') title: string;
  @Input() active = false;

}

And Tabs Component:
  import { Component, OnInit,ContentChildren,QueryList ,AfterContentInit} from '@angular/core';
    import { Tab } from './tab.component.ts';

    @Component({
      selector: 'tabs',
      template: `

        {{tab.title}}

    <ng-content></ng-content>`,
      styleUrls: ['./tabs.component.css']
    })
    export class Tabs implements AfterContentInit{
      @ContentChildren(Tab) tabs: QueryList<Tab>;

     ngAfterContentInit() {
      let activeTabs = this.tabs.filter((tab)=>tab.active);

      if(activeTabs.length === 0) {
        this.selectTab(this.tabs.first);
      }
    }

    selectTab(tab: Tab){
      this.tabs.toArray().forEach(tab => tab.active = false);
      tab.active = true;
    }
    }

Please note : its first time i am working with Plunker, so please excuse me.
I hope someone can help me with this .
Thanks.

A: I have a very easy solution
home.component.ts

Tab 1

Tab 2

Tab 3
df

    ABC TAB 1

    ABC TAB 2

    ABC TAB 3

This is very easy without using any third party component
if you want to active any tab on page load
then assign value to "tab" variable
home.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  tab: number = 3;
  constructor() { }

  ngOnInit() {
  }

}

A: Angular is not loaded.
You need to set your plunker as angular 2 app when you create it.


text:
Q: fetch the comma separate field in mysql query My table id and skillid values are
      1=>3
      2 =>5
      3 =>5,6,8

I have tried the query to fetch the value from my table
 SELECT * FROM mytable WHERE skillid IN ('3', '5');
But i am getting only two rows, that was first and second row.
But i need the result three rows.
Thanks in advance.

A: The 'IN' comparison operator works like an equality operator. This:
expr IN ('3','5')

is equivalent to:
( expr = '3' OR expr = '5' )

That should be sufficient to explain why your query is not returning what you expect.

If your table has a character column that contains a comma separated list, like this:
id  skill_id_list
--  -------------
 1  3
 2  5
 3  5,6,8

Then one option, to search for a particular id value in the list is to make use of the MySQL FIND_IN_SET function. For example:
SELECT t.id
     , t.skill_id_list
  FROM mytable t
 WHERE FIND_IN_SET('3', t.skill_id_list)
    OR FIND_IN_SET('5', t.skill_id_list)

The MySQL FIND_IN_SET function is documented here:
https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_find-in-set
Of course, that's only one option. There are several other ways to get an equivalent result.
If there are no spaces in the skill_id_list column, then another option is to use a LIKE operator, but taking care to handle the edge cases.
There are four cases you would need to check for the id value appearing:

*

*as the only one in the list

*at the beginning of the list

*in the middle of the list

*at the end of the list

To explicitly handle those four cases, you could check each one, for example:
 WHERE skill_id_list LIKE '3'        -- only one in list
    OR skill_id_list LIKE '3,%'      -- beginning of list
    OR skill_id_list LIKE '%,3,%'    -- middle of list
    OR skill_id_list LIKE '%,3'      -- end of list

Or, another way to approach that is to turn all of those cases into the single "middle of the list" by just appending a comma to the beginning and end of the list, and then doing a single check, for example:
 WHERE CONCAT(',',skill_id_list,',') LIKE '%,3,%'

Note that spaces embedded in the list could cause a row not to match. The MySQL REPLACE function can be used to remove spaces, replacing all spaces with an empty string, something like this:
 WHERE CONCAT(',',REPLACE(skill_id_list,' ',''),',') LIKE '%,3,%'

NOTE
The preceding attempts to to answer the question you asked. The following addresses a fundamentally different (though closely related) issue, concerning the relational dataa model and normalization.
Repeating attributes in normalized relational model are represented in separate table. That's the normative relational model. We typically avoid storing comma separated lists, and instead implement a separate table to store the repeating attributes.
For example, if a job has multiple skills, we would typically create another table to hold the list of job skills:
CREATE TABLE job
( id  INT NOT NULL PRIMARY KEY
, description VARCHAR(10)
);

CREATE TABLE job_skill
( job_id   INT NOT NULL COMMENT 'FK ref job.id'
, skill_id INT NOT NULL COMMENT ''
, PRIMARY KEY (job_id, skill_id)
, FOREIGN KEY job_skill_FK1 (job_id) REFERENCES job (id)
);

We'd represent the data in your model as five separate rows:
job_skill
job_id  skill_id
------  --------
1       3
2       5
3       5
3       6
3       8

That's the normative pattern.
To get back a list of job ids that require skills 3 or 5:
SELECT s.job_id
  FROM job_skill s
 WHERE s.skill_id in (3,5)
 GROUP BY j.job_id

To get back a list of job ids that require skills 3 and 5, there's several ways to do that, for example:
SELECT s.job_id
  FROM job_skill s
    ON s.job_id = t
 WHERE s.skill_id in (3,5)
 GROUP BY j.job_id
HAVING COUNT(DISTINCT s.skill_id) = 2

If it's more convenient for your use case to get back a comma separated list as a string, you can use the GROUP_CONCAT aggregate function:
SELECT j.id AS job_id
     , GROUP_CONCAT(s.skill_id ORDER BY s.skill_id) AS skill_id_list
  FROM job j
  LEFT
  JOIN job_skill s
    ON s.job_id = j.id
 WHERE ...
 ORDER BY ...

A: Please check
SELECT * FROM mytable WHERE 5 IN (skillid) OR 3 IN (skillid);

A: SELECT * FROM mytable WHERE skillid LIKE '3%' OR skillid LIKE '5%';
Definetly this is NOT the way to do it...
YOU SHOULD NORMALIZE your table to avoid this kind of problems

A: This is not good practice, you should normalize your table table, but REGEXP  would be helpful
Please try this way
SELECT * FROM mytable WHERE
skillid REGEXP '[[:<:]]3[[:>:]]' OR skillid REGEXP '[[:<:]]5[[:>:]]'


text:
Q: Android SDK Extras/ directory is missing I'm following the setup doc here to get started implementing in-App purchase for Android.
The docs reference the <sdk>/extras/google/play_billing/ directory and say to grab the IInAppBillingService.aidl file from that directory and add it to your project.
Despite having downloaded the latest SDK and associated files using Android SDK Manager, the Extras/ directory and this IInAppBillingService.aidl file are not present. Where can I find them?
(Frustrated side note: why are Google's Android docs so bad? Why do I need to copy a single file into my project instead of simply including a complete in-app-purchase jar?)
Edit:

A: I would make sure you don't have a duplicate SDK. Android Studio (if you're using it) comes with it's own Android SDK. If all else fails, I would probably uninstall that specific package and re-install it or a last resort of deleting the SDK and starting from scratch.

A: You must download the Google Play Billing Library via the SDK Manager (in the Extras category). The SDK Manager will then create the <sdk>/extras/google/play_billing/ directory, the IInAppBillingService.aidl file, and sample projects as well.

A: First of all, download Google Play Billing library using SDK manager.

Then go to

..\android-sdk\extras\google\market_billing

. There you can find the file.


text:
Q: Error while getting JSON when data has spaces I am facing issue while fetching json data when data has white spaces .
I am using spring,
In spring controller i am doing like below,
String json=new Gson().toJson(agents, new TypeToken>() {
                    }.getType())
I am able to see proper json in logger too, after that I am setting to model attribute like below one
model.addAttribute("json",json);
here model is 'org.springframework.ui.ModelMap'
In JSP I am able fetching data till no space found.
Example :
Original JSON String: ILOVE JAVA
Fetching string in JSP: ILOVE
Only please help me out this with out using encoding string.


text:
Q: Where can I get an opinion? I want to see developers' opinions on the use of a certain language feature, where is the right place to ask that question?

A: Not on the main sites
These sites are not for gathering opinions--they are for clear, definitive answers. asking on the appropriate chat is fine.
On the other hand, if you modified your question to a "what are the pros and cons of feature X" (which would be on topic), and formed your own opinion based on the answers, I think you'd have better results.

A: On Stack Exchange!
Not on Stack Exchange!
Let me explain. No, let the FAQ explain.
Good: You should only ask practical, answerable questions based on actual problems that you face. "I'm designing a plugin system with X, Y, and Z features. Based on  these requirements, would I be better off basing my system around interfaces or abstract classes, and why?"
Bad: every answer is equally valid. "Are interfaces better than abstract classes?"
Ugly: it is a rant disguised as a question. "Interfaces suck, amirite?"

A: You can try an appropriate chat room.


text:
Q: Change of basis, transition matrices, and representation matrices The following four questions were presented to me on an introductory-level linear algebra study guide. Before diving into some conceptual questions I have, here are the questions and my attempts at solving them:

$T$ is the projection onto the vector $\vec{w}=(3,1)$ in $R^2$ which is given as the following: $$T(\vec{x})=\frac{\vec{x}\cdot\vec{w}}{\vec{w}\cdot \vec{w}}\vec{w}$$

For simplicity, I will reduce $T(\vec{x})$ to $$T(\vec{x})=\frac{\vec{x}\cdot(3,1)}{10}(3,1)$$

(a) Find the standard representation matrix $A$ corresponding to the linear transformation above.

$$T[(1,0)]=\frac{(1,0) \cdot (3,1)}{10}(3,1)=(\frac{9}{10},\frac{3}{10})$$
$$T[(0,1)]=\frac{(0,1) \cdot (3,1)}{10}(3,1)=(\frac{3}{10},\frac{1}{10})$$
Thus the standard representation matrix A is
$$A=
\begin{bmatrix}
\frac{9}{10} & \frac{3}{10} \\
\frac{3}{10} & \frac{1}{10} \\
\end{bmatrix}$$

(b) Find the transition matrix P from the non-standard basis $B=\{(1,-1),(0,1)\}$ to the standard basis.

Choosing $B'=\{(1,0),(0,1)\}$ to represent the standard matrix, the transition matrix $P$ from $B$ to $B'$ can be found by rewriting $[B'\space B]$ as $[I^3\space P]$.
$$\begin{bmatrix}
1 & 0 & 1 & 0 \\
0 & 1 & -1 & 1 \\
\end{bmatrix}$$
$$P=
\begin{bmatrix}
1 & 0 \\
-1 & 1 \\
\end{bmatrix}$$

(c) By using the formula $A'=P^{-1}AP$, find the representation matrix $A'$ that corresponds to the linear transformation above, relative to the basis $B$.

If $[B'\space B]$ reduces to $[I^3\space P]$, then $[B\space B']$ should reduce $[I^3\space P^{-1}]$.
$$\begin{bmatrix}
1 & 0 & 1 & 0 \\
-1 & 1 & 0 & 1 \\
\end{bmatrix}\rightarrow
\begin{bmatrix}
1 & 0 & 1 & 0 \\
0 & 1 & 1 & 1 \\
\end{bmatrix}$$
$$P^{-1}=
\begin{bmatrix}
1 & 0 \\
1 & 1 \\
\end{bmatrix}$$
And finally $$A'=P^{-1}AP=\begin{bmatrix} 1 & 0 \\ 1 & 1 \\ \end{bmatrix}
\begin{bmatrix} \frac{9}{10} & \frac{3}{10} \\ \frac{3}{10} & \frac{1}{10} \\ \end{bmatrix}
\begin{bmatrix} 1 & 0 \\ -1 & 1 \\ \end{bmatrix}=
\begin{bmatrix} \frac{6}{10} & \frac{3}{10} \\ \frac{8}{10} & \frac{4}{10} \\ \end{bmatrix}$$

(d) Find $T(\vec{v})$ relative to basis $B$ where $\vec{v}=(7,4)$ by using $A'$.

While normally we might use the equation $[T(\vec{v})]_{B}=A'[\vec{v}]_{B'}$, since $B'$ is the $2\times 2$ Identity Matrix, we can simplify it to
$$[T(\vec{v})]_{B}=A'\vec{v}=
\begin{bmatrix} \frac{6}{10} & \frac{3}{10} \\ \frac{8}{10} & \frac{4}{10} \\ \end{bmatrix}
\begin{bmatrix} 7 \\ 4 \\ \end{bmatrix}=
\begin{bmatrix} \frac{27}{5} \\ \frac{36}{5} \\ \end{bmatrix}$$

Firstly, what I am curious about is the choice of $P$ and $P^{-1}$. Specifically, will $P^{-1}$ always represent the transition matrix from some basis to the basis we are trying to solve $T(\vec{v})$ with respect to? Order matters when multiplying matrices (i.e. $AB$ is not necessarily equal to $BA$) so what I am getting at is that there must be a reason we picked $P$ to be the transition matrix from $B$ to $B'$.
My next question is about why I am able to get two different values for $A'$. I had the impression that I solved (d) incorrectly, so I tried it another way, where $A'=[[T[(1,0)]]_{B} | [T[(0,1)]]_{B}]$.
$T[(1,0)]=(\frac{9}{10}, \frac{3}{10})$ and $T[(0,1)]=(\frac{3}{10}, \frac{1}{10})$ so
$\begin{bmatrix} 1 & -1 \\ 0 & 1 \\ \end{bmatrix}[T[(1,0)]]_{B}=\begin{bmatrix} \frac{9}{10} \\ \frac{3}{10} \\ \end{bmatrix}\rightarrow [T[(1,0)]]_{B}=\begin{bmatrix} \frac{9}{10} \\ \frac{12}{10} \\ \end{bmatrix}$
$\begin{bmatrix} 1 & -1 \\ 0 & 1 \\ \end{bmatrix}[T[(0,1)]]_{B}=\begin{bmatrix} \frac{3}{10} \\ \frac{1}{10} \\ \end{bmatrix}\rightarrow [T[(0,1)]]_{B}=\begin{bmatrix} \frac{3}{10} \\ \frac{4}{10} \\ \end{bmatrix}$
therefore
$$A'=
\begin{bmatrix}
\frac{9}{10} & \frac{3}{10} \\
\frac{12}{10} & \frac{4}{10} \\
\end{bmatrix}$$
which, interestingly enough, is the same as $P^{-1}A$. Of course, if I plug this into the equation I used in part (d), I get a completely different answer. However, I know almost certainly that, at least for the method of obtaining $A'$ shown right above, that the equation in (d) should work in finding $[T(\vec{v})]_{B}$.
What I am thinking now is that I am either solving the wrong equation for part (d) or that I messed up somewhere in finding my transition matrices. Any clarification would be greatly appreciated.

A: I haven't checked your calculations, but your second method of computing $A'$ is wrong. By definition,
$$ A' = [T]_{\mathcal{B}}^{\mathcal{B}} = [[T(1,-1)]_{\mathcal{B}} \, | \, [T(0,1)]_{\mathcal{B}}] $$
and not what you wrote. You take each element of the basis $\mathcal{B}$, apply $T$ to it, represent the result with respect to the same basis $\mathcal{B}$ and put in in a column. Instead, you have taken the standard basis, applied $T$ to it and then represented the result with respect to a different basis.

Regarding your question about $P$, there is a notorious ambiguity between different authors regarding what is called "a change of basis matrix from $\mathcal{B}$ to $\mathcal{C}$". What some authors call $P$ might be called $P^{-1}$ by other authors and the formula for one author will look like $A' = P^{-1}AP$ while for another it will look like $A' = PAP^{-1}$. In my opinion, the change of basis formula should be written as
$$ [T]_{\mathcal{B}} = [\operatorname{id}]_{\mathcal{B}}^{\mathcal{B}'} [T]_{\mathcal{B}'}^{\mathcal{B'}} [\operatorname{id}]_{\mathcal{B}'}^{\mathcal{B}}. $$
Notice the "cancellation across diagonals" property which makes the formula easy to remember. Then, $P = [\operatorname{id}]_{\mathcal{B}'}^{\mathcal{B}}$ is the matrix whose columns are the elements of the basis $\mathcal{B}$, represented in the basis $\mathcal{B}'$. By the formula $[\operatorname{id}]_{\mathcal{B}'}^{\mathcal{B}} [v]_{\mathcal{B}} = [v]_{\mathcal{B}'}$, this matrix allows us to convert a representation of a vector in the basis $\mathcal{B}'$ to the representation of the same vector in the basis $\mathcal{B}$ by multiplying the representation $[v]_{\mathcal{B}}$ with $P$. This point of view makes it harder to confuse $P$ and $P^{-1}$.


text:
Q: Conda config no muestra canales estoy tratando de hechar andar anaconda pero realmente no se cual sea el problema. Ya lo tenia instalado pero tuve que instalar pyqt5 para usar pyqtDesigner todo de maravilla pero al instalarlo deje de funcionar Spyder. Asi que volvi a reinstalar y ahora no quiere ni si quiera abrir Anaconda Navigator. Cabe mencionar que la instalacion completa tardo mas de 12 horas, si asi como lo ven 12 hrs tuve que dejar la laptop ensendida toda la noche y simplemente no quiere abrir anaconda navigator. He estado viendo algunos hilos pero no he encontrado una solucion muchos mencioonan que el problema es con uno de los canales, pero cuando ejecuto el comando:
conda config

Este no retorna ningun canal, por lo cual no se como podria reestablecer los canales por default o corregir el problema.
Nota: Necesito tener anaconda y poder ejecutar spyder, pyqtDesigner, jupyter y visual studio code. Pero valla que me he liado.
Alguna sugerencia para resolver el problema?
Les dejo unos pantallasos con los comandos que he ejecutado:

Espero puedan ayudarme.
Saludos
DS


text:
Q: How to print the fractional part of float number while converting to string I have a code which will  convert the float value to string, i have written like below
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
    float myFloat= 10.80;
    std::ostringstream ss;
    ss << myFloat;
    cout<<"value = " << ss.str();
    std::string s(ss.str());
    cout<<"value = " << s;

    return 0;
}

But the problem is when my value is 10.66 its coming 10.66 but when its 10.80 its coming like 10.8 or when its 10.00 its coming 10 only .
How can i print the complete value

A: Try this code .
 Use the setprecision function with '2' .
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

int main() {

float myFloat= 10.80;
stringstream stream;
stream << fixed << setprecision(2) << myFloat;
string s = stream.str();
cout<<"value = " << s;
       return 0;
}

A: The trailing zeros are only kept if you set either fixed or scientific mode.
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    double x  = 4.2;
    cout << fixed << setprecision(2);
    cout << x << endl;
    return 0;
}

A: Probably the least complicated way would be to use printf instead of std::cout. There you can specifically specify how many digits are to be displayed.
#include "stdio.h"

printf("%3.2f",myfloat);

where 3 is the # of digits before and 2 the # of digits after the dot, either can be left out. Append '\n' to the string if you want a new line.
EDIT: Ok, I did not know about setprecision(2).

A: It seems you want something like below.
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;

int main() {
    float myFloat= 10.80;
    std::ostringstream ss;
ss << fixed << setprecision(2) << myFloat;
    cout<<"value = " << ss.str();
std::string s(ss.str());
    cout<<"value = " << s;
}


text:
Q: select table cell by an UIImageView I have a view that has a set of messages that the user receives, I'm trying to accomplish a UX similar to how gmail works.
I want when a user taps on the user's image it selects the row for whatever action they want to do (delete, mark as read, etc) and then if they tap anywhere else it shows the message. Below is a basic proof of concept.

I thought about setting up a tap gesture on the imageview but I feel like there's cleaner way than doing that and possibly something built into the table view, but I'm striking out.

A: What you're trying to do is have separate tap functions depending on the location. You'll have to add separate tap actions on each part of your cell.
So, in the Source of your TableView, you have to update the override UITableViewCell GetCell so that it updates the Image Button and adds the ability to allow user interaction and add a single tap gesture.
public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
    var cell = tableView.DequeueReusableCell (cellIdentifier);
    // where cellIdentifier is you TableView Cell key

    if (cell == null)
        cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier);
    cell.TextLabel.Text = tableItems [indexPath.Row];

    // Add other generic code above, but here's what you need
    cell.ImageButton.UserInteractionEnabled = true;
    var singleTapGestureRecognizer = new UITapGestureRecognizer(() =>  // Do work
                                                                );
    cell.ImageButton.AddGestureRecognizer(singleTapGestureRecognizer);

    return cell;
}


text:
Q: Gulp run task as per key in array of object For copying files to destination I am using simple gulp's src and dest
I want to specify this copy action as per key in obj:
    var copy = {
            first: {
                dest: 'dist/index.scala.html',
                src: 'app/index.scala.html'
            },
            second: {
                dest: 'dist/setup.scala.html',
                src: 'app/setup.scala.html'
            }
      };

I am able to create copy task and copy files as per src and dest mentioned in object But I need something like:
    gulp copy:first //this will only copy from src to dest as specifided under 'first' key

    gulp copy:second //this will only copy from src to dest as specifided under 'second' key

Like how we achieve in grunt.

A: According to this article "it's not possible to pass arguments on the command line which can be used by that task".
That said, you can do something like this:
const gulp = require("gulp");

const copy = {
    first: {
        dest: 'dist/index.scala.html',
        src: 'app/index.scala.html'
    },
    second: {
        dest: 'dist/setup.scala.html',
        src: 'app/setup.scala.html'
    }
};

for (let key in copy) {
    gulp.task('copy:' + key, cb => {
        console.log('copy[key]: ', copy[key]);
        cb();
    });
}

Note: I've changed copy = [...] to copy = {...} because arrays can't have strings (such as 'first') as keys but objects can.
Then to run the gulp commands:
gulp copy:first
gulp copy:second
You may also want to have a look at Pass Parameter to Gulp Task.


text:
Q: My dedicated server accept only 777 for uploads I don't know if somebody can help me, but i have a dedicated server on linux and the problem is only the 777 rule accepts uploads or write.
 if the path of my site is /var/www/ffolder/data/www/mysite.com how i can enable the rule 755 for uploads and write?
best regards!

A: Just make sure that the owner of /var/www/ffolder/data/www/mysite.com are the same you use to try the upload.
If the upload is made by some script ran by Apache or nginx, the user owning the directory must be the same user used to start the webserver.


text:
Q: Snake Game Win forms Ive been trying to create a snake game using win forms and ive been having trouble with moving my button tool with event handling using the arrow keys. it would be very helpful if someone could explain to me how make it work

A: From the very limited information you've provided, generally the approach should be to handle the KeyDown event of the Form containing your game. While the form has focus, this event will be raised whenever a key is pressed, at the time it's pressed. (the KeyPress event requires the key to be pressed and released before it is raised; the same action also raises a combination of KeyDown and KeyUp).
When handling the KeyDown event, examine the KeyData property of the KeyEventArgs. That property (read-only) is a flagged enumeration (meaning it can have a combination of the available values). You need to see if one or more of the following are pressed: Keys.Up, Keys.Down, Keys.Left, and Keys.Right. These are the arrow keys. You may also allow the user to use the numpad keys 8, 2, 4, and 6 respectively, which have different Keys enum values. If KeyData has one of these, change the direction the snake is moving, and also set the Handled property of the KeyEventArgs to true, which will tell any other code that responds to the key press not to proceed. This will prevent default behaviors associated with the arrow keys from causing problems.
Understand that the user may press multiple arrow keys. If those keys are in opposite directions, or you don't allow movement in one direction, you will need to decide how to handle this situation. The simple solution is to do nothing. The more complex solution is to track which arrow keys are currently pressed, and if multiple ones are pressed, listen for a KeyUp event that will tell you when one or more has been released, and only change direction when one key is currently pressed.


text:
Q: How to sync Keychain passwords between iOS and macOS? I'd like to share passwords between macOS and iOS. I've enabled iCloud keychain, moved all relevant passwords in Keychain App to iCloud but for some reason they don't appear in my iPhone. I check my passwords and there's nothing there. How can I debug this?

A: Only passwords stored via Safari are synced between devices. Passwords manually added to Keychain App are not sent to iOS.

A: Keychain must be turned on in both iOS and macOS. While data is moved back-and-forth through iCloud, data is not accessible from iCloud and need not (and should not) be moved manually from a computer or device into the user's iCloud storage. You can see Apple's directions for iOS here, and for macOS here. A good long-form discussion of Keychain synching is here. Apple's iOS page notes that Keychain synching is not available in all countries.
Briefly:

*

*Turn on Keychain synching on your iPhone in Settings > iCloud > Keychain. The Keychain slider must be "On." (This is iOS 12.2; your iOS may vary.)

*Turn on Keychain synching on your Mac in System Preferences > iCloud > Keychain. The checkbox next to "Keychain" must be checked.

*Confirm that both the iPhone and the Mac are signed in to iCloud.
You don't need to manually move files; it all happens seamlessly behind the scenes.


text:
Q: how to pad zero on left with String.Format i tried to use String.Format string with leading zero
Dim formatstring As String = ("{0,0}{1}{2,0:YYYY-MM-DD}{3}{4,0:00000}{5}{6,0:00000}{7}{8}{9}{10}{11}{12}")

with {4,0:00000} it would be fill zero on left
example
     014  to 00014
with {6,0:00000} it would be fill zero on left too
example
     547 to 00547
but it's not happen just still shown 014 and 547

A: For what you want to happen, the objects passed in the 4th and 6th indices need to support the IFormattable interface. From the docs:

If you specify formatString, the argument referenced by the format item must implement the IFormattable interface. Types that support format strings include:

*

*All integral and floating-point types. (See Standard Numeric Format Strings and Custom Numeric Format Strings.)

*DateTime and DateTimeOffset. (See Standard Date and Time Format Strings and Custom Date and Time Format Strings.)

*All enumeration types. (See Enumeration Format Strings.)

*TimeSpan values. (See Standard TimeSpan Format Strings and Custom TimeSpan format Strings.)

*GUIDs. (See the Guid.ToString(String) method.)

That you have a value of 014, rather than simply 14, implies that what you have is already a string. The String type does not implement IFormattable. To get this to work, you need to first parse the strings to integers or similar type.


text: Q: Algorithm for converting ext4 filenames to FAT filenames I need to move a directory structure from an ext4 partition to a FAT partition.  There are different rules for filenames for the two.  For example, ext4 allows two files foo and Foo to be in the same directory and be unique.  This is not true for FAT.  I am looking to see if there is an algo already out there for converting names between the two.  It is ok for the filename to be changed in my case, but I need to be able to read the new FAT name and be able to know what old ext4 name it corresponded with.  So the algo has to be something that can be reversed.  Does anyone know of such a thing?


text:
Q: Make 1 exception on X-Frame-Options SAMEORIGIN I use
Header set X-Frame-Options SAMEORIGIN
in .htaccess
But i would like to have 1 html page that isn't blocked when shown in iframe on other websites.....
How can i make 1 exception?

A: The Header directive provides an additional argument that allows you to set the header conditionally based on whether an environment variable is set or not.
You could then set an env var when this one URL is requested. And only allow the header to be set when the env var is not set.
For example:
SetEnvIf Request_URI "^/one-page-not-blocked\.html$" DO_NOT_BLOCK

Header set X-Frame-Options SAMEORIGIN env=!DO_NOT_BLOCK

The above SetEnvIf directive sets the env var DO_NOT_BLOCK to the value 1 when the regex matches the requested URL.
The env=!DO_NOT_BLOCK argument is successful when the env var is not set (denoted by the ! prefix).
This method allows you to add additional URLs to not block by simply adding more SetEnvIf directives.


text:
Q: program crashes when attempting to set the value of a string issue with cin >> This is a bizarre error that I have never seen before, and do not know how to fix it. The crash occurs on
na = m
Here is the relevant code. The line in question is marked with *:
In Main:
#include <cstdlib>
#include <iostream>
#include "stu.h"
#include <string>
#include <iomanip>

using namespace std;

int main(int argc, char *argv[])
{
    stu stu;
    int score[2];

    std::string name;
    std::cout <<"enter name:";
    std::cin >> name;
     //THIS IS AN EDIT IN  AFTER SEEING THAT A IMPORTANT ERROR POINT WAS NOT SHOWN TO THE FIRST COUPLE REPLY
       ************************************************************
     //THIS IS CAUSING THE PROBLEM WHEN I COMMENT IT OUT THE PROGRAM WORKS
     std::cout << "enter score 1:";
     std::cin >> score[0];
     std::cout << "enter score 2:";
     std::cin >> score[2];
     std::cout << "enter score 3:";
     std::cin >> score[3];
      *************************************************************
    stu.setname( name );

    // ...
}

In stu.ccp:
void stu::setname(std::string m)
{
    std::cout <<"1";//<--to find where the code was crashing

    na = m; // *** the crash

    std::cout <<"1";
}

In stu.hpp:
class stu
#include <string>
{
public:
    stu();
    void setname(std::string);
    std::string getname();
    void settest(int, int,int);
    void display();

private:
    std::string na;

    int score[2];
};

A: When you define int score[2] you get an array of 2 int and the valid array indices are 0..1.
Your later code writes past the end of the array and trashes whatever follows it in memory, in this case the string object name.
std::cout << "enter score 1:";
std::cin >> score[0];
std::cout << "enter score 2:";
std::cin >> score[2];
std::cout << "enter score 3:";
std::cin >> score[3];

The last two array references are incorrect.

A: You allocated enough space for two integers in an array, having valid indices 0 and 1.
 int score[2];

Then you tried to read more elements than that
 std::cin >> score[2];
 std::cout << "enter score 3:";
 std::cin >> score[3];

This is undefined behavior and anything is allowed to happen, including your entire computer disappearing in a fireball.  In your case, it overwrote the memory next to the array, which was your string variable.  Making a copy of a corrupted string can easily crash the program.

A: I've tried your code, it compiles and also runs with no problem.
Except for what you've provided I've just defined also the constructor, moved #include <string> before class stu in stu.h and removed that std::cout << "1".

A: int score [2]

will only have score[0] and score [1] spots for values. use
Try
   int score[3]

Then store your values in
 score[0];
 score[1];
 score[2];


text:
Q: Proper & complete way to declare website graphical-logo microdata I looked for the proper way to declare logo image in HTML5 with microdata
in this address: https://support.google.com/webmasters/answer/146861?hl=en also by clicking Microdata (recommended) sublink it can be seen that

became

So my 1st question is why they omitted alt tag. What if I code as below. Technically it'll be still correct, right? Or is there any conflict between alt tag and itemprop="logo"?

my 2nd question is
I have a complex, great-in-size logo and with my logo image I want to tell to search engines the story of my logo. (the symbols, their meanings, creators of that symbols etc.)
So which micro data tag I need with which syntax to achieve my aim if any? thanks

A: That's a very bad example from Google:

*

*The alt content "logo" is usually not appropriate for a logo (unless the company/etc. is named "logo").

*An img with Microdata's itemprop attribute still needs an alt attribute.

There are no conflicts between alt and itemprop. Your example with both of these attributes is fine.

To describe your logo in greater detail, you would need to find an appropriate Microdata vocabulary. If you want to use the schema.org vocabulary, the type ImageObject is probably the best you can get currently.
You could also use the longdesc attribute (currently a Working Draft) "to link descriptions to images in HTML5 content".


text:
Q: Android Studio redeclaration error when compiling release while having Kotlin Poet generated classes My app uses Kotlin Poet to generate some classes at compile time. These classes are generated in app/build/generated/source/kaptKotlin [main] and there in two subfolders debug."packagename" and release [main]/"packagename", depending on if I compile for debug or release.
When I compile for debug and then for release both subfolders will be present and thus resulting in a compiler error Redeclaration: classname.
I can work around that by deleting the opposite subfolder before I compile, i.e. deleting the debug subfolder when I compile for release and vice versa.
Still this is annoying and I am wondering if there are some settings I could apply to avoid this.


text:
Q: How to implement a plugin in MKDocs project? UPDATE!!!!
Watch the indent! My plugin section was indented in my code editor so it read as part of the package theme. Now that I have at least one of my plugins working, I feel somewhat sane. Now on to debug the other one...
Thanks and leaving this up in case anyone else makes the same mistake!
As for reference:
MKDocs 1.0.4
Pip 19.2.3
Python 3.8.1
Apologies for not posting original code because that probably would've helped since it took another coworker developer to notice that for me.

ORIGINAL POST:
I'm not quite sure where the disconnect occurred, but I feel like I've followed the MKDocs instruction on installing a plugin ten times and still have yet to actually see something work? I've made sure to install my desired plugins first before adding it in the configuration file.
These are the two that I'm trying to work towards at the moment before I try any others.
1: PDF Export Plugin
Pip installed that which seemed to work fine. I've added the pdf-export plugin under the plugins section of the mkdocs.yml file and I've rebuilt, rebuilt with the --clean, and reserved in a variety of combinations but when it tells me PDF documents should be automatically generating at the build command, I see nothing.

*Git Revision Date

Pip installed that which seemed to work fine. I've added the {{ git_revision_date }} portion to my index.md file to see what it would generate. Merely outputting the code through the browser.
Help?!
Do I need to add anything else anywhere else? I feel like I'm missing something since none of my plugins are showing me any response. I've been combing the MKDocs documentation, as well as the individual plugin documentation and have not found anything so far.

A: INDENT PROBLEM. Was pushed too far over so it was reading as the Theme section and not a plugin section.


text:
Q: How to get bold font Figure style with memoir class? I'm trying to modify the defaut figure style with the memoir class.
More precisely, I would like to have the Figure X.Y part in bold.
To get X.Y in bold isn't a problem, as the \captionnamefont{\bfseries} does the job.
But what about "Figure" ?
Note that adding the caption package conflicts with memoir, for those not knowing...

A: Just \captionnamefont{\bfseries} must work. May you are using the subfig package?. In any case, try with this MWE:
\documentclass{memoir}

  % "This may cause unexpected or inconsistent results
  % if you use any of memoir's captioning
  % facilities" (but work in other case?)
  %\usepackage{caption}
  %\captionsetup[figure]{labelfont=bf,textfont={bf,it}}

  % Still not working captioning facilities?.
  % Conflits with another packages?
  %\captionnamefont{\bfseries}

  %Starting from scratch

 \makeatletter
  \renewcommand{\fnum@figure}{\textbf
  {\figurename~\thefigure}}
  \renewcommand{\fnum@table}{\textbf
  {\tablename~\thetable}}
 \makeatother

\begin{document}
 \begin{figure}[!h]
  \centering\framebox{Image}
  \caption{The caption}
 \end{figure}
\end{document}

A: Are you using subfigures and LyX? If so, there's a behavior that IMHO is a bug. Here's an explanation.
Recent versions of LyX implement subfigures using the subfig package, and by default subfig uses the captions package. In turn, Memoir turns off its own captioning when the captions package is being used. So if you're using LyX and subfigures, all that Memoir goodness won't work.
IMHO, LyX ought to fix this by adding a checkbox on the Document Class tab of Document Settings. The checkbox should be "Use internal captioning?" A yes would use the captioning built into the selected document class; no check would load the caption package.
Then, somewhere in LyX there would be something like this pseudocode:
if box is checked
     \usepackage[caption=false]{subfig}
else
      \usepackage{subfig}
fi

If the caption package is loaded, Memoir's custom captioning is deactivated. Rather than make users waste 5-8+ hours tracking down the source of the problem, the proposed fix will let the user choose which captioning to use.


text:
Q: WPF Ribbons: Comparison of Microsoft, DevExpress or Fluent? In the new WPF application we write, we will be using DevExpress controls suite, and will have a Ribbon.
Currently, the options I see are:

*

*Microsoft - The vendor's offer, probably will get into the library on the next release

*DevExpress - The controls library we know and love

*Fluent - Open-source, got generally good recommendations

How do the different available ribbon controls compare? What features are / are not supported?

A: Fluent Ribbon here!
The Microsoft one lacks good support
Update:
Please vote on the Microsoft UserVoice site about the buggy Ribbon control:
https://visualstudio.uservoice.com/forums/121579-visual-studio-ide

A: Fluent Ribbon is I believe a great choice if you're looking to customize the styling of your ribbon. For example, Microsoft's Ribbon control has had theme options removed and is now only shipped with a single theme.
From my experience, Fluent Ribbon is not so great at design time building in Visual Studio, but in all other areas is superb. It is Open Source so can be customised to your needs and, coupled with MahApps Metro package, you can have complete Metro-styled applications with ease. Below is a screenshot of a sample application made with Fluent.Ribbon, using its 'Office 2013' theme.

Other commercial Ribbons are available and offer more features (such as three-state visibility, as show below in a screenshot from Outlook 2013)

I would advise making a list of all the features you require from the Ribbon control before deciding which one to use and whether a paid commercial Ribbon makes sense for your scenario. In your case, you already have access to DevExpress, so perhaps that may be your best choice.

A: I believe one of the most used is the Microsoft one.

A: Microsoft's Ribbon library (October 2010) does not work well with non standard DPI settings. And it's design time support is not good.
Comparing to Microsoft one, I personally think Actipro Ribbon is a better choice. It has EXCELLENT design time support, and works well with non standard DPI.
I have not tried any other Ribbon library yet.


text:
Q: Can I use a function passed by parameters? I have a function, and inside this function I should execute another function of 3 posibilities.
The simple way should be passing a parameter, doing a if-elif to exec function acording to that parameter, but I'd like to know it it's posible to pass the name of a funtion by params and use that, something like:
FunctionA(Param1, Param2, FunctionNameToUse)
    ....Code....
    FunctionNameToUse(Value1, Value2)
    ....Code....
endFunctionA

Depending on how functionA is called, it will use one Function or another, I dont know if I explained well...
Thanks mates!

A: Functions themselves are first class objects in Python. So there's no need to pass the name: pass the actual function itself, then you can call it directly.
def func1(a, b):
    pass

def func2(a, b):
    pass

def functionA(val1, val2, func):
    func(val1, val2)

# now call functionA passing in a function
functionA("foo", "bar", func1)

A: In python, functions are first-class values, which means they can be passed around as arguments, returned from functions, and so on.
So the approach you want to take should work (However you're not passing the name, you're passing the actual function).
Take a look at map and filter in the standard library, they do exactly this.

A: Yes, you can. As other have mentioned, functions are first-class objects, i.e. you can do everything you can think of to it (see What are "first class" objects? for more info).
So then, how does this really work when you pass in a function as parameter? If you have taken any ComSci class, you'd know that each process has a special area in memory allocated for its code; all of your functions are defined here. Whenever you call a function, the CPU would move the Program Counter (a special pointer that points to whatever code it is executing at the moment) to the beginning of that function's code, and go from there. Thus, after the function is loaded in memory, all that's needed to call it is its address. When you pass a function A's "name" as an argument to another function B in Python, what you are doing is really passing a reference (in C term, a pointer) that contains the address to the code that represents A in memory.


text:
Q: Converting character to hex in assembler So right now I'm working on reading in a single character from the keyboard and displaying its hex value. At the moment I believe I'm getting the correct hex value, but it is not being displayed correctly. For example, 'k' is 6F in hex, but it's displaying as '6;'. I know that the correction must be made in my DIS16 procedure, but I'm not sure when and what to do. If anyone can help, I'd really appreciate it.
DIS16   PROC

    mov cx, 0

    mov bx, 16

numdiv:

    mov dx, 0

    div bx

    push dx

    add cx, 1

    cmp ax, 0

    jne numdiv

dispnum:

    pop dx

    add dl, 30h

    mov ah, 02h
    int 21h

    loop    dispnum

RET
DIS16   ENDP

A: Since the characters 'A' thru 'F' do not immediately follow '9', you have to adjust for that.

; as you have it
pop dx
add dl, 30h
cmp dl, '9'
jbe skip
add dl, 7 ; bump up to 'A' - 'F'
skip:
; print it... as you were


text:
Q: React: Hiding or Removing the component is more efficient? I have three components in my app which are  <Video />, <VideoPreview /> , <VideoWrapper />,
here VideoWrapper component conditionally renders other two components based on a state isDragging, whenever someone starts dragging it renders,
the code is like isDragging ? <VideoPreview /> : <Video />
Here in this question, I saw they prefer using the current (JSX short circuit rendering) approach. But in my case, the <Video /> component renders some other components, and it makes an HTTP request on every render to load the video from CDN.
So I'm confused about which one should be better, the current approach or passing the isDragging state to the video component and toggling the visibility using CSS when isDragging=true. Can anyone explain which one should be better?

A: You definitely want to drag the preview, and not the component itself. Depending on what you use for drag 'n drop, the dragged component could rerender multiple times during the full cycle.


text:
Q: Android - ViewRootImpl$CalledFromWrongThreadException 2 This is what i want to do: I have a website with some buttons. The website is connected to my android app (via spacebrew). Depending on what button i click the background of an ImageButton changes. But every time i click on a button "setBackground" throws above exception.
This is my code:
public class MainActivity extends Activity{
    ImageButton display;
    SpacebrewClient client;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
        }
        ...
        //calls the method "changeDisplay"
        client.addSubscriber("changeDisplay", SpacebrewMessage.TYPE_STRING, "changeDisplay");
    }

    public void changeDisplay(String input){
        if(input.equals("topay")){
            display = (ImageButton)findViewById(R.id.imageButton1);
            display.setBackground(getResources().getDrawable(R.drawable.display_2));
        }
        ...
    }
}

I found this possible solution: first answer. But that doesn't seem to work for me.
I still get the same exception.
Edit:
Tried the second solution, as well. Now "setBackground" throws a NullPointerException.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
    display = (ImageButton)findViewById(R.id.imageButton1);
}
public void changeDisplay(String input){
    if(input.equals("topay")){
        runOnUiThread(new Runnable() {
            public void run() {
                display.setBackground(getResources().getDrawable(R.drawable.display_2));
            }
      });}

A: Ok, i managed to solve my problem. Here's what i did:
I created a Handler ...
Handler handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
          Bundle bundle = msg.getData();
          String input = bundle.getString("input");
          ImageButton display = (ImageButton)findViewById(R.id.imageButton1);
          if(input.equals("topay")){
              display.setBackground(getResources().getDrawable(R.drawable.display_2));
          }
          else if ...
         }
     };

... and then a new Runnable, which passes the input of changeDisplay to the Handler.
Runnable runnable = new Runnable() {
            public void run() {
                Message msg = handler.obtainMessage();
                Bundle bundle = new Bundle();
                String message = "";
                if(input.equals("topay")){
                    message = "topay";
                }
                else if ...
                bundle.putString("input", message);
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
      };
      Thread mythread = new Thread(runnable);
         mythread.start();

Now it's working! :-)
But thanks for your help, anyway!


text:
Q: How can I find match string in array javascript? How can I find a match in an array of strings using Javascript? For example:
var str = "https://exmaple.com/u/xxxx?xx=x";
var filter = ["/u","/p"];
if (!str.includes(filter)){
  return 1;
}

In the above code I want to search for var str if match this two values of array filter

A: This should work:

var str = "https://exmaple.com/u/xxxx?xx=x";
var filters = ["/u","/p"];

for (const filter of filters) {
  if (str.includes(filter)) {
    console.log('matching filter:', filter);
    break; // return 1; if needed
  }
}

A: In your array you need to find the element which includes "/u". filter will return an array and will contain only those element which includes u

var x = ["https://exmaple.com/u/xxxx?xx=x", "https://exmaple.com/p/xxxx?xx=x"];
let matched = x.filter(item => item.includes("/u"));

console.log(matched)

A: Try this:

var x = ["https://exmaple.com/u/xxxx?xx=x","https://exmaple.com/p/xxxx?xx=x"], i;

for (i = 0; i < x.length; i++) {
  if(x[i].includes('/u')) {
    document.write(x[i]);
  }
}

This loops through all the URLs and picks the one that has /u in it. Then it just prints that out.


text: Q: What are ways to manage scheduling in platforms? I am trying to figure out how scheduling works. For example, if we take a social media platform as an example where you can schedule a post – do you have to set up a cron job every time someone schedules one? Or, like an option for users to run something every X hour, days they want?


text:
Q: (de)compress base64 string PHP code:
$txt="John has cat and dog."; //plain text
$txt=base64_encode($txt); //base64 encode
$txt=gzdeflate($txt,9); //best compress
$txt=base64_encode($txt); //base64 encode
print_r($txt); //print it

Below code return:

C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA

I'm trying compress string in Java.
        // Encode a String into bytes
     String inputString = "John has cat and dog.";
     inputString=Base64.encode(inputString);

     byte[] input = inputString.getBytes("UTF-8");

     // Compress the bytes
     byte[] output = new byte[100];
     Deflater compresser = new Deflater();
    //compresser.setLevel(Deflater.BEST_COMPRESSION);
     compresser.setInput(input);
     compresser.finish();
     int compressedDataLength = compresser.deflate(output);
     String outputString = new String(output, 0, compressedDataLength,"UTF-8");
     outputString=Base64.encode(outputString);
     System.out.println(outputString);

But print wrong string: eD8L

Pz9PP3Q/Pz9NPzRyMz90dys/cnY/TjJKLgUAPygJTA==

must be:

C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA

How fix it? Thanks.

A: Use Deflater like this :
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compresser);
deflaterOutputStream.write(input);
deflaterOutputStream.close();
byte[] output = stream.toByteArray();

To decompress what is compressed:
    ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
    Inflater decompresser = new Inflater(true);
    InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream2, decompresser);
    inflaterOutputStream.write(output);
    inflaterOutputStream.close();
    byte[] output2 = stream2.toByteArray();

A:  String outputString = new String(output, 0, compressedDataLength,"UTF-8");

You are taking some compressed data and trying to interpret it as a UTF-8 string. This is unsafe, and is resulting in the encoded string containing a bunch of "?"s instead of the intended data.


text:
Q: Angular 2 service constructor with parameter I want to initialize a service with argument. Each component will have its own service instance.
@Injectable()
export class LoggingService {
  constructor( @Inject('group') @Optional() public group?: string) {
    this.group = group;
  }
}

It can be injected in to the component like this :
@Component({
    selector: 'test',
    templateUrl: 'test.component.html',
    providers: [
        LoggingService,
        { provide: 'group', useValue: 'Anythings goes here' }
    ]
})
export class TestComponent implements OnInit {
    constructor(private logger : LoggingService) {

    }
}

Above functionality is working fine for me.
I also want to inject LoggingService into TimeCalculationService. How I can provide 'group' from TimeCalculationService
@Injectable()
export class TimeCalculationService {

    constructor(private logger : LoggingService) {

    }
}

Is there anything like this
@Injectable({
    providers : [
        { provide: 'group', useValue: 'Anythings goes here' }
    ]
})


text:
Q: Azure SQL Sync is a resource drain on laptop despite frequency setting We have a SQL server running on a development laptop and would like to we'd like to deploy multiple laptops and use Azure Sync to distribute changes to each user.  Performance is too slow to have a remote SQL database with our current application -- that's a separate issue.  Speed isn't critical and I don't anticipate collisions between users.  I set the update to 12 hours and conflict resolution to member win.
Everything seems to be working as intended except the Microsoft SQL Data Sync 2.0 Windows service process is continuously consuming 2%-5% of the CPU and streaming data at about 80 kbps continuously.  I'm worried this will drain the batteries when the laptops are in the field.  Is there a better way to do this?
Here's the resource utilization from the Azure database.  I stopped the sync at some point to see if the frequency setting would automatically restart it (it does not).

A: You can write your own sync application based on your needs. This and this resources provides you a good guidance. Below you will see a sample application.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.SqlClient;

using Microsoft.Synchronization.Data.SqlServer;

using Microsoft.Synchronization.Data;

using Microsoft.Synchronization;

namespace SQLAzureDataSync

{

    class Program

    {

        public static string sqlazureConnectionString = "Server=[Your SQL Azure Server].database.windows.net;Database=AdventureWorksLTSQLAzure;User ID=[Your SQL Azure User Name]@[Your SQL Azure Server];Password=[Your SQL Azure Password];Trusted_Connection=False;Encrypt=True;";

        public static string sqllocalConnectionString = "Server=(local);Database=AdventureWorksLT2008;Trusted_Connection=True";

        public static readonly string scopeName = "alltablesyncgroup";

        static void Main(string[] args)

        {

            // Test if input arguments were supplied:

            if (args.Length == 0)

            {

                System.Console.WriteLine("Please enter an argument.");

                System.Console.WriteLine("Usage: SyncTest.exe -setup");

                System.Console.WriteLine("       SyncTest.exe -sync");

            }

            else if (args[0] == "-setup")

                Setup();

            else if (args[0] == "-sync")

                Sync();

        }

        public static void Setup()

        {

            try

            {

                SqlConnection sqlServerConn = new SqlConnection(sqllocalConnectionString);

                SqlConnection sqlAzureConn = new SqlConnection(sqlazureConnectionString);

                DbSyncScopeDescription myScope = new DbSyncScopeDescription(scopeName);

                DbSyncTableDescription Customer = SqlSyncDescriptionBuilder.GetDescriptionForTable("Customer", sqlServerConn);

                DbSyncTableDescription Product = SqlSyncDescriptionBuilder.GetDescriptionForTable("Product", sqlServerConn);

                // Add the tables from above to the scope

                myScope.Tables.Add(Customer);

                myScope.Tables.Add(Product);

                // Setup SQL Server for sync

                SqlSyncScopeProvisioning sqlServerProv = new SqlSyncScopeProvisioning(sqlServerConn, myScope);

                if (!sqlServerProv.ScopeExists(scopeName))

                {

                    // Apply the scope provisioning.

                    Console.WriteLine("Provisioning SQL Server for sync " + DateTime.Now);

                    sqlServerProv.Apply();

                    Console.WriteLine("Done Provisioning SQL Server for sync " + DateTime.Now);

                }

                else

                    Console.WriteLine("SQL Server Database server already provisioned for sync " + DateTime.Now);

                // Setup SQL Azure for sync

                SqlSyncScopeProvisioning sqlAzureProv = new SqlSyncScopeProvisioning(sqlAzureConn, myScope);

                if (!sqlAzureProv.ScopeExists(scopeName))

                {

                    // Apply the scope provisioning.

                    Console.WriteLine("Provisioning SQL Azure for sync " + DateTime.Now);

                    sqlAzureProv.Apply();

                    Console.WriteLine("Done Provisioning SQL Azure for sync " + DateTime.Now);

                }

                else

                    Console.WriteLine("SQL Azure Database server already provisioned for sync " + DateTime.Now);

                sqlAzureConn.Close();

                sqlServerConn.Close();

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex);

            }

        }

        public static void Sync()

        {

            try

            {

                SqlConnection sqlServerConn = new SqlConnection(sqllocalConnectionString);

                SqlConnection sqlAzureConn = new SqlConnection(sqlazureConnectionString);

                SyncOrchestrator orch = new SyncOrchestrator

                {

                    LocalProvider = new SqlSyncProvider(scopeName, sqlAzureConn),

                    RemoteProvider = new SqlSyncProvider(scopeName, sqlServerConn),

                    Direction = SyncDirectionOrder.UploadAndDownload

                };

                Console.WriteLine("ScopeName={0} ", scopeName.ToUpper());

                Console.WriteLine("Starting Sync " + DateTime.Now);

                ShowStatistics(orch.Synchronize());

                sqlAzureConn.Close();

                sqlServerConn.Close();

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex);

            }

        }

        public static void ShowStatistics(SyncOperationStatistics syncStats)

        {

            string message;

            message = "\tSync Start Time :" + syncStats.SyncStartTime.ToString();

            Console.WriteLine(message);

            message = "\tSync End Time   :" + syncStats.SyncEndTime.ToString();

            Console.WriteLine(message);

            message = "\tUpload Changes Applied :" + syncStats.UploadChangesApplied.ToString();

            Console.WriteLine(message);

            message = "\tUpload Changes Failed  :" + syncStats.UploadChangesFailed.ToString();

            Console.WriteLine(message);

            message = "\tUpload Changes Total   :" + syncStats.UploadChangesTotal.ToString();

            Console.WriteLine(message);

            message = "\tDownload Changes Applied :" + syncStats.DownloadChangesApplied.ToString();

            Console.WriteLine(message);

            message = "\tDownload Changes Failed  :" + syncStats.DownloadChangesFailed.ToString();

            Console.WriteLine(message);

            message = "\tDownload Changes Total   :" + syncStats.DownloadChangesTotal.ToString();

            Console.WriteLine(message);

        }

    }

}


text:
Q: Algorithm to organize table into many tables to have less cells? I'm not really trying to compress a database. This is more of a logical problem. Is there any algorithm that will take a data table with lots of columns and repeated data and find a way to organize it into many tables with ID's in such a way that in total there are as few cells as possible, and that this tables can be then joined with a query to replicate the original one.
I don't care about any particular database engine or language. I just want to see if there is a logical way of doing it. If you will post code, I like C# and SQL but you can use any.

A: I don't know of any automated algorithms but what you really need to do is heavily normalize your database.  This means looking at your actual functional dependencies and breaking this off wherever it makes sense.
The problem with trying to do this in a computer program is that it isn't always clear if your current set of stored data represents all possible problem cases.  You can't only look at numbers of values either.  It makes little sense to break off booleans into their own table because they have only two values, for example, and this is only the tip of the iceberg.
I think that at this point, nothing is going to beat good ol' patient, hand-crafted normalization.  This is something to do by hand.  Any possible computer algorithm will either make a total mess of things or make you define the relationships such that you might as well do it all yourself.


text:
Q: Android Studio HAXM update issues Android Studio 2.1.3
I can't seem to update HAXM. Every time I open the AVD, it gives me the following error message:

Virtual machine acceleration driver out-of-date

It then gives me a button to "Reinstall Haxm". Clicking that leads to an installation screen where I can choose the RAM allocation, where I hit Next and it starts installing. I then see it start installing and an extracting dialog flash up and disappear immediately:

It then finishes and says it was updated successfully, but then I hit Finish and it wants me to update again.
I've ensured Hyper-V isn't enabled and that virtualization is enabled in the BIOS. I've also tried installing it manually, and that looks like it all works successfully. And yet, no change in behavior by Android Studio. I have also seen this solution and tried it, with no success.
I can run the ARM EABI v7a emulators; just not the x86 ones. The ARM ones are so slow they're almost unusable, so I'd really like to find a way to fix this!
This machine does have VMWare vSphere installed on it, which is used on a regular basis. Could that be why this is happening?

A: First a warning.  If you have a really old version of HAXM installed, follow their instructions to uninstall the old version before installing the new one.

Before installing latest HAXM, the previous versions from 1.1.4 and
  below must be uninstalled using:
  sudo /System/Library/Extensions/intelhaxm.kext/Contents/Resources/uninstall.sh

The Intel HAXM installation instructions are confusing and outdated, but this part is correct:

once you have installed the package, the status will appear as
  'Installed', which is misleading as this is not the case. The SDK
  only copies the Intel HAXM executable on your machine, and it is up to
  you to install the executable.

I'm using Android Studio 3.0.1 on a Mac (10.11 El Capitan) and have not seem a "Reinstall HAXM" button like you described, but when an emulator is launched I do see this in the Event Log:

Emulator: WARNING: HAXM 6.0.5 is installed. Please install HAXM >= 6.2.1 to fix compatibility issues on Mac.

In SDK Manager -> SDK Tools it says the Intel X86 Emulator Accelerator (HAXM installer) is version 6.2.1.  I have updated it via the SDK Manager from previous versions several times in the past but didn't realize the update was not complete.
Solution on Windows: Find the IntelHAXM.exe file and run it.
It might be at C:\Program Files\Android\android-sdk\extras\Intel\Hardware_Accelerated_Execution_Manager\IntelHaxm.exe
Solution on Mac: Find the .dmg file, open it, and double-click on the .mpkg file inside to start the actual installation.  It will say the software is already installed.  Press OK -> Continue -> Install to "re-install" it (meaning actually to install the newer version).
In my case the .dmg file was found at Users/{username}/Library/Android/sdk/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM_6.2.1.dmg


text:
Q: MinMaxScaler is showing weird output on any of NumPy array I am having a numpy array that you can get by the folowing lines of code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import requests
from sklearn.preprocessing import MinMaxScaler
url = "https://query1.finance.yahoo.com/v7/finance/download/RELIANCE.BO?period1=1577110559&period2=1608732959&interval=1d&events=history&includeAdjustedClose=true"
r = requests.get(url)
open(stock+'.csv','wb').write(r.content) #________download the stock data and save it in a csv
r = pd.read_csv(r'RELIANCE.csv',date_parser='Date') #________read the dataset
r.head(1) #view the sample of dataset

I want to convert it to numbers between 0 and 1 with the MinMaxScaler,So for that I wrote the following code:
rc = r['Close'] #________select only the Close column
rc = np.array(rc) #________convert it into a np.array
def remove_nan(ac): #________the dataset has an NaN value, so to remove it I made this function
    array1 = np.array(ac)
    nan_array = np.isnan(array1)
    not_nan_array = ~ nan_array
    ac = array1[not_nan_array]
    return ac
rc = remove_nan(rc)
rc = rc.reshape(1, -1) #________reshaping the data for conversion, as asked in the fucntion
scale = MinMaxScaler() #________initialize the scaler
rc = scale.fit_transform(rc) #________transform the data
print('rc') #see the result

But on implementing the code, I got an np.array that contains only 0s:
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

A: MinMaxScaler expects the first dimension to index the individual samples. That is, the shape in your case must be (NUM_SAMPLES, 1). But you reshaped it to be (1, NUM_SAMPLES). Try the code with:
rc = rc.reshape(-1, 1)


text:
Q: Administrator password reset in AD (Windows 2k3 SBS) My friend forgot all Administrator password (BUILTIN\Administrator, Domain Administrator, Recovery Mode Password) for his w2ks SBS based domain. I've found article about resetting domain admin password.
I want to know: are there any implications on reset AD Administrator password? I know, that resseting user password result in loss of key to decrypt EFS encrypted data. Are any other consequences or implications?
I was thinking about backup procedure:

*

*Shutdown all domain controllers (1 - its SBS domain :)

*Take bit by bit image copy of DC disks (if something goes wrong), restore by copy image back to disk.

*Reset password

Do you recomend any other steps?

A: To know what the implications of changing a password are you first need to know exactly where the password is used. At the very least you need to check all services and scheduled tasks, as some of those may be running under one of the accounts you will be changing.

A: There's only 1 Administrator password because there's only 1 Administrator account. Knowing the Recovery Mode password wouldn't help as you still wouldn't know the Administrator password after performing an authoritative restore.


text:
Q: UICollectionView AutoLayout max width? I'm having a  dilemma maybe someone can  help. I followed this tutorial that showed me how to dynamically adjust the height of a collectionview to match the height of the text.
https://possiblemobile.com/2016/02/sizing-uicollectionviewcell-fit-multiline-uilabel/
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSizeMake(1, 1) }

cell.label.preferredMaxLayoutWidth = 50

But the issue I'm having is now the collection view wraps around the text instead of conforming to collectionView.bounds.width. So when i have text that is smaller than the collectionview width, the cell wraps around the text. I want the cell to match the height of the text but have a set width set to collectionview bounds. How could I achieve this?


text:
Q: Error php and mymql First time programming a simple database.
But I cant figure out how to solve this error:

Parse error: syntax error, unexpected '$row' (T_VARIABLE) in
  W:...\index.php on line 39

This is my script..
$result = mysqli_query($link,"SELECT * FROM studenten");

echo "

first name
last name
studentnummer

";

while($row = mysqli_fetch_array($result)) {

  id = $row[id]; //this is line 39
  echo "
";
  echo "" . $row['voornaam'] . "	";
  echo "" . $row['studentnummer'] . "	";
  echo " Edit";
  echo " Delete";
  echo "
";
}

echo "
";

can someone help me?

A: id = $row[id]; //this is line 39

Shouldn't that be
$id = $row['id']; //this is line 39

You're missing the $ from your id variable and quotes for your array key.

A: use
mysqli_fetch_assoc
because
mysqli_fetch_array

returns a indexed array
and on line 39
$id = $row['id'];


text:
Q: dumping static properties in linqpad public class Test
{
    public int a = 2;
    public static int b = 5;
    public struct C
    {
        public int d = 9;
        public static int e = 7;
    }
}

new Test().Dump();

The code above will dump the newly created object and list a as a property but won't list b or the nested static struct C or anything inside of it.
If I have alot of auto generated static properties how do I dump everything?

A: Reflection works
typeof(Test)
.GetFields(BindingFlags.Static | BindingFlags.Public)
.Select(f => new { name = f.Name, value = f.GetValue(null)})
.Dump();

A: The static instance variables are not part of the "new Test()" instance that you are creating. They are part of the static instance of of the Test class. You can read up on static classes and Static class members here.
You can see the static variables by using
(Test.b).Dump();
(Test.C.e).Dump();

Hope this helps.


text:
Q: How to write a query selecting reasonable trade-offs? In a table I have two columns obs and abd.  I am interested in finding
low values for both obs and abd, but a low value for abd is more
important than a low value for obs.  In the real world I have a
trade-off between low obs and low abd which is not easy to define
mathematically and would be difficult to explain, but the point is that
what I want to see from the query is some data that would make
reasonable trade-offs.  I would like to know several data pairs within a
range of obs values.  For example:
mysql> select obs, abd from flow where obs < 2000 order by abd,obs limit 10;

    +------+--------------+
    | obs  | abd          |
    +------+--------------+
    | 1372 | 0.0000004744 |
    | 1734 | 0.0000017704 |
    | 1010 | 0.0000017716 |
    | 1999 | 0.0000017716 |
    | 1637 | 0.0000036486 |
    |  383 | 0.0000066084 |
    |  745 | 0.0000066084 |
    | 1107 | 0.0000066084 |
    | 1469 | 0.0000066084 |
    | 1831 | 0.0000066084 |
    +------+--------------+

From the above results, it can be seen that there are several values
of obs that have the same abd value.  I am interested in only the one
with the lowest obs value for every abd value.  All the other
duplicate abd values should be discarded.  This is easily done by
using a group by clause:
mysql> select obs, abd from flow where obs < 2000 group by abd order by abd,obs limit 10;

    +------+--------------+
    | obs  | abd          |
    +------+--------------+
    | 1372 | 0.0000004744 |
    | 1734 | 0.0000017704 |
    | 1010 | 0.0000017716 |
    | 1637 | 0.0000036486 |
    |  383 | 0.0000066084 |
    |  648 | 0.0000066096 |
    | 1540 | 0.0000097586 |
    | 1928 | 0.0000109544 |
    | 1566 | 0.0000119724 |
    |  913 | 0.0000119736 |
    +------+--------------+

So far, so good.  Now the problem is that after having seen the first
entry where obs is 1372 and abd is 0.0000004744 I am not interested in
seeing the second entry where both obs and abd are higher.  I am
interested in seeing the third entry where obs is lower but abd is
higher because there is a trade-off between obs and abd.  Again, I am
not interested in seeing the fourth entry because it has values of obs
and abd that are both higher than what is already shown in the third
entry.  The fifth entry is one I am particularly interested in because
although the abd value is somewhat higher, the obs value is far lower.
As for the rest of the entries, I would like to not see them because
they have both higher obs and abd than what has already been seen.
In summary, I would like a query that would show me:
+------+--------------+
| obs  | abd          |
+------+--------------+
| 1372 | 0.0000004744 |
| 1010 | 0.0000017716 |
|  383 | 0.0000066084 |
+------+--------------+

plus another seven entries where obs continues to decrease and abd
continues to increase.  Is there a way to get the set of data pairs
with one query without resorting to a procedure?

A: To get the lowest obs by abd, here is how you go:
select min(obs), abd
from flow
where obs < 2000
group by abd
order by abd

But it seems to me like the trade-off rule is kind of ad-hoc. You should try to figured out the best rules you can think of and them lay them on the table so that we can achieve what you are trying to do.

A: You could just say you want a Pareto front
It's not going to be fast but try this:
SELECT a.obs
     , a.abd
FROM flow a
  LEFT JOIN flow b
    ON   ( b.obs <= a.obs AND b.abd <  a.abd )
      OR ( b.obs <  a.obs AND b.abd <= a.abd )
WHERE b.obs IS NULL
ORDER BY a.abd

Also:
SELECT a.obs
     , a.abd
FROM flow a
WHERE NOT EXISTS
  ( SELECT 1
    FROM flow b
    WHERE ( b.obs <= a.obs AND b.abd <  a.abd )
      OR ( b.obs <  a.obs AND b.abd <= a.abd )
  )
ORDER BY a.abd

And this:
SELECT a.obs
     , a.abd
FROM flow a
WHERE NOT EXISTS
  ( SELECT 1
    FROM flow b
    WHERE b.obs <= a.obs
      AND b.abd <  a.abd
  )
  AND NOT EXISTS
  ( SELECT 1
    FROM flow b
    WHERE b.obs < a.obs
      AND b.abd = a.abd
  )
ORDER BY a.abd

or this:
SELECT a.obs
     , a.abd
FROM flow a
WHERE NOT EXISTS
  ( SELECT 1
    FROM flow b
    WHERE b.obs <= a.obs
      AND b.abd <= a.abd
      AND (b.obs, b.abd) <> (a.obs, a.abd)
  )
ORDER BY a.abd

Check which of the 4 is faster. I would guess the 4th, if you have indexes on obs and abd. Or better, (as Unreason pointed), two indexes: one on (obs, abd) and one on abd.

UPDATE:
(small correction on 3rd query).


text:
Q: Как сравнить две текстовые переменные на php? Есть две переменные в одной из них значение поля "пароль" в другой "повторите пароль"... И как их можно сравнить на совпадение?
A: Сравнивать нужно либо:
strcmp(str1,str2)

либо
if( $str1 === $str2 ) ... //(это не опечатка, а 3 равно)

ибо
var_dump("044" == "44");
//выведет bool(true)

A: $string1 = "Hello";
$string2 = "World";
if ($string1 == $string2){ print "Переменные равны"; }
else { print "Переменные не равны"; }

A: да хоть так:
if ($password == $confirm)

или так:
http://ru2.php.net/manual/en/function.strcmp.php
A: strcmp(str1,str2)

Подробнее: http://php.su/functions/?strcmp


text:
Q: Django overridden choices failing validation I am overriding the choices option defined in the model, which is just a blank tuple.
Here's my models.py
#For assigning Ciena loopbacks
class Dia_Address(models.Model):

    order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE)
    equipment_hostname = models.CharField(max_length=500, null=True, verbose_name="Equipment Hostname", help_text="Hostname of the DIA device.")
    subnet = models.CharField(max_length=200, null=True, choices=DIA_SUBNETS, help_text="Subnet in which the DIA device requires an address.")

Contents of my forms.py, which overrides the model choices.
class Dia_AddressForm(ModelForm):
        class Meta:
                model = Dia_Address
                fields = ['equipment_hostname', 'subnet']

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            #order_id = str(order_reference.id)
            dcn_address_handler = AddressHandler
            subnet_id = "94806"

            DIA_SUBNETS = ()
            NEW_SUBNETS = dcn_address_handler.get_subnet_data(dcn_address_handler, subnet_id)

            DIA_SUBNETS = NEW_SUBNETS + DIA_SUBNETS

            self.fields['subnet'].choices = DIA_SUBNETS

Contents of my views.py
def addDia_Address(request, pk_test):
    order = Order.objects.get(id=pk_test)
    dia_address_form = Dia_AddressForm()
    if request.method == 'POST':
        dia_address_form = Dia_AddressForm(request.POST)
        dia_address_form.instance.order_reference = order
        if dia_address_form.is_valid():
            dia_address_form.save()
            return redirect('order', pk_test)

    context = {'dia_address_form':dia_address_form}
    return render(request, 'orchestration/dia_address_form.html', context)

The issue I have is this form is failing validation. I am able to select the appropriate option from the form dropdown menu. Is there any way I can disable this validation for just this one charfield?

A: The form validation is failing because of the empty choices tuple on your model. Regardless of what you set your choices to in the form, the validation will actually consider what the model dictates - in this case nothing! Remove the empty tuple and your form should validate.


text:
Q: Multiple row form - how to update specific row when input field names are same in column I have a report that, when it goes into input mode, creates a form where you have multiple rows of data, and on each row, there is a button and an input field.  The input field name is the same for each row (it's easier for the CGI program to process the input that way).  What I would also like, but having trouble doing, is if the user clicks on the button of that row, it should automatically update the input field in that same row.  How can javascript find the input field for the same row where the button is?
I was stuck coming out of the gates, so don't even know where to start.
Here's a simplified version of the HTML:

Frank
Burns
<input type="text" name="overtime" value="1000">
<input type="button" name="averageIN" value="Average In" onclick="return avgIN('1000,'2000');">

John
Doe
<input type="text" name="overtime" value="500">
<input type="button" name="averageIN" value="Average In" onclick="return avgIN('500,'2000');">

Here's the incomplete javascript:
function avgIN(orig, avg) {

    let text = "Request to Average In Overtime:\n\n"+
       "Current OT Total: "+orig+"\n"+
       "Averaged In Total: "+avg+"\n\n"+
       "Click OK to accept";
    if (confirm(text) == true) {
        // do something here to set the overtime input field on the same row to the value of "avg"
        }
    else {
        alert("Average In function canceled");
        }
    }

A: use event delegation...
and do something like that:

const myTable = document.querySelector('#my-table')

myTable.onclick = e =>
  {
  if (!e.target.matches('button[data-avg-in]')) return // exit

  let
    [orig, avg] = e.target.dataset.avgIn.split(',').map(Number)
  , txt =
`Request to Average In Overtime:

Current OT Total: ${orig}
Averaged In Total: ${avg}

Click OK to accept`
       ;
  if (confirm(txt))
    {
    e.target.closest('tr').querySelector('input[name="overtime[]"]').value = 'avg'
    }
  else
    {
    alert('Average In function canceled');
    }
  }

    Frank
    Burns
    <input type="text" name="overtime[]" value="1000">
    <button data-avg-in="1000,2000" >Average In</button>

    John
    Doe
    <input type="text" name="overtime[]" value="500">
    <button data-avg-in="500,2000" >Average In</button>


text:
Q: How would one replace a vector with a linked list c++ I have a code with a template class and a few data members, the code for vector looks like this
std::vector<Check> ck(100);

how would one go about making this into a linked list?

A: Like this:
std::list<Check> lck(ck.begin(), ck.end());

std::list is a doubly-linked list.
If you want a singly linked list, you can use std::forward_list:
std::forward_list<Check> lck(ck.begin(), ck.end());


text:
Q: How Do I Hide a Class from Other Subsystems I can make the class private and write it inside a public class. Then no other sub system will have access to it. How do I create it in such a way that it does not have to be written inside the same public class.

A: There is no concept of access specifiers at type level in C++. You can achieve keeping classes private in two ways:

*

*nested class inside another class, as you already mentioned

*no public constructor; if a class does not have an accessible constructor it cannot be instantiated.

A: You can put it in a separate .cpp file and give it no header file. This has the effect that you can't access it from other C++ code.
Here is an example:
worker.h
#pragma once
class Worker{
    //some class definition
};

worker.cpp
#include "worker.h"
class Hidden{
    //some class definition
};
//implementation of Worker class which uses Hidden class

some_other_file.cpp
//if you only include the header, the class Hidden does not exist
#include "worker.h"

How do I compile this?
g++ -c worker.cpp -o worker.o
g++ some_other_file.cpp  worker.o -o some_other_file


text:
Q: NHibernate multiple column mapping collection I have this situation:
I have several tables table_1, table_2... table_n, they belong to different data but they have some fields in common, record_id, form_id where id is the primary key. All these tables are represented by a single class Record (Id, Form, Attributes)
I have another table tbl_attachments which have attachment_id, record_id, form_id (record_id is not enough because the record_id can be repeated over table_X tables.
The problem I have is I want to have property Attachments in class Record, to get the records attachments from tbl_attachments if any.
Can you help me with the mapping on nhibernate to get this done?
I appreciate any help.
Edit: Forgot to say that a Record on table_X can have multiple attachments :)

A: you can achieve this using AnyMapping
abstract class RecordBase
{
    public virtual int Id { get; set; }

    public virtual int FormId { get; set; }
    public virtual ICollection<Attachment> Attachments { get; set; }
}

class RecordA : RecordBase
{ }

class Attachment
{
    public virtual int id { get; set; }

    public virtual RecordBase Record { get; set; }
}

class RecordAMap : ClassMap<RecordA>
{
    public RecordAMap()
    {
        HasMany(x => x.Attachments)
            .Where("Form_Id = 5");
    }
}

class AttachmentMap : ClassMap<Attachment>
{
    public AttachmentMap()
    {
        ReferencesAny(x => x.Record)
            .EntityIdentifierColumn("record_id")
            .EntityTypeColumn("form_id")
            .IdentityType<int>()
            .AddMetaValue<RecordA>("5");
    }
}

UPDATE: xml mappings
<bag where="form_id=5">
  <key column="record_id"/>
  <one-to-many class="Attachment1"/>
</bag>

<any name="Item" id-type="System.Int32" meta-type="System.Int32">
  <column name="form_id" />
  <column name="record_id" />
</any>


text:
Q: Find out which Music is currently playing [Android] Is there a way to find out which music is currently playing in the android Music player ? So I want to catch the title time and maybe the author of this music and show it with Textview. Is this possible ?

A: In concordance with the Android API here:
AudioManager should be what you are looking for
You can create an AudioManager and then call the isMusicActive to retrieve a boolean if it is playing.
You can then use the MediaPlayer API and call the getTrackInfo method which returns an Array of track-related information.
Edit:
Also, MediaPlayer has an isPlaying method which really makes AudioManager rather useless in this scenario.
[Update]
For future viewers of this question; when you create a MediaPlayer object and call the getTrackInfo method; it returns an array TrackInfo[]; the API for TrackInfo[] and it's methods can also be found here.


text:
Q: Apply changes across the page. Jquery I have these lines of Jquery code to manipulate the HTML
$('#Remarks li:gt(1)').wrapAll('
');
$("#btRowMargin").appendTo("#Remarks");
$('#Remarks ul:lt(2)').wrapAll('
');

I want  the above code to take effect across the page where ever #Remarks is present. For that I wrote
$.each($("#Remarks"), function() {
    $('#Remarks li:gt(1)').wrapAll('
');
    $("#btRowMargin").appendTo("#Remarks ");
    $('#Remarks ul:lt(2)').wrapAll('
');
});

But it doesn't seem to be working.
JSfiddle here
Originally HTML looks like this

Showing Information

Remarks:

Occupant NameListing Office

Occupancy/ShowListing Agent

Occupant TypeN/A

Occupant PhoneN/A

Other Phone NumberN/A

Phone To ShowN/A

LockBox LocationN/A

LockBox TypeN/A

Showing AccessN/A

After applying the jquery the HTML looks like :

Showing Information

Remarks:

Occupant NameListing Office

Occupancy/ShowListing Agent

Occupant TypeN/A

Occupant PhoneN/A

Other Phone NumberN/A

Phone To ShowN/A

LockBox LocationN/A

LockBox TypeN/A

Showing AccessN/A

But I want like this :

Showing Information

Remarks:

Occupant NameListing Office

Occupancy/ShowListing Agent

Occupant TypeN/A

Occupant PhoneN/A

Other Phone NumberN/A

Phone To ShowN/A

LockBox LocationN/A

LockBox TypeN/A

Showing AccessN/A

A: Change it to a class instead of an id ..
As id is supposed to be unique on a HTML page.
And then use the this context to apply those changes to only the current element in iteration
$(".Remarks").each(function () {
    $('li:gt(1)', this).wrapAll('
');
    $("#btRowMargin").appendTo(this);
    $('ul:lt(2)', this).wrapAll('
');
});

Similarly if element with id btRowMargin is in multiple places replace that with the class and use the this context for that as well.

A: Ok, here a liste of your misstake.
1: Id's must be unique, so when you have a the jQuery selector $('#Remarks'), it return only 1 element. No loop in the each. Changing you id with class will make a loop.
Side note: when looping through jquery element, you can use .each() like that : $(selector).each(function(){}). The way you are using it now is for arrays or objects.
2: Inside the .each(), you need to use this, else your are reselecting every element and have no "real controle" :
$('.Remarks').each(function(){
     var $this = $(this) //Caching the object for optimisation
     $this.find('li:gt(1)').wrapAll('
');
     //this line has to change, see point 3
     $this.find('ul:lt(2)').wrapAll('
');
})

3: This is a guess, but this line :
$("#btRowMargin").appendTo('#Remarks');

will probably have to change. You'll probly need to use some DOM traversal function but i can't tell you what since we don't have access to your DOM. but it will finish with .appendTo($this).
$this.siblings('.bottomRow.MarginFix').appendTo($this.find('li :eq(2)'));


text:
Q: ExtJS 5 - Specifying the position for a button's tooltip I'm using ExtJS 5 and am having some issues with tooltip positioning.  Specifically, when I have a button in the bottom right corner of the page, the tooltip covers the entire button itself.
I've tried using the anchorTo property but it doesn't seem to affect anything.  Trying to figure out how I can position the tooltip above the button instead of right on top of it.  I'm sure there's an easy solution - any help would be greatly appreciated.  Thanks.
See fiddle here: https://fiddle.sencha.com/#fiddle/j94

A: You can try by adding this attribute -
tooltipType: 'title'

here..
bbar: {
                items: ['->', {
                    text: 'My Button',
                    tooltip: 'tooltip positioned on top of button',
                    tooltipType: 'title'
                }]
            }

Here's what it says in the doc - http://docs.sencha.com/extjs/5.0/5.0.1-apidocs/#!/api/Ext.button.Button-cfg-tooltipType
qtip will work if you've more space below the button, in your fiddle there is no space available to draw your qtip over the button. You can check it by changing the layout to form -
layout: 'form'

or by adding padding as
padding: '20 20 20 20',

to your fit layout

A: I was able to get it to work by inspecting the inner workings for the tooltip mechanism and adding a 'mouseOffset' array:
tooltip: {
            text: 'tooltip positioned on top of button',
            mouseOffset: [0,-60]
         }