learning powershell, and having some issues with GetADUser with -Filter

Question: So I am having some issues with the below script. The weird part is, when I run the apparently offending part separately by itself, it works fine. It's only when it tries to run in the add_Click function that it throws an error message.
<code>[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

$SearchTermTest=Read-Host -Prompt "Enter First or last name"
$UsersTest = Get-ADUser -Filter "GivenName -eq '$SearchTermTest' -or SurName -eq '$SearchTermTest'"
Write-Output $UsersTest

# Create the form
$SearchForm = New-Object System.Windows.Forms.Form
$SearchForm.Text = "Search User"
$SearchForm.Size = New-Object System.Drawing.Size(500,500)

# Create the label and textbox for user input
$FirstLastNameLabel = New-Object System.Windows.Forms.Label
$FirstLastNameLabel.Location = New-Object System.Drawing.Size(20,20)
$FirstLastNameLabel.Text = "Enter First or Last Name"
$SearchForm.Controls.Add($FirstLastNameLabel)

$InputTextBox = New-Object System.Windows.Forms.TextBox
$InputTextBox.Location = New-Object System.Drawing.Size(150,20)
$SearchForm.Controls.Add($InputTextBox)

# Create the DataGridView
$DataGridView1 = New-Object System.Windows.Forms.DataGridView
$DataGridView1.Location = New-Object System.Drawing.Size(20,50)
$DataGridView1.Size = New-Object System.Drawing.Size(450,400)
$SearchForm.Controls.Add($DataGridView1)

# Create the search button
$SearchButton = New-Object System.Windows.Forms.Button
$SearchButton.Location = New-Object System.Drawing.Size(280,20)
$SearchButton.Size = New-Object System.Drawing.Size(100,20)
$SearchButton.Text = "Search"
$SearchButton.Add_Click({
    $SearchTerm = $InputTextBox.Text
    $Users = Get-ADUser -Filter "GivenName -eq '$SearchTerm' -or SurName -eq '$SearchTerm'"
    $DataGridView1.DataSource = $null
    $DataGridView1.DataSource = $Users
    $DataGridView1.AutoResizeColumns([System.Windows.Forms.DataGridViewAutoSizeColumnMode]::DisplayedCells)
})
$SearchForm.Controls.Add($SearchButton)

$SearchForm.ShowDialog()

</code>
<code>
Get-ADUser : The search filter cannot be recognized
At C:\Users\ad_forrest.vasilinda\Desktop\user password search.ps1:36 char:14
+ ...    $Users = Get-ADUser -Filter "GivenName -eq '$SearchTerm' -or SurNa ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
</code>
Error message is above. Any ideas? I am at my wits end honestly. I have the exact same GetADUser statement running with the same filter at the beginning of the script with no errors, its only in the add_click function it throws it.
Update -- changing some of the variable names to be more descriptive and not match any of the reserved names now only causes the error to pop up when the field is left blank. However, now when there is text in the field and I push the button, nothing happens.
Comment: `$input` is an automatic variable. You should never use that name for self defined variables. Choose a better name for that like `$inputTextBox` for instance. Also, is that `{` just in front of Get-ADUser a typo?
Comment: That was just a typo yes, I tried wrapping it in {} to see if that would change anything, but looks like I missed taking the first one out when I was changing it back. And appreciate the advise on the variable naming
Comment: Try `$SearchTerm = $InputTextBox.Text.Trim()` and make sure that the search term contains no `'` chars. - you'd have to escape them as `''`
Comment: @mklement0 Nope, still the same behavior even with that change
Comment: Does `Get-ADUser -Filter 'GivenName -eq $SearchTerm -or SurName -eq $SearchTerm'` (sic) at least produce a different symptom?
Comment: Don't know if you read close enough in the OP, but I do have literally the same filter running at the beginning of the script with no issues, it's only when its in the add_click function it has issues.
Comment: @ForrestVasilinda, you missed the `'` around the `-Filter` argument in my previous suggestion. Also, the value of `$SearchText` matters with respect to whether your `"..."`-based `-Filter` breaks or not.
Comment: 2 things
1)You are right, I missed that on your suggested code statement, copy/pasted it directly to ensure it as exact and now it is back to the original behavior described in my update in the OP

2)I am aware of that, and make sure to always enter the same thing for both the test code in the beginning and the textbox when the actual GUI appears, and it works fine when I enter it directly into the prompt in the console, but when entering the exact same thing into the textbox is was causes the issue/errors
Comment: So I replaced the $SearchTerm assignment with the same Read-Host prompt as my test code at the beginning just to ensure everything would match exactly when running the filter, and noted that when I type something and then hit enter, it just shows the cursor blinking on the next line by itself until the search button is pushed again which brings up the same prompt again.
Comment: _Manually attempting_ to make sure that two inputs are the same isn't necessarily the same as actually ensuring they are. _Hard-code_ a `$SearchTerm` value in both scenarios, and if it only works in one of them, further investigation is needed.
Comment: Okay good point and suggestion, I hard coded a variable as
$SearchTermHC = "forrest" and used it in both the code at the beginning, and the add click function. Again it is running fine at the beginning and outputs the expected list of user objects to the console, but when I click the search button in the GUI nothing happens.
Comment: `$SearchTermHC` is different from `$SearchTerm` -  did you account for that in the `-Filter` argument? Are you saying that you _no longer get an error_?
Comment: Yes I changed it in both places for the -Filter arguments. And not getting an error is not new behavior, if you read the OP, I specify in my update from before you and I started working together here in the comments that the error is only thrown when the textfield is left blank, whenever there is something in the textfield there is no error but nothing happens.
Answer: I was getting a blank screen as well so I changed it a bit and added some error checking.  Now you can search an empty string or part of the name.  I changed the filter to -Like so you get better results.
I added a variable $properties so you can add/remove the AD attributes you would like to use.
Cheers
<code>[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

# Properties to display
$properties = "GivenName","SurName","Mail","UserPrincipalName","Company"

# Create the form
$SearchForm = New-Object System.Windows.Forms.Form
$SearchForm.Text = "Search User"
$SearchForm.Size = New-Object System.Drawing.Size(800,500)

# Create the label and textbox for user input
$FirstLastNameLabel = New-Object System.Windows.Forms.Label
$FirstLastNameLabel.Location = New-Object System.Drawing.Size(20,20)
$FirstLastNameLabel.Text = "Enter First or Last Name"
$SearchForm.Controls.Add($FirstLastNameLabel)

$InputTextBox = New-Object System.Windows.Forms.TextBox
$InputTextBox.Location = New-Object System.Drawing.Size(160,20)
$SearchForm.Controls.Add($InputTextBox)

# Create the DataGridView
$DataGridView1 = New-Object System.Windows.Forms.DataGridView
$DataGridView1.Location = New-Object System.Drawing.Size(20,50)
$DataGridView1.Size = New-Object System.Drawing.Size(750,400)
$dataGridView1.ColumnCount = $properties.count
$dataGridView1.ColumnHeadersVisible = $true
$i=0
$properties | %{
    $dataGridView1.Columns[$i++].Name = $_
}
$SearchForm.Controls.Add($DataGridView1)

# Create the search button
$SearchButton = New-Object System.Windows.Forms.Button
$SearchButton.Location = New-Object System.Drawing.Size(280,20)
$SearchButton.Size = New-Object System.Drawing.Size(100,20)
$SearchButton.Text = "Search"
$SearchButton.add_click({
    $SearchTerm = ($InputTextBox.Text).trim()
    $filter = "*"
    if ($searchTerm) {
        $filter = "GivenName -like '*$SearchTerm*' -or SurName -like '*$SearchTerm*'"
    }
    [array]$users = Get-ADUser -Filter $filter -Properties $properties | select $properties
    $DataGridView1.Rows.Clear()
    if ($users) {
        $users | %{
            $DataGridView1.Rows.Add($_.psobject.Properties.value)
        }
    }
    $DataGridView1.AutoResizeColumns([System.Windows.Forms.DataGridViewAutoSizeColumnMode]::DisplayedCells)
})
$SearchForm.Controls.Add($SearchButton)
$SearchForm.ShowDialog()
</code>
Comment: My man! Just wish I knew what was wrong in the first place just for the knowledge since I am still learning, but nonetheless thank you very much :) Having a working script is still useful and I will take a look to see what you did different and take into account for the future. Thanks again!
Comment: Oddly enough changing all my variable names to be more descriptive and not match any of the reserved ones now only causes the error to show when I leave the field blank and push the button. However, when I put any text in the field and hit enter, now nothing happens at all. No error, and nothing is populating the table. I even changed it to write the $Users straight to the console and still nothing.
Comment: You're welcome. Assuming you tested it and it works for you?
Comment: Hi sorry missed your comment but yes it is working for what I needed it for, and was able to implement some other features as well. Thanks again for the help :)!!


Stationary points of $z(x, y)=\cos{x}e^{-x^2-y^2}$

Question: This is a problem from one of past exams from my course.

Consider a function $z(x, y)=\cos{x}e^{-x^2-y^2}$.
Show that stationary points of $z$ lie along the $x$-axis, and satisfy $\tan{x}=k(x)$. Give an expression for $k(x)$.

This one I managed to do, I got that for $z_x=z_y=0$ we have $y=0$ and $\tan{x}=-2x$.

Determine the nature of these stationary points of $z(x,y)$.

This one I have problems with. I know the conditions for maxima, minima etc. in two variables ($D=z_{xx}z_{yy}-z_{xy}^2$ test), but I got into some horrible algebraic mess when trying to determine $D$.
Is there any "cleverer" method to determine the nature of the stationary points?
For what it's worth, $z_x = -e^{-x^2-y^2}(2x\cos{x}+\sin{x})$ and $z_y = -2y\cos{x}e^{-x^2-y^2}.$
Comment: Do you mean singular points?  Instead of stationary?
Comment: @dmtri As far as I know, points such that $\frac{\partial{z}}{\partial{x}}=0$ and similarly for $y$ are called stationary points, see for instance http://personal.maths.surrey.ac.uk/S.Zelik/teach/calculus/max_min_2var.pdf
Answer: At any stationary point $(x,0)$ we have
$$\eqalign{
\left[\matrix{z_{xx}&z_{xy}\cr z_{xy}&z_{yy}}{}\right]&=
\left[
\begin{array}{cc}
 e^{-x^2} \left(\left(4 x^2-3\right) \cos (x)+4 x \sin (x)\right) & 0 \\
 0 & -2 e^{-x^2} \cos (x) \\
\end{array}
\right]\cr
&=-\cos(x)e^{-x^2}\left[\matrix{3+4x^2&0\cr0&2}\right]
}
$$
where in the last step, I used $\tan(x)=-2x$.  Now, we have a local minimum
on every stationary point $(x,0)$ with $\tan(x)=-2x$ and $\cos(x)<0$ and a local maximum on every stationary point $(x,0)$ with $\tan(x)=-2x$ and $\cos(x)>0$.


