text:
Q: Insert data to maria db using php Having trouble getting the data to insert into Maria DB. While attempting this project I have used about every source I can think of and I'm resorting to posting a question online. Below is my code and the error it produces is "Fatal error: Call to undefined method mysqli::mysqli_prepare() in C:\xampp\htdocs\scripts\insert.php on line 12". Been mulling over this for a couple days and so far I have found nothing at all on youtube or stackoverflow.
<?php
//Set up credentials
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
$db = new PDO("mysql:host=localhost;dbname=test;","$username","$password");
// Create connection
$link = new mysqli($servername,$username,$password,$database) or                            die($mysqli->error);
$a = $_POST["a"];
$sql = "INSERT INTO ass (asdf) VALUES('$a')";
$result = $link->mysqli_prepare($sql);
$stmt  = $database->mysqli_prepare($sql);
$stmt->execute(array($_POST['a']));
$stmt->close();
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the difference between the Derived class override the base class's virtual function with or not with a "virtual" prefix? class A
{
    virtual void funcion()
    {
        //...
    }
}
class B:public A
{
     //1:virtual void function();
     //2:void function();
}

What's the differences between the 1 and 2 ? Or it is the same?

A: They're the same. A function declared virtual in the base class is virtual all through the inheritance chain.
I find it useful to add the virtual for clarity (more often than not, the classes aren't in the same file).

A: They're exactly the same. Once a function has been declared virtual in a base class, any class that inherits from it will also have that function declared virtual by default.


text:
Q: Can i define in the persistence.xml two database? I'm working on an application in Java EE. I must use two database ,how can I define two database in my persistence.xml?
Thank you in advance for your suggestions

A: Create another persistence-unit in your exisiting persistent.xml and give it a different name. Then create another entity manager depending on newly added persistent unit.


text:
Q: Automatically adding an SSL Certificate to a new AWS EC2 instance on creation I've written a script that creates an AWS EC2 instance via API and I need to automate the install of the wildcard certificates to be used by this new instance for HTTPS via Apache.
Previously, I had this solved by running LetsEncrypt/CertBot on the user-data script being passed via API, but because of the TLS-SNI-01 vulnerability issues, I decided to get a proper wildcard certificate to my domain and I'm updating the script accordingly.
As such, I'm wondering which strategy would best fit my purpose. Ultimately, I would just need to copy the cert files to a certain folder on the newly created instance, but I'm afraid I might be just reinventing the wheel -  does Amazon have any tool to facilitate this?
On the other hand, should I have to resort to simply copying files, what would be a good place to store them so that they could be obtained via  the user-data script? AWS S3?
I'm fairly new to server deployment/configuration, especially on AWS, so any help would be very welcome.

A: While I agree with ceejayoz that the best option is to use an ALB or ELB for SSL offloading, if you must terminate at the EC2 level, you can do a one time import of the certificate via the cli command 'aws acm import-certificate' documented at https://docs.aws.amazon.com/cli/latest/reference/acm/import-certificate.html then during the startup of EC2 instances download the cert via 'aws acm get-certificate' documented at
https://docs.aws.amazon.com/cli/latest/reference/acm/get-certificate.html


text:
Q: How to implement refresh tokens in angular? I am trying to implement refresh tokens in my angular app. I have written an http interceptor which tries to get a new access token whenever I get a 401 error. I don't know why but this doesn't work. I am still getting a 401 response.

A: You need to check if response code is 401 then request for refresh token and wait for response after receiving response process pending requests.
refresh token with http interceptor

A: Generate refreshToken before request if need it
export class HttpRequestInterceptor implements HttpInterceptor {
constructor(private router: Router, private service: AuthService) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {

    return from(this.tokenHandler(request)).pipe(mergeMap((req: HttpRequest<any>) => {
        return next.handle(req).pipe(catchError(err => {
            if ([401].indexOf(err.status) != -1) {
                // auto logout if 401 response returned from api
            }
            else {
                throw err;
            }

            return EMPTY;
        }));
    }));
}

private async tokenHandler(request: HttpRequest<any>): Promise<HttpRequest<any>> {
    if (request.url.indexOf("REFRESHTOKEN_URL") == -1) {
        await this.service.GenerateNewTokenIfNeed(); //Important this function would be async and put httpClient call to ToPromise() and await it. Save token somewhere and get from there to #token# place
    }
    else {
        //RefreshTokenRequest
    }

    const authReq = request.clone({
        setHeaders: {
            Authorization: "Bearer #token#"
        },
    });

    return authReq;
}


text:
Q: Браузер сохраняет, но не отправляет куки Здравствуйте.
Проблема возникает следующая: отправляю запрос на авторизацию через AJAX. Передаю данные пользователя. Сервер в ответ отправляет статус выполнения задачи в формате JSON и передает куку с ID сессии.
Сам запрос:
$.ajax({
        type:   "POST",
        xhrFields: { withCredentials: true },
        data:   "login="+Login+"&password="+Password+"&code="+FA2Code,
        url:        "/dashboard/api/auth",

        beforeSend: function() {
            $('#load-indicator').show();
        },

        success:        function(data) {
            $('#load-indicator').hide();
            if ( data.code == 201 ) {
                $("div#fa2").fadeIn(2000);
                return;
            }

    if ( data.code == 200 ) {
      window.location = "/dashboard/home/";
    }
        }
    })

Браузер куку сохранил. Я ее вижу в хранилище и данные переданы верно. НО! При редиректе на страницу /dashboard/home/ кука не отдается. Не могу понять в чем моя ошибка, подскажите?
Дополнительно:
Кука сессионная (если не установлен флаг "Запомнить меня"), иначе сохраняется на 24 часа.
Вид заголовков после успешной авторизации:

Кука сохранена и браузер ее видит:

A: Куку следует устанавливать для пути /, чтобы она была видна на всем сайте. У вас же (по скрину вижу) кука установлена только для /dashboard/api/.
P.S. Так же в обязательном порядке при отправке куки с сервера установите флаг HttpOnly в true, иначе любой скрипт может скопировать ее содержимое.


text:
Q: What model of video card does a GeForce GT 620 qualify as? I recently got a new computer with a GeForce GT 620 video card and I'm trying to determine which games it will run.  Specifically "Aliens: Colonial Marines".  There's a page with a drop down menu that lets you select your card here:
http://www.game-debate.com/games/index.php?g_id=514&game=Aliens:%20Colonial%20Marines
but I have no idea which option to select.  Any help would be appreciated.  Thanks in advance.

A: 430 = 530 = 620.  NVidia rebrands cards constantly.  Links such as this state as such, but just throw 'rebrand 620 530' into Google to see the unofficial acknowledgements.
At the low-end range with NVidia, you can expect just about every card you touch to be rebranded to/from.
Additionally, there are online tools to automate specific game concerns (including your own game).

A: I'm guessing you're confused by the fact that there's multiple models listed. . The first model listed is the standard model, and the second one has half the ram. The 'GT620 Core GF108' seems to use a different core than the GF119 based model listed on wikipedia, and the rest are models specific to various card makers - these can be differenciated by the amount of ram they have or other factors. To make things worse, the OEM model uses a different core.
The simplest way to sort this out is to grab a copy of GPU-Z - (apologies for the asus branded version - its what I have installed)- this should give you a definitive answer on what your video card is.

I've highlighted the necessary bits - its likely yours is one of the first 3, and the core type and ram amount (1gb is standard) should determine between them

A: Nvidia, 600 series, GeForce GT 620.
Edited to add: What I'm describing above is the exact answer to the question posted.

There's a page with a drop down menu that lets you select your card here:
  http://www.game-debate.com/games/index.php?g_id=514&game=Aliens:%20Colonial%20Marines
  but I have no idea which option to select. Any help would be appreciated. Thanks in advance.


text:
Q: How to solve this recurrence relation (related to discrete Fourier transform)? I am having trouble with the following recurrence relation:
$$c_{n+1} - c_{n-1} = 2\alpha \sin \frac{(2n-1)\pi}{N} c_n, \quad\forall n \in \mathbb{Z},$$
where $N$ is odd and the initial condition is $c_0 = c_1 = 1$.
Solving explicitly for $c_2$, $c_3$, ..., it is obvious that $c_k$ is a polynomial in $\alpha$ with a maximum degree of $k-1$. A closer analysis reveals that its degree reaches its maximum up to $k = \lfloor N/2 \rfloor+1$, after which the highest order terms start cancelling out one by one, recovering previous values in reverse order and leaving $c_N = c_{N+1} = 1$ again. Hence I know is that the solution is periodic with a period of $N$ and symmetric with respect to $n \mapsto 1-n$. Not much more, however. Rewriting the problem in the discrete Fourier image provides no help as—quite interestingly—the form of the equation stays exactly the same (only the value of $\alpha$ becomes reciprocal).
Can anyone help shed some light on finding a closed form solution of this kind of problem? It seems to be related quite tightly to the analysis of discrete Fourier transform eigensystem but that is beyond my current knowledge.


text:
Q: What is a good native image size to use for a full width (100% of browser) slider? I am building a website which includes a full width slider; 100% of browser window.
The CSS would be like this
.slider {
    width:100%;
}

... where the slider's parent is <body>, not some wrapper div.
My dilemma is that if I use an image of say 1600px width, and scale it to 100% using CSS then this will be fine for anyone who's maximised browser is (monitor width) is less than 1600px as the image will be scaled down not up ( leaving mobile/responsive size considerations out of the picture for the moment ) however someone using a maximised browser on a very large monitor will have that image scaled up not down and thus it will have a slightly degraded appearance.
I checked out a couple of sliders and they are using image widths of approx 2000px, but is there a width that would not need to be scaled up on a large percentage of monitors?
Please Note: I am not asking about CSS, a grid system, twitter Bootstrap, a responsive or adaptive site, a 960px width website or anything like that. Neither am I talking about a slider which is 100% of the website wrapper. I am simply asking about the pixel width of the image file used to create a slider which is scaled 100% of the browser width.

A: 1920px is the highest you want to go. That is considered the "high-end" for screen resolution sizes, and anything higher will make the browsers act up. As long as you set your slide width to 100% it will adjust to screen sizes of a higher resolution than 1920 without a problem. This will also solve the problem of taking up too much bandwidth and won't affect your load time (which is key for functionality of your site).

A: According to the global stats of screen resolutions of the year 2013, the display size of 1920x1080 is the fourth one among other top 10 popular current screen sizes. This one is also the last high definition display for the monitors so far.

A: I think its more of a persnal choice, depending upon your target audience. These stats might help you make an educated decision. http://www.w3schools.com/browsers/browsers_display.asp

A: Catching up with ever-large resolution display devices in yr2019, I would recommend size of 2400x1600px, optimized jpeg or next-gen image format with fallback support for jpeg.
<picture>
    <source srcset="sample_image.webp" type="image/webp">
    <source srcset="sample_image.jpg" type="image/jpg">
    <img src="sample_image.jpg" alt="">
</picture>

Sources:
https://flothemes.com/flothemes-image-sizes/
https://freshman.tech/image-optimisation/

You may even go many steps smarter and use CDN which supports image optimization & delivery of responsive images like (free tier available) https://cloudinary.com/ or https://www.cloudimage.io

A: 960px is the standard full width for any content area of a web page to HOPEFULLY not have any overflow in a full browser window.
http://960.gs/

A: As already noticed above, the standard width is 960 pixels.
But many sites are doing adaptive, so you can not say for sure.
My monitor, for example, has a resolution of 2560x1440. No one makes such a large site resolution.
If you want to make an adaptive site as a monitor and a mobile device, I can only advise to use the twitter bootstrap or something similar. You can also use grid system, for example: designinfluences.


text:
Q: Does your location or equip influence drawn cards? Apart from the base char modifiers, does your current location or equip (such as items granting special chars like Bizarre or Respectable) influence the opportunity cards you draw?

A: Opportunity cards are added to your deck based on whether you qualify for them with your current qualities; this includes the main qualities like Persuasive and Shadowy, but also story-related qualities like Admirer of Art, Touched by Fingerwork, and Scholar of the Correspondence. While you can freely affect your main qualities via equipment (and you will qualify for stories including the effects of equipment), you can't affect story qualities via equipment. You can also change your Bizarre, Dreaded, and Respectable via equipment, but there are no opportunity cards that are unlocked by those three qualities.
Owning certain items can make you qualify for particular cards. Equipping an item does not have any further effect. The earliest examples are pets: the Sulky Bat, the Deshrieked Mandrake, and the Reprehensible Lizard will each add a new card to your opportunity deck if you own one.
Most locations will alter the opportunity deck, too. Various places around Fallen London proper might add a few cards to the opportunity deck. The full list is on one of the wikis, but, for example, Watchmaker's Hill has the cards "A tavern dust-up", "Deal with a drunk old soldier", and "The Departed".
A handful of locations will completely replace your opportunity deck with entirely different cards, first discarding any face-up cards you have. The earliest example is the Pickpocket's Promenade in Spite, but there are many others: sailing on the Zee, Polythreme, each of the Places of Menace, etc. In those strange locations, none of the opportunity cards unlocked by your owned items will be in the opportunity deck.


text:
Q: Proof of Blumenthal's $0-1$ Law Statement: The $σ$-algebra $\mathcal{F}_{0+}$ is trivial in the sense that $\mathbb{P}[A] = 0$ or $1$ for every $A ∈ \mathcal{F}_{0+}$, where $\mathcal{F}_{0+}=\bigcap_{s>0}\mathcal{F}_s$
The proof I'm looking at starts like this:
Proof: Let $0 < t_1 < t_2 ··· < t_k$ and let $g : \mathbb{R}^k
 → \mathbb{R}$ be a bounded continuous function.
Also, fix $A ∈ \mathcal{F}_{0+}$. Then by a continuity argument,
$$\mathbb{E}[1_Ag(B_{t_1}
,...,B_{t_k}
)] = \lim_{
ε↓0}
\mathbb{E}[1_Ag(B_{t_1} −B_ε ,...,B_{t_k} −B_ε )]$$
What I don't understand is the continuity argument - we are really interchanging an integral with a limit without explicit enough conditions to use MCT, DCT etc.

A: Since $g$ is bounded, the Bounded Convergence Theorem allows the swapping of $\Bbb E$ and $\lim\limits_{\epsilon \downarrow 0}$.
$$\lim_{
ε↓0}
\mathbb{E}[1_Ag(B_{t_1} −B_ε ,...,B_{t_k} −B_ε )] = \Bbb{E}[\lim\limits_{\epsilon \downarrow 0} 1_A g(B_{t_1} - B_\epsilon, \dots, B_{t_k} - B_\epsilon)]$$
Pass the limit sign into the bracket as $g$ is continuous.
$$\Bbb{E}[\lim\limits_{\epsilon \downarrow 0} 1_A g(B_{t_1} - B_\epsilon, \dots, B_{t_k} - B_\epsilon)] = \Bbb{E}[1_A g(\lim\limits_{\epsilon \downarrow 0} (B_{t_1} - B_\epsilon, \dots, B_{t_k} - B_\epsilon))]$$
Since the brownian motion $B_t$ has continous trajectory, $B_\epsilon \to B_0 = 0$ as $\epsilon \downarrow 0$.
$$\Bbb{E}[1_A g(\lim\limits_{\epsilon \downarrow 0} (B_{t_1} - B_\epsilon, \dots, B_{t_k} - B_\epsilon))] = \mathbb{E}[1_Ag(B_{t_1},\dots,B_{t_k})]$$
Combine the equalities to end the proof.


text:
Q: Can't find columns in R I'm quite new to R.
I am in the process of retrofitting code from using "10, Total All Industries" to "1013 Manufacturing" as a filter in the below code.
The overall process is where I am taking data from a two .csv files, computing a year over year average, and then ranking based on an ID.
I'm Getting the error below.
   "Error: Can't find columns `JulyEmployment`, `AugustEmployment`,
   `SeptemberEmployment` in `.data`."

My primary question is whether I should be adjusted the c and l that proceed the word/phrase, keeps?
In the previous version, the variables were current and last with no m.
 currentm %>%
 filter(AreaType=="State" & Ownership=="Private" & Industry=="1013
 Manufacturing")->currentm
 lastm %>%
 filter(AreaType=="State" & Ownership=="Private" & Industry=="1013
 Manufacturing")->lastm

 keepsc <-
 c("St","Year","JulyEmployment","AugustEmployment","SeptemberEmployment")
 current<- current[keepsc]

 keepsl <- c("St","JulyEmployment","AugustEmployment","SeptemberEmployment")
 last<- last[keepsl]

  sample data

  structure(list(`Area
  Code` = c("1000", "2000", "4000", "5000",
  "6000", "8000"), St = c("1", "2", "4", "5", "6", "8"), Cnty = c(0,
  0, 0, 0, 0, 0), Own = c(5, 5, 5, 5, 5, 5), NAICS = c(1013, 1013,
  1013, 1013, 1013, 1013), Year = c(2018, 2018, 2018, 2018, 2018,
  2018), Qtr = c(3, 3, 3, 3, 3, 3), AreaType = c("State", "State",
  "State", "State", "State", "State"), StName = c("Alabama", "Alaska",
  "Arizona", "Arkansas", "California", "Colorado"), Area = c("Alabama --
  Statewide",
  "Alaska -- Statewide", "Arizona -- Statewide", "Arkansas -- Statewide",
  "California -- Statewide", "Colorado -- Statewide"), Ownership =
  c("Private",
  "Private", "Private", "Private", "Private", "Private"), Industry = c("1013
  Manufacturing",
  "1013 Manufacturing", "1013 Manufacturing", "1013 Manufacturing",
  "1013 Manufacturing", "1013 Manufacturing"), StatusCode = c(NA_character_,
  NA_character_, NA_character_, NA_character_, NA_character_, NA_character_
  ), EstablishmentCount = c(5582, 590, 5006, 2923, 43616, 5807),
  JulyEmployment = c(267000, 23611, 170553, 160677, 1330268,
  148444), AugustEmployment = c(267558, 19253, 170715, 160761,
  1334919, 148235), SeptemberEmployment = c(267609, 13392,
  170936, 161102, 1332249, 147649), TotalQuarterlyWages = c(3684759051,
  252044635, 3013769930, 1905042213, 29819289717, 2502830607
  ), AverageWeeklyWage = c(1060, 1034, 1358, 911, 1721, 1300
  ), EmploymentLocationQuotientRelativetoU.S. = c(1.57, 0.46,
  0.7, 1.52, 0.88, 0.64), TotalWageLocationQuotientRelativetoU.S. = c(1.58,
  0.52, 0.83, 1.46, 1.02, 0.63)), class = c("tbl_df", "tbl",
  "data.frame"), row.names = c(NA, -6L), .Names = c("Area\nCode",
  "St", "Cnty", "Own", "NAICS", "Year", "Qtr", "AreaType", "StName",
  "Area", "Ownership", "Industry", "StatusCode", "EstablishmentCount",
  "JulyEmployment", "AugustEmployment", "SeptemberEmployment",
  "TotalQuarterlyWages", "AverageWeeklyWage",
  "EmploymentLocationQuotientRelativetoU.S.",
  "TotalWageLocationQuotientRelativetoU.S."))


text:
Q: How to duplicate column rows and fill an added column with one item in list I have a dataframe with the following columns:
tester <- data.frame(id = c(123456789, 987654321))
tester$furniture <- list(c("chair"), c("bed", "bench", "barstool"))
tester$count <- c(1,3)

Based on the value in the count column, each row is repeated [count] number of times:
tester[rep(seq_len(dim(tester_2)[1]), tester$count), ]

The number of items in the furniture list will always be equal to the count value
I want to create a new column that contains one item from the list, in order from the first through the last list item. I would manually input what  I want in this new column as:
tester$new <- c("chair", "bench", "bed", "barstool")

but this doesn't work now because the dataframe resulting from the above code only technically has two rows.
Any advice would be greatly appreciated!

A: You could also use the function unchop from tidyr like this:
tester <- data.frame(id = c(123456789, 987654321))
tester$furniture <-  list(c("chair"), c("bed", "bench", "barstool"))
tester$count <- c(1,3)

library(tidyr)
unchop(tester, id:count)
#>          id furniture count
#> 1 123456789     chair     1
#> 2 987654321       bed     3
#> 3 987654321     bench     3
#> 4 987654321  barstool     3

Created on 2022-07-14 by the reprex package (v2.0.1)
And if you want to keep the furniture column you can use this:
tester <- data.frame(id = c(123456789, 987654321))
tester$furniture <-  list(c("chair"), c("bed", "bench", "barstool"))
tester$count <- c(1,3)

library(dplyr)
library(tidyr)
tester %>%
  mutate(new = furniture) %>%
  unchop(new)
#>          id            furniture count      new
#> 1 123456789                chair     1    chair
#> 2 987654321 bed, bench, barstool     3      bed
#> 3 987654321 bed, bench, barstool     3    bench
#> 4 987654321 bed, bench, barstool     3 barstool

Created on 2022-07-14 by the reprex package (v2.0.1)

A: You could achieve it with unnest() from tidyr:
tidyr::unnest(tester, furniture)

# # A tibble: 4 × 3
#          id furniture count
#       <dbl> <chr>     <dbl>
# 1 123456789 chair         1
# 2 987654321 bed           3
# 3 987654321 bench         3
# 4 987654321 barstool      3

If you want to preserve the list-column, then
library(tidyverse)

tester %>%
  mutate(new = furniture) %>%
  unnest(new)

# # A tibble: 4 × 4
#          id furniture count new
#       <dbl> <list>    <dbl> <chr>
# 1 123456789 <chr [1]>     1 chair
# 2 987654321 <chr [3]>     3 bed
# 3 987654321 <chr [3]>     3 bench
# 4 987654321 <chr [3]>     3 barstool


text:
Q: mongoDB updateOne not updating a record I am trying to update a record in mongoDB using updateOne, the un updating record is in array, and all fields are updating except one field which is country, I have tried to update it using MongoChef (a GUI of MongoDB for linux), but it doesn't work, also If I update one the Document using Edit in GUI then that record is ready to update after that.
I have tried with the following query in MongoChef
db.institutions.updateOne({
    "campus": { "$elemMatch": { "_id": ObjectId("578500ef87e4c326183e520e")} },
    "_id": ObjectId("57f25706762c06cb7d9422fc")
    },
    {
    "$set" : { "campus.$.country" : "SS1"
    }
});

Only country field is not updating If I update any other field it works fine.
The document structure is listed under
{
    "_id" : ObjectId("57f26824762c06cb7d982e37"),
    "campus" : [
        {
            "_id" : ObjectId("578500ee87e4c326183e5201"),
            "country" : "GB",
            "coreId" : NumberInt(1),
            "city" : "Norwich",
        }
    ]
}

Thanks in advance any help is appreciatiable

A: try this query
db.institutions.updateOne(
    {
      "campus._id": ObjectId("578500ef87e4c326183e520e"),
      "_id": ObjectId("57f25706762c06cb7d9422fc")
    },
    {
      "$set" : { "campus.$.country" : "SS1"}
    }
);

N.B: if use mongodb driver or mongoose then no need to use ObjectId("") just use "578500ef87e4c326183e520e"


text:
Q: Filter out the selected value in a slicer within a duplicate slicer ( power bi ) I'm struggling to solve this problem on my ticket. Suppose you have a slicer and has 3 fields. A, B and C and when you select B and C lets say; it will show up somewhere else tile/slicer and there you can filter out and these two slicers are the same slicers but duplicates. How can we achieve this ? thanks
What I found is: I can bring in a text box whatever selected but I can't do any actions on it. Also, I can show in a card whatever is selected and it looks like pill visual but you can't do any actions. If I could filter out by clicking the pills (buttons) there but card doesnt work this way.


text:
Q: Does Green's Theorem hold for polar coordinates? I was working on a proof of the formula for the area of a region $\mathcal R$ of the plane enclosed by a closed, simple, regular curve $\mathcal C$, where $\mathcal C$ is traced out by the function (in polar coordinates) $r = f(\theta)$. My concern was that the last application of Green's Theorem (towards the end of the proof) was invalid since I'm not using it over Cartesian coordinates. But I get the same answer as would come from the change of coordinates formula, so maybe it's right after all?
By Green's Theorem, we can evaluate the area inside of the curve as
\begin{align*}
A & = \int_{\mathcal C} x\, dy = \int_{\mathcal C} {f(\theta)\cos\theta (f(\theta)\cos\theta + f'(\theta)\sin\theta )\,d\theta} \\
& = \int_{\mathcal C} (f(\theta)^2\cos^2\theta + f(\theta) f'(\theta)\sin\theta\cos\theta )\,d\theta \\
& = \int_{\mathcal C} r^2\cos^2\theta\,d\theta + r\sin\theta\cos\theta \, dr \\
& = \int_{\mathcal C} Q\, d\theta + P \, dr,
\end{align*}
where $Q(r,\theta) = r^2\cos^2\theta$ and $P(r,\theta) = r\sin\theta\cos\theta$. Then
\begin{align*}
\frac{\partial Q}{\partial r} = 2r\cos^2\theta \hspace{0.5cm} \text{and} \hspace{0.5cm} \frac{\partial R}{\partial \theta} = -r\sin^2\theta + r\cos^2\theta.
\end{align*}
Finally, Green's Theorem tells us that
\begin{multline*}
A = \int_{\mathcal C} P\,dr + Q\,d\theta = \iint_{\mathcal R} \left(\frac{\partial Q}{\partial r} - \frac{\partial P}{\partial \theta}  \right) \,dr\,d\theta \\ = \iint_{\mathcal R} (r\cos^2\theta + r\sin^2\theta) \, dr \,d\theta = \iint_{\mathcal R} r \,dr\,d\theta.
\end{multline*}

A: You are justified. If you apply Stokes theorem with cylindrical polar coordinates to $$F(\mathbf{x})=P\mathbf{e}_r + \frac{Q}{r}\mathbf{e}_\theta$$ over a flat surface orientated in the positive $z$ direction you can prove this.

A: Your application of Green's Theorem is justified. You can think of $r$ and $\theta$ as the labels of axes in a different Cartesian plane. You have to be a little careful about $\mathcal C$ and $\mathcal R$ with this point of view, though—they need to be replaced by their preimages under the polar-to-Cartesian map.


text:
Q: Kops rotates x509 client certificate in kubeconfig I have a Kops cluster where I want to rotate the client certificate in the kubeconfig. I read and follow https://kops.sigs.k8s.io/operations/rotate-secrets/, but the certificate in the kubeconfig is still valid.
I check kops get keypair kubecfg and see the kubecfg keypair is not rotated. If I try kops create keypair kubecfg, I get this error
Error: adding keypair to "kubecfg" is not supported

Can anyone please help?
Thanks a lot in advance.


text:
Q: Calucalted colum in list on SharePoint 2010 Hope you're well;
Can I have help with the following SharePoint list, I would like the expiry alert date column to automatically update to 6 months post the contract expiry date column;
Is possible to do . How do I do it.

kind regards,
Anees

A: Good day!
Here is a source for some syntax around calculated columns!
Source: https://support.office.com/en-us/article/examples-of-common-formulas-in-sharepoint-lists-d81f5f21-2b4e-45ce-b170-bf7ebf6988b3
For your problem, you want to add 6 months contract expiry date. Here is the formula:
=DATE(YEAR([ContactExpiry Date]),MONTH([ContactExpiry Date])+6,DAY([ContactExpiry Date]))
Hope that helps!

A: You can create a Calculated column to store the expiry alert date, then add the following into formula setting:
=DATE(YEAR([Column1]),MONTH([Column1])+6,DAY([Column1]))

Note: You need to change Column1 to your contract expiry date column.


text:
Q: Conserved currents in Yang-Mills theory: gluon current vs. quark current In Yang-Mills theory there are two currents we can construct. There is the well-known quark current related to the global $SU(3)_C$ symmetry,
$$j{}^{\mu\,A}_\text{quark} = \overline{\psi}{}^i \gamma{}^\mu \left(\hat{t}{}^A\right){}^j{}_i \psi{}_j \, .
$$
On the other hand, we can also write down the expression
$$j{}^{\mu\,A}_\text{gluon} = f{}^{ABC} F{}^{\mu\nu}{}_B A{}_{\nu C} \, , $$
where $f{}_{AB}{}^C$ are the $SU(3)_C$ structure constants, and the Killing metric $\delta{}^{AB} = \tfrac12 \text{Tr}\left( \hat{t}{}^A \hat{t}{}^B \right)$ was used to raise two indices to obtain $f{}^{ABC} = \delta{}^{AI} \delta{}^{BJ} f{}_{IJ}{}^C$.
My question: what is the physical interpretation of this ''gluon current?'' Is it related to some symmetry as well?


text:
Q: Virtual function pitfalls and using base functions I have been coding up a reference thing for virtual functions since I always forget some piece of how they work. Here is what I have thus far:
#include <iostream>

using namespace std;

struct Base
{
    virtual void foo(int one = 1, int two = 2) = 0;

    virtual Base* bar() { cout << "Base bar\n"; return this; }

    virtual void baz(Base*) { cout << "Base baz\n"; }

    virtual void boo(Base*) { cout << "Base boo\n"; }

    // Error: templates may not be virtual
    //template <typename T> virtual T bad(T t) {return t}

    virtual ~Base() {}
};

struct Derived : public Base
{
    void foo(int one = 3, int two = 4)
        { cout << "one: " << one << " two: " << two << endl; }

    Derived* bar() { cout << "Derived bar\n"; return this; }

    void baz(Derived*) { cout << "Derived baz\n"; }

    using Base::boo;
    void boo(Derived*) { cout << "Derived boo\n"; }
};

void example1()
{
    Base*       pB = new Derived();
    Derived*    pD = new Derived();

    // Foo is called with default parameters based on pointer
    pB->foo();  // one: 1 two: 2
    pD->foo();  // one: 3 two: 4

    // Bar is overridden because return type can be implicitly converted
    pB->bar();  // Derived bar
    pD->bar();  // Derived bar

    // Baz is not overridden because parameters differ
    pB->baz(pB);    // Base baz
    pB->baz(pD);    // Base baz
    //pD->baz(pB);  // invalid conversion from Base* to Derived*
    pD->baz(pD);    // Derived baz

    // Boo using test
    pB->boo(pB);    // Base boo
    pB->boo(pD);    // Base boo
    pD->boo(pB);    // Base boo
    pD->boo(pD);    // Derived boo

    delete pB;
    delete pD;
}

struct Base2
{
    void foo(int one = 1, int two = 2) { foo_impl(one, two); }

    virtual ~Base2() {}

private:
    virtual void foo_impl(int one, int two) = 0;
};

struct Derived2 : public Base2
{
private:
    void foo_impl(int one, int two)
        { cout << "one: " << one << " two: " << two << endl; }
};

void example2()
{
    Base2*       pB = new Derived2();
    Derived2*    pD = new Derived2();

    // Now one set of default parameters exists
    pB->foo();  // one: 1 two: 2
    pD->foo();  // one: 1 two: 2

    delete pB;
    delete pD;
}

int main()
{
   example1();
   example2();
   return 0;
}

I am confused by the boo() function. It seems to me that pB->boo(pD) near the end of example1() should call the overridden version of the function, but it calls the base version. Why? If you could explain where all using is needed and how it works, that would be helpful, thanks.
Also, if you can think of other pitfalls to watch for when using virtual functions, feel free to post those too. Thanks.

A: The answer can be see by what happens with the baz function. As you note in your comment, the derived class's baz does not override the base class's version because the parameters differ. That's the same case for boo.
Your using Base::boo; statement doesn't in any way change boo not overriding. Instead it just brings the base version in scope for the derived class. Essentially, it's as if the derived class then has two overloads of the function.
However with pB->boo(pD); overloads aren't relevant since the pointer is typed in terms of Base. So the compiler only knows about the base class's boo function. And thus since nothing is overriding boo it ends up calling the base version.


text:
Q: Is there a way to have separate Excel files be imported into a Master document I have 60 files all with the same headers.  What I need is from 1 Master document a way to import data from all 60 files or 1 folder (where all 60 files are housed).  These are all Excel Spreadsheets - there is no code written, there are no buttons.  I just need guidance on how to go about doing this.  Could I use one of Excel's 'Get External Data' buttons?  Any suggestion would be appreciated.

A: This can be done with Power Query, a free download from Microsoft for Excel 2010 and Excel 2013 and built into Excel 2016 as Get & Transform.
You can import all files from a folder and combine them into one result table. When new files are added to the folder, you just need to refresh the query.
Most of this can be done by clicking buttons. There's just one line of code you need to enter manually. Ken Puls has a tutorial in his blog post here.
You don't need to go all the way with creating a function. To get started, you could simply paste this into the Advanced Editor of Power Query and adjust the file path:
let
    Source = Folder.Files("D:\Folder\Subfolder"),
    RemovedOtherColumns = Table.SelectColumns(Source,{"Content", "Name"}),
    GetExcelTables = Table.AddColumn(RemovedOtherColumns, "content", each Excel.Workbook([Content])),
    ExpandedExcelContent = Table.ExpandTableColumn(GetExcelTables, "content", {"Data"}, {"Data"})
in
    ExpandedExcelContent


text:
Q: Add summary/teaser to Full content in drupal 7 I want to have both Summary and Body in full content view in Drupal 7 but I can't understand how it is possible.

A: You can edit theme template files to do that. just edit node.tpl.php or page.tpl.php in your theme.
For example get summary in node.tpl.php:
// Load node summary view
$node_view = node_view($node,'summary');

// Get the summary
$summary = $node_view['body'][0]['#markup'];

Or use views to create the content you want.


text:
Q: ASUS Wireless Utility Mac Crashing I purchased an ASUS usb wireless device, installed the provided application for my mac pro 10.6.8. I plug in the key, it discovers networks, but when I'm trying to connect to any of them the application just crashes. I contacted ASUS with the problem, however I thought maybe someone here can help decode the apple error report so I can solve this issue and get back online.
Bellow is the error:
http://dumpz.org/200425/

A: I have the same problem.  The only solution I have is to the wps tab and connect via the PBS button, remembering to press the wps button on your router.  This only works if you can actually access the router and would be no use in coffee shops etc.
The device can access open networks - there is clearly a bug in trying to access secure networks.


text:
Q: Alerting Special Characters using jQuery/JavaScript How do i display a string with Special Characters like € in a Javascript/jQuery alert?
eg: I want to display a message box with "The Price is €10"
But when i use the below code:
alert("The Price is €10");

The Output shown in the message box is "The Price is €10", I want my output to be "The Price is €10".
Can some help me with this please? Thanks in advance.

A: The native alert method does not decode HTML encoded entities.
But browsers do while rendering HTML. One hack is to create a HTML element with the specific text as its innerHTML (so it does the character processing), then get back its text property and alerting it out.
function alertSpecial(msg) {
    msg = $('<span/>').html(msg).text();
    alert(msg);
}
alertSpecial('The Price is €10');

This will work for all &xxx characters that the browser can display, without needing to find out the character code for each special character you may want to use.

A: Check :
alert("The Price is \u20AC 10");

http://jsfiddle.net/Nseum/
Unicode Character 'EURO SIGN' (U+20AC)

A: Use this as the alert. Works fine for me.
alert(' The Price is \u20AC 10');

The description is here : http://leftlogic.com/projects/entity-lookup/


text:
Q: What would cause a ColdFusion server to return a 500 error when sending XML data? I am attempting to send XML data to a remote ColdFusion server using the code below:
[HttpPost]
        public ActionResult Index(Transmission t)
        {
            ViewBag.ErrorMessage = "";
            ViewBag.OtherMessage = "";
            ViewBag.ResponseHtml = "";

            //set request properties
            var request = (HttpWebRequest)WebRequest.Create("theUrl");
            request.ContentType = "application/xml";
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
            request.Timeout = 60000;

            //serialize the ViewModel
            XmlSerializer ser = new XmlSerializer(typeof(Transmission));
            XmlWriterSettings xws = new XmlWriterSettings();
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", "");
            xws.OmitXmlDeclaration = true; //omit the xml declaration line
            Stream stream = new MemoryStream();
            StringBuilder sb = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(sb, xws);
            ser.Serialize(writer, t, ns);

            using (StreamReader sr = new StreamReader(stream))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    sb.AppendLine(line);
                }
                byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
                request.ContentLength = postBytes.Length;

                try
                {
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(postBytes, 0, postBytes.Length);
                        requestStream.Close();
                    }
                    using (var response = (HttpWebResponse)request.GetResponse())
                    {
                        ViewBag.ResponseHtml = response.ToString();
                        return View("Error"); //TODO: change this to success when I get the 500 error fixed
                    }

                }
                catch (Exception ex)
                {
                    ViewBag.ErrorMessage = ex.Message;
                    request.Abort();
                    return View("Error");
                }
            }
        }

I have no access to the ColdFusion administrator, as it is a third-party vendor. According to a developer on their end, they are able to see transactions in their database logs, but I am getting a 500 error on my end. Is there something in the code I've posted that I should change, or would this be due to some setting on their side? The only information that I'm able to get is that it is a 500: Internal Server Error. When I put breakpoints in my code, the program throws an exception at this line: using (var response = (HttpWebResponse)request.GetResponse()).
Any help would be greatly appreciated. I would be happy to provide any further information necessary.

A: While the 500 error may be coming from the front end server, Coldfusion has a setting in CF Admin under 'settings' called 'Enable HTTP Status Codes.' When enabled, it will send a 500 along with a CF error to whatever the front end server is, and that server may be configured to obfuscate the details and not relay the CF content.
So while it is possible that it's not from CF, it is a common configuration for production services not to be sending CF stack traces. Their logs should still show the actual error, or you could ask them to disable this setting temporarily.


text:
Q: dependency property registered in generic base class I am trying to construct a validating textbox control using a generic abstract base class as follows and register Min and Max value properites:
public abstract class ValidatingTextBoxBase<T, C>
    : TextBox where T : Icomparable<T>

public static readonly DependencyProperty MinValueProperty =
    DependencyProperty.Register("MinValue", typeof(T), typeof(C),
    new FrameworkPropertyMetadata(DefaultMinValue));

    public T MinValue
    {
        get { return (T)GetValue(MinValueProperty); }
        set { SetValue(MinValueProperty, value); }
    }

Then I declare several text box controls:
public class IntegerTextBox : ValidatingTextBoxBase<int, IntegerTextBox>
{

public class DecimalTextBox : ValidatingTextBoxBase<decimal, DecimalTextBox>
    {

At runtime this works great however I get a lot of design time errors for
'MinValue' property was already registered by 'DecimalTextBox'

or it will be IntegerTextBox or one of the others depending on which view is open.
Any thoughts/help would be appreciated.


text:
Q: Homomorphisms from $\mathbb{Z}_{20}$ to $\mathbb{Z}_8$ I am trying to find all homomorphisms from $\mathbb{Z}_{20}$ to $\mathbb{Z}_8$. I understand how to do it - one completely determines any homomorphism, say $\phi$, by computing multiples of $\phi(1)$ or more generally $\phi(g)$ where $g$ generates $\mathbb{Z}_{20}$. Call $\phi_i$ the mapping taking $1$ to $i$ in $\mathbb{Z}_8$. I don't know how else to determine whether each $\phi_i$ is a homomorphism besides going through the painstaking process of calculating each $\phi_i(x+y)$ and comparing it to $\phi_i(x)+\phi_i(y)$.
Is there a way to easily rule out certain $\phi_i$s?
Any help would be greatly appreciated.

A: You are correct about looking at $\phi(1)$: since $1$ generates the domain (i.e. $\mathbb Z_{20}$), you can just look at where $1$ gets sent under the homomorphism. The only other thing you need to check is that the homomorphism preserves the relations. There is one relation in $\mathbb Z_{20}$, namely $20=0$. So $\phi$ better send $20$ to $0$ in $\mathbb Z_8$ (i.e. a multiple of $8$). For example, if you have a map which sends $1$ to $3$, then this would send $20$ to $60$, which would mean it's not a homomorphism (since $60$ is not $0$ in $\mathbb Z_8$).
The real reason behind this is the universal property of quotients. Basically you're looking at group homomorphisms $\mathbb Z\to\mathbb Z_8$ (which are completely determined by where $1$ is sent, and you can send $1$ anywhere) and then asking that the kernel contains the ideal $20\mathbb Z\subseteq\mathbb Z$ so that it factors as a map $\mathbb Z_{20}\to\mathbb Z_8$.

A: We need to find how many $i \in \mathbb{Z}_{8}$ satisfy the relation $20i=0$. There are only $8$ cases to consider:

*

*$i=0$ works ($0$ is divisible by $8$)

*$i=1$ doesn't work ($20$ is not divisible by $8$)

*$i=2$ works ($40$ is divisible by $8$)

*$i=3$ doesn't work ($60$ is not divisible by $8$)

*$i=4$ works ($80$ is divisible by $8$)

*$i=5$ doesn't work ($100$ is not divisible by $8$)

*$i=6$ works ($120$ is divisible by $8$)

*$i=7$ doesn't work ($140$ is not divisible by $8$)

So, there are exactly $4$ group homomorphisms from $\mathbb{Z}_{20}$ to $\mathbb{Z}_{8}$. Only even values of $i$ work, and the odd values can be ruled out.

A: By the First Homomorphism Theorem, the quotient $\Bbb Z_{20}/\operatorname{ker}\phi$ is isomorphic to the image of $\phi$. Since $|\operatorname{im}\phi|$ must be a common divisor of $20$ and $8$, the only possible options for the image of $\phi$ are:

*

*$\operatorname{im}\phi=\{0\}$;

*$\operatorname{im}\phi\cong \Bbb Z_2$;

*$\operatorname{im}\phi\cong \Bbb Z_4$.

Option 1 corresponds to the trivial homomorphism: all the elements of $\Bbb Z_{20}$ are sent to $0$.
Option 2 would correspond to $\operatorname{ker}\phi\cong \Bbb Z_{10}$: $\operatorname{ker}\phi$ is sent to $0$, and $1+\operatorname{ker}\phi$ (which has order $2$ in the quotient) is sent to $4$. You can check that this is indeed a homomorphism.
Option 3 would correspond to $\operatorname{ker}\phi\cong \Bbb Z_{5}$:

*

*$\operatorname{ker}\phi$ is sent to $0$;

*$1+\operatorname{ker}\phi$ (which has order $4$ in the quotient) is sent to either $2$ or $6$;

*$2+\operatorname{ker}\phi$ (which has order $2$ in the quotient) is sent to $4$;

*$3+\operatorname{ker}\phi$ (which has order $4$ in the quotient) is sent to either $6$ or $2$, according to where $1+\operatorname{ker}\phi$ was sent to before.

You can check that both these are indeed homomorphisms.


text:
Q: how to set up a dynamic terraform plan in bash? i want my terraform command plan to have some additional variable override according to if some variables are setted up prior in the bash script.
that is to say: the usual terraform plan i want to expand to terraform plan -var="foo=bar" if some variable is set up.
i tried up
terraform plan "${_TERRAFORM_DOCKER_IMAGE_OPTION:-}"
but this fails due to the terraform error:

Too many command line arguments. Configuration path expected.

is there a way to do a dynamic plan command for terraform?

the bash script is a slight modification of the bash SIMPLE boilerplate by alphabetum.
https://github.com/alphabetum/bash-boilerplate/blob/master/bash-simple
with a couple of conditionals to create the -var strings.
if [[ -n "${_DOCKER_IMAGE}" ]]
  then
    _TERRAFORM_DOCKER_IMAGE_OPTION="-var=\"app_image=${_DOCKER_IMAGE}\""
fi

after the variable strings are setted up, i try to use them in the terraform plan command as:
terraform plan "${_TERRAFORM_DOCKER_IMAGE_OPTION}" "${_TERRAFORM_APPLICATION_COUNT_OPTION}"
what i expect is the terraform plan to work without parameters when the vars are unset, or use the respective -var strings when they are setted up

A: Here you go.
Sample output when run... as you can see i just echo out the terraform plan command plus the variables..
export TF_VAR_region=eu-west-1
export TF_VAR_ami=ami-12434555666633
export TF_VAR_name=development

bash-3.2$ ./terraform.sh
terraform plan  -var="region=eu-west-1" -var="ami=ami-12434555666633" -var="name=development"

#! /bin/bash

VarsArray=()

if [[ -z "$TF_VAR_region"  ]]
then
      echo "\$TF_VAR_region is empty"
else
      ### add to terraform command array
      VarsArray+=('-var="region='$TF_VAR_region'"')

fi

if [[ -z "$TF_VAR_ami" ]]
then
      echo "\$TF_VAR_ami is empty"
else
  ### add to terraform command array
  VarsArray+=('-var="ami='$TF_VAR_ami'"')

fi

if [[  -z "$TF_VAR_name"  ]]
then
      echo "\$TF_VAR_name is empty"
else
  ### add to terraform command array
  VarsArray+=('-var="name='$TF_VAR_name'"')

fi
tfCommand=$(printf " %s " "${VarsArray[@]}")
tfCommand=${tfCommand:1}
echo "terraform plan " $tfCommand

If you commit a certain variable... or leave them out all together, you get your normal... terraform plan command
bash-3.2$ unset TF_VAR_ami
bash-3.2$ ./terraform.sh
$TF_VAR_ami is empty
terraform plan  -var="region=eu-west-1" -var="name=development"

unset TF_VAR_region
unset TF_VAR_ami
unset TF_VAR_name
./terraform.sh
$TF_VAR_region is empty
$TF_VAR_ami is empty
$TF_VAR_name is empty
terraform plan


text:
Q: Arduino battery power stay on for button - Not quite working I have been trying to get a circuit to work that would power an Arduino from a set of 4 18650 batteries. It needs to turn on with a button press, then stay on for 30 seconds, then completely power down.
My plan was to have the pushbutton connect the ground wire of the voltage regulator so it would be a physical switch to turn on power. Then in the logic of the Arduino turn on digital pin 5 right away and keeping it on until its ready to power down. That digital pin would control a mosfet which keep the power on.
I have the following components in my current almost, but not working scheme.

*

*Arduino Nano

*MP1584EN DC-DC 3A power Step-Down Amazon link

*N-Channel MOSFET Digi-Key link

*10k OHM Resistor

*Pushbutton Image Link

*330 OHM Resistor

*4 18650 Batteries producing about 14v

In the following diagram the +14v and GND on the left side represent the battery connections.

I am using a 10k ohm resistor connecting the gate to the battery ground in order to pull it low so it does not float. I am using a 330ohm resistor between the gate and the digital pin on the Arduino for protection.
Everything seems fine until I plug in the Arduino to breadboard. That is I use my voltage tester to check that the Arduino VIN and GND pins do measure at 5v. Also if I press the button then connect a wire to the mosfet gate pin to my 5v rail the power does stay on. So it seams if I plug in the Arduino and it sets the digital pin high (5v) on the mosfet it would work.
Instead of working like I had hoped. There is a little smoke from the Arduino and its trashed. Another weird thing is if I have my voltage meter measuring the outputs of the voltage regulator, the output suddenly reads a much higher voltage. I was not sure where that change comes from, maybe its my voltage meter interacting with the voltage regulator in the Arduino. I found if I don't connect the mosfet drain to the battery ground the Arduino seems to work correctly, does not smoke and get fried, and I still get the weird high voltage reading. When the drain is connected the Arduino is instantly fried.
Any help would be greatly appreciated.

A: Your DC-DC converter is not isolated, and it places the whole supply at its output when its negative input terminal is floating.
This means that the Arduino has the full input supply from its Vdd and Gnd terminals to the 330ohm resistor on its output and from there it should turn on the mosfet.
If you have Gnd otherwise connected to the Arduino, then you have 19V across it.
You should use a high-side switch, or a converter with an enable/shutdown pin instead.


text:
Q: Knockout JS: object always returns undefined, even when should have values I'm new to Knockout and am still trying to understand how it works. I have this function that should be returning data from an ajax call but when I try to get the values the object is saying it is undefined.
My model where the data is undefined:
    function ViewModel() {
    var self = this;
    self.Organization = ko.observable();
    self.App = ko.observableArray([]);
    self.Deployed = ko.observableArray([]);
    self.EngagementSolutions = ko.observableArray([]);
    self.MS = ko.observable();

   self.ActiveEngagements = ko.computed(function () {
        var ActiveEngagements = 0;
        ko.utils.arrayForEach(self.EngagementSolutions(), function (item) {
            if (item.IsActive) {
                ActiveEngagements++;
            }
        });
        return ActiveEngagements;
    });
    self.TicketCount = ko.computed(function () {
        console.log(self.Organization.UniqueICount);
        var uniqueOpenICount = (self.Organization.UniqueOpenICount === "undefined" ? self.Organization.UniqueOpenICount : 0);
        var uniqueICount = (self.Organization.UniqueICount === "undefined" ? self.Organization.UniqueICount : 0);
        console.log(uniqueOpenICount + " / " + uniqueICount);
        return uniqueOpenICount + " / " + uniqueICount;
    });

My function where the values are populating the object:
    function SucessFunction(data) {
    console.log(data.Organizations[0].UniqueICount);

        var newOrganization = new OrganizationObject();
        newOrganization.UniqueICount = data.Organizations[0].UniqueICount;
        newOrganization.UniqueOpenICount = data.Organizations[0].UniqueOpenICount;

        console.log(newOrganization);
        viewModel.Organization = newOrganization;
        console.log(viewModel.Organization);
    }
});

Thank you in advance for the help

A: You're using observable incorrectly. KO's observables are functions.
You set their value by calling them with a new value as an argument:
viewModel.Organization(newOrganization);

not
viewModel.Organization = newOrganization; // Not this

You get their value by calling them without an argument:
console.log(viewModel.Organization());
// -------------------------------^^

not
console.log(viewModel.Organization);      // Not this

Primarily, the way you're misusing it will cause the computed not to work correctly and the view not to update.
There are a few other problems as well:

*

*When you start using the observable correctly, you'll also need to update the computed's code not only to get its value correctly, but to allow for the fact that it starts off being undefined, which means you can't read those subordinate properties from it.

*You're comparing property values with "undefined". My guess is you probably meant to compare their type with "undefined" or compare their value to undefined. But comparing their value with "undefined" will give you false unless, of course, they actually contain the string "undefined".

*There are also some curly brace and parentheses mismatches, at least in the code in the question.

Here's a rough update, but it's not meant to do all the work, just to point you in the right direction:
function ViewModel() {
    var self = this;
    self.Organization = ko.observable();

    self.TicketCount = ko.computed(function() {
        // *** Reading the value, using a local variable to remember it during this call,
        // branching if we don't have one y et
        var organization = self.Organization();
        if (!organization) {
            // We don't have one yet
            return "-/-";
        }
        console.log(organization.UniqueICount);
        // *** Handling undefined by values via ||
        var uniqueOpenICount = organization.UniqueOpenICount || 0;
        var uniqueICount = organization.UniqueICount || 0;
        console.log(uniqueOpenICount + " / " + uniqueICount); // *** Beware that 0/0 is NaN, and n/0 is Infinity, so
        return uniqueOpenICount + " / " + uniqueICount;       // *** ...you probably want more logic here
    });
}

function SucessFunction(data) {
    console.log(data.Organizations[0].UniqueICount);

    var newOrganization = new OrganizationObject();
    newOrganization.UniqueICount = data.Organizations[0].UniqueICount;
    newOrganization.UniqueOpenICount = data.Organizations[0].UniqueOpenICount;

    console.log(newOrganization);
    // *** Note setting it via call
    viewModel.Organization(newOrganization);
    // *** Note getting it via call
    console.log(viewModel.Organization());
}


text:
Q: android - Dialog not working I'm creating a custom dialog having this layout (title with image, text, 2 buttons):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal"
    android:background="@color/white">
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="30dip"
        android:paddingTop="10dip">
        <ImageView
            android:id="@+id/dialog_title_image"
            android:layout_alignParentLeft="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/info"/>
        <TextView
            android:id="@+id/dialog_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_centerInParent="true"
            android:text="Title"
            android:layout_toRightOf="@id/dialog_title_image"
            android:textColor="@color/black"
            android:textSize="30sp"/>

    </RelativeLayout>
    <TextView
            android:layout_width="fill_parent"
            android:layout_height="2dip"
            android:background="@color/header_grep"
            android:layout_marginTop="5dip"/>
    <TextView
        android:id="@+id/dialog_msg"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/dark_gray"
        android:layout_marginTop="10dip"
        android:layout_marginLeft="10dip"/>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dip"
        android:gravity="bottom|center_horizontal"
        android:paddingBottom="5dip">
        <Button
            android:id="@+id/positive_button"
            android:layout_alignParentLeft="true"
            android:layout_width="100dip"
            android:layout_height="wrap_content"
            style="@style/Gradient"
            android:text="Si"/>
        <Button
            android:id="@+id/negative_button"
            android:layout_width="100dip"
            style="@style/Gradient"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/positive_button"
            android:text="No"/>
    </RelativeLayout>

 </LinearLayout>

This is CustomDialog.java
public class CustomDialog extends Dialog {

    Context context;

    public CustomDialog(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        this.context = context;
    }

    public CustomDialog(Context context, int theme) {
        super(context, theme);
        // TODO Auto-generated constructor stub
        this.context = context;
    }

    public CustomDialog(Context context, boolean cancelable,
            OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        // TODO Auto-generated constructor stub
    }

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

}

and this is the method i've implemented to show it:
      private void showDialog(String msg, String title)

    {
        final Dialog dialog = new CustomDialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.custom_dialog);

    TextView title_dialog = (TextView) dialog.findViewById (R.id.dialog_title);
    title_dialog.setText(title);

    TextView text = (TextView) dialog.findViewById(R.id.dialog_msg);
    text.setText(msg);

    Button positiveButton = (Button) dialog.findViewById(R.id.positive_button);
    Button negativeButton = (Button) dialog.findViewById(R.id.negative_button);

    positiveButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {

            finish();
        }

    });

    negativeButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {

            dialog.dismiss();
        }

    });

    dialog.show();

}

when i launch the app and the dialog is shown, the title and the text are that ones defined in the xml file (so 'Title' and nothing for the body of the dialog) and if i click on the buttons nothing happens.
Can anyone help me? Thank you in advance.

A: You must pass Application context on Dialog. If you passed this as context and you called customdialog from button onclick() event then it's refer this as button onclicklistner() object and that is wrong. so you must passed your activity or your application context.
final Dialog dialog = new CustomDialog(yourappliactioncontext);

A: Try it out:
final Dialog dialog = new Dialog(YourActivity.this);
instead of
final Dialog dialog = new Dialog(context);
If you are going to reuse this code, as a reusable component or as a mechanism to create dialogs at multiple places, create a base activity class and have this method in there, and use it in sub-classed activities as needed.


text:
Q: jqgrid - serializeGridData with additional postData params I am trying to use serializeGridData to convert my postdata to JSON using this answer from Oleg. Here is my code.
jQuery(function() {
   $('#grid').jqGrid({
       ........
       ........
       postData: {
        param1: function() { return $("param1").val(); },
        param2: function() { return $("param2").val(); },
        searchText: function() { return $("searchText").val(); },
        totalRecords: function() { return msgGrid.getGridParam("records"); }
    },
    serializeGridData: function (postData) {
           return JSON.stringify(postData);
    },
    ajaxGridOptions : {
        contentType: 'application/json; charset=utf-8'
    }
    });
});