How to save item with navigation property to DB Entity Framework 6

Question: public void Add(Site obj)
{
    if(obj.Id == 0 || obj.Id >= 10000)
    {
        context.Sites.Add(obj);
    } else
    {
        Site dbEntry = context.Sites.Find(obj.Id);
        if (dbEntry != null)
        {
             ...
        }
    }
    context.SaveChanges();
    return res;
}

class Site {
  public virtual List<Page> Pages { get; set; }
}

class Page {
    public virtual Site Site {get;set;}
}

In Add method Obj.Pages.Site(foreach of pages) is null, but Site.Pages not, I expected that when I save to DB Site A Site.Pages will be saved to DB too,and for each Page navigation property Site will be set to A. Pages are saving, but Site_Id in db is null. Should I create my own foreign keys or there is possibility to use entity-framework keys?
Comment: Are you keeping your `context` open all the time? Why don't you put in a `using`?
Comment: @LuisLavieri There are methods from SiteRepository and PageRepository, context is private field: `private SiteContext context = new SiteContext();`
Answer: Move your SaveChanges() to the if statement after you add the site. Basically,
You have to Save the changes and commit the transaction before being able to access all your navigation properties. Commiting the transaction using context.Database.BeginTransaction() is optional, so you are able to rollback in the case of a problem. But the savechanges has to be before trying to access the navigation properties. Try to separate the code into functions so it is easier to read. An example would be like this:
public void Add(Site obj)
{
    using(var context = new SiteContext())
    {
        using(var dbContextTransaction = new context.Database.BeginTransaction())
        {
            try
            {
                context.Sites.Add(obj);
                context.Entry(obj).State = obj.Id == 0 ? EntityState.Added : EntityState.Modified;
                context.SaveChanges();
                dbContextTransaction.Commit();
            }
            catch (Exception ex)
            {
                dbContextTransaction.Rollback();
                throw;
            }
        }
    }
}

Then, if you want to get the same entry you should do something like
public Site GetSiteById(int id)
{
    using(var context = new SiteContext())
    {
        return context.Sites.FirstOrDefault(i => i.Id == id);
    }
}

But, the context has to save changes and commit the transaction first. Then, you will have all your properties filled.
Comment: I don't know about EntityState, if 1) Add obj with existing id 2)set EntityState to Modified 3)SaveChanges - will be these actions update record in db according to obj?
Comment: Yes. Because I see that you are checking the Id. To avoid any conflicts with duplicate keys, you need to set the state to modified if its something different than zero. Those Actions will make your Add function better. Because it can save Sites and Update them if required.
Comment: I need this check because some objects are generating in json format on client side, their Id start from 10000. Id is a part of markdown and Id should be different, so objects with Id>=10000 I need to add to DB as wel as with Id 0.
Comment: Alright. Maybe in the front end you could add a condition that if the id is greater than 10000, set it to zero. But, you understand your requirements better than me. Are you satisfied with my answer or you are still having problems to update the navigation properties?
Comment: I've found your answer very usefull, but in my case I do the next: 1)add `public int FieldId` for each nav property 2)drop and recreate database 3)`int` is not nullable by default so now when try to add new record EF throws exception and I've found where I'd made the mistake. After this I've realized that when setting navigation properties if they nullable(as in my question) entity framework in case of exception just set them to `Null`. I don't like this behaviour and in future I'll always will use both: `virtual ClassA Nav; int NavId`.
Comment: OK. If you like that behavior of setting the Ids eventually to `null`, what if you use `int?` instead of `int`?
Comment: "I don't like this behaviour" but if set `int?` the behaviour will the same as without `int NavId`. Obviously I use this when I need to set ForeignKey that can be nullable(0 or 1 relationship).
Comment: It sounds more complicated than it should be. Maybe you should reconsider the design of the database.
Answer: This code is valid. To find out the problem I've done the next:
1)add public int FieldId for each nav property
2)drop and recreate database
3)int is not nullable by default so now when try to add new record EF throws exception
In other words I make EF throws exception if it can't set navigation property, it helps me to find the error in my code(just set break point before crash and debug step by step). By default if it is not possible to set a navigation property EF set it to NULL


What is this part on my dishwasher, and why is it leaking?

Question: I noticed our dishwasher was leaking last night.  Below is a stock picture of the pump assembly, part #wpw10195599 which would actually be positioned upside down from what you see in the picture.  The water appeared to be coming from the round hole that is circuled in red.
I can only find the entire assmble for sale, but would like to try to fix the actuall part that's defective first.
Does anyone know what the white part is that's circled?
Does it make sense that that's where water could be leaking from?
If so, is there anything I can do besides replace the entire assembly?
Comment: A photo of the part itself we may be able to read the writing. Who knows it could be a temp sensor, flow sensor hard to tell unless you have done one lately.
Answer: OK. I was able to find out that it's called the "diverter motor".  It spins the wash arm.  It seems that its leeking through a grommet seal where the white hole is.
So, I was able to order a new "diverter motor" and grommet seal.  Hopefully that will fix it?
Thanks


How to perform a fast join in BigQuery with Apache BEAM

Question: According to BEAM's programming guide, and according to many threads join can be achieved by CoGropByKey or KeyedPCollectionTuple (coockbook).
No one is talking about the performance of these kind of transformations.
My flow should be very simple: Input of rows batch from BQ table (TableRow) and join them (or "enrich") with other value from other BQ table by the same key. So the final output should be also of type TableRow.
I want to understand what will be the best practice to join 2 tables in BEAM with BQ Tables.
For example I could create a View in BQ and replace all this pipeline and perform a more efficient join operation, but I want to handle all the logic in code
What is happening under the hood when a join operation is handling?
Would DirectRunner perform n queries to the second BQ table in order to join all the pipeline batch (item after item)? or BEAM is smart enough to aggregate it and perform 1 query of all the batch?
Does Google DataflowRunner works in a different way?
How can I check the performance of this pipeline other than check the running time?
Answer: TTBOMK you don't want to write full SQL in code, for instance WHERE clauses.
Beam or really any code based SQL joins will fail on substantial data that is kept in BQ.
So any such "enrichment" should really be done by the underlying data crunching solution, be it SQL on top of BQ OR Spark on top of RDDs/DataFrames/etc.
Please note that it is less suitable for streaming, more for batch flows.
If you want to follow along the pure streaming way, you ought to use fast DBs, per your domain and avoid OLAP style (true columnar) DBs. BQ has a substantial delay per query.
Tell us how it goes :)


"Permission denied" error

Question: Alright so I installed Ubuntu last night and I am very new to everything.
Right now I am trying to run a program called JES, (Jython Environment for Students). The instructions tell me to cd to the JES directory I have, so I type
cd /home/Programs/JES

It takes me to the directory I need to be in, so far so good. Then I have to type in:
./JES.sh

And I get this returned to me:
bash: ./JES.sh: Permission denied

I have very little comprehension of what to do in Terminal or anything of the sort. Any help would be appreciated.
I have tried using
sudo -l

to get permissions but it still persists.
Answer: Looks like the file does not have permission to execute it:
chmod +x JES.sh

"Permission denied" error


Finding modular of a fraction

Question: In the context of cryptography, I need to find the private key of a message and I need to use modular arithmetic. I understand how modular arithmetic using a clock with whole numbers. But I get really stuck when I get to fractions, for example:

1/3 mod 8

How do I find a modular of a fraction? Is there a method for finding this?
Thanks in advance!
Answer: Writing fractions like $\frac{1}{3} \pmod{8}$ is the same as writing $3^{-1} \pmod{8}$ which is the inverse of $3$ modulo $8$.
In other words, when you write $\frac{a}{b} \pmod{n}$ you're referring to a number $k$ such that $bk \equiv a \pmod {n}$ but you should pay attention that this fraction is defined if and only if $\gcd(b,n)=1$. In other words, the denominator must be relatively prime to the modulus.
To find what number modulo $n$ this fraction represents, you need to evaluate $b^{-1}$. You can do that by using the Euclidean algorithm to solve the Bézout equation $bx + ny = 1$. The $x$ in this equation will give you $b^{-1}$. If you know the factorization of $n$ you can also use Euler's totient function by noting that $b^{-1} \equiv b^{\varphi(n)-1} \pmod{n}$. After you know what $b^{-1}$ is you will see that $k \equiv a \dot b^{-1} \pmod {n}$.
Comment: One of the best way to explain the concept. I loved your way of explaining, I was searching for something related to this and got this answer. Thanks a lot.
Answer:
<code>n  ≡ (1/3)  (mod 8)
3n ≡ 1      (mod 8)
try n= 1,2,3
  when n=1, 3 mod 8 is 3
  when n=2, 6 mod 8 is 6
  when n=3, 9 mod 8 is 1, (this is our answer)
</code>

So answer is 3
This method can be used for any fractions
Another example:   2/5 mod 3
<code> 5n mod 3 = 2
 try group of {0, 1, 2} which satisfy the above,
</code>
result n=1
Comment: Note: **(1)** If $0\leq a < k$ and $a \equiv b ~~(\text{mod }k)$ then $a = b~\text{mod }k$ (i.e., the remainder of $b$ when divided by $k$). | **(2)** $a \equiv b ~~(\text{mod }k) \iff b \equiv a ~~(\text{mod }k) $. So:
$$
\frac{2}{5}~~(\text{mod }3) \iff 5n \equiv 2~~(\text{mod }3)\iff 2\equiv 5n~~(\text{mod }3) \implies 2 = 5n ~\text{mod }3
$$
Answer: The important property of $1/3$ is that $1/3 \cdot 3 = 1$. So, what number, when multiplied by $3$, is $1$ mod $8$?
Showing when $x^{-1} \pmod n$ exists and that it is unique is not too terrible either
EDIT: I didn't see "finding it". Check out the Extended Euclidian algorithm.
Comment: is the number 1? Because 1 mod 8 = 1 as 1 < 8. But I don't get how `what number, when multiplied by 3` corresponds to 1. as 1x3 =3. Thanks!
Comment: But it can be suggested that 1/3 * 3= 1.
Comment: Take the numbers from $0$ to $7$, and multiply them by $3$. Are any of those products equal to $1$ mod $8$?
Answer: Calculating modulo 8, we have $\frac{1}{3} = \frac{3}{9} = \frac{3}{1} = 3$.