postData coming to serializeGridData does not replace the custom params defined in postData {} with actual values. I have debugged in firebug and this is how the data is coming to serializeGridData method. So eventually JSON.stringify is not converting param1, param2.. values in the request data. How can fix it to send the actual values for custom params? Thanks in advance..
_search     false
nd      1349195468864
page        1
rows        25
sidx        "sortcol_name"
sord        "desc"
param1      function()        // expect to have actual param1 value
param2      function()
searchText          function()
totalRecords    function()

A: When JSON.stringify encounters a function, it censors it to null. Try setting the data without functions, like this:
postData: {
    param1: $("param1").val(),
    // etc.
}

A: I think you should enumerate all properties of postData inside of serializeGridData callback and use $.isFunction inside of it to verify whether some property is a method. In case of method you should call the method and save the result in the property with the same name. Look at the implementation of serializeRowData from the answer or in the code of the answer.


text:
Q: Change a PHP array into separate strings I have an array returned from sql and I need to get them into separate strings to use on the page. It is out of a single row in the database and lists all the folders a user has.
example in database john has a red folder, green folder, blue folder.
I run the query and use fetchAll to return john's folders. I have it in an array. I can echo the array and it outputs redfoldergreenfolderbluefolder
How can I take the array and split it into separate strings?
PHP code
  $query = "SELECT album_name FROM albums WHERE username = :username";
    $query_params = array(
    ':username' => $email
    );

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {
        echo 'Database Error, please try again.';
    }

    $rows = $stmt->fetchAll();

    foreach ($rows as $row) {
    $post             = array();
    $post["album_name"] = $row["album_name"];
    echo $post["album_name"];  // This just lists all albums together no spaces or commas

    }

    $text = implode(",", $post);
    echo $text;  // This just outputs the last item (bluefolder)

A: The below needs correction :
foreach ($rows as $row) {
    $post             = array();
    $post["album_name"] = $row["album_name"];
    echo $post["album_name"];  // This just lists all albums together no spaces or commas

}

$text = implode(",", $post);
echo $text;  // This just outputs the last item (bluefolder)

Change the above to :
$post = array();
foreach( $rows as $row )
{
//  $post = array(); // This line should not be here . It should be outside and above foreach
//  The below echo is for test purpose . Comment it if you don't need it
    echo $row["album_name"] ,' ';
//  $post["album_name"] = $row["album_name"]; // This keeps assigning $row["album_name"] to same index "album_name" of $post . Eventually you will have only one value in $post
    $post[] = $row["album_name"];
}

// $text = implode(",", $post); // With coma's as separator
$text = implode(" ", $post); // With blank's as separator
echo 'John has ' , $text;

A: try print_r($post); on your last line.

A: The reason why it only show the last folder is because you do "$post = array()" at the beginning of your loop. It reset the array everytime... just take it out of the loop and put it above the foreach.
1: http://php.net/manual/en/function.imThe reason why it only show the last folder is because you do "$post = array()" at the beginning of your loop. It reset the array everytime... just take it out of the loop and put it above the foreach.
EDIT:
Try it this way :
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$post = array();