Finding modular of a fraction


Error: The getter 'value' isn't defined for the class 'XmlNode'

Question: Error: The getter 'value' isn't defined for the class 'XmlNode'.

'XmlNode' is from 'package:xml/src/xml/nodes/node.dart' ('/C:/Users/User/AppData/Local/Pub/Cache/hosted/pub.dev/xml-6.2.2/lib/src/xml/nodes/node.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'value'.
.map((node) => node.value)

Anyone had experience with this error
Answer: It is not a good idea to solve it by editing the local cache.
The error happens because you need to update xml version to >= 6.3.0
if you are not using xml directly in pubspec.yaml, then there are packages that you are using depend on the xml package and you have to update them.
To know which packages depend on xml, run flutter pub deps
Answer: i was facing the same issue i changed

from this

final text = element.children
    .where((node) => node is XmlText || node is XmlCDATA)
    .map((node) => node.value)
    .join()
    .trim();

to this

final text = element.children
    .where((node) => node is XmlText || node is XmlCDATA)
    .map((node) => node.text) //change value to text
    .join()
    .trim();

in /home/munsif/.pub-cache/hosted/pub.dev/pdf-3.10.2/lib/src/svg/text.dart
and this solve my problem.
Answer: I cleared that error.I added 2 dependancys pdf and xml for testing. but i didnt  used that.
then i deleted from pubspec.yamel.But the dependecys cache stored in pubspec.lock.
then i dlt 2 dependancys caches but that regenerate itselt.them i edited that dependancys pub.dev link and runned success fully
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How to extract character from array in golang?

Question: need to extract the random characters from string
here is what i got:
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  b := make([]byte, 1)
for i := range b {
    b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
fmt.Println(string(b))

but it always returns "X"
but, i need to return every time new character using rand function.
any help would be really appreciated.
Thanks.
Comment: What did you try? What was the problem?
Comment: Thanks. just updated the query .. please suggest
Comment: Another thing to note is in Go we can have UTF-8 characters and one single byte is not enough to hold those characters.
Comment: Possible duplicate of [How to generate a random string of a fixed length in golang?](https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang/31832326#31832326)
Comment: no. it always gives the same output. plz see code here: https://gist.github.com/anonymous/a90bdbd0ec0770b373890286322d9063
Comment: see my comment below, it won't work on play.golang.org
Answer: Start by seeding the pseudorandom number generator. For example,
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    b := make([]byte, 7)
    for i := range b {
        b[i] = letterBytes[rand.Intn(len(letterBytes))]
    }
    fmt.Println(string(b))
}

Output:
jfXtySC

The Go Playground
About the Playground
In the playground the time begins at 2009-11-10 23:00:00 UTC
  (determining the significance of this date is an exercise for the
  reader). This makes it easier to cache programs by giving them
  deterministic output.

Therefore, in the Go playground, time.Now().UnixNano() always returns the same value. For a random seed value, run the code on your computer.

For any Unicode code point (Go rune),
package main

import (
    "fmt"
    "math/rand"
    "time"
)

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    chars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ世界!@=")
    r := make([]rune, 50)
    for i := range r {
        r[i] = chars[rand.Intn(len(chars))]
    }
    fmt.Println(string(r))
}

Output:
世QRYSp=@giJMIKly=tXRefjtVkeE!yHhTSQHvLyUYdRNIBbILW

Comment: thanks. i added the code as you mentioned . but it always outputs "Bb"
Comment: here is the updated code: https://gist.github.com/anonymous/a90bdbd0ec0770b373890286322d9063
Comment: @user2315104: See the comment about the Go plaground in my revised answer.
Comment: can this logic be applicable to special characters as well ?
Comment: @user2315104: Use `rune` instead of `byte`. See my revised answer.
Answer: You probably don't need cryto/rand. Just set the seed to something different each time. The math/rand package is deterministic with the same seed, so you just need to change the seed each time. Assuming this is not super secure, just add this line.
rand.Seed(time.Now().Unix())

Also note if you're using play.golang.org to test it that's not going to work because the time pkg doesn't work there. It'll work fine anywhere else.
If you actually want a random selection of characters though, use crypto/rand.Read NOT a homemade version - you can encode it if you need it within a given character range. Finally, don't roll your own crypto, just in case that's what you're doing here.
Comment: can this logic be applicable to special characters as well ?


i'm stuck in Warning: require_once(C:\xampp\htdocs\test04/vendor/composer/autoload.php): and Fatal error: Uncaught Error: Class "Mpdf\Mpdf"

Question: I change $mpdf = new Mpdf\Mpdf(); to $mpdf = new mpdf\mpdf(); but still error i'm using mpdf/mpdf (v6.1.3)
Fatal error: Uncaught Error: Class "Mpdf\Mpdf" not found in C:\xampp\htdocs\test04\makepdf.php:11 Stack trace: #0 {main} thrown in C:\xampp\htdocs\test04\makepdf.php on line 11
<?php
require_once __DIR__ . '/composer/autoload.php';

    $Fname = $_POST['Fname'];
      $Lname = $_POST['Lname'];
      $User = $_POST['User'];
      $City = $_POST['City'];
      $State = $_POST['State'];
      $Zip = $_POST['Zip'];

      $mpdf = new Mpdf\Mpdf();

      $data ='';

      $data ='Your Details';

      $data ='First Name' .$Fname . '
';
      $data ='First Name' .$Lname . '
';
      $data ='First Name' .$User . '
';
      $data ='First Name' .$City . '
';
      $data ='First Name' .$State . '
';
      $data ='First Name' .$Zip . '
';

      $mpdf->WriteHTML($data);

      $mpdf->Output('myfile.pdf', 'D');

[here's the code i copied for require_once][1]

  [1]: https://i.stack.imgur.com/B94sr.png

Comment: What have you tried to resolve the problem? Where are you stuck? I would assume that you are not requesting the autoloader properly
Answer: If your package is located in other directory than file from you are calling it you must include full namespace.
Try changing
$mpdf = new Mpdf\Mpdf();

to
$mpdf = new \Mpdf\Mpdf();

Comment: Please add some explanation to your answer such that others can learn from it. Why should that make any difference? The given code does not use any namespace
Comment: Fatal error: Uncaught Error: Class "Mpdf\Mpdf" not found still error
Answer: mPDF has not used any namespacing until v7 (released in late 2017). Older versions than that simply use
$mpdf = new Mpdf();

If you are starting a new project, please do not use v6.1.3 - that version has been released in 2016 and is horribly outdated
Answer: You are either missing the required library or else calling it incorrectly.
Possible fixes include:

Instead of:
$mpdf = new Mpdf\Mpdf();

Use:
$mpdf = new Mpdf();

Make sure that your dependencies are available and installed. Preferrably install via composer so that all dependencies are installed.


Block-diagonalizing an antisymmetric matrix

Question: I was wondering how to block-diagonalize a $10 \times 10$ antisymmetric matrix into block matrices along the diagonal. Can I just diagonalize each non-diagonal block?
Thanks!
Comment: The problem here could stand clarification.  The last part is easy, if I understand it correctly:  If you have a block diagonal matrix, then you can diagonalize it by diagonalizing each block separately.  However in the subject line you use "antisymmetric" to describe the matrix, suggesting that the (real?) matrix will have imaginary eigenvalues and involve some complex arithmetic if you want to diagonalize it.  See [real Jordan canonical form](http://en.wikipedia.org/wiki/Jordan_canonical_form#Real_matrices) for a discussion of using a block diagonal real matrix (with 2x2 blocks).
Comment: yeah, it's an antisymmetric matrix and it will probably have compex eigenvalues. so, my question is how to put it in block diagonal form. Thanks!
Comment: Hessenberg transformation is available in python/scipy as well https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.hessenberg.html
Answer: Without knowing what level of understanding you're looking for, I'm going to respond with some high level remarks.  Feel free to ask for clarification if something strikes your interest.
A widely referenced work for eigenvalue and decomposition algorithms is Golub and van Loan's Matrix Computations (3rd ed., 1996), and Chapter 7 ("The Unsymmetric Eigenvalue Problem") in particular.  In Sec. 7.4 you would read about the real Schur decomposition in which real matrix $A$ can be factored as $Q^T T Q$ where $Q$ is orthogonal and $T$ is quasi-triangular (block upper triangular such that the diagonal blocks are either $1\times1$ or $2\times2$ blocks).  Hereafter we may refer to sections of this book by prefixing GvL to the section numbers.
In your case there is special structure in that $A$ is real(?) antisymmetric (or skew symmetric as many prefer), and its eigenvalues will occur in purely imaginary conjugate pairs.  Thus the matrix is orthogonally similar to a block diagonal form with $2\times2$ blocks like:
$$ \begin{pmatrix} 0 & \sigma_i \\ -\sigma_i & 0 \end{pmatrix} $$
It is natural to ask if structure-preserving algorithms will have any special advantage in speed or accuracy, and the answer seems to be yes.
Note that the related matrix $iA$ is Hermitian, and by standard direct algorithms (GvL8.3.1 and problem P8.3.5 at end of section 8.3) is unitarily similar to a real tridiagonal matrix.  This suggests there should exist a real orthogonal $Q$ such that $Q^T A Q = T$ is antisymmetric and tridiagonal (and thus has all zeros on the diagonal).  Such a direct computation is the first problem in this course assignment (see also problem GvL8.3 P8.3.8).
As it happens, M. Wimmer in Efficient numerical computation of the Pfaffian for dense and banded skew-symmetric matrices (2011) connects the tridiagonalization of a even-dimensional real antisymmetric matrix with its ("real" Jordan) canonical form (Sec. I.B).  Appendix A spells out the details of this connection, which requires the SVD of a bidiagonal matrix easily derived from $T$.  Sec. II compares several ways of tridiagonalizing a real antisymmetric matrix, including by the Householder transformations required by the references above.

Here is my quick-and-dirty version of tridiagonalizing real antisymmetric matrices:
<code>#{
    Skew Symmetric Tridiagonalization

    Real skew symmetric matrix A can be reduced by direct
    orthogonal (Householder) transformations to a similar
    tridiagonal skew symmetric matrix T.

    The implementation below using Octave (Matlab) syntax is
    motivated by this course assigment, though lacking its
    thoughtful performance optimizations:

    http://www.cs.cornell.edu/courses/CS6210/2010fa/A6/A6.pdf

    See also Golub & van Loan (3rd ed.) as in my answer here:

    http://math.stackexchange.com/a/167191/3111

    Copyright Chip Eastham, July 2012, and dual licensed under
    GNU GPLv3, see http://www.gnu.org/licenses/gpl-3.0.html
    or CC-Wiki, see http://creativecommons.org/licenses/by-sa/3.0/
    with attribution/share-alike required per StackExchange policy.
#}

function [Q, T] = SkewReduce (A)

# usage: [Q, T] = SkewReduce (A)
#
#   A  :  real skew symmetric (square) matrix
# returning:
#   Q  :  real orthogonal matrix s.t. A = QTQ' where
#   T  :  tridiagonal real skew symmetric matrix

   n = size(A,1);  % assume n > 2 (done if n =< 2)
   Q = eye(n);     % initialize to accumulate product
   T = A;          % copy of A to be tridiagonalized

   for k = 1:n-2
      v = T(k+1:n,k);
      r = norm(v);
      v(1) = v(1) + r;
      q = v' * v;
      P = blkdiag(eye(k),eye(n-k) - (2/q)*v*v');
      Q = P*Q;
      T = P*T*P;   % because P is symmetric orthogonal

   endfor

endfunction
</code>
A brief test case is this:
<code>octave:3> A = [0,2,-1;-2,0,-4;1,4,0]
A =

   0   2  -1
  -2   0  -4
   1   4   0

octave:4> [Q,T] = SkewReduce(A)
Q =

   1.00000   0.00000   0.00000
   0.00000   0.89443  -0.44721
   0.00000  -0.44721  -0.89443

T =

   0.00000   2.23607  -0.00000
  -2.23607  -0.00000   4.00000
   0.00000  -4.00000   0.00000
</code>
Note that this tridiagonalization does not depend on matrix size being even.
Answer: The above procedure is equivalent to the Hessenberg transformation and may be achieved in Matlab using

[Q, T] = hess(A)


Masked inputs - to clean or not to clean?

Question: What are the arguments, from the UX perspective, to clean or not to clean masked inputs?
Consider credit card validity:
_ _ / _ _
Partially filling that field makes no sense, the partial value has no business meaning, and might be technically difficult to handle, especially if you store it in the background as year and month.
1 _ / _ _ represents no year, and invalid month (since the 2nd character is unknown, it can't be converted into number)
The techs would like to clean up the partially filled masked inputs on blur, arguing that it's not only technical problematic, but such values look weird for the user, and it's exactly how a date control is working - either you fill the date fully, or you get nothing.
On the other side, it might be annoying to have full value reseted only because you've forgotten the last character, and it's inconsistent with behaviour for wrong inputs (like 15/20), which are accompanied with validation errors.
Which one is better from the UX perspective of an average web user?
Please notice that in our system, locking the user on the formular is not an option. The user must be able to leave formular in any moment and all changes that weren't refused by the control are persisted. So, for example, negative weight will be saved, but the user will be shown, that the data is not consistent. The only data that are not saved are the data that are refused by the inputs. For example, letters in the number fields or incomplete dates.
Comment: I'm not sure I fully understand this. Your users are adding incomplete data to fields. Are the masks in place while they're editing (not necessarily a good idea) or do they appear on blur? If it's the second, then surely on blur you validate the data and, if it's wrong,  just return the user to the field in its unmasked state (focus) and throw out an error message to get them to correct it? Or am I missing something here?
Answer: Don't reset the partial field on blur; put the field into an error state and call attention to it. Sometimes users have partial information and they want to finish the larger task (getting through the form) before coming back to it. An example would be when the user remembers the first few digits of a credit card number but needs to get up and grab the credit card to complete the field. Destroying the data they've already entered could cause annoyance. Your engineers should prevent the user from submitting the form until all error states are cleared.
Comment: I don't like modifying questions after they were posted, but the 2nd part of your answer is out of discussion, I've added details
Comment: It's OK to modify questions here, thanks for the additional detail. What happens in the case where a user has entered a value that is validated by the input pattern, but is incorrect - are they not allowed to change it?
Comment: they are allowed to change invalid value any time, but some business actions are blocked as long as the data are not valid


Multiple Local Notification in iPhone

Question: In my app, I have list of friends say: 3 friends, all these three have birthday details. I need to schedule local notification to show their b'days alert. I know and handled a local notification but how will I handle these multiple notification?
I am setting fire date in "for loop".Is it proper, See the code.
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
        return;
    NSDateFormatter *formatter = [[[NSDateFormatter alloc]init]autorelease];
    for (int i = 0; i< [delegate.viewController.contactList count] ; i++) {
        NSString *birthday = [[myArray objectAtIndex:i]objectForKey:@"birthday"];

        [formatter setDateFormat:@"MM/dd/yyyy"];
        NSDate *date = [formatter dateFromString:birthday];

        localNotif.fireDate = [date dateByAddingTimeInterval:10];
        localNotif.timeZone = [NSTimeZone defaultTimeZone];
        NSLog(@"local %@",localNotif.fireDate);
    }

    localNotif.applicationIconBadgeNumber = 1;

    NSString *itemName = @"Friend Name";
    NSDictionary *userDict = [NSDictionary dictionaryWithObjectAndKey:itemName,@"msg", nil];

    localNotif.userInfo = userDict;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [localNotif release];

What I want,in this method only I have to set notification for all the friend based on their date. can any one tell me where I'm doing wrong and if I'm missing anything please inform me.
Answer: Just make three (or more) local notifications and schedule every one of them with  scheduleLocalNotification:, what's the problem?
For example this is what I did in my project:
for (int i = 0; i < 6; i++) {
    UILocalNotification *localNotification = [prototypeNotification copy];
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:dates];
    [notifications addObject:localNotification];

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

    [localNotification release];
}

UPD
// ...this goes earlier:
static NotificationController *sharedNotificationController = nil;

- (id) init
{
    if (self = [super init]) {
        notifications = [[NSMutableArray alloc] init];

        prototypeNotification = [[UILocalNotification alloc] init];
        prototypeNotification.repeatCalendar = [NSCalendar currentCalendar];
        prototypeNotification.repeatInterval = NSMinuteCalendarUnit;

        prototypeNotification.timeZone = [NSTimeZone defaultTimeZone];
        prototypeNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
        prototypeNotification.applicationIconBadgeNumber = 0;
        prototypeNotification.alertBody = NSLocalizedString(@"Body", nil);
        prototypeNotification.alertAction = NSLocalizedString(@"Action", nil);

        enabled_ = NO;
    }
    return self;
}

Comment: hey Олеr, one more thing to ask, how have u handled applicationDidEnterBackground,method.In my case, its scheduling only for the last localNotification.
Comment: My problem is that, whenever app goes in background, its scheduling for the last notification.
Comment: @iCoder477 So have you got the solution for it?
Comment: Thnx buddy!!! but if m having more than 500 friend and have to schedule everyone.Won't it be performance effective?
Comment: It's nothing but notification (little window to show two strings of text). I don't think performance would suffer.
Comment: What is here prototypeNotification, is it a property??
Comment: In my case it is just instance variable in my class, NotificationController
Comment: I'm not sure if I didn't misunderstood you, but answer is nothing at all. Local notifications is handled by iOS, not your app.
Comment: D'oh, if it's true, I will be in trouble... I' m going to check it.
Comment: I've checked it. Six notifications were scheduled, and all six alarmed at corresponding fire dates.
Comment: Can u please, show me ur code on applicationDidEnterBackground method.
Comment: It's empty. I don't use it. What's the problem?
Comment: I have difficulties in understanding you. 1) You want to schedule notifications when your app run in background? 2) You only get one last notifiacation, but not others?

Multiple Local Notification in iPhone


Equal class misunderstanding

Question:
I have my own data type to represent nodes and edges of a graph as follows:
data Node a = Node a deriving (Show, Eq)

data Label a = Label a deriving (Show)

data Cost = CostI Int | CostF Float deriving (Show)

data Edge label node = Edge (Label label, (Node node,Node node), Cost) deriving (Show)

Now, I create a function to check whether an edge contains 2 nodes or not as follows:
isEdge:: (Eq n) => (Edge l n) -> (Node n, Node n) -> Bool
isEdge (Edge (_, (n1,n2), _)) (n3, n4) = result
     where result = (n1 == n3) && (n2 == n4)

The function works well, the problem here is if I remove (Eq n) from the function, it fails. So, why is that, even though in the declaration above I declared Node as deriving from Eq class?
data Node a = Node a deriving (Show, Eq)

Comment: Just a stylistic point, there no point in writing `data A = A (x, y, z)` rather than `data A = A x y z` and the first version actually uses more space and is more awkward to pattern match on (there is an extra layer of indirection), `data Edge label node = Edge (Label label) (Node node) (Node node) Cost` works just fine.
Comment: Also, you don't need to look inside the pairs of nodes to compare for equality -- you can just write `result = (n1,n2) == (n3,n4)`.  Finally, it's a bit unstylistic to name your type variables `label` and `node` -- usually they'd just be `a` and `b`, or, if you want, something like `n` and `l`.
Answer: The Eq instance GHC derives for Node a is something like this:
instance Eq a => Eq (Node a) where
    (Node x) == (Node y) = x == y
    (Node x) /= (Node y) = x /= y

You can view the generated code by compiling with -ddump-deriv.  The Eq a constraint is needed for obvious reasons.  So, GHC couldn't infer an instance of Eq for, say, Node (a -> b) since functions can't be compared.
However, the fact that GHC can't infer an instance of Eq for Node a for some a doesn't mean it will stop you from constructing a values of type Node a where a isn't an equality type.

If you wanted to stop people from constructing non-comparable Nodes, you could try putting a constraint like this:
data Eq a => Node a = Node a deriving (Eq, Show)

But now GHC tells us we need a compiler pragma:
Illegal datatype context (use -XDatatypeContexts): Eq a =>

OK, let's add it to the top of our file:
{-# LANGUAGE DatatypeContexts #-}

Now compile:
/tmp/foo.hs:1:41: Warning: -XDatatypeContexts is deprecated: It was widely
considered a misfeature, and has been removed from the Haskell language.

The problem is that now every function using Nodes will need an Eq class constraint, which is annoying (your functions still need the constraint!).  (Also, if your user wants to create Nodes using a non-equality type but never tests them for equality, what's the problem?)

There's actually a way to get GHC to do what you want, however: Generalized Algebraic Data Types (GADTs):
{-# LANGUAGE GADTs, StandaloneDeriving #-}

data Node a where
  Node :: Eq a => a -> Node a

This looks just like your original definition, except that it emphasizes the Node value constructor (the one formerly on the right hand side of the data declaration) is just a function, which you can add constraints to.  Now GHC knows that only equality types can be put into Nodes, and unlike our earlier attempted solution, we can make new functions that don't need a constraint:
fromNode :: Node a -> a
fromNode (Node x) = x

We can still derive Eq and Show instances, but with a slightly different syntax:
deriving instance Eq   (Node a)
deriving instance Show (Node a)

(Hence the StandaloneDeriving pragma above.)
For this to work, GHC also requires us to add a Show constraint to our GADT (if you look at the generated code again, you'll see the constraints are now gone):
data Node a where
  Node :: (Eq a, Show a) => a -> Node a

And now we can take the Eq constraint off isEdge, since GHC can infer it!
(This is definitely overkill for such a simple situation -- again, if people want to construct nodes with functions inside them, why shouldn't they?  However, GADTs are extremely useful in pretty similar situations when you want to enforce certain properties of your data types.  See a cool example).

EDIT (from the future): you can also write
data Node a = (Eq a, Show a) => Node a

but you still need to enable GADT extensions and derive instances separately.  See this thread.
Comment: @Fixnum one big issue is that it's no longer possible to create `Node`s for types without the appropriate class.  For `Eq` this might not be an issue, but for `Show` it likely would be.  Another downside is increased memory usage; a `Node` must store an extra pointer for every type class mentioned in the GADT.  If you have a lot of nodes, this could be significant.
Comment: Interesting with GADTs, using type constraint in every function is really annoying. I will take a look at GADTs. Thanks @Fixnum
Comment: I'm curious as to the community's thoughts on this.  Other than the loss of generality and portability to non-GHC compilers, are there other reasons to eschew this "solution"?  (Proliferation of constraints really isn't a problem as far as I know, unlike, say, proliferation of instances, and can be useful documentation.)
Answer: When you add a deriving clause to a data declaration, the derived clause will include any necessary constraints for the type variable in scope at the declaration.  In this case, deriving Eq will create essentially the following instance:
instance Eq a => Eq (Node a) where
    (Node a) == (Node b) = a == b
    (Node a) /= (Node b) = a /= b

Any derived Eq instance will depend upon the Eq instance of types that appear to the right of the data constructor.
This is because there's really no other way to derive an Eq instance automatically.  Two values are equal if they have the same type and all their components are equal.  So you need to be able to test the components for equality.  In order to generically test a polymorphic component for equality, you need an Eq instance.
This is true not just for Eq, but for all the derived classes.  For example this code
toStr :: Edge l n -> String
toStr = show

won't work without adding the constraint (Show l, Show n).  Without that constraint, the function to show an Edge doesn't know what to call to show its internal Labels and Nodes.

Equal class misunderstanding


Would lots of idle clients cause a "service too busy" exception?

Question: I have a WCF service that has an instance mode of Single and a concurrency mode of Multiple. I have the following code:
    public static ICmsDataServiceWcf data
    {
        get
        {
            if (HttpContext.Current != null && HttpContext.Current.Session != null && HttpContext.Current.Session["DataService"] == null)
            {
                HttpContext.Current.Session.Add("DataService", GetDataService());
            }

            if (HttpContext.Current != null && HttpContext.Current.Session != null && HttpContext.Current.Session["DataService"] != null)
            {
                return (ICmsDataServiceWcf)HttpContext.Current.Session["DataService"];
            }
            return GetDataService();
        }
    }

    private static ICmsDataServiceWcf GetDataService()
    {
        string url = ConfigurationManager.AppSettings["service_url"];
        EndpointAddress endPoint = new EndpointAddress(url);

            var binding = new WSHttpBinding(SecurityMode.None);

            CachedWebServiceChannelFactory<ICmsDataServiceWcf> cf = new CachedWebServiceChannelFactory<ICmsDataServiceWcf>(binding, endPoint);

            var channel = cf.CreateChannel();

            return channel;
    }

The idea is that every client gets their own WCF client which only blocks for their requests and I don't have to suffer the overhead of creating/destroying clients multiple times.
Recently I have been getting some "service too busy" exceptions. Most of these clients are sat idle most of the time. Does an idle client still consume resources on the server? Is its instance persisted somehow server side?
Can anyone see a reason why this could cause issues? (Except for the memory wastage of letting lots of clients sit around until sessions get abandoned - I'm looking at using a pool of clients and periodically culling inactive/errored ones.)
Thanks,
Joe
EDIT: I forgot to mention that I've implemented my own proxy - not sure if that would have any impact:
public class CachedWebServiceProxy<T> : RealProxy
{
    private Type _typeOfProxy;
    public object _channel;
    public CachedWebServiceProxy(Type typeOfProxy, object channel)
        : base(typeOfProxy)
    {
        _typeOfProxy = typeOfProxy;
        _channel = channel;
    }
    public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg)
    {
        try
        {
            var methodCall = msg as IMethodCallMessage;
            var methodInfo = methodCall.MethodBase as MethodInfo;
            object result = null;
    // Caching code removed
                result = methodInfo.Invoke(_channel, methodCall.Args);
            return new ReturnMessage(result, null, 0, methodCall.LogicalCallContext, methodCall);
        }
        catch (Exception ex)
        {
            // Throw the actual error fro mthe webservice
            if (ex is TargetInvocationException && ex.InnerException != null)
            {
                throw ex.InnerException;
            }
            throw ex;
        }
    }
}

Answer: Instead of creating a ChannelFactory for each channel, throwing out the factory and then holding on to the channel, you might want to try creating the ChannelFactory (this is the expensive piece of work), and then instantiating a Channel each time you want to use it.
Taking and holding a channel is not the best practice - you should create, use, close and dispose. It's like holding a database connection - it won't be disposed unless you explicitly get rid of it.
private CachedWebServiceChannelFactory<ICmsDataServiceWcf> factory;

public ICmsDataServiceWcf GetDataService()
{
    if (factory == null) // or factory needs rebuilding
    {
        string url = ConfigurationManager.AppSettings["service_url"];
        EndpointAddress endPoint = new EndpointAddress(url);
        var binding = new WSHttpBinding(SecurityMode.None);

        factory = new CachedWebServiceChannelFactory<ICmsDataServiceWcf>
            (binding, endPoint);
    }

    return factory.CreateChannel();
}

and to force the close & dispose, wrap this method in a using
using (var client = GetDataService())
{
    // do stuff
} // client will be disposed upon reaching the end of the using block

Comment: Ah, thank you. I'll do some benchmarking tomorrow and then vote as best answer. Also - would you say that what I've referenced in my answer would be a bad solution and I shouldn't use it? Thanks, Joe.
Comment: I don't know if I'd go so far as saying it is a 'bad' solution, but if you are creating a lot of connections then it's definitely best practice to close them as soon as you are done with them.
Comment: Ok thanks, the main issue that I have is that I have been brought in on a project where everything is based around the property above and the other developer has done lots of things like this:

helper.data.WcfCall(123);
helper.data.OtherWcfCall("foo");

I guess that I'll just have to tell him to fix his code.
Answer: Just found this http://weblogs.asp.net/pglavich/archive/2007/05/07/wcf-client-channel-pool-improved-client-performance.aspx which looks like exactly what I need.
Comment: It seems a bit flakey


How can I show that $T : L^2(0, \pi/2) \to L^2(0, \pi/2)$ defined as $T(f) = x + \frac{1}{4}\cos(x)\int_{0}^{\frac{\pi}{2}}f(y)dy$ is a contraction?

Question: I've tried the following:
\begin{equation}
    \|T(f)-T(g)\| = \|\frac{1}{4}cos(x)\int_0^{\frac{\pi}{2}}f(y) - g(y)dy\| = \frac{1}{4}|\int_0^{\frac{\pi}{2}}f(y) - g(y)dy| \|cos(x)\| = \frac{\sqrt{\pi}}{8}|\int_0^{\frac{\pi}{2}}f(y) - g(y)dy|
\end{equation}
How can I relate this with $\|f-g\| = \sqrt{\int_0^{\frac{\pi}{2}}(f(y) - g(y))^2dy}$ ?
Answer: Let $f,g\in L^2(0,\pi/2)$. Then \begin{align*}
\|Tf-Tg\|_{L^2(0,\pi/2)}^2&= \frac 1{16} \int_0^{\pi/2}\cos^2(x) \bigg ( \int_0^{\pi/2} f(y)-g(y) \, dy \bigg )^2 \, dx\\
&=\frac 1{16}\bigg ( \int_0^{\pi/2} f(y)-g(y) \, dy \bigg )^2 \int_0^{\pi/2}\cos^2(x)  \, dx \\
&= \frac \pi{64}\bigg ( \int_0^{\pi/2} f(y)-g(y) \, dy \bigg )^2
\end{align*} By Hölder's inequality, \begin{align*}
\bigg \vert \int_0^{\pi/2} f(y)-g(y) \, dy \bigg \vert &\leqslant \int_0^{\pi/2}  \vert f(y)-g(y) \vert \, dy \\
&\leqslant \bigg ( \int_0^{\pi/2}  1 \, dy \bigg )^{1/2} \bigg ( \int_0^{\pi/2}  \vert f(y)-g(y) \vert^2 \, dy \bigg )^{1/2} \\
&= (\pi/2)^{1/2} \bigg ( \int_0^{\pi/2}  \vert f(y)-g(y) \vert^2 \, dy \bigg )^{1/2}.
\end{align*} Hence, \begin{align*}
\|Tf-Tg\|_{L^2(0,\pi/2)}^2 &\leqslant \frac {\pi^2}{128}\int_0^{\pi/2}  \vert f(y)-g(y) \vert^2 \, dy = \frac {\pi^2}{128} \| f-g\|_{L^2(0,\pi/2)}^2.
\end{align*} Thus, $$ \|Tf-Tg\|_{L^2(0,\pi/2)}\leqslant \frac{\pi}{4\sqrt2}\| f-g\|_{L^2(0,\pi/2)}$$ and $\frac{\pi}{4\sqrt2} \approx 0.56<1$.
Comment: Thanks! Didn't know Hölder inequality even existed, that makes it much easier


Split a file using specific word in C#

Question: there is a file which i want to split
MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M
MSH|^~\&||||^qweqwewqe|||qwewqeqw|637226866166648574|637226866166648574|2.4
EVN|P03|20200416|20200416
PID|1|PW907441|PW907441|PW907441|Purvis^Walter^Rayshawn||19700524|M

I want to split it using MSH so that the result would be an array of string
array[0]=
"MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";

array[1]=
"MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";

What I have tried so far:
string[] sentences = Regex.Split(a, @"\W*((?i)MSH(?-i))\W*");

result:
array[0]="";
array[1]="MSH";
array[2]="asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
    EVN|asd|20200416|20200416
    PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";
array[3]="MSH";
array[4]="asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
    EVN|asd|20200416|20200416
    PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";

Or atleast it should not miss |^~\&||||^ after split in index 1 and 2
Comment: What is the programming issue you are facing? You only posted a *task*.
Comment: @WiktorStribiżew i have added the code and problem.
Comment: Try `(?i)(?!^)(?=MSH)`. Can your string have `Msh` or `mSh`? Or will it always be uppercased `MSH` only?
Comment: It can have msh Msh MsH etc
Answer: You can simply use the Split() function for this. Below generates an IEnumerable, which you can make an array using ToArray if you wanted to:
void Main()
{
    string s = @"MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M
MSH|^~\&||||^qweqwewqe|||qwewqeqw|637226866166648574|637226866166648574|2.4
EVN|P03|20200416|20200416
PID|1|PW907441|PW907441|PW907441|Purvis^Walter^Rayshawn||19700524|M";

    foreach (var element in s.Split(new string[] { "MSH" }, StringSplitOptions.RemoveEmptyEntries).Select(x => $"MSH{x}"))
    {
        Console.WriteLine(element);
    }
}

Comment: @WiktorStribiżew and you simply missed the fact that it was later added to requirements. There is no way to know what is in one's mind beforehand. We don't have magic 8 ball here.
Comment: On the contrary. Your solution misses the fact OP used a case insensitive `MSH` string to split. Your solution won't work if there is `Msh` or `mSh`, so it is wrong.
Comment: No, it was not later added, it was there when you posted the answer. Do you understand what `(?i)` means? That is exactly why OP used a regex in the first place.
Comment: @WiktorStribiżew I see your math is a bit lacking. Check the timings.
Comment: I have been here all the time, no math required. Please fix your answer or remove.
Comment: No I am not going to remove it. Nobody on SO continuously scans for the OP questions' changes in time to update their answers. My answer was perfectly valid and correct at the point of time as the question stands. Later it was added that it could be case insensitive. If you have asked if that should be at a word boundary and or new line then he would probably say yes, word boundary, new line etc and you would start to add \b ... There is no end to such cases. You are free to down vote. If you could simply check the timings you would see my answer was before any edits.
Comment: No. If you like you can vote to close the question instead. What is your problem with the "correct" answer. It is your sole opinion that it is irrelevant.
Answer: If you want to split on MSH, Cetin Basoz is right. It will perfectly work doing that :
var sentences = a.Split(new String[] { "MSH" }, StringSplitOptions.RemoveEmptyEntries);

If you wanna be case insensitive, you can use that which is much simpler than the regex you used previously :
var sentences = Regex.Split(a, "MSH", RegexOptions.IgnoreCase);

Comment: No, first is not case insensitive, second will remove `MSH` from the matches.

Split a file using specific word in C#


Using LVM2 RAID on Ubuntu 12.04 LTS

Question: I would like to use LVM2's built-in RAID support (lvconvert -m1 --type raid1 vgname/lvname) on my Ubuntu 12.04 LTS server.  Unfortunately this feature appeared in LVM2 2.02.89 (assuming I've read the changelog correctly), while Ubuntu 12.04 has LVM2 2.02.66.
What are my options?  Is there a backport of newer LVM2 somewhere?  Will a newer lvm2 package require a newer kernel than the one in 12.04, or are these features managed in userspace somehow?
Answer: A backported LVM package seems safe enough. If the kernel doesn't support the md/dm integration, I expect it will fail the conversion step, at which point you could just backport the kernel too.

Using LVM2 RAID on Ubuntu 12.04 LTS


How does energy loss work in Redstone Energy Conduits

Question:
In this situation you see I have my conduits linearly running along the line of engines. It says on the wiki that the conduits have a 5% energy loss, implemented at points where energy enters the line. Does this mean that with 5 entry points linearly spread (like I have here) that by the time the energy reaches me I've lost 25% of my energy, or still just 5%?
Answer: The moment energy enters a Redstone Energy Conduits or a Redstone Energy Cell from the outside, you lose 5% power.
Once energy is in the system, there is no loss. Moving Energy between Redstone Energy Conduits and/or Redstone Energy Cells is lossless, and there is no distance based loss. So your loss is 5% from each engine, which (because math) is 5% of your total energy output, not 25%.
Answer: You have five entry points, and at each point, energy passing through decreases by 5%. However, you are not losing 25% of your energy, since any energy entering your system only passes through one entry point, not all five.


Can I build a mitered aluminum glass frame from glass edge banding?

Question: Can I build a more substantial window frame from ultra thin aluminum edge banding by mitering the corners and installing a super low profile corner key?
Comment: More substantial than what? Where are you using this window? There are usually code requirements to meet...
Comment: @freeman Stronger at the corners than just gluing the mitered edge frame to the glass.  Something that will transmit forces applied from the clips pressing on the aluminum banding to the whole length of banding and through the corner, not forcing the last inch of glass at the corner to take the load.  Creating a FRAME around the glass. But ultra thin, with a super low profile channel for the key.
Answer: What you describe as to structure can be built if you have:

A source for the aluminum extrusion frame material. If no source you may need to design its cross section profile yourself and then finance a manufacturer to extrude the material for you.
A source for the corner brace piece. For a custom designed extrusion you would need to design around some existing corner or design and get custom corner pieces stamped out. Be prepared for a tooling charge for custom parts.
The tools needed to cut the aluminum extrusions and a press to push in the corner brackets. Depending upon the method used to retain the corner pieces you may also need  a tool to crimp or rivet the part in place.
Patience to put it together with the glass panels.

What is not at all certain is if this will provide the protection against glass breakage and shattering that you desire. Obviously the design of the frame will need a good bit of engineering modeling to fully understand the rigidity and strength of the frame to protect the glass. It is almost assured the slimmer, thinner and lower profile the frame the less protection it will offer to the glass. There will also be considerations on the type of glass used, its panel size and thickness.
Another factor that also plays into the protection level is if the frame will include a rubber or vinyl isolation strip between the frame and the glass. This alone will likely require considerable engineering work and experimentation.
Comment: Thorough, informed, incisive, elucidating, and apparently correct.  Do you happen to have a dozen removable glazing panels for an Andersen 2817 basement hopper window?
Comment: @AndyzSmith - Why would you think I would have those specific windows?
Comment: @AndyzSmith - Maybe you can find them here: https://parts.andersenwindows.com/search.jsp?fs_0_UnitNumberandSize=2817&category=w_basement
Comment: Yeah i have that site, and 0240816 is the exact match hopper sash, BUT the replacement sash unit doesnt come with the options (the removable glazing) that were offered on new installation.


redirection is happening in ionic serve but not on device

Question: I am launching external url on a button click by using window.location.replace
Login(){
    window.location.replace("https://localdomain.com");
}

In ionic serve, after the click it redirects to "https://localdomain.com/uaa/login" and letting me to Login with corresponding cookies & header info coming as expected.
But if the same is tried in mobile i.e. after the apk build and opened in the device.
After the click, It shows below instead of redirecting to /uaa/login. so if understand correctly, redirection is not handled by default in ionic's webview? if so how to handle it?

I see the below console log from device inspect when above error comes.
Failed to load resource: the server responded with a status of 401 () /favicon.ico:1

Comment: you need to check the console. Connect your device and go to chrome://inspect
Comment: added console logs.
Comment: Use: https://ionicframework.com/docs/native/in-app-browser
Comment: You have to use InAppBrowser plugin to open any external URL from the app.
Answer: There is no problem with inappbrowser. The back end server of the URL I'm loading in inappbrowser is having error in the logs. Resolved after fixing them


Discord API, can not get data from json array inside array from user input arg[1] in Node JS

Question: I am using Discord API on Node JS.
I got a JSON array and I am trying to get the client output the corresponding value for what the user typed inside a json array.
Inside the client.js
let name = (arg[1])
message.author.send('Result: ' + data.name.desc + data.name.code)

Inside the JSON:
{
   "Server1": {
    "desc": "A Fun Place",
    "code": "9021da"
    },
   "Server2": {
    "desc": "A Chill Place",
    "code": "90a11d"
    }
}

What I am trying to do is giving the user the desc and the code of the server that they type.
(There are over 100 of these)
Answer: You have to use bracket notation:
message.author.send('Result: ' + data[name].desc + data[name].code)


How to Handle Undefined Values in TypeScript with RenderIf Component Similar to JS && Check

Question: I have recently moved over to typescript and have been enjoying the benefits it has provided. I was trying to move over a pattern I used in React with javascript that I liked of a RenderIf component that checked whether it should show the content below or return null. The following code does work in typescript when not passing a potentially undefined value. I am stumped on how to help the typescript compiler realize that we already did the && check to validate that the value exists if the value can be undefined. Any typescript masters out there who know how I might fix this?
RenderIf Component
type RenderIfProps = {
  condition: boolean;
};

export const RenderIf: React.FC<RenderIfProps> = (props) => {
  const { condition = false, children } = props;
  const isConditionMetAndHasChildren = condition === true && !!children;

  if (isConditionMetAndHasChildren) {
    return <>{children}</>;
  }
  return null;
};

Example of typescript not being happy with RenderIf
const someComponent = (props: { someValue?: string }) => {
  return (
    <RenderIf condition={!!props?.someValue}>
      <ComponentA definedValue={props.someValue} />
    </RenderIf>
  )
}

Example of typescript being happy with &&
const someComponent = (props: { someValue?: string }) => {
  return (
    !!props?.someValue && <ComponentA definedValue={props.someValue} />
  )
}

Edit: This is the error message
TS18049:  props  is possibly  null  or  undefined
Comment: Please update the type RenderIfProps.
type RenderIfProps = {
  condition: boolean;
  children: React.ReactNode;
};
Comment: I see, so TypeScript will not know that your RenderIf valdiated your props and it should be OK within the children part, that's why second work as you assure it is defined.
Comment: Please make sure you use .tsx instead of .ts.
Comment: Thanks for the tip @JasonMing. I am using tsx and that still is not solving the problem, unfortunately.  Any other ideas?
Comment: Can you also provide exact TypeScript error along your code?
Comment: @JasonMing I believe that is taken care of via the FC. Either way that still is not a solution to the problem I am trying to solve.
Comment: @Lukasz'Severiaan'Grela just updated with the TS Error
Answer: Why doesn't it work? Because that's not how TypeScript works.

The props.someValue typing will always be the same on the same scope. In this case, the RenderIf and ComponentA functional components are in the same scope.
function SomeComponent(props: { someValue?: string }) {
  return (
    <RenderIf condition={!!props?.someValue}>
      <ComponentA definedValue={props.someValue} />
    </RenderIf>
  );
}

That's why definedValue props on ComponentA get this error: Type 'string | undefined' is not assignable to type 'string'.

Solution 1 - Children Structure
To make it work, we need to define the typescript scope of the functional component. If you want to keep the children-like structure like your example, I can share a solution to this.
1. We need to adjust the RenderIf component:
type RenderIfProps = {
  definedValue?: string;
  children(definedValue: string): ReactElement;
};
function RenderIf(props: PropsWithChildren<RenderIfProps>) {
  const { definedValue, children } = props;

  if (!definedValue || !children) {
    return null;
  }

  return children(definedValue);
}

I adjusted the RenderIf functional component to:

Accept definedValue string | undefined (not the boolean state)
Re-define the children props from accepting a component to a function, this way I can change the scope of the typescript into the typing that I want.

2. We need to adjust SomeComponent when calling RenderIf
function SomeComponent(props: { someValue?: string }) {
  return (
    <RenderIf definedValue={props?.someValue}>
      {(value) => <ComponentA definedValue={value} />}
    </RenderIf>
  );
}

I change how I call the children inside the RenderIf component. Instead of directly adding a component, I add a function, in which the parameter is a string type, not string | undefined like before. This is what I previously called changing the scope of the typing.
CodeSandbox example: here

I put the most similar solution to your example. Depending on the use case, this solution might not be the best. And since there are a lot of ways to achieve what you want, I put the "Solution 1" above.
Let me know if it doesn't work for you.
Answer: Type narrowing like this sadly isn't possible, but there are some alternative solutions.
I think that most idiomatic is simply using && or ternary:
const SomeComponent = (props: { someValue?: string }) => {
  return props.someValue ? (
    <ComponentA definedValue={props.someValue} />
  ) : (
    <></>
  );
};

For more complicated expressions (like using a switch statement deep inside some component) I reach out to IIFE-s, but it's a better practice to move complicated logic out of the component into the hook anyway, so try not to use this:
const SomeComponent = (props: { someValue?: string }) => {
  return (
    <>
      {(() => {
        if (props.someValue && props.someValue.length > 12) {
          return
{props.someValue}
;
        } else if (props.someValue) {
          return
{props.someValue}
;
        } else {
          return "";
        }
      })()}
    </>
  );
};

You can get quite close to your RenderIf if you limit yourself to existence conditions and pass to it component wrapped as a function - so typescript can do type inference:
function RenderIf<T>({
  component,
  props,
}: {
  component: (props: T) => JSX.Element;
  props: T | null | undefined;
}) {
  if (props !== null && props !== undefined) {
    return component(props);
  } else {
    return <></>;
  }
}

const someComponent = (props: { someValue?: string }) => {
  return (
    <RenderIf
      component={(someValue) => <ComponentA definedValue={someValue} />}
      props={props.someValue}
    />
  );
};

Alternatively if you limit the RenderIf to checking if all props are present, you can shorten it even more using a custom type predicate:
function isFull<T extends {}>(props: Partial<T>): props is T {
  for (const key in props) {
    if (props[key] === undefined) {
      return false;
    }
  }

  return true;
}

function RenderIfAllProps<T extends {}>({
  component,
  props,
}: {
  component: (props: T) => JSX.Element;
  props: Partial<T> | null | undefined;
}) {
  if (props !== null && props !== undefined && isFull(props)) {
    return component(props);
  } else {
    return <></>;
  }
}

const SomeComponent = (props: { someValue?: string }) => {
  return (
    <RenderIfAllProps
      component={ComponentA}
      props={{ definedValue: props.someValue }}
    />
  );
};

On the risk of repeating myself let me emphasize again that out of these && and ternary statement are by far the simplest and thus probably best.


Force function to show result when they received with jquery.get method

Question: this function gets results with $.get method from an asp ashx XML file :
$.get("http://www.example.com/example.ashx",
                { From: txtFrom, To: txtTo, Date: txtTime },
                function (data) {
                    var arrFrom = [], arrTo = [], arrPrice = [];
                    $(data).find("F").each(function (index, item) {
                        arrFrom[index] = [];
                        arrTo[index] = [];
                        arrPrice[index] = [];
                        $(item).find("From").each(function (i, fromIndex) {
                            arrFrom[index].push($(fromIndex).text());
                        });
                        $(item).find("To").each(function (i, toIndex) {
                            arrTo[index].push($(toIndex).text());
                        });
                        $(item).find("Price").each(function (i, priceIndex) {
                            arrPrice[index].push($(priceIndex).text());
                        });
                    });
                    /**********************************************************/
                    var htmlResult = "
";
                    for (i = 0; i < arrFrom.length; i++) {
                        htmlResult += "
" + arrFrom[i] + "	" +
                            "" + arrTo[i] + "	" +
                            "" + arrPrice[i] + "
"
                    };
                    htmlResult += "
";

                    $('#divSearchResults').html(htmlResult);
                    /**********************************************************/

                }, "text");

but ashx needs some time (unpredictable) to response.
I used a function to recall this each 5seconds, but it is not affordable.
how can I make htmlResult be created right when the response is received?
Comment: If you replay this call, you're actually making another call to your backend, possibly extending the time it takes for it to answer. Your code should work just like you asked as it is.
Comment: Except that you're redeclaring `htmlResult` just before using it. Remove the last `var htmlResult;`
Comment: as jquery docs I tried .done after that, but no luck. would you please refer to a sample?
Comment: Please explain how is this not working. It should work as it is.
Comment: example.ashx need some time to response, but GET method won't wait for the response and htmlResult is always empty.
I think there must be somthing like : Get -> receiveRespose -> showHtmlResults.
Answer: Your sample code is correct, in the sense that the anonymous function that you've defined fires as soon as your backend responds. If your data is empty, it could mean that something happens to the data while you're processing it in your javascript, your backend returned an empty dataset, or your backend timed out. To check whether the problem is with your backend or your data processing, try this:
$.get("http://www.example.com/example.ashx",
    { From: txtFrom, To: txtTo, Date: txtTime },
    function (data) {
        console.log(data);
        //Or in case you don't have a developer console use alert:
        alert(data);
    }, "text");

You should now be able to verify that you are indeed getting data. If that's the case, then something is happening to the data when you're parsing it, and you should debug that code instead, perhaps with a static dataset. You could also make your life a lot easier by sending json encoded data instead of plaintext. I don't know how you would do that with your backend but I'm sure Google will help. On the javascript side of things you could then change the last line to:
    }, "json");

Then, instead of find()ing things, you would have a neat json object to work with.


Google CalDAV PROPFIND response

Question: We are coding Plugins for Roundcube.
We noticed that Google stopped to return vcard URL's on a PROPFIND request to ...
https://google.com/m8/carddav/principals/__uids__/user%40gmail.com/lists/default/

Due to this issue Thunderbird/SoGo stopped sync'ing contacts too.
Issue was reported first time 03/28/2013.
Does anyone know a workaround?
Answer: I don't think the URL you're sending the requests to is valid anymore. You should use the one, which can be discovered by sending a PROPFIND to https://www.googleapis.com/.well-known/carddav, which at this moment is:

https://email@example.com/lists/default

Google CalDAV PROPFIND response


One page checkout with add to cart at the top to enhance conversation rate?

Question: We are building an E-commerce website for a client that only sells one product (with different size). The customer can buy multiple quantity and different size every time.
Now, we're having a discussion on whether if we should:
A) Put the product add to cart button on the check out page so the customer will have a seamless checkout

B) Or back to the traditional way, where we put the add to cart on the product description page. The checkout page will only consist of the overview of your cart, addresses, and payment details
I personally think option B is the way to go because in option A user doesn't get the full visual and descriptive details of the product on the checkout page. And I also think the checkout flow is weird when you can add to cart and edit the cart at the same page.
But other team members think option A will increase conversation way since everything is on one page.
My question is, if anyone have any experience/suggestion on which flow has the advantages when doing a single product e-commerce checkout?
Comment: How does the user get to these pages in the first place? If doing A, does the user come from a product description page first? What about in the B scenario?
Comment: @KevinBorders Good question.

For A, the user can get access to this page from the product description page and also from the menu say a "Buy Now" button.

For B, it will be more of a traditional approach, so the user will be able to add to cart in the product description page, then click Cart on the menu to land on this checkout page with only the overview of the cart, account, payment details..etc..
Answer: While A has the add-to-cart and the cart information on the same page, you still have to arrive at that page via a product description page. So, it is still a two-step process like B.
The design of B actually exposes more of the workflow (selecting quantity and hitting add to cart) on the first page the user sees instead of the second page. So, if you are judging only based on how early the user sees the workflow, then B is actually better. However, there are always other considerations (such as following conventions to provide familiarity) and it depends on your exact website. The only way to know for sure is to A/B test it.
Comment: Agreed that to get the best comparison result is to A/B test. But user on **A** can also get to the cart page through the menu as well, so is actually one step shorter. But if you think about the user pattern, a user wouldn't directly to go the cart page to add product, most likely he/she would want to see the product itself first before adding the product to the cart. I believe it is more stimulating to have the add to cart button on the product description page, rather then going to another page and do it. Then you'll sort of lose the interest without all the supportive elements.
Answer: Reasons for not getting rid of the cart:

The cart often gets perceived as a "saving items for a later purchase" feature.
it is a metaphor for real life purchase: First you put it in the cart, then go to the cashier, then buy it. This is a useful mechanic for non-tech-savy to understand what's happening.

The argument "everything is on one page" is a hard one: A one-step-checkout (which you did not build - yours is a "one-step-cart-and-checkout-product-page") always brings the danger of information overload and massively collaborates with what users EXPECT to happen on a product page.
So even if you think your feature is great, expectations will work against you.
Then, as well, for marketing you will run into different problems: How to create mailings for cart abandonment? Which page will you redirect to?
Where will you show the current amount of items "on the cart"? How does the user navigate to the list of items he selected two days before?
I think the consequences are broader than the benefits.
Comment: Thanks, well descriptive point of view to the issue. Agreed that this is more like a "one-step-cart-and-checkout-product-page" then a one step checkout page. To me the most unnatural user flow is putting the cart and checkout in one page, which is confusing. Because "checkout" should be as simple as possible to just checkout, but we added an extra step for people to add products to the same page!


Replace all occurrences of a string in given char/byte array in C#

Question: I come from C++ background and was wondering whether in C# exist any magic that would let me to do the following:
char[] buf = new char[128*1024*1024];
// filling the arr
buf = buf.ToString().Replace(oldstring, newstring).ToArray();

Is there a chance to do it fast (not write all things by hand) and efficient (have one copy of buffer)?
Answer: Not very clear what is really your char array is in code provided, but...
Use String[] ctor overload to construct the string from your char array, and after call replace with desired parameters.
Comment: it's used as (binary / text) file buffer. Suppose you got a really big file, get a piece of it and process the data in a iterative manner. btw calling `string strbuf = new string(buf)` will allocate more memory, it this true?
Comment: Yes, strings are immutable in C#, so it will allocate a new block of memory.
Answer: Since strings are immutable in .NET, the most memory efficient way of manipulating them is by using the StringBuilder class, which internally treats them as mutable.
Here's an example:
var buffer = new StringBuilder(128*1024*1024);

// Fill the buffer using the 'StringBuilder.Append' method.
// Examples:
// buffer.Append('E');
// buffer.Append("foo");
// buffer.Append(new char[] { 'A', 'w', 'e', 's', 'o', 'm', 'e' });
// Alternatively you can access the elements of the underlying char array directly
// through 'StringBuilder.Chars' indexer.
// Example:
// buffer.Chars[9] = 'E';

buffer = buffer.Replace(oldstring, newstring);

Comment: @Hans Passant Mine was just an example. The `StringBuilder` class treats strings as mutable, so the manipulation itself is memory efficient.
Comment: ToString() generates a copy.  So: no.
Answer: If you need to stay with the array (and cannot use something else to start with, e.g. as others suggested a StringBuilder), then no. There is no built in, "zero-copy", way to "replace a (sub-)char-array with another (sub-)char-array in a given char-array".


Can I prevent flashing?

Question: I notice that once I'm above 1,000,000 cookies or so, I get the flashing background. However this only happens when I click the cookie. If I don't click the cookie will it never happen? How does this affect the Elder Pledges?
Comment: This looks really funny from the front page, since there's no mention of the spoiler. It just says "I notice that once Im" and that's it XD
Answer: Given the date of this question, it was asked before "The Big Update" which removed this issue, but moreover completely revamped the game. To play as it was at the time of the question, one can still go back to cookie clicker classic.
In the update log of cookie clicker classic, you should note that the very next day, in version 0.125, an option to disable flashing was added. To prevent flashing, simply update to the newest version of cookie clicker classic (refresh the page) or upgrade to the entirely revamped cookie clicker where this is not an issue.
According to the source code in 0.125, this will affect the elder pledge:

if (Cookies>=1000000 && Pledge<=0 && Flashing)
{
    var r=(Cookies-1000000)/2000000;
    var r2=Math.max(0,(Cookies-100000000)/400000000);
    var icon='grandmaicon';
    if (Cookies>=2000000)
    {
        l('buyElder Pledge').style.display='block';
        if (Math.random()<0.02) icon='grandmaiconinvert';
        else if (Math.random()<0.02) icon='grandmaiconlustful';
    }
    if (Cookies>=10000000 && Math.random()<0.02) icon='skellington';
    if (Cookies>=1000000000) l('whole').style.background='url(kaleigrandma.png) '+Math.floor(T*0.2)+'px -'+Math.floor(T*0.1)+'px';
    else if (Math.random()<r)
    {
        l('whole').style.background='url('+icon+'.png) '+Math.floor(Math.random()*4)+'px '+Math.floor(Math.random()*4)+'px';
        l('whole').style.backgroundSize=Math.floor(r2*Math.random()*64+64)+'px '+Math.floor(r2*Math.random()*64+64)+'px ';
    }
}//sorry
else l('whole').style.background='#ccc';

As noted in the if statement, turning off flashing will disable the whole of the grandmapocalypse. Also, as this is in the main function, it should not be dependent upon any clicking and should happen on its own - perhaps it coincided with your clicks due to your browser or simply by coincidenced.

Can I prevent flashing?


Movie play error - nil string

Question: I am trying to play a movie in ios but i keep getting error.
My code:
<code>-(IBAction)playMovie:(id)sender

NSString *filepath   =   [[NSBundle mainBundle] pathForResource:@"big-buck-bunny-clip" ofType:@"m4v"];
NSURL    *fileURL    =   [NSURL fileURLWithPath:filepath];
MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(moviePlaybackComplete:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:moviePlayerController];
[self.view addSubview:moviePlayerController.view];
moviePlayerController.fullscreen = YES;
[moviePlayerController play];
</code>
}
<code>- (void)moviePlaybackComplete:(NSNotification *)notification

MPMoviePlayerController *moviePlayerController = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:MPMoviePlayerPlaybackDidFinishNotification
                                              object:moviePlayerController];
[moviePlayerController.view removeFromSuperview];

[moviePlayerController.view setFrame:CGRectMake(38, 100, 250, 163)];
[self.view addSubview:moviePlayerController.view];
//moviePlayerController.fullscreen = YES;
[moviePlayerController play];
</code>
}
the error is:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '*** -[NSURL
  initFileURLWithPath:]: nil string parameter'