foreach ($rows as $key => $folder) {
    array_push($post, $folder)
}

$text = implode(",", $post);

A: please use print_r($text) in side the for each and then you will get all the arry with commos
and remove $post = arry from there and put above of foreach.
i am trying to help you,may this help
thanks
anand

A: Try this:
$post  = array();
foreach ($rows as $row) {

array_push($post, 'album_name', $row["album_name"]);

}

$text = implode(",", $post);
echo $text;

No assoc ver:
$post  = array();
foreach ($rows as $row) {

$post[] = $row["album_name"];

}

$text = implode(",", $post);
echo $text;


text:
Q: SerialPort DataReceived Event Makes Communication Slower I'm working on a serial port communication application for Windows on .NET 3.5. For legacy purposes, I cannot use any other .NET version.
I need to send some data to some device, wait to see if any data comes within a specific time period. If data comes, I need to process it. If no data comes within the given period, nothing needs to handle.
My first approach to wait for data is timer based:
[Code 1]
using (System.Timers.Timer timer = new System.Timers.Timer(nDefaultWait))
{
    bool timeout = false;
    timer.AutoReset = false;
    timer.Elapsed += (s, e) => { timeout = true; };
    int nTotalRead = 0;

    do
    {
        timeout = false;
        timer.Start();
        while (!timeout && sp.BytesToRead + nTotalRead < nExpectedBytes)
            ;
        timer.Stop();

        if (sp.BytesToRead == 0)
        {
            // No data received for a time period, consider timed out
            break;
        }

        byte[] inBuffer = ReadSerialPort(sp);
        receivedBytes.AddRange(inBuffer);
        nTotalRead += inBuffer.Length;

    } while (receivedBytes.Count < nExpectedBytes);

As it is very CPU bound, it slows down slow computers. I'm trying to modify the code using DataReceived event handler:
[Code 2]
nTotalRead = 0;
nExpectedBytes = nExpBytes;

do
{
    allDataRead.Reset(); // allDataRead is a ManualResetEvent which is Set from DateReceived event
    allDataRead.WaitOne(nDefaultWait);

    if (sp.BytesToRead == 0)
    {
        // No data received for a time period, consider timed out
        break;
    }

    byte[] inBuffer = ReadSerialPort(sp);
    receivedBytes.AddRange(inBuffer);
    nTotalRead += inBuffer.Length;

} while (receivedBytes.Count < nExpBytes);

And the DataReceived event looks like:
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    if (serialPort.BytesToRead + nTotalRead >= nExpectedBytes)
    {
        allDataRead.Set();
    }
}

The same code is used for 2 different devices (say Type A and Type B) to communicate. Both kind of devices follow same protocol. But they have different Windows drivers.
Performance is a mandatory requirement. A set of commands needs to complete execution as quickly as possible. Both Code 1 and Code 2 performs almost identically for Type A devices. But, To my surprise for Type B devices, Code 2 is 100x-150x times slower (50 ms vs 7500 ms). Not only that, for Type B devices, the performance of Code 2 to isn't consistent. Sometimes it completes in 3000 ms (where Code 1 completes in 50 ms consistently), some other time it completes in 10000 ms or anywhere in between.
What could possibly be the reason behind this?
EDIT
Here is the code for ReadSerialPort:
private byte[] ReadSerialPort(SerialPort sp)
{
    byte[] inBuffer = new byte[sp.BytesToRead];
    sp.Read(inBuffer, 0, inBuffer.Length);
    return inBuffer;
}


text:
Q: laravel 5.7 many to many with custome table name Goods Model
class goods extends Model
{
  protected $table = "goods";
  public function sales(){
    return $this->belongsToMany('App\sales', 'sales_details', 'goods', 'sales');
  }
}

Sales Model
class sales extends Model
{
  protected $table = "sales";
  public function goods(){
    return $this->belongsToMany('App\goods','sales_details','sales','goods');
  }
}

i also make this model but i don't know if i ever need it or not
class salesDetail extends Model
    {
      protected $table = "sales_details";
    }

my controller
public function test()
    {
      $goods = goods::all();
      return view('test',compact('goods'));
    }

my test.blade.php
@foreach($goods as $data)

{{ $data->name }} - {{ $data->company->kind }} {{ $data->company->name }}

{{ $goods->sales }}

  @endforeach

i connect goods table with sales table with many to many without following laravel naming.
This is my table contents
goods
-id
-name

sales
-id
-date

sales_details
-goods
-sales
-qty
-price

and i couldn't make it work. i just wanted to show the result like this
sales -id
sales - date
goods - name
sales_details - qty
sales_details - price

this should be the result

A: In your @foreach loop you're trying to access sales on the collection of goods rather than the instance in the loop. Also, because the sales() relationship is a belongsToMany (many-to-many) you're going to get a collection and not a single instance so you're going to need to loop through them as well e.g.
@foreach($goods as $data)

        {{ $data->name }} - {{ $data->company->kind }} {{ $data->company->name }}

        @foreach($data->sales as $sale)

{{ $sale->date }} - {{ $sale->pivot->qty }}

        @endforeach

@endforeach

To access data from your pivot table you will first need to tell Laravel to include that information in the relationship:
public function sales()
{
    return $this->belongsToMany('App\sales', 'sales_details', 'goods', 'sales')
        ->withPivot('qty', 'price');
}

You should also add the withPivot method to the good() relationship in the sales class as well.
Then you'll be able access the information from the pivot property. This is happening in the example above with {{ $sale->pivot->qty }}.
Many to many docs (scroll down to Retrieving Intermediate Table Columns )


text:
Q: ios swift show/hide an element in textView cell and clear its space I have a dynamic tableView. TableViewCell prototype looks like this:
"------------------"
 label
 segmentedControl  (yes | no)
 textView
"------------------"
My question is how can i hide and then show textView that tableView can autoresize its cell height
Here is my tableViewCell class:
class QuestionTableViewCell: UITableViewCell {

@IBOutlet weak var question: UILabel!
@IBOutlet weak var answer: UISegmentedControl!
@IBOutlet weak var comment: UITextView!

And here is my tableView cellForRowAtIndex:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->   UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("QuestionCell", forIndexPath: indexPath) as! QuestionTableViewCell

    cell.question.text = "\(indexPath.row + 1). " + questions[indexPath.row]
    // check answer and set it to segmentedControl and set color
    if questionsAnswers[indexPath.row] == "YES" {
        cell.answer.selectedSegmentIndex = 0
        cell.answer.tintColor = UIColor(hex: 0x42DC5A)
    } else {
        cell.answer.selectedSegmentIndex = 1
        cell.answer.tintColor = UIColor(hex: 0xD9393E)
    }

    if cell.comment != nil {
        cell.comment.delegate = self
        cell.comment.text = "Add a note if necessary.."
        cell.comment.textColor = UIColor.lightGrayColor()
    }

    if questionsAnswers[indexPath.row] == "YES" {
        // here i have to hide cell.comment and its space
    } else {
        // here i have to show it if its possible
    }

    // pass indexPath.row to action
    cell.answer.tag = indexPath.row
    cell.answer.addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged)

    return cell
}

// fires when user taps on segmentedControl
func valueChanged(sender: UISegmentedControl){
    // switch segment and update questionsAnswers array
    switch sender.selectedSegmentIndex {
    case 0:
        questionsAnswers[sender.tag] = "YES"
        sender.tintColor = UIColor(hex: 0x42DC5A)
    case 1:
        questionsAnswers[sender.tag] = "NO"
        sender.tintColor = UIColor(hex: 0xD9393E)
    default:
        break
    }
}

questions - an array with text of question
questionsAnswers - an array when i save value from segmented control
Sorry if my question is bad, i'm newbie in ios programming(

A: Open the xib in the interface builder. Then ctrl + drag the constraints to the UIViewController for that view.
For your case you will need a height of textView and spacing between either segmentedControl or the bottom layout.
After that just set your heightConstraint.constant = 0 and spacingConstraint.constant = 0.
If you only set the height one, you will have two spacings between the segmentedControl and the bottom layout as it is suggested in other answers.
If you need to show it again, just make sure you save the initial values for constraint constants and then set them back like this heightConstraint.constant = initialHeight and spacingConstraint.constant = initialSpacing

A: If you are using Auto Layout, you could add a height constraint to the text view, and add an IBOutlet to it in your cell subclass. Just set myConstraint.constant to zero if you want to hide it.

A: Thank you guys, i created an IBOutlet for textView's height constraint in my tableViewCell class:
@IBOutlet weak var heightConstraint: NSLayoutConstraint!

Then i replace this code:
if questionsAnswers[indexPath.row] == "YES" {
    cell.heightConstraint.constant = 0.0
} else {
    cell.heightConstraint.constant = 70.0
}

And it works well, but i got this in the debugger:

Probably at least one of the constraints in the following list is one
  you don't want. Try this: (1) look at each constraint and try to
  figure out which you don't expect; (2) find the code that added the
  unwanted constraint or constraints and fix it. (Note: If you're seeing
  NSAutoresizingMaskLayoutConstraints that you don't understand, refer
  to the documentation for the UIView property
  translatesAutoresizingMaskIntoConstraints)

 "<NSLayoutConstraint:0x7f9fc2f45300 V:[UITextView:0x7f9fc3017a00'Add a note if necessary..'(70)]>",
 "<NSLayoutConstraint:0x7f9fc2df4460 UILabel:0x7f9fc2f40410'3. Question sadsadas das ...'.top == UITableViewCellContentView:0x7f9fc2f402d0.topMargin>",
 "<NSLayoutConstraint:0x7f9fc2df4550 V:[UILabel:0x7f9fc2f40410'3. Question sadsadas das ...']-(NSSpace(8))-[UISegmentedControl:0x7f9fc2f40e20]>",
 "<NSLayoutConstraint:0x7f9fc2df4700 UITextView:0x7f9fc3017a00'Add a note if necessary..'.bottom == UITableViewCellContentView:0x7f9fc2f402d0.bottomMargin>",
 "<NSLayoutConstraint:0x7f9fc2df4750 V:[UISegmentedControl:0x7f9fc2f40e20]-(NSSpace(8))-[UITextView:0x7f9fc3017a00'Add a note if necessary..']>",
 "<NSLayoutConstraint:0x7f9fc2ed5060 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7f9fc2f402d0(81.5)]>" )

Should i change some constraints?
And one more question if user click "NO" on segmentedControl i want to show that textView to user.
Can i do it like this:
// pass indexPath.row to action
cell.answer.tag = indexPath.row
cell.answer.addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged)

// fires when user taps on segmentedControl
func valueChanged(sender: UISegmentedControl){
    // switch segment and update questionsAnswers array
    switch sender.selectedSegmentIndex {
    case 0:
        questionsAnswers[sender.tag] = "YES"
        sender.tintColor = UIColor(hex: 0x42DC5A)
        tableView.reloadData()
    case 1:
        questionsAnswers[sender.tag] = "NO"
        sender.tintColor = UIColor(hex: 0xD9393E)
        tableView.reloadData()
    default:
        break
    }
}

Just reload tableView with new questionsAnswers array?


text:
Q: Why Both 8GB USB Flash Drives Have Different Integrities? USB 3.0 SuperTalent Express DUO 8GB recently had its partition corrupted and declared itself "write-protected" and I was told in chat by @sidran32 that this usually means that flash drive gone bad due to writing cycles limit being reached. Having this thumbdrive for over a year being used infrequently, I was in doubt and referred to SuperTalent's support. I was given recovery tool which I executed but it failed first time prompting me to reinsert it. After that, I formatted it with Windows 7 integrated format utility since recovery tool offered to do this as well which was successful.
The problem as I have noticed is with integrity of SuperTalent:

Compare above to SanDisk's Micro Cruzer 8GB:

Am I missing something? Both thumbdrives are of 8GB and have same FAT32 file system.

A: The lifetime of a flash memory cell is reduced each time the cell is used. After some time, a much-used cell becomes faulty and cannot be used anymore. Then it will be automatically sorted out by the flash memory controller and marked as not available.
The most logical explanation to me is the one you already got: Your Super Talent flash drive seems to have several "sorted-out" cells.
However, since you said that you didn't use your drive very often, another explanation could be that Super Talent typically sell their flash drives with a lower capacity compared to the ones from SanDisk. Nevertheless, the minimum capacity a factory-new 8 GB flash drive should provide is 8,000,000,000 bytes (which is not the case with this Super Talent drive).
Please note that 1 GB (109 bytes) is not equal to 1 GiB (10243 bytes). Drive manufacturers use the exact SI prefixes which often leads to confusion dependent on which units are used by the operating systems to display the drive capacity.


text:
Q: Enable Zoom on an ESNet react-timeseries-charts Chart I'm currently playing with ESnet's react timeseries charting components, with the specific goal of allowing a user to zoom into a displayed chart, as in their currency example.
According to their documentation and to the best of my understanding of the example's source code, it should be enough, if one is rendering a chart like this:
<ChartContainer timeRange={series.range()}>
   ...
</ChartContainer>

To add enablePanZoom={true} to the props to enable zooming. E.g:
<ChartContainer timeRange={series.range()} enablePanZoom={true}>
   ...
</ChartContainer>

However, this is not working and I cannot understand why. I guess something from the doc or the example eludes me:

*

*running the zoomable examples locally works as expected

*running the non-zoomable example with the zoom flag enabled does not work

Hence, the question: How to make a react-timeseries-charts chart zoomable?
edit: Turns out the answer was obvious: one must make use of onTimeRangeChanged and update the state, otherwise, well, poof...

A: On their example, they use
onTimeRangeChanged={this.handleTimeRangeChange}
if you look in the example source code, at https://github.com/esnet/react-timeseries-charts/blob/master/src/website/packages/charts/examples/currency/Index.js
they define the function as
handleTimeRangeChange = timerange => {
    this.setState({ timerange });
};

Have you tried that?


text:
Q: qtwebengine fails to compile. cant find EGL/egl.h in yocto using Yocto Krogoth to build a distro for atom x64 with opengl support. bitbake will build fine without qtwebengine added but adding it causes the error:

fatal error: EGL/egl.h: No such file or directory

my conf/local.conf i have added:
DISTRO_FEATURES_append = " opengl x11 "
IMAGE_INSTALL = "qtbase qtwebengine \
x11-common mesa-gl \
"

CORE_IMAGE_BASE_INSTALL += "mesa-megadriver"
CORE_IMAGE_BASE_INSTALL += "libegl-gallium"
CORE_IMAGE_BASE_INSTALL += "libegl-mesa"
CORE_IMAGE_BASE_INSTALL += "libgbm"
CORE_IMAGE_BASE_INSTALL += "libgbm-gallium"
CORE_IMAGE_BASE_INSTALL += "mesa-driver-pipe-swrast"
CORE_IMAGE_BASE_INSTALL += "mesa-driver-pipe-vmwgfx"
CORE_IMAGE_BASE_INSTALL += "mesa-driver-pipe-i915"
CORE_IMAGE_BASE_INSTALL += "libgles1-mesa"
CORE_IMAGE_BASE_INSTALL += "libgles2-mesa"

PREFERRED_PROVIDER_virtual/libgl  ?= "mesa-gl"
PREFERRED_PROVIDER_virtual/mesa  ?= "mesa-gl"
PREFERRED_PROVIDER_mesa-driver-swrast = "mesa-gl"
PREFERRED_PROVIDER_virtual/libgles1 = "mesa-gl"
PREFERRED_PROVIDER_virtual/libgles2 = "mesa-gl"

and if i set virtual/egl to mesa i get

ERROR: Nothing PROVIDES 'virtual/egl'
ERROR: mesa PROVIDES virtual/egl but was skipped: PREFERRED_PROVIDER_virtual/libgl set to mesa-gl, not mesa
ERROR: mesa PROVIDES virtual/egl but was skipped: PREFERRED_PROVIDER_virtual/libgl set to mesa-gl, not mesa

and if i set everything to mesa, qtbase will not build because LGL cant be found.
how can i get passed this.

A: Maybe this patch from the mesa homepage will help you.
diff --git a/include/GL/mesa_glinterop.h b/include/GL/mesa_glinterop.h
index b76bd7e..5c172c6 100644
--- a/include/GL/mesa_glinterop.h
+++ b/include/GL/mesa_glinterop.h
@@ -51,7 +51,7 @@
 #define MESA_GLINTEROP_H

 #include <stddef.h>
-#include <EGL/egl.h>
+#include <stdint.h>

 #ifdef __cplusplus
 extern "C" {
@@ -61,6 +61,10 @@ extern "C" {
 typedef struct _XDisplay Display;
 typedef struct __GLXcontextRec *GLXContext;

+/* Forward declarations to avoid inclusion of EGL/egl.h */
+typedef void *EGLDisplay;
+typedef void *EGLContext;
+
 /** Returned error codes. */
 enum {
    MESA_GLINTEROP_SUCCESS = 0,


text:
Q: How to protect/encrypt R objects in RData files due to EU-GDPR I want to protect the content of my RData files with a strong encryption algorithm
since they may contain sensitive personal data which must not be
disclosed due to (legal) EU-GDPR requirements.
How can I do this from within R?
I want to avoid a second manual step to encrypt the RData files after creating them to minimize the risk of forgetting it or overlooking any RData files.
I am working with Windows in this scenario...

A: library(openssl)

x <- serialize(list(1,2,3), NULL)

passphrase <- charToRaw("This is super secret")
key <- sha256(passphrase)

encrypted_x <- aes_cbc_encrypt(x, key = key)

saveRDS(encrypted_x, "secret-x.rds")

encrypted_y <- readRDS("secret-x.rds")

y <- unserialize(aes_cbc_decrypt(encrypted_y, key = key))

You need to deal with secrets management (i.e. the key) but this general idiom should work (with a tad more bulletproofing).

A: I know it's very late but checkout this package endecrypt
Installation :
devtools::install_github("RevanthNemani\endecrypt")

Use the following functions for column encryption:
airquality <- EncryptDf(x = airquality, pub.key = pubkey, encryption.type = "aes256")

For column decryption:
airquality <- DecryptDf(x = airquality, prv.key = prvkey, encryption.type = "aes256")

Checkout this Github page
Just remember to generate your keys and save it for first use. Load the keys when required and supply the key object to the functions.
Eg
SaveGenKey(bits = 2048,
              private.key.path = "Encription/private.pem",
              public.key.path = "Encription/public.pem")

# Load keys already stored using this function
prvkey <- LoadKey(key.path = "Encription/private.pem", Private = T)

It is very easy to use and your dataframes can be stored in a database or Rdata file.


text:
Q: Can someone explain how the shortened code equals to the longer one? Can someone explain to me how
const { value, name } = event.target;

is equal to
event.target.name
event.target.value

A: Destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
example for arrays :
const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1
console.log(z); // 2

another example for destructuring with objects
const user = {
id: 42,
is_verified: true
};

const {id, is_verified} = user;
console.log(id); // 42
console.log(is_verified); // true

reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment


text:
Q: Why is my header format applying to all cells when I insert to excel file from SSIS I am using SSIS to export a sql query to a pre formatted template excel file. The template file has the header row formatted with text wrapping, and the rest of the rows normal formatting. I want the data to insert with normal formatting, when it inserts, every row has text wrapping.

A: Turns out Excel was automatically wrapping text where the cell value didn't fit the cell width rather than hiding the text.


text:
Q: Let $\{a_n\}_{n=1}^\infty$ be an infinite sequence. Does there exist an infinite series whose partial sums is $\{a_n\}_{n=1}^\infty$? Definition: By an Infinite Sequence of real numbers, we shall mean any real valued function whose domain is the set of all positive integers.
Definition: By an Infinite Series of real numbers, we shall mean an ordered pair of infinite sequences of real numbers $$(\{a_n\}_{n=1}^\infty, \{s_n\}_{n=1}^\infty)$$ such that $$s_1=a_1, \space s_2=a_1+a_2, \space s_3=a_1+a_2+a_3$$ and in general $$s_k= a_1+a_2+ \dotsb +a_k$$  The sequence $\{a_n\}_{n=1}^\infty$ is called the sequence of terms of the infinite series. The sequence $\{s_n\}_{n=1}^\infty$ is called the sequence of partial sums of the infinite series.
Exam Question:

Let $\{a_n\}_{n=1}^\infty$ be an infinite sequence of real numbers.  Does there exist an infinite series of real numbers whose sequence of partial sums is $\{a_n\}_{n=1}^\infty$? Why or why not?

My answer is Yes and here is why. Consider the constant sequence $\{0\}_{n=1}^\infty$.  This sequence has the value $0$ for all $n \in \mathbb Z^+$.  Now, if we consider the infinite series of this sequence, then the sequence of partial sums has the value $0$ for all $n \in \mathbb Z^+$. So, in this case $$(\{a_n\}_{n=1}^\infty, \{s_n\}_{n=1}^\infty) = (\{0\}_{n=1}^\infty, \{0\}_{n=1}^\infty) = (0,0)$$
Therefore, $\{a_n\}_{n=1}^\infty = 0 = \{s_n\}_{n=1}^\infty$ for all $n \in \mathbb Z^+$.
However, on turning in my exam, my professor stated this was incorrect.  Why is this so?

A: Certainly:
$$
\text{Let }b_0 = a_0\text{ and }b_{n+1} = a_{n+1}-a_n.
$$
Then
\begin{align}
b_0 & = a_0 & = a_0 \\
b_0 + b_1 & = a_0 + (a_1-a_0) & = a_1 \\
b_0 + b_1 + b_2 & = a_0 + (a_1-a_0)+(a_2-a_1) & = a_2 \\
b_0 + b_1 + b_2 + b_3 & = a_0 + (a_1-a_0)+(a_2-a_1)+(a_3-a_2) & = a_3 \\
& {}\,\,\vdots & \vdots\phantom{a_n}
\end{align}

A: Because it only works when $a_n=0$ for all $n$. Let $s_0=a_0$, and $s_n=a_n-a_{n-1}$. Now
$$\sum_{n=0}^ks_n=a_0+(a_1-a_0)+\dots +(a_k-a_{k-1})=a_k.$$


text:
Q: Can't change background colour of ActionBar I'm trying to change the background colour of my Android app, but I'm not being able to. I've searched through a lot of posts but none solution solved mine.
Here's mine styles.xml:
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/ActionBar</item>
</style>

<style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="android:background">#ff0000</item>
</style>

</resources>

As you can see, I'm just trying to set the bar to red.
Here's my manifest:
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MenuActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

The theme is properly set, as you can see. And just so you can see, here's my gradle:
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    ...
    minSdkVersion 15
    targetSdkVersion 21

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

So, even though this looks alright, it is not setting my ActionBar to red. I tried following a lot of guides (including the official one) and I've done everything as they say. What am I missing? Thank you for your patience in advance :)

A: Since you are using the AppCompat library, you should handle older android versions too (just like it was when using the ActionBarSherlock library):
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/ActionBar</item>
        <item name="actionBarStyle">@style/ActionBar</item>
    </style>

    <style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@android:color/red</item>
        <item name="background">@android:color/red</item>
    </style>
</resources>

The items without the android namespace are for styling the appcompat actionbar used on older android versions.
See this answer for further reference.
You should also check, that you probably have more styles.xml files generated for various screen sizes and sdk version.
You may want to add your ActionBar style declarations to these other styles too: it looks like your test device uses another one, not the default.

A:
<style name="Demo_Theme" parent="Theme.AppCompat.Light">
    <item name="android:actionBarStyle">@style/actionBG</item>
    <!-- Support library compatibility -->
    <item name="actionBarStyle">@style/actionBG</item>
</style>

<style name="actionBG" parent="Widget.AppCompat.Light.ActionBar">
    <item name="android:background">@color/test_bg_color</item>
    <!-- Support library compatibility -->
    <item name="background">@color/test_bg_color</item>
</style>

This should work fine.


text:
Q: I need an algorithm for rendering soft paint brush strokes I have an array of mouse points, a stroke width, and a softness. I can draw soft circles and soft lines. Which algorithm should I use for drawing my array of points? I want crossed lines to look nice as well as end points.

A: I would definitely choose the Bezier for that purpose, and in particular I will implement the piecewise cubic Bezier - it is truly easy to implement and grasp and it is widely used by 3D Studio max and Photoshop.
Here is a good source for it:
http://local.wasp.uwa.edu.au/~pbourke/surfaces_curves/bezier/cubicbezier.html
Assuming that you have an order between the points, in order to set the four control points you should go as follows:
I define the tangent between point P[i] and point P[i+1]

*

*T1 = (P[i+1] - P[i-1])

*T2 = (P[i+2] - P[i])

And to create the piecewise between two points I do the following:

*

*Control Point Q1: P[i]

*Control Point Q2: the point lying along the tangent from Q1   => Q1 + 0.3T1

*Control Point Q3: the point lying along the tangent to Q4     => Q4 - 0.3T2

*Control Point Q4: P[i+1]

The reason I chose 0.3T is arbitrary in order to give it enough 'strength' but not too much, you can use more elaborated methods that will take care of acceleration (C2 continuity) as well.
Enjoy

A: Starting from Gooch & Gooch's Non-Photorealistic Rendering, you might find Pham's work useful - see PDF explaining algorithm.
There's a nice overview article by Tateosian which explains the additional techniques in less detail with pretty pictures.Bezier curve drawing alone doesn't produce the effects you want (depending on how fancy you want to get). However, I'd certainly start with Paul's work and see if just using that to draw with your soft brush is good enough.
Be warned there are lots of patents in this space, sigh.

A: I think maybe you're looking for a spline algorithm.
Here is a spline tutorial, which you might find helpfull:
[http://www.doc.ic.ac.uk/~dfg/AndysSplineTutorial/index.html]
The subject is also covered in most books on graphics programming.
Cheers.

A: I figured it out - use a very soft gradient circle, draw repeatedly to make a stroke, blend using multiply.


text:
Q: Why does one get an illusion as moon following him? When you run or ride bike at night if you observe the moon you feel like he moves along with you as the same speed you are going. Why?

A: Suppose you're walking past a nearby tree:

As you pass the tree the angle of the line joining you and the tree changes. From your perspective it looks as if you are standing still and the tree has moved backwards.
However the Moon is so far away that, as you walk, the angle of the line joining you to the Moon doesn't change by any significant amount:

So, from your perspective it looks as if the moon is keeping up with you i.e. it's traveling at the same speed as you are.
This effect is particularly marked if there are any nearby landmarks. For example, nearby trees seem to move backwards as you pass them, and this enhances the feeling that the Moon is moving forwards to keep up with you.

A: The moon is a lot further away than the horizon or nearby buildings, trees, hills or mountains.
As you pass these nearby objects, from your perspective you see them apparently move backwards relative to your motion.
This is a matter of simple trigonometry.
This is because, the angle between your bicycle and (for example) a tree 100 metres away changes noticeably when you move forward 10 metres.
The change in angle for the moon 384,400,000 metres away is imperceptible.
This is an example of parallax

For a very distant object, such as the moon, $\alpha$ will be almost zero


text:
Q: TypeError: pivot_table() got an unexpected keyword argument 'rows' I'm trying to use the pivot_table method of a pandas DataFrame;
mean_ratings = data.pivot_table('rating', rows='title', cols='gender', aggfunc='mean')

However, I receive the following error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-55-cb4d494f2f39> in <module>()
----> 1 mean_ratings = data.pivot_table('rating', rows='title', cols='gender', aggfunc='mean')

TypeError: pivot_table() got an unexpected keyword argument 'rows'

The above command was taken from the book 'Python for Data Analysis' by Wes McKinney (the creator of pandas)

A: The solution for me was to change 'rows=>index' and 'cols=>columns'):
From:
mean_ratings = data.pivot_table('rating', rows='title', cols='gender', aggfunc='mean')

to:
mean_ratings = data.pivot_table('rating', index='title', columns='gender', aggfunc='mean')


text:
Q: Problems with SDL image I'm running on a mac OS 10.8.2 and compiling my program with the following command;
g++ main.cpp `sdl-config --cflags --libs` -o whateverfilename

I can compile SDL programs just fine but as soon as I try to use the SDL image library, things go wrong - I get the following errors:
Undefined symbols for architecture x86_64:
  "_IMG_Init", referenced from:
      _SDL_main in cco8lzYA.o
  "_IMG_Load_RW", referenced from:
      _SDL_main in cco8lzYA.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

I'm guessing the linker is missing a search path or something. I've been trying to look up and edit the linker search paths but can't seem to manage even that so if someone could tell me how to do that or what other problems I might be causing I'd appreciate it :)

A: I think you need to add the lSDL_Image compiler flag, I'm very much a noob when it comes to C++ and SDL, it was ages since I've done anything with it.
I also very much recommend LazyFoo's tutorials


text:
Q: Contact Form 7 + Google reCAPTCHA - How do I set up server-side configuration? Thank you for reading my problem in advance. I am trying to incorporate Google's new reCAPTCHA (https://www.google.com/recaptcha/) into a Wordpress site that is using Contact Form 7. I have inserted the front-end code provided by Google:

However, I can't figure out how to get the server-side integration configured. From what I can tell, I need to insert this code into my contact form HTML (see https://code.google.com/p/recaptcha/wiki/HowToSetUpRecaptcha#Part_2:_Installation):
<?php
 require_once('recaptchalib.php');
 $publickey = "YOUR_PUBLIC_KEY"; // you got this from the signup page
 echo recaptcha_get_html($publickey);?>

When I do that on the Contact Form 7 backend, it just displays the text in between "< ?" and "? >". I'm also a little confused about the other steps and there are not many resources online about this new captcha.
Thanks again.
-Trent