Answer: ok i got it .. i forgot to add the file in build phase ...
Comment: You should add more explicit details to make this a proper answer.

Movie play error - nil string


Removing degree-2 vertices from a graph

Question: Consider a map of a river system. Each point on the river line is a graph vertex. Some points have degree 1, at the start and end of a river, some have degree > 2 where rivers merge (or more rarely, split) and a load of vertex points will have degree 2 as a river winds along. This graph is generated from the spatial coordinates of the river.
However, the degree 2 vertices are not relevant to the topology of the river system, so I want to remove them. I'll end up with a kind of 'skeleton' graph, with just vertices of degree 1 or >2 connected but without the degree-2 vertices.
Does this transformation have a name? I can't find anything from a bit of research, but it can sometimes be hard to get through all the graph theory jargon (cliques, induced subgraphs, etc etc).
I'm using R and the igraph package. I have coded up an iterative process that repeatedly removes a single degree-2 node and joins its neighbours until no degree-2 vertices are left, but I wonder if there's a trick I'm missing.
Since I want this to be more general than just river networks (which are likely to be but not necessarily be trees) I'll have to think about what to do with a circular graph where all vertices are degree-2. I think I want to end up with one arbitrary vertex with an edge to itself.
Anyway, maybe someone will know exactly what this is...
Comment: Also, maybe this is what you are looking for http://en.wikipedia.org/wiki/Homeomorphism_(graph_theory).
Comment: so its either repeatedly "lifting" [utdiscant] or "smoothing" [wikipedia]. At least I know what to call my R function instead of "removeDegreeTwo". Thanks!
Comment: If you have edges $xy$ and $yz$, and perform the operation of removing $xy$ and $yz$ while adding $xz$, that is called lifting $\{xy,yz\}$. But lifts in graphs can also mean other things, so be careful when googling for the term.
Comment: I've seen the opposite procedure, the introduction of vertices of degree 2, referred to as "expansion".
Comment: @GerryMyerson I have always heard that referred to as subdivision (http://planetmath.org/encyclopedia/TopologicalMinor.html)
Comment: @utd, yes, I've also seen the word "subdivision" used for that.
Comment: i'll sign up at this math stackexchange just to upvote your question and comment about "removeDegreeTwo :) i have almost the same in my openstreetmap road network use case)
Answer: There seems to be multiple names for this operation.
If one has two edges $xy$ and $yz$, the operation of removing $xy$ and $yz$ while adding $xz$ is called lifting the edges $\{xy,yz\}$. Thus one can repeatedly lift edges adjacent to vertices of degree 2.
This is also referred to as smoothing here, where smoothing is described in the same way. Thus one could define the operation of smoothing a graph, as repeatedly smoothing the vertices of degree 2.
Answer: My incremental method was slow, so I came up with an algorithm that works slightly faster.

Start with graph G
Take the subgraph of G of all degree=2 vertices. This has to be a disconnected set of simple chains (ie two degree=1 vertices connected by zero or more degree=2 vertices) or single (degree-zero) vertices
For each of the chains,

find the neighbors of the endpoints of the chain from G (this relies on graph ID values being propagated in the subgraph process)
add a new edge to G connecting those endpoints
delete all vertices in G in the chain

Note the speed improvement comes from deleting potentially many vertices at once and making fewer new edges. Its not really an algorithmic improvement.
Still need to think about how to handle loops and multiple edges and so forth, but at the risk of turning this into a programming question and having it kicked to StackOverflow I'll stop now.
Answer: I don't believe there is a trick you are missing.
Assuming a directed graph, the algorithm for this is as follows:
Initialize a queue Q of all the vertices

While Q is not empty:
  Pop the top of Q into N

  If N does not have an one incoming and one outgoing edge:
    Continue to the next item in Q

  If N has been seen:
    Continue to the next item in Q

  Mark N as Seen

  Let Up be the node which points into N
  Let Down be the node which N points to

  Create an edge Up-Down with Weight=Weight[Up]+Weight[Down]

  Remove the edges Up-N and N-Down

You can see that each node is added to Q only once and all of the nodes are eventually removed from the Q.
Therefore, the algorithm runs in O(N) time. There is no way you can do better than this. The alternative algorithm you suggest in your answer may work faster, but this is only because of implementation details.

Removing degree-2 vertices from a graph


Why do I suddenly have this erroneous font in prompt and output of gnome-terminal?

Question: I'm experiencing replacement of all occurrences of certain characters in the prompt and output of gnome-terminal (3.6.2 in Ubuntu 14.04), e.g.

(latin d is replaced with some kind of uppercase D in exponent and some other pixels below).
reset and clear don't help. Copying the output/prompt returns the character sequence without replacements. What could cause this?
Comment: Have you checked your .bashrc file? More specifically the $PS1 theme?
Answer: This can happen after reading from /dev/random or /dev/urandom with cat. This seems to be fixed in version 3.20.2 of gnome-terminal. In older versions it's necessary to open a new terminal or try @Meow's solution below.
Answer: try
gconftool-2 --set /apps/gnome-terminal/profiles/Default/font --type string "Ubuntu Mono derivative Powerline 11"

Comment: It's not that easy to reproduce, I assume `gnome-terminal` has been immunized